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
Scavenge/darkstar
scripts/zones/Riverne-Site_A01/npcs/Unstable_Displacement.lua
17
1049
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement -- ENM Battlefield ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SPACE_SEEMS_DISTORTED); 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
SvenRoederer/packages
libs/lua-math-polygon/src/math-polygon.lua
1
1763
local M = {} -- Source with pseudocode: https://de.wikipedia.org/wiki/Punkt-in-Polygon-Test_nach_Jordan -- see also https://en.wikipedia.org/wiki/Point_in_polygon -- parameters: points A = (x_a, y_a), B = (x_b, y_b), C = (x_c, y_c) -- return value: −1 if the ray from A to the right bisects the edge [BC] (the lower vortex of [BC] -- is not seen as part of [BC]); -- 0 if A is on [BC]; -- +1 else function M.cross_prod_test(x_a, y_a, x_b, y_b, x_c, y_c) if y_a == y_b and y_b == y_c then if (x_b <= x_a and x_a <= x_c) or (x_c <= x_a and x_a <= x_b) then return 0 end return 1 end if not (y_a == y_b and x_a == x_b) then if y_b > y_c then -- swap b and c local h = x_b x_b = x_c x_c = h h = y_b y_b = y_c y_c = h end if y_a <= y_b or y_a > y_c then return 1 end local delta = (x_b-x_a) * (y_c-y_a) - (y_b-y_a) * (x_c-x_a) if delta > 0 then return 1 end if delta < 0 then return -1 end end return 0 end -- Source with pseudocode: https://de.wikipedia.org/wiki/Punkt-in-Polygon-Test_nach_Jordan -- see also: https://en.wikipedia.org/wiki/Point_in_polygon -- let P be a 2D Polygon and Q a 2D Point -- return value: +1 if Q within P; -- −1 if Q outside of P; -- 0 if Q on an edge of P function M.point_in_polygon(poly, point) local t = -1 for i=1, #poly-1 do t = t * M.cross_prod_test(point.lon, point.lat, poly[i].lon, poly[i].lat, poly[i+1].lon, poly[i+1].lat) if t == 0 then break end end return t end -- Convert rectangle defined by two point into polygon function M.two_point_rec_to_poly(rec) return { rec[1], { lon = rec[2].lon, lat = rec[1].lat }, rec[2], { lon = rec[1].lon, lat = rec[2].lat }, } end return M
gpl-2.0
Scavenge/darkstar
scripts/globals/items/mammut.lua
41
1059
----------------------------------------- -- ID: 18503 -- Item: Mammut -- Additional Effect: Ice Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 10; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(4,15); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_ICE,0); dmg = adjustForTarget(target,dmg,ELE_ICE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_ICE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_ICE_DAMAGE,message,dmg; end end;
gpl-3.0
smanolache/kong
spec/integration/04-admin_api/kong_routes_spec.lua
1
4656
local json = require "cjson" local utils = require "kong.tools.utils" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local env = spec_helper.get_env() -- test environment local dao_factory = env.dao_factory describe("Admin API", function() setup(function() spec_helper.prepare_db() spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Kong routes", function() describe("/", function() local meta = require "kong.meta" it("should return Kong's version and a welcome message", function() local response, status = http_client.get(spec_helper.API_URL) assert.are.equal(200, status) local body = json.decode(response) assert.truthy(body.version) assert.truthy(body.tagline) assert.equal(meta._VERSION, body.version) end) it("should have a Server header", function() local _, status, headers = http_client.get(spec_helper.API_URL) assert.equal(200, status) assert.equal(string.format("%s/%s", meta._NAME, meta._VERSION), headers.server) assert.falsy(headers.via) -- Via is only set for proxied requests end) it("should return method not allowed", function() local res, status = http_client.post(spec_helper.API_URL) assert.equal(405, status) assert.equal("Method not allowed", json.decode(res).message) local res, status = http_client.delete(spec_helper.API_URL) assert.equal(405, status) assert.equal("Method not allowed", json.decode(res).message) local res, status = http_client.put(spec_helper.API_URL) assert.equal(405, status) assert.equal("Method not allowed", json.decode(res).message) local res, status = http_client.patch(spec_helper.API_URL) assert.equal(405, status) assert.equal("Method not allowed", json.decode(res).message) end) end) end) describe("/status", function() it("should return status information", function() local response, status = http_client.get(spec_helper.API_URL.."/status") assert.equal(200, status) local body = json.decode(response) assert.truthy(body) assert.equal(2, utils.table_size(body)) -- Database stats -- Removing migrations DAO dao_factory.daos.migrations = nil assert.equal(utils.table_size(dao_factory.daos), utils.table_size(body.database)) for k, _ in pairs(dao_factory.daos) do assert.truthy(body.database[k]) end -- Server stats assert.equal(7, utils.table_size(body.server)) assert.truthy(body.server.connections_accepted) assert.truthy(body.server.connections_active) assert.truthy(body.server.connections_handled) assert.truthy(body.server.connections_reading) assert.truthy(body.server.connections_writing) assert.truthy(body.server.connections_waiting) assert.truthy(body.server.total_requests) end) end) describe("Request size", function() it("should properly hanlde big POST bodies < 10MB", function() local response, status = http_client.post(spec_helper.API_URL.."/apis", { request_host = "hello.com", upstream_url = "http://mockbin.org" }) assert.equal(201, status) local api_id = json.decode(response).id assert.truthy(api_id) local big_value = string.rep("204.48.16.0,", 1000) big_value = string.sub(big_value, 1, string.len(big_value) - 1) assert.truthy(string.len(big_value) > 10000) -- More than 10kb local _, status = http_client.post(spec_helper.API_URL.."/apis/"..api_id.."/plugins/", { name = "ip-restriction", ["config.blacklist"] = big_value }) assert.equal(201, status) end) it("should fail with requests > 10MB", function() local response, status = http_client.post(spec_helper.API_URL.."/apis", { request_host = "hello2.com", upstream_url = "http://mockbin.org" }) assert.equal(201, status) local api_id = json.decode(response).id assert.truthy(api_id) -- It should fail with more than 10MB local big_value = string.rep("204.48.16.0,", 1024000) big_value = string.sub(big_value, 1, string.len(big_value) - 1) assert.truthy(string.len(big_value) > 10000000) -- More than 10kb local _, status = http_client.post(spec_helper.API_URL.."/apis/"..api_id.."/plugins/", { name = "ip-restriction", ["config.blacklist"] = big_value }) assert.equal(413, status) end) end) end)
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/chili/Skins/DarkHive/skin.lua
17
4554
--//============================================================================= --// Skin local skin = { info = { name = "DarkHive", version = "0.1", author = "luckywaldo7", } } --//============================================================================= --// skin.general = { --font = "FreeSansBold.ttf", fontOutline = false, fontsize = 13, textColor = {1,1,1,1}, --padding = {5, 5, 5, 5}, --// padding: left, top, right, bottom backgroundColor = {0.1, 0.1, 0.1, 0.7}, } skin.icons = { imageplaceholder = ":cl:placeholder.png", } skin.button = { TileImageBK = ":cl:tech_button.png", TileImageFG = ":cl:empty.png", tiles = {22, 22, 22, 22}, --// tile widths: left,top,right,bottom padding = {10, 10, 10, 10}, backgroundColor = {1, 1, 1, 0.7}, DrawControl = DrawButton, } skin.button_disabled = { TileImageBK = ":cl:tech_button.png", TileImageFG = ":cl:empty.png", tiles = {22, 22, 22, 22}, --// tile widths: left,top,right,bottom padding = {10, 10, 10, 10}, color = {0.3,.3,.3,1}, backgroundColor = {0.1,0.1,0.1,0.8}, DrawControl = DrawButton, } skin.checkbox = { TileImageFG = ":cl:tech_checkbox_checked.png", TileImageBK = ":cl:tech_checkbox_unchecked.png", tiles = {3,3,3,3}, boxsize = 13, DrawControl = DrawCheckbox, } skin.imagelistview = { imageFolder = "folder.png", imageFolderUp = "folder_up.png", --DrawControl = DrawBackground, colorBK = {1,1,1,0.3}, colorBK_selected = {1,0.7,0.1,0.8}, colorFG = {0, 0, 0, 0}, colorFG_selected = {1,1,1,1}, imageBK = ":cl:node_selected_bw.png", imageFG = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, --tiles = {17,15,17,20}, DrawItemBackground = DrawItemBkGnd, } --[[ skin.imagelistviewitem = { imageFG = ":cl:glassFG.png", imageBK = ":cl:glassBK.png", tiles = {17,15,17,20}, padding = {12, 12, 12, 12}, DrawSelectionItemBkGnd = DrawSelectionItemBkGnd, } --]] skin.panel = { --TileImageFG = ":cl:glassFG.png", --TileImageBK = ":cl:glassBK.png", --tiles = {17,15,17,20}, TileImageBK = ":cl:tech_button.png", TileImageFG = ":cl:empty.png", tiles = {22, 22, 22, 22}, backgroundColor = {1, 1, 1, 0.6}, DrawControl = DrawPanel, } skin.progressbar = { TileImageFG = ":cl:tech_progressbar_full.png", TileImageBK = ":cl:tech_progressbar_empty.png", tiles = {10, 10, 10, 10}, font = { shadow = true, }, DrawControl = DrawProgressbar, } skin.scrollpanel = { BorderTileImage = ":cl:panel2_border.png", bordertiles = {14,14,14,14}, BackgroundTileImage = ":cl:panel2_bg.png", bkgndtiles = {14,14,14,14}, TileImage = ":cl:tech_scrollbar.png", tiles = {7,7,7,7}, KnobTileImage = ":cl:tech_scrollbar_knob.png", KnobTiles = {6,8,6,8}, HTileImage = ":cl:tech_scrollbar.png", htiles = {7,7,7,7}, HKnobTileImage = ":cl:tech_scrollbar_knob.png", HKnobTiles = {6,8,6,8}, KnobColorSelected = {1,0.7,0.1,0.8}, scrollbarSize = 11, DrawControl = DrawScrollPanel, DrawControlPostChildren = DrawScrollPanelBorder, } skin.trackbar = { TileImage = ":cl:trackbar.png", tiles = {10, 14, 10, 14}, --// tile widths: left,top,right,bottom ThumbImage = ":cl:trackbar_thumb.png", StepImage = ":cl:trackbar_step.png", hitpadding = {4, 4, 5, 4}, DrawControl = DrawTrackbar, } skin.treeview = { --ImageNode = ":cl:node.png", ImageNodeSelected = ":cl:node_selected.png", tiles = {9, 9, 9, 9}, ImageExpanded = ":cl:treeview_node_expanded.png", ImageCollapsed = ":cl:treeview_node_collapsed.png", treeColor = {1,1,1,0.1}, DrawNode = DrawTreeviewNode, DrawNodeTree = DrawTreeviewNodeTree, } skin.window = { TileImage = ":cl:tech_dragwindow.png", --TileImage = ":cl:tech_window.png", --TileImage = ":cl:window_tooltip.png", --tiles = {25, 25, 25, 25}, --// tile widths: left,top,right,bottom tiles = {62, 62, 62, 62}, --// tile widths: left,top,right,bottom padding = {13, 13, 13, 13}, hitpadding = {4, 4, 4, 4}, captionColor = {1, 1, 1, 0.45}, boxes = { resize = {-21, -21, -10, -10}, drag = {0, 0, "100%", 10}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = function() end, DrawResizeGrip = DrawResizeGrip, } skin.control = skin.general --//============================================================================= --// return skin
gpl-2.0
Scavenge/darkstar
scripts/zones/Mhaura/npcs/Willah_Maratahya.lua
14
3824
----------------------------------- -- Area: Mhaura -- NPC: Willah Maratahya -- Title Change NPC -- @pos 23 -8 63 249 ----------------------------------- require("scripts/globals/titles"); local title2 = { PURVEYOR_IN_TRAINING , ONESTAR_PURVEYOR , TWOSTAR_PURVEYOR , THREESTAR_PURVEYOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { FOURSTAR_PURVEYOR , FIVESTAR_PURVEYOR , HEIR_OF_THE_GREAT_LIGHTNING , ORCISH_SERJEANT , BRONZE_QUADAV , YAGUDO_INITIATE , MOBLIN_KINSMAN , DYNAMISBUBURIMU_INTERLOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER , ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER , LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY , BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER , MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER , XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR , APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x2711,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x2711) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
lups/ParticleClasses/StaticParticles.lua
10
10887
-- $Id: StaticParticles.lua 3345 2008-12-02 00:03:50Z jk $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local StaticParticles = {} StaticParticles.__index = StaticParticles local billShader,sizeUniform,frameUniform local colormapUniform,colorsUniform = {},0 ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function StaticParticles.GetInfo() return { name = "StaticParticles", 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, rtt = false, ctt = false, } end StaticParticles.Default = { particles = {}, dlist = 0, --// visibility check los = true, airLos = true, radar = false, emitVector = {0,1,0}, pos = {0,0,0}, --// start pos partpos = "0,0,0", --// particle relative start pos (can contain lua code!) layer = 0, life = 0, lifeSpread = 0, rot2Speed = 0, --// global effect rotation size = 0, sizeSpread = 0, sizeGrowth = 0, colormap = { {0, 0, 0, 0} }, --//max 12 entries srcBlend = GL.ONE, dstBlend = GL.ONE_MINUS_SRC_ALPHA, alphaTest = 0, --FIXME texture = '', count = 1, repeatEffect = false, --can be a number,too } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- --// 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 spGetUnitLosState = Spring.GetUnitLosState local spGetPositionLosState = Spring.GetPositionLosState local spGetUnitViewPosition = Spring.GetUnitViewPosition 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 glCallList = gl.CallList local glRotate = gl.Rotate local glColor = gl.Color local glBeginEnd = gl.BeginEnd local GL_QUADS = GL.QUADS local glMultiTexCoord= gl.MultiTexCoord local glVertex = gl.Vertex ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function StaticParticles:CreateParticleAttributes(partpos,n) local life, pos, size; size = rand()*self.sizeSpread life = self.life + rand()*self.lifeSpread local part = {size=self.size+size,life=life,i=n} pos = { ProcessParamCode(partpos, part) } return life, size, pos[1],pos[2],pos[3]; end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local lasttexture = nil function StaticParticles:BeginDraw() gl.UseShader(billShader) lasttexture = nil end function StaticParticles:EndDraw() glTexture(false) glBlending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) gl.UseShader(0) end function StaticParticles:Draw() if (lasttexture ~= self.texture) then glTexture(self.texture) lasttexture = self.texture end glBlending(self.srcBlend,self.dstBlend) glUniform(sizeUniform,self.usize) glUniform(frameUniform,self.frame) glPushMatrix() glTranslate(self.pos[1],self.pos[2],self.pos[3]) glRotate(90,self.emitVector[1],self.emitVector[2],self.emitVector[3]) glRotate(self.rot2Speed*self.frame,0,1,0) glCallList(self.dlist) glPopMatrix() end local function DrawParticleForDList(size,life,x,y,z,colors) glMultiTexCoord(0,x,y,z,1.0) glMultiTexCoord(1,size,colors/life) glVertex(-0.5,-0.5,0,0) glVertex( 0.5,-0.5,1,0) glVertex( 0.5, 0.5,1,1) glVertex(-0.5, 0.5,0,1) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function StaticParticles:Initialize() billShader = gl.CreateShader({ vertex = [[ uniform float size; uniform float frame; uniform vec4 colormap[12]; uniform int colors; varying vec2 texCoord; void main() { #define pos gl_MultiTexCoord0 #define csize gl_MultiTexCoord1.x #define clrslife gl_MultiTexCoord1.y #define texcoord gl_Vertex.pq #define billboardpos gl_Vertex.xy #define pos gl_MultiTexCoord0 #define csize gl_MultiTexCoord1.x #define clrslife gl_MultiTexCoord1.y #define texcoord gl_Vertex.pq #define billboardpos gl_Vertex.xy float cpos = frame*clrslife; int ipos1 = int(cpos); float psize = csize + size; if (ipos1>colors || psize<=0.0) { // paste dead particles offscreen, this way we don't dump the fragment shader with it const vec4 offscreen = vec4(-2000.0,-2000.0,-2000.0,-2000.0); gl_Position = offscreen; }else{ int ipos2 = ipos1+1; if (ipos2>colors) ipos2 = colors; gl_FrontColor = mix(colormap[ipos1],colormap[ipos2],fract(cpos)); // calc vertex position gl_Position = gl_ModelViewMatrix * pos; // offset vertex from center of the polygon gl_Position.xy += billboardpos * psize; // end gl_Position = gl_ProjectionMatrix * gl_Position; texCoord = texcoord; } } ]], fragment = [[ uniform sampler2D tex0; varying vec2 texCoord; void main() { gl_FragColor = texture2D(tex0,texCoord) * gl_Color; } ]], uniformInt = { tex0 = 0, }, uniform = { frame = 0, size = 0, }, }) if (billShader==nil) then print(PRIO_MAJOR,"LUPS->StaticParticles: Critical Shader Error: " ..gl.GetShaderLog()) return false end sizeUniform = gl.GetUniformLocation(billShader,"size") frameUniform = gl.GetUniformLocation(billShader,"frame") colorsUniform = gl.GetUniformLocation(billShader,"colors") for i=1,12 do colormapUniform[i] = gl.GetUniformLocation(billShader,"colormap["..(i-1).."]") end end function StaticParticles:Finalize() gl.DeleteShader(billShader) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function StaticParticles:Update(n) self.frame = self.frame + n self.usize = self.usize + n*self.sizeGrowth end -- used if repeatEffect=true; function StaticParticles:ReInitialize() self.usize = self.size self.frame = 0 self.dieGameFrame = self.dieGameFrame + self.life + self.lifeSpread end function StaticParticles:CreateParticle() local maxSpawnRadius = 0 self.ncolors = #self.colormap-1 local partposCode = ParseParamString(self.partpos) self.dlist = gl.CreateList(function() glUniformInt(colorsUniform, self.ncolors) for i=1,min(self.ncolors+1,12) do local color = self.colormap[i] glUniform( colormapUniform[i] , color[1], color[2], color[3], color[4] ) end gl.BeginEnd(GL.QUADS, function() for i=1,self.count do local life,size,x,y,z = self:CreateParticleAttributes(partposCode,i-1) DrawParticleForDList(size,life, x,y,z, -- relative start pos self.ncolors) local spawnDist = sqrt(x*x+y*y+z*z) if (spawnDist>maxSpawnRadius) then maxSpawnRadius=spawnDist end end end) end) self.usize = self.size self.frame = 0 self.firstGameFrame = Spring.GetGameFrame() self.dieGameFrame = self.firstGameFrame + self.life + self.lifeSpread --// visibility check vars self.radius = self.size + self.sizeSpread + maxSpawnRadius + 100 self.sphereGrowth = self.sizeGrowth end function StaticParticles:Destroy() for _,part in ipairs(self.particles) do gl.DeleteList(part.dlist) end --gl.DeleteTexture(self.texture) end function StaticParticles:Visible() local radius = self.radius + 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 losState = GetUnitLosState(self.unit) local ux,uy,uz = spGetUnitViewPosition(self.unit) if not ux then return false end posX,posY,posZ = posX+ux,posY+uy,posZ+uz radius = radius + (spGetUnitRadius(self.unit) or 0) 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) end if ((not losState) and self.airLos) then losState = IsPosInAirLos(posX,posY,posZ) end if ((not losState) and self.los) then losState = IsPosInLos(posX,posY,posZ) end end return (losState)and(spIsSphereInView(posX,posY,posZ,radius)) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function StaticParticles.Create(Options) local newObject = MergeTable(Options, StaticParticles.Default) setmetatable(newObject,StaticParticles) --// make handle lookup newObject:CreateParticle() return newObject end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return StaticParticles
gpl-2.0
Kyklas/luci-proto-hso
modules/base/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
Zero-K-Experiments/Zero-K-Experiments
effects/gauss.lua
17
12979
local retEffects = { ["gauss_tag_l"] = { tealflash = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[0.5 1 1 0.03 0 0 0 0.01]], size = 80, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, trail = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, dir = [[dir]], explosiongenerator = [[custom:GAUSS_RING_L]], pos = [[0, 0, 0]], }, }, water_trail = { air = false, class = [[CExpGenSpawner]], count = 1, ground = false, water = true, unit = false, underwater = true, properties = { dir = [[dir]], explosiongenerator = [[custom:GAUSS_BUBBLE_1]], pos = [[0, 0, 0]], }, }, }, ["gauss_bubble_1"] = { tealring = { air = false, class = [[CBitmapMuzzleFlame]], count = 1, ground = false, water = true, unit = false, underwater = true, properties = { colormap = [[0 1 0.5 0.03 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[null]], length = 0.15, sidetexture = [[smoketrailthinner]], size = 1, sizegrowth = 15, ttl = 15, }, }, waterpop = { air = false, class = [[heatcloud]], count = 3, ground = false, water = true, unit = false, underwater = true, properties = { heat = 18, heatfalloff = 0.4, maxheat = 15, pos = [[-5 r10, -5 r10, -5 r10]], size = 3, sizegrowth = 0.01, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, }, ["gauss_ring_l"] = { tealring = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, water = true, properties = { colormap = [[0 1 0.5 0.03 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[bluering]], length = 0.15, sidetexture = [[smoketrailthinner]], size = 1, sizegrowth = 15, ttl = 15, }, }, }, ["gauss_tag_h"] = { tealflash = { air = true, class = [[CSimpleGroundFlash]], count = 1, ground = true, water = true, properties = { colormap = [[0.5 1 1 0.08 0 0 0 0.01]], size = 160, sizegrowth = 0, texture = [[groundflash]], ttl = 10, }, }, trail = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 3, dir = [[dir]], explosiongenerator = [[custom:GAUSS_RING_H]], pos = [[0, 0, 0]], }, }, water_trail = { air = false, class = [[CExpGenSpawner]], count = 1, ground = false, water = true, unit = false, underwater = true, properties = { dir = [[dir]], explosiongenerator = [[custom:GAUSS_BUBBLE_1]], pos = [[0, 0, 0]], }, }, }, ["gauss_bubble_h"] = { tealring = { air = false, class = [[CBitmapMuzzleFlame]], count = 1, ground = false, water = true, unit = false, underwater = true, properties = { colormap = [[0 1 0.5 0.05 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[null]], length = 0.15, sidetexture = [[smoketrailthinner]], size = 1, sizegrowth = 31, ttl = 31, }, }, waterpop = { air = false, class = [[heatcloud]], count = 6, ground = false, water = true, unit = false, underwater = true, properties = { heat = 36, heatfalloff = 0.4, maxheat = 40, pos = [[-5 r20, -5 r20, -5 r20]], size = 6, sizegrowth = 0.02, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, }, ["gauss_ring_h"] = { tealring = { air = true, class = [[CBitmapMuzzleFlame]], count = 1, ground = true, water = true, properties = { colormap = [[0 1 0.5 0.05 0 0 0 0.01]], dir = [[dir]], frontoffset = 0, fronttexture = [[bluering]], length = 0.15, sidetexture = [[smoketrailthinner]], size = 1, sizegrowth = 31, ttl = 31, }, }, }, ["gauss_hit_l"] = { sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.5, color = [[0.5,1,1]], expansionspeed = 4, ttl = 8, }, }, groundflash = { air = false, underwater = true, circlealpha = 0.6, circlegrowth = 2, flashalpha = 0.9, flashsize = 20, ground = false, ttl = 10, water = false, color = { [1] = 0, [2] = 0.60000001192093, [3] = 1, }, }, expand = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 4, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = 6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, contract = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 2, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = -6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, }, ["gauss_hit_m"] = { inner = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, dir = [[dir]], explosiongenerator = [[custom:GAUSS_HIT_L]], pos = [[0, 0, 0]], }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.5, color = [[0.5,1,1]], expansionspeed = 6, ttl = 8, }, }, groundflash = { air = false, underwater = true, circlealpha = 0.6, circlegrowth = 2, flashalpha = 0.9, flashsize = 20, ground = false, ttl = 10, water = false, color = { [1] = 0, [2] = 0.60000001192093, [3] = 1, }, }, expand = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 4, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = 6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, contract = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 2, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = -6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, }, ["gauss_hit_h"] = { inner = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, dir = [[dir]], explosiongenerator = [[custom:GAUSS_HIT_M]], pos = [[0, 0, 0]], }, }, sphere = { air = true, class = [[CSpherePartSpawner]], count = 1, ground = true, water = true, properties = { alpha = 0.5, color = [[0.5,1,1]], expansionspeed = 8, ttl = 8, }, }, groundflash = { air = false, underwater = true, circlealpha = 0.6, circlegrowth = 2, flashalpha = 0.9, flashsize = 20, ground = false, ttl = 10, water = false, color = { [1] = 0, [2] = 0.60000001192093, [3] = 1, }, }, expand = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 4, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = 6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, contract = { air = false, class = [[heatcloud]], count = 1, ground = false, water = false, unit = true, underwater = true, properties = { heat = 30, heatfalloff = 2, maxheat = 30, pos = [[0,0,0]], size = 20, sizegrowth = -6, speed = [[0, 0, 0]], texture = [[sonic_glow]], }, }, }, } return retEffects
gpl-2.0
IronDominion/IronDominion
mods/id/bits/manager.lua
1
2511
eras = { {["duration"] = 3000, ["prerequisite"] = "start_phase", ["text"] = "The game has started."}, {["duration"] = 4500, ["prerequisite"] = "early_phase1", ["text"] = "You've advanced to Early Phase I."}, {["duration"] = 4500, ["prerequisite"] = "early_phase2", ["text"] = "You've advanced to Early Phase II."}, {["duration"] = 4500, ["prerequisite"] = "early_phase3", ["text"] = "You've advanced to Early Phase III."}, {["duration"] = 4500, ["prerequisite"] = "mid_phase1", ["text"] = "You've advanced to Mid Phase I."}, {["duration"] = 4500, ["prerequisite"] = "mid_phase2", ["text"] = "You've advanced to Mid Phase II."}, {["duration"] = 4500, ["prerequisite"] = "mid_phase3", ["text"] = "You've advanced to Mid Phase III."}, {["duration"] = 4500, ["prerequisite"] = "late_phase1", ["text"] = "You've advanced to Late Phase I."}, {["duration"] = 4500, ["prerequisite"] = "late_phase2", ["text"] = "You've advanced to Late Phase II."}, {["duration"] = 4500, ["prerequisite"] = "late_phase3", ["text"] = "You've advanced to Late Phase III."}, {["duration"] = 4500, ["prerequisite"] = "post_phase", ["text"] = "You've advanced to Post Phase."} }; currentEra = 1; remainingTime = eras[1].duration; players = nil; if pcall(function() UserInterface.SetMissionText("") end) then -- Not shellmap WorldLoaded = function() players = Player.GetPlayers(nil); end Tick = function() if currentEra >= #eras then UserInterface.SetMissionText(""); return; end if remainingTime < 0 then currentEra = currentEra + 1; remainingTime = eras[currentEra].duration; SpawnUnitForEachPlayer(eras[currentEra].prerequisite); Media.DisplayMessage(eras[currentEra].text); end remainingTime = remainingTime - 1; UserInterface.SetMissionText("Next era in " .. SecondsToClock(remainingTime / DateTime.Seconds(1)) .. "."); end SpawnUnitForEachPlayer = function(ActorName) for index, value in ipairs(players) do Actor.Create(ActorName, true, {Owner = value, Location = CPos.New(0,0)}); end end function SecondsToClock(seconds) local seconds = tonumber(seconds); if seconds <= 0 then return "00:00"; else hours = string.format("%02.f", math.floor(seconds / 3600)); mins = string.format("%02.f", math.floor(seconds / 60 - (hours * 60))); secs = string.format("%02.f", math.floor(seconds - hours * 3600 - mins * 60)); return mins .. ":" .. secs; end end end
gpl-3.0
PredatorMF/Urho3D
Source/ThirdParty/LuaJIT/src/jit/p.lua
40
9092
---------------------------------------------------------------------------- -- LuaJIT profiler. -- -- Copyright (C) 2005-2016 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module is a simple command line interface to the built-in -- low-overhead profiler of LuaJIT. -- -- The lower-level API of the profiler is accessible via the "jit.profile" -- module or the luaJIT_profile_* C API. -- -- Example usage: -- -- luajit -jp myapp.lua -- luajit -jp=s myapp.lua -- luajit -jp=-s myapp.lua -- luajit -jp=vl myapp.lua -- luajit -jp=G,profile.txt myapp.lua -- -- The following dump features are available: -- -- f Stack dump: function name, otherwise module:line. Default mode. -- F Stack dump: ditto, but always prepend module. -- l Stack dump: module:line. -- <number> stack dump depth (callee < caller). Default: 1. -- -<number> Inverse stack dump depth (caller > callee). -- s Split stack dump after first stack level. Implies abs(depth) >= 2. -- p Show full path for module names. -- v Show VM states. Can be combined with stack dumps, e.g. vf or fv. -- z Show zones. Can be combined with stack dumps, e.g. zf or fz. -- r Show raw sample counts. Default: show percentages. -- a Annotate excerpts from source code files. -- A Annotate complete source code files. -- G Produce raw output suitable for graphical tools (e.g. flame graphs). -- m<number> Minimum sample percentage to be shown. Default: 3. -- i<number> Sampling interval in milliseconds. Default: 10. -- ---------------------------------------------------------------------------- -- Cache some library functions and objects. local jit = require("jit") assert(jit.version_num == 20100, "LuaJIT core/library version mismatch") local profile = require("jit.profile") local vmdef = require("jit.vmdef") local math = math local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor local sort, format = table.sort, string.format local stdout = io.stdout local zone -- Load jit.zone module on demand. -- Output file handle. local out ------------------------------------------------------------------------------ local prof_ud local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth local prof_ann, prof_count1, prof_count2, prof_samples local map_vmmode = { N = "Compiled", I = "Interpreted", C = "C code", G = "Garbage Collector", J = "JIT Compiler", } -- Profiler callback. local function prof_cb(th, samples, vmmode) prof_samples = prof_samples + samples local key_stack, key_stack2, key_state -- Collect keys for sample. if prof_states then if prof_states == "v" then key_state = map_vmmode[vmmode] or vmmode else key_state = zone:get() or "(none)" end end if prof_fmt then key_stack = profile.dumpstack(th, prof_fmt, prof_depth) key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x) return vmdef.ffnames[tonumber(x)] end) if prof_split == 2 then local k1, k2 = key_stack:match("(.-) [<>] (.*)") if k2 then key_stack, key_stack2 = k1, k2 end elseif prof_split == 3 then key_stack2 = profile.dumpstack(th, "l", 1) end end -- Order keys. local k1, k2 if prof_split == 1 then if key_state then k1 = key_state if key_stack then k2 = key_stack end end elseif key_stack then k1 = key_stack if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end end -- Coalesce samples in one or two levels. if k1 then local t1 = prof_count1 t1[k1] = (t1[k1] or 0) + samples if k2 then local t2 = prof_count2 local t3 = t2[k1] if not t3 then t3 = {}; t2[k1] = t3 end t3[k2] = (t3[k2] or 0) + samples end end end ------------------------------------------------------------------------------ -- Show top N list. local function prof_top(count1, count2, samples, indent) local t, n = {}, 0 for k, v in pairs(count1) do n = n + 1 t[n] = k end sort(t, function(a, b) return count1[a] > count1[b] end) for i=1,n do local k = t[i] local v = count1[k] local pct = floor(v*100/samples + 0.5) if pct < prof_min then break end if not prof_raw then out:write(format("%s%2d%% %s\n", indent, pct, k)) elseif prof_raw == "r" then out:write(format("%s%5d %s\n", indent, v, k)) else out:write(format("%s %d\n", k, v)) end if count2 then local r = count2[k] if r then prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or (prof_depth < 0 and " -> " or " <- ")) end end end end -- Annotate source code local function prof_annotate(count1, samples) local files = {} local ms = 0 for k, v in pairs(count1) do local pct = floor(v*100/samples + 0.5) ms = math.max(ms, v) if pct >= prof_min then local file, line = k:match("^(.*):(%d+)$") local fl = files[file] if not fl then fl = {}; files[file] = fl; files[#files+1] = file end line = tonumber(line) fl[line] = prof_raw and v or pct end end sort(files) local fmtv, fmtn = " %3d%% | %s\n", " | %s\n" if prof_raw then local n = math.max(5, math.ceil(math.log10(ms))) fmtv = "%"..n.."d | %s\n" fmtn = (" "):rep(n).." | %s\n" end local ann = prof_ann for _, file in ipairs(files) do local f0 = file:byte() if f0 == 40 or f0 == 91 then out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file)) break end local fp, err = io.open(file) if not fp then out:write(format("====== ERROR: %s: %s\n", file, err)) break end out:write(format("\n====== %s ======\n", file)) local fl = files[file] local n, show = 1, false if ann ~= 0 then for i=1,ann do if fl[i] then show = true; out:write("@@ 1 @@\n"); break end end end for line in fp:lines() do if line:byte() == 27 then out:write("[Cannot annotate bytecode file]\n") break end local v = fl[n] if ann ~= 0 then local v2 = fl[n+ann] if show then if v2 then show = n+ann elseif v then show = n elseif show+ann < n then show = false end elseif v2 then show = n+ann out:write(format("@@ %d @@\n", n)) end if not show then goto next end end if v then out:write(format(fmtv, v, line)) else out:write(format(fmtn, line)) end ::next:: n = n + 1 end fp:close() end end ------------------------------------------------------------------------------ -- Finish profiling and dump result. local function prof_finish() if prof_ud then profile.stop() local samples = prof_samples if samples == 0 then if prof_raw ~= true then out:write("[No samples collected]\n") end return end if prof_ann then prof_annotate(prof_count1, samples) else prof_top(prof_count1, prof_count2, samples, "") end prof_count1 = nil prof_count2 = nil prof_ud = nil end end -- Start profiling. local function prof_start(mode) local interval = "" mode = mode:gsub("i%d*", function(s) interval = s; return "" end) prof_min = 3 mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end) prof_depth = 1 mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end) local m = {} for c in mode:gmatch(".") do m[c] = c end prof_states = m.z or m.v if prof_states == "z" then zone = require("jit.zone") end local scope = m.l or m.f or m.F or (prof_states and "" or "f") local flags = (m.p or "") prof_raw = m.r if m.s then prof_split = 2 if prof_depth == -1 or m["-"] then prof_depth = -2 elseif prof_depth == 1 then prof_depth = 2 end elseif mode:find("[fF].*l") then scope = "l" prof_split = 3 else prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0 end prof_ann = m.A and 0 or (m.a and 3) if prof_ann then scope = "l" prof_fmt = "pl" prof_split = 0 prof_depth = 1 elseif m.G and scope ~= "" then prof_fmt = flags..scope.."Z;" prof_depth = -100 prof_raw = true prof_min = 0 elseif scope == "" then prof_fmt = false else local sc = prof_split == 3 and m.f or m.F or scope prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ") end prof_count1 = {} prof_count2 = {} prof_samples = 0 profile.start(scope:lower()..interval, prof_cb) prof_ud = newproxy(true) getmetatable(prof_ud).__gc = prof_finish end ------------------------------------------------------------------------------ local function start(mode, outfile) if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end if outfile then out = outfile == "-" and stdout or assert(io.open(outfile, "w")) else out = stdout end prof_start(mode or "f") end -- Public module functions. return { start = start, -- For -j command line option. stop = prof_finish }
mit
Scavenge/darkstar
scripts/globals/mobskills/Abrasive_Tantara.lua
27
1028
--------------------------------------------- -- Abrasive Tantara -- -- Description: Inflicts amnesia in an area of effect -- Type: Enfeebling -- Utsusemi/Blink absorb: Ignores shadows -- Range: 10' as well as single target outside of 10' -- Notes: Doesn't use this if its horn is broken. It is possible for Abrasive Tantara to miss. - See discussion --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() == 1 and mob:getFamily() == 165) then -- Imps without horn return 1; else return 0; end end; function onMobWeaponSkill(target, mob, skill) local message = MSG_MISS; local typeEffect = EFFECT_AMNESIA; local power = 1; local duration = 60; skill:setMsg(MobStatusEffectMove(mob, target, typeEffect, power, 0, duration)); return typeEffect; end;
gpl-3.0
cohadar/tanks-of-harmony-and-love
client.lua
1
3766
--- @module client local client = {} require "enet" local conf = require "conf" local tank = require "tank" local bullets = require "bullets" local utils = require "utils" local world = require "world" local history = require "history" local text = require "text" local effects = require "effects" local _host = nil local _server = nil local _connected = false local _indexOnServer = 0 local _clientTick = 0 ------------------------------------------------------------------------------- function client.getTick() return _clientTick end ------------------------------------------------------------------------------- function client.incTick() _clientTick = _clientTick + 1 return _clientTick end ------------------------------------------------------------------------------- function client.isConnected() return _connected end ------------------------------------------------------------------------------- function client.init() -- nothing end ------------------------------------------------------------------------------- function client.connect( address, port ) client.quit() _host = enet.host_create() _server = _host:connect( address .. ":" .. port ) end ------------------------------------------------------------------------------- local function tank_sync( msg ) if conf.NETCODE_DEBUG then world.updateTank( msg.index, msg.tank ) end local do_sync = false local old_tank = history.getAndClear( msg.client_tick ) if old_tank == nil then text.print( "nil_sync", _clientTick, msg.client_tick ) do_sync = true elseif tank.neq( old_tank, msg.tank ) then text.print( "forced_sync", _clientTick, msg.client_tick ) do_sync = true end if do_sync then history.reset() world.updateTank( 0, msg.tank ) history.set( msg.client_tick, msg.tank ) _clientTick = msg.client_tick end end ------------------------------------------------------------------------------- function client.update( tank_command ) if _connected then local datagram = utils.pack{ type = "tank_command", tank_command = tank_command } _server:send( datagram, 0, "unsequenced" ) end if not _server then return end repeat event = _host:service(0) if event then if event.type == "connect" then text.status( "Connected to", event.peer ) elseif event.type == "receive" then local msg = utils.unpack( event.data ) if msg.type == "broadcast" then if _indexOnServer == msg.index then tank_sync( msg ) else world.updateTank( msg.index, msg.tank ) end bullets.importTable( msg.bullets_table ) if msg.tank.hit_x and msg.tank.hit_y then effects.addExplosion( msg.tank.hit_x, msg.tank.hit_y, 0.2 ) end elseif msg.type == "index" then _indexOnServer = msg.index _connected = true world.connect( _indexOnServer ) love.window.setTitle( "Connected as Player #" .. _indexOnServer ) text.print( "index on server: ", _indexOnServer ) elseif msg.type == "player_gone" then world.playerGone( msg.index ) -- TODO: display disconnected tanks in gray for a short time else text.print("ERROR: unknown msg.type: ", msg.type, event.data ) end elseif event.type == "disconnect" then text.status( "disconnect" ) love.window.setTitle( "Not Connected" ) client.quit() -- TODO: handle disconnect gracefully else text.print( "ERROR: unknown event.type: ", event.type, event.data ) end end until not event end ------------------------------------------------------------------------------- function client.quit() if _server ~= nil then _server:disconnect() _host:flush() end _server = nil _connected = false end ------------------------------------------------------------------------------- return client
mit
Scavenge/darkstar
scripts/zones/North_Gustaberg/MobIDs.lua
23
1385
----------------------------------- -- Area: North Gustaberg -- Comments: -- posX, posY, posZ --(Taken from 'mob_spawn_points' table) ----------------------------------- -- Stinging Sophie Stinging_Sophie=17211561; Stinging_Sophie_PH={ [17211532] = '1', -- 352.974, -40.359, 472.914 [17211534] = '1', -- 353.313, -40.347, 463.609 [17211535] = '1', -- 237.753, -40.500, 469.738 [17211533] = '1', -- 216.150, -41.182, 445.157 [17211536] = '1', -- 197.369, -40.612, 453.688 [17211531] = '1', -- 196.873, -40.415, 500.153 [17211556] = '1', -- 210.607, -40.478, 566.096 [17211557] = '1', -- 288.447, -40.842, 634.161 [17211558] = '1', -- 295.890, -41.593, 614.738 [17211560] = '1', -- 356.544, -40.528, 570.302 [17211559] = '1', -- 363.973, -40.774, 562.355 [17211581] = '1', -- 308.116, -60.352, 550.771 [17211582] = '1', -- 308.975, -61.082, 525.690 [17211580] = '1', -- 310.309, -60.634, 521.404 [17211583] = '1', -- 285.813, -60.784, 518.539 [17211579] = '1', -- 283.958, -60.926, 530.016 }; -- Maighdean Uaine Maighdean_Uaine=17211702; Maighdean_Uaine_PH={ [17211698] = '1', -- 121.242, -0.500, 654.504 [17211701] = '1', -- 176.458, -0.347, 722.666 [17211697] = '1', -- 164.140, 1.981, 740.020 [17211710] = '1', -- 239.992, -0.493, 788.037 [17211700] = '1', -- 203.606, -0.607, 721.541 [17211711] = '1', -- 289.709, -0.297, 750.252 };
gpl-3.0
LuaDist2/vida
output/vida.lua
3
15745
if __COMBINER == nil then __COMBINER = { MODULE = {}, __nativeRequire = require, require = function(id) assert(type(id) == 'string', 'invalid require id:' .. tostring(id)) if package.loaded[id] then return package.loaded[id] end if __COMBINER.MODULE[id] then local f = __COMBINER.MODULE[id] package.loaded[id] = f(__COMBINER.require) or true return package.loaded[id] end return __COMBINER.__nativeRequire(id) end, define = function(id, f) assert(type(id) == 'string', 'invalid define id:' .. tostring(id)) if package.loaded[id] == nil and __COMBINER.MODULE[id] == nil then __COMBINER.MODULE[id] = f else print('__COMBINER module ' .. tostring(id) .. ' already defined') end end, } end __COMBINER.define('md5', (function(require) -- simple md5 library -- Copied from bitop library (http://bitop.luajit.org/) -- Original copyright info: -- MD5 test and benchmark. Public domain. local bit = require("bit") local tobit, tohex, bnot = bit.tobit or bit.cast, bit.tohex, bit.bnot local bor, band, bxor = bit.bor, bit.band, bit.bxor local lshift, rshift, rol, bswap = bit.lshift, bit.rshift, bit.rol, bit.bswap local byte, char, sub, rep = string.byte, string.char, string.sub, string.rep local function tr_f(a, b, c, d, x, s) return rol(bxor(d, band(b, bxor(c, d))) + a + x, s) + b end local function tr_g(a, b, c, d, x, s) return rol(bxor(c, band(d, bxor(b, c))) + a + x, s) + b end local function tr_h(a, b, c, d, x, s) return rol(bxor(b, c, d) + a + x, s) + b end local function tr_i(a, b, c, d, x, s) return rol(bxor(c, bor(b, bnot(d))) + a + x, s) + b end local function transform(x, a1, b1, c1, d1) local a, b, c, d = a1, b1, c1, d1 a = tr_f(a, b, c, d, x[ 1] + 0xd76aa478, 7) d = tr_f(d, a, b, c, x[ 2] + 0xe8c7b756, 12) c = tr_f(c, d, a, b, x[ 3] + 0x242070db, 17) b = tr_f(b, c, d, a, x[ 4] + 0xc1bdceee, 22) a = tr_f(a, b, c, d, x[ 5] + 0xf57c0faf, 7) d = tr_f(d, a, b, c, x[ 6] + 0x4787c62a, 12) c = tr_f(c, d, a, b, x[ 7] + 0xa8304613, 17) b = tr_f(b, c, d, a, x[ 8] + 0xfd469501, 22) a = tr_f(a, b, c, d, x[ 9] + 0x698098d8, 7) d = tr_f(d, a, b, c, x[10] + 0x8b44f7af, 12) c = tr_f(c, d, a, b, x[11] + 0xffff5bb1, 17) b = tr_f(b, c, d, a, x[12] + 0x895cd7be, 22) a = tr_f(a, b, c, d, x[13] + 0x6b901122, 7) d = tr_f(d, a, b, c, x[14] + 0xfd987193, 12) c = tr_f(c, d, a, b, x[15] + 0xa679438e, 17) b = tr_f(b, c, d, a, x[16] + 0x49b40821, 22) a = tr_g(a, b, c, d, x[ 2] + 0xf61e2562, 5) d = tr_g(d, a, b, c, x[ 7] + 0xc040b340, 9) c = tr_g(c, d, a, b, x[12] + 0x265e5a51, 14) b = tr_g(b, c, d, a, x[ 1] + 0xe9b6c7aa, 20) a = tr_g(a, b, c, d, x[ 6] + 0xd62f105d, 5) d = tr_g(d, a, b, c, x[11] + 0x02441453, 9) c = tr_g(c, d, a, b, x[16] + 0xd8a1e681, 14) b = tr_g(b, c, d, a, x[ 5] + 0xe7d3fbc8, 20) a = tr_g(a, b, c, d, x[10] + 0x21e1cde6, 5) d = tr_g(d, a, b, c, x[15] + 0xc33707d6, 9) c = tr_g(c, d, a, b, x[ 4] + 0xf4d50d87, 14) b = tr_g(b, c, d, a, x[ 9] + 0x455a14ed, 20) a = tr_g(a, b, c, d, x[14] + 0xa9e3e905, 5) d = tr_g(d, a, b, c, x[ 3] + 0xfcefa3f8, 9) c = tr_g(c, d, a, b, x[ 8] + 0x676f02d9, 14) b = tr_g(b, c, d, a, x[13] + 0x8d2a4c8a, 20) a = tr_h(a, b, c, d, x[ 6] + 0xfffa3942, 4) d = tr_h(d, a, b, c, x[ 9] + 0x8771f681, 11) c = tr_h(c, d, a, b, x[12] + 0x6d9d6122, 16) b = tr_h(b, c, d, a, x[15] + 0xfde5380c, 23) a = tr_h(a, b, c, d, x[ 2] + 0xa4beea44, 4) d = tr_h(d, a, b, c, x[ 5] + 0x4bdecfa9, 11) c = tr_h(c, d, a, b, x[ 8] + 0xf6bb4b60, 16) b = tr_h(b, c, d, a, x[11] + 0xbebfbc70, 23) a = tr_h(a, b, c, d, x[14] + 0x289b7ec6, 4) d = tr_h(d, a, b, c, x[ 1] + 0xeaa127fa, 11) c = tr_h(c, d, a, b, x[ 4] + 0xd4ef3085, 16) b = tr_h(b, c, d, a, x[ 7] + 0x04881d05, 23) a = tr_h(a, b, c, d, x[10] + 0xd9d4d039, 4) d = tr_h(d, a, b, c, x[13] + 0xe6db99e5, 11) c = tr_h(c, d, a, b, x[16] + 0x1fa27cf8, 16) b = tr_h(b, c, d, a, x[ 3] + 0xc4ac5665, 23) a = tr_i(a, b, c, d, x[ 1] + 0xf4292244, 6) d = tr_i(d, a, b, c, x[ 8] + 0x432aff97, 10) c = tr_i(c, d, a, b, x[15] + 0xab9423a7, 15) b = tr_i(b, c, d, a, x[ 6] + 0xfc93a039, 21) a = tr_i(a, b, c, d, x[13] + 0x655b59c3, 6) d = tr_i(d, a, b, c, x[ 4] + 0x8f0ccc92, 10) c = tr_i(c, d, a, b, x[11] + 0xffeff47d, 15) b = tr_i(b, c, d, a, x[ 2] + 0x85845dd1, 21) a = tr_i(a, b, c, d, x[ 9] + 0x6fa87e4f, 6) d = tr_i(d, a, b, c, x[16] + 0xfe2ce6e0, 10) c = tr_i(c, d, a, b, x[ 7] + 0xa3014314, 15) b = tr_i(b, c, d, a, x[14] + 0x4e0811a1, 21) a = tr_i(a, b, c, d, x[ 5] + 0xf7537e82, 6) d = tr_i(d, a, b, c, x[12] + 0xbd3af235, 10) c = tr_i(c, d, a, b, x[ 3] + 0x2ad7d2bb, 15) b = tr_i(b, c, d, a, x[10] + 0xeb86d391, 21) return tobit(a+a1), tobit(b+b1), tobit(c+c1), tobit(d+d1) end -- Note: this is copying the original string and NOT particularly fast. -- A library for struct unpacking would make this task much easier. local function md5hash(msg) local len = #msg msg = msg.."\128"..rep("\0", 63 - band(len + 8, 63)) ..char(band(lshift(len, 3), 255), band(rshift(len, 5), 255), band(rshift(len, 13), 255), band(rshift(len, 21), 255)) .."\0\0\0\0" local a, b, c, d = 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476 local x, k = {}, 1 for i=1,#msg,4 do local m0, m1, m2, m3 = byte(msg, i, i+3) x[k] = bor(m0, lshift(m1, 8), lshift(m2, 16), lshift(m3, 24)) if k == 16 then a, b, c, d = transform(x, a, b, c, d) k = 1 else k = k + 1 end end return tohex(bswap(a))..tohex(bswap(b))..tohex(bswap(c))..tohex(bswap(d)) end return { hash=md5hash } end)) __COMBINER.define('path', (function(require) -- simple path manipulation module local ffi = require('ffi') local path = {} local sep = '/' if ffi.os == 'Windows' then sep = '\\' end function path.join(...) local arg = {...} return table.concat(arg, sep) end return path end)) __COMBINER.define('temp', (function(require) local ffi = require('ffi') local temp = {} function temp.name() if ffi.os == 'Windows' then return os.getenv('TEMP') .. os.tmpname() end return os.tmpname() end return temp end)) return (function(require) -- Requires LuaJIT if type(jit) ~= 'table' then error('This modules requires LuaJIT') end local os = require('os') local ffi = require('ffi') local md5 = require('md5') local path = require('path') local temp = require('temp') local vida = {} -- Optionally update value local function update(old, new) if new ~= nil then return new else return old end end -- Parse bool, no error on nil local function toboolean(val) if val == nil then return nil end return val == 'true' or val == 'True' or val == 'TRUE' end -- Update value with environmental variable value local function update_env(old, name) return update(old, os.getenv(name)) end vida.version = "v0.1.9" vida.useLocalCopy = update_env(true, 'VIDA_READ_CACHE') vida.saveLocalCopy = update_env(true, 'VIDA_WRITE_CACHE') local home_vidacache = '.vidacache' local home = os.getenv('HOME') local libsuffix local objsuffix if ffi.os == 'Linux' or ffi.os == 'OSX' then vida.compiler = update_env(update_env('clang', 'CC'), 'VIDA_COMPILER') vida.compilerFlags = update_env('-fpic -O3 -fvisibility=hidden', 'VIDA_COMPILER_FLAGS') vida.justCompile = '-c' vida.linkerFlags = update_env('-shared', 'VIDA_LINKER_FLAGS') libsuffix = '.so' objsuffix = '.o' if home then home_vidacache = string.format('%s/.vidacache', home) end elseif ffi.os == 'Windows' then vida.compiler = update_env('cl', 'VIDA_COMPILER') vida.compilerFlags = update_env('/nologo /O2', 'VIDA_COMPILER_FLAGS') vida.justCompile = '/c' vida.linkerFlags = update_env('/nologo /link /DLL', 'VIDA_LINKER_FLAGS') libsuffix = '.dll' objsuffix = '.obj' else error('Unknown platform') end vida.cachePath = update_env(home_vidacache, 'VIDA_CACHE_PATH') vida._code_prelude = update_env('', 'VIDA_CODE_PRELUDE') vida._interface_prelude = update_env('', 'VIDA_INTERFACE_PRELUDE') -- Fixed header for C source to simplify exports vida._code_header = [[ #line 0 "vida_header" #ifdef _WIN32 #define EXPORT __declspec(dllexport) #else #define EXPORT __attribute__ ((visibility ("default"))) #endif ]] vida.cdef = ffi.cdef -- Read in a file function read_file(name) local f = io.open(name, 'r') if f == nil then return nil end local txt = f:read('*a') f:close() return txt end -- Check if file exists function file_exists(name) local f = io.open(name, 'r') if f ~= nil then io.close(f) return true end return false end -- Give C header interface function vida.interface(txt, info) local res = { vida = 'interface', code = txt, filename = 'vida_interface', linenum = 1, } if info == true or info == nil then -- Get filename and linenumber of caller -- This helps us give good error messages when compiling -- Add caller filename and line numbers for debugging local caller = debug.getinfo(2) res.filename = caller.short_src res.linenum = caller.currentline end return res end -- Give C source code function vida.code(txt) local res = { vida='code', code=txt, filename = 'vida_code', linenum = 1, } if info == true or info == nil then -- Get filename and linenumber of caller -- This helps us give good error messages when compiling -- Add caller filename and line numbers for debugging local caller = debug.getinfo(2) res.filename = caller.short_src res.linenum = caller.currentline end return res end -- Give interface file function vida.interfacefile(filename) local interface = read_file(filename) if not interface then error('Could not open file ' .. filename .. ' for reading', 2) end return { vida='interface', code=interface, filename = filename, linenum = 1, } end -- Give source code file function vida.codefile(filename) local src = read_file(filename) if not src then error('Could not open file ' .. filename .. ' for reading', 2) end return { vida='code', code=src, filename = filename, linenum = 1, } end -- Add code or interface to common prelude function vida.prelude(...) local args = {...} -- Put together source string local srcs = { vida._code_prelude } local ints = { vida._interface_prelude } for k, v in ipairs(args) do if not type(v) == 'table' then error('Argument ' .. k .. ' to prelude not Vida code or interface', 2) end if v.vida == 'code' then srcs[#srcs + 1] = string.format('#line %d "%s"', v.linenum, v.filename) srcs[#srcs + 1] = v.code elseif v.vida == 'interface' then ints[#ints + 1] = v.code else error('Argument ' .. k .. ' to prelude not Vida code or interface', 2) end end vida._code_prelude = table.concat(srcs, '\n') vida._interface_prelude = table.concat(ints, '\n') end -- Given chunks of C code and interfaces, return working FFI namespace function vida.compile(...) local args = {...} -- Put together source string local srcs = { vida._code_header, vida._code_prelude } local ints = { vida._interface_prelude } for k, v in ipairs(args) do if type(v) == 'string' then -- Assume code local caller = debug.getinfo(2) srcs[#srcs + 1] = string.format('#line %d "%s"', caller.currentline, caller.short_src) srcs[#srcs + 1] = v elseif type(v) ~= 'table' then error('Argument ' .. k .. ' to compile not Vida code or interface', 2) elseif v.vida == 'code' then srcs[#srcs + 1] = string.format('#line %d "%s"', v.linenum, v.filename) srcs[#srcs + 1] = v.code elseif v.vida == 'interface' then ints[#ints + 1] = v.code else error('Argument ' .. k .. ' to compile not Vida code or interface', 2) end end local src = table.concat(srcs, '\n') local interface = table.concat(ints, '\n') -- Interpret interface using FFI -- (Do this first in case there is an error here) if interface ~= '' then ffi.cdef(interface) end local name = md5.hash(src) -- Check for local copy of shared library local locallib = path.join(vida.cachePath, ffi.os .. '-' .. name .. libsuffix) if vida.useLocalCopy then if file_exists(locallib) then return ffi.load(locallib) end end -- If we don't have a compiler, bail out now if not vida.compiler then error('Error loading shared library, compiler disabled', 2) end -- Create names local fname = temp.name() .. name local cname = fname .. '.c' local oname = fname .. objsuffix local libname = fname .. libsuffix local localcname = path.join(vida.cachePath, name .. '.c') -- Write C source contents to .c file local file = io.open(cname, 'w') if not file then error(string.format('Error writing source file %s', cname), 2) end file:write(src) file:close() -- Compile local r if ffi.os == 'Windows' then r = os.execute(string.format('%s %s %s %s /Fo%s >nul', vida.compiler, vida.compilerFlags, vida.justComile, cname, oname)) if r ~= 0 then error('Error during compile', 2) end r = os.execute(string.format('%s %s %s /OUT:%s >nul', vida.compiler, oname, vida.linkerFlags, libname)) if r ~= 0 then error('Error during link', 2) end -- Save a local copy of library and source if vida.saveLocalCopy then os.execute(string.format('mkdir %s >nul 2>nul', vida.cachePath)) -- Ignore errors, likely already exists r = os.execute(string.format('copy %s %s >nul', libname, locallib)) if r ~= 0 then error('Error saving local copy', 2) end r = os.execute(string.format('copy %s %s >nul', cname, localcname)) if r ~= 0 then error('Error saving local copy2', 2) end end else r = os.execute(string.format('%s %s %s %s -o %s', vida.compiler, vida.compilerFlags, vida.justCompile, cname, oname)) if r ~= 0 then error('Error during compile', 2) end -- Link into shared library r = os.execute(string.format('%s %s %s -o %s', vida.compiler, vida.linkerFlags, oname, libname)) if r ~= 0 then error('Error during link', 2) end -- Save a local copy of library and source if vida.saveLocalCopy then r = os.execute(string.format('mkdir -p %s', vida.cachePath)) if r ~= 0 then error('Error creating cache path', 2) end r = os.execute(string.format('cp %s %s', libname, locallib)) if r ~= 0 then error('Error saving local copy', 2) end r = os.execute(string.format('cp %s %s', cname, localcname)) if r ~= 0 then error('Error saving local copy', 2) end end end -- Load the shared library return ffi.load(libname) end return vida end)(__COMBINER.require)
mit
xebecnan/UniLua
Assets/StreamingAssets/LuaRoot/lib/ffi.lua
5
13616
local cs = require "ffi.cs" local CONSTRUCTOR = "_New" local TYPE_ACCESS = "_Type" local CONVERT_FROM = "_ConvertFrom" ---------------------------------------------------------------------- local type_alias = { bool = "Boolean", char = "Char", byte = "Byte", sbyte = "SByte", short = "Int16", ushort = "UInt16", int = "Int32", uint = "UInt32", long = "Int64", ulong = "UInt64", float = "Single", double = "Double", decimal = "Decimal", string = "String", object = "Object", } local function get_type(typename) return cs.get_type(type_alias[typename] or typename) end local function typename_to_type(typename) local t = get_type(typename) if not t then error(">>>>>>>>>>>>>>>> typename_to_type unknown typename:" .. tostring(typename)) end return t end local function parse_signature(signature) -- print("parse_signature:", signature) local ret, fname, partypes = cs.parse_signature(signature) -- print("ret:", ret) -- print("fname:", fname) -- print("partypes:", partypes) local params if partypes then params = {} for i, pname in ipairs(partypes) do params[i] = typename_to_type(pname) end end return { ret_typename = ret, fname = fname, partypes = params, } -- local s = 1 -- local types = {} -- while true do -- local e = string.find(signature, ",", s) -- if e then -- local typename = string.sub(signature, s, e-1) -- local t = typename_to_type(typename) -- table.insert(types, t) -- s = e + 1 -- else -- local typename = string.sub(signature, s) -- if #typename > 0 then -- local t = typename_to_type(typename) -- table.insert(types, t) -- end -- break -- end -- end -- return types end ---------------------------------------------------------------------- local function constructor(self, signature) table.insert(self.__constructor, signature) return self end local function method(self, signature) table.insert(self.__methods, signature) return self end local function static_method(self, signature) table.insert(self.__static_methods, signature) return self end local function field(self, signature) table.insert(self.__fields, signature) return self end local function property(self, signature) table.insert(self.__properties, signature) return self end local function static_property(self, signature) table.insert(self.__static_properties, signature) return self end ---------------------------------------------------------------------- local function new_class_mgr() local all_classes = {} local function declare_class(clsname) all_classes[clsname] = { -- cls = {}, cls_methods = {}, cls_fields = {}, inst_methods = {}, inst_fields = {}, } end local function is_class_declared(clsname) return all_classes[clsname] ~= nil end local function define_class(clsname) local clsinfo = all_classes[clsname] -- local cls = clsinfo.cls local cls_methods = clsinfo.cls_methods local cls_fields = clsinfo.cls_fields local inst_methods = clsinfo.inst_methods local inst_fields = clsinfo.inst_fields local function add_inst_method(name, mtd) inst_methods[name] = mtd end local function add_inst_field(field_name, index, newindex) inst_fields[field_name] = {index, newindex} end local function add_class_method(name, mtd) -- cls[name] = mtd cls_methods[name] = mtd end local function add_class_field(field_name, index, newindex) cls_fields[field_name] = {index, newindex} end local mt = { __index = { add_inst_method = add_inst_method, add_inst_field = add_inst_field, add_class_method = add_class_method, add_class_field = add_class_field, }, } return setmetatable({}, mt) end local function make_class(clsname) local clsinfo = all_classes[clsname] -- local cls = clsinfo.cls local cls_methods = clsinfo.cls_methods local cls_fields = clsinfo.cls_fields local cls_mt = { __index = function(self, key) if cls_fields[key] then return cls_fields[key][1](self, key) elseif cls_methods[key] then return cls_methods[key] end end, -- __index = cls, __newindex = function(self, key, value) if cls_fields[key] then return cls_fields[key][2](self, key, value) end end, } return setmetatable({}, cls_mt) end local function make_instance(clsname, this) local clsinfo = all_classes[clsname] local inst_methods = clsinfo.inst_methods local inst_fields = clsinfo.inst_fields local inst_mt = { __index = function(self, key) if inst_fields[key] then return inst_fields[key][1](self, key) elseif inst_methods[key] then return inst_methods[key] end end, __newindex = function(self, key, value) if inst_fields[key] then return inst_fields[key][2](self, key, value) end end, } return setmetatable({ __this = this, }, inst_mt) end local mt = { __index = { declare_class = declare_class, is_class_declared = is_class_declared, define_class = define_class, make_class = make_class, make_instance = make_instance, }, } return setmetatable({}, mt) end ---------------------------------------------------------------------- local function build_class(cls_mgr, self) local clsname = self.__class_name local def = cls_mgr.define_class(clsname) local function wrap_retval(retval, clsname) if cls_mgr.is_class_declared(clsname) then return cls_mgr.make_instance(clsname, retval) else return retval end end local function unwrap_param(val, clsname) if cls_mgr.is_class_declared(clsname) then return rawget(val, "__this") else return val end end local type_info = assert(get_type(clsname), clsname) def.add_class_method(TYPE_ACCESS, function() return type_info end) def.add_class_method(CONVERT_FROM, function(self) local this = rawget(self, "__this") return cls_mgr.make_instance(clsname, this) end) ---------------- -- CONSTRUCTOR ---------------- for _, signature in ipairs(self.__constructor) do local func_sig = parse_signature(signature) assert(func_sig.fname == clsname) local con_info = cs.get_constructor(type_info, func_sig.partypes) assert(con_info, func_sig.fname) def.add_class_method(CONSTRUCTOR, function(...) local this = cs.call_method(con_info, nil, ...) return cls_mgr.make_instance(clsname, this) end) end ---------------- -- METHODS ---------------- for _, signature in ipairs(self.__methods) do local func_sig = parse_signature(signature) local mtd_info = cs.get_method(type_info, func_sig.fname, func_sig.partypes) assert(mtd_info, func_sig.fname) def.add_inst_method(func_sig.fname, function(self, ...) local this = rawget(self, "__this") return wrap_retval( cs.call_method(mtd_info, this, ...), func_sig.ret_typename ) end) end ---------------- -- STATIC METHODS ---------------- for _, signature in ipairs(self.__static_methods) do local func_sig = parse_signature(signature) local mtd_info = cs.get_static_method(type_info, func_sig.fname, func_sig.partypes) assert(mtd_info, func_sig.fname) def.add_class_method(func_sig.fname, function(...) -- print("call static method:", func_sig.fname) local ok, val = pcall( cs.call_method, mtd_info, nil, ...) if not ok then error("call static method("..func_sig.fname..") error: "..val) end return wrap_retval( val, func_sig.ret_typename ) end) end ---------------- -- FIELDS ---------------- for _, signature in ipairs(self.__fields) do local sig = parse_signature(signature) local field_info = cs.get_field(type_info, sig.fname) assert(field_info, sig.fname) local field_type = get_type(sig.ret_typename) local function index(self, key) local this = rawget(self, "__this") return wrap_retval( cs.get_field_value(field_info, this, field_type), sig.ret_typename ) end local function newindex(self, key, value) local this = rawget(self, "__this") local raw_value = unwrap_param(value, sig.ret_typename) cs.set_field_value(field_info, this, raw_value, field_type) end -- sig.ret_typename def.add_inst_field(sig.fname, index, newindex) end ---------------- -- PROPERTIES ---------------- for _, signature in ipairs(self.__properties) do local sig = parse_signature(signature) local prop_info = cs.get_prop(type_info, sig.fname) assert(prop_info, sig.fname) local prop_type = get_type(sig.ret_typename) local function index(self, key) local this = rawget(self, "__this") return wrap_retval( cs.get_prop_value(prop_info, this, prop_type), sig.ret_typename ) end local function newindex(self, key, value) local this = rawget(self, "__this") local raw_value = unwrap_param(value, sig.ret_typename) -- print("property __newindex", this, key, raw_value) cs.set_prop_value(prop_info, this, raw_value, prop_type) end def.add_inst_field(sig.fname, index, newindex) end ---------------- -- STATIC PROPERTIES ---------------- for _, signature in ipairs(self.__static_properties) do local sig = parse_signature(signature) local prop_info = cs.get_static_prop(type_info, sig.fname) assert(prop_info, sig.fname) local prop_type = get_type(sig.ret_typename) local function index(self, key) return wrap_retval( cs.get_prop_value(prop_info, nil, prop_type), sig.ret_typename ) end local function newindex(self, key, value) local raw_value = unwrap_param(value, sig.ret_typename) cs.set_prop_value(prop_info, nil, raw_value, prop_type) end def.add_class_field(sig.fname, index, newindex) end return cls_mgr.make_class(clsname) end local class_mt = { __index = { constructor = constructor, method = method, static_method = static_method, field = field, property = property, static_property = static_property, }, } ---------------------------------------------------------------------- local function assembly(builder, assembly) table.insert(builder.assembly_list, assembly) end local function using(builder, namespace) table.insert(builder.using_list, namespace) end local function class(builder, clsname) assert( not builder.class_list[clsname] ) local inst = { __class_name = clsname, __constructor = {}, __methods = {}, __static_methods = {}, __fields = {}, __properties = {}, __static_properties = {}, } local obj = setmetatable(inst, class_mt) builder.class_list[clsname] = obj return obj end ---------------------------------------------------------------------- local function new_builder() return { assembly_list = {}, using_list = {}, class_list = {}, } end local function resolve_builder(builder) local mod = {} cs.clear_assembly_list() for _, assembly in ipairs(builder.assembly_list) do cs.add_assembly(assembly) end cs.clear_using_list() for _, namespace in ipairs(builder.using_list) do cs.using(namespace) end local cls_mgr = new_class_mgr() for clsname, class_info in pairs(builder.class_list) do cls_mgr.declare_class(clsname) end for clsname, class_info in pairs(builder.class_list) do mod[clsname] = build_class(cls_mgr, class_info) end return mod end local function build(init_func) local builder = new_builder() local wrap = function(func) return function(...) return func(builder, ...) end end local env = { assembly = wrap(assembly), using = wrap(using), class = wrap(class), } init_func(env) return resolve_builder(builder) end return { build = build, }
mit
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/items/nunoboko_no_ken.lua
1
4323
--[[ Author: PicoleDeLimao Date: 04.09.2016 Attachs sword particle when equiped ]] function Equip(event) local caster = event.caster local ability = event.ability local damageIncrease = ability:GetLevelSpecialValueFor("elemental_damage_bonus", ability:GetLevel() - 1) caster.nunobokoNoKenCount = (caster.nunobokoNoKenCount or 0) + 1 caster.katonDmg = caster.katonDmg + damageIncrease caster.suitonDmg = caster.suitonDmg + damageIncrease caster.dotonDmg = caster.dotonDmg + damageIncrease caster.fuutonDmg = caster.fuutonDmg + damageIncrease caster.raitonDmg = caster.raitonDmg + damageIncrease caster.yinDmg = caster.yinDmg + damageIncrease caster.yangDmg = caster.yangDmg + damageIncrease if caster.nunobokoNoKenCount == 1 then local particle = ParticleManager:CreateParticle("particles/items/NunobokoNoKen/nunoboko_no_ken.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster) ParticleManager:SetParticleControlEnt(particle, 0, caster, PATTACH_POINT_FOLLOW, "attach_attack1", caster:GetAbsOrigin(), true) caster.nunobokoNoKenParticle = particle caster.nunobokoNoKenParticleName = event.ParticleName end end function Unequip(event) local caster = event.caster local ability = event.ability local damageIncrease = ability:GetLevelSpecialValueFor("elemental_damage_bonus", ability:GetLevel() - 1) caster.katonDmg = caster.katonDmg - damageIncrease caster.suitonDmg = caster.suitonDmg - damageIncrease caster.dotonDmg = caster.dotonDmg - damageIncrease caster.fuutonDmg = caster.fuutonDmg - damageIncrease caster.raitonDmg = caster.raitonDmg - damageIncrease caster.yinDmg = caster.yinDmg - damageIncrease caster.yangDmg = caster.yangDmg - damageIncrease if caster.nunobokoNoKenCount == 1 then ParticleManager:DestroyParticle(caster.nunobokoNoKenParticle, false) caster.nunobokoNoKenParticle = nil end caster.nunobokoNoKenCount = caster.nunobokoNoKenCount - 1 end function CriticalStrike(event) local caster = event.caster local target = event.target local ability = event.ability local bonus = ability:GetLevelSpecialValueFor("crit_bonus", ability:GetLevel() - 1) / 100.0 local radius = ability:GetLevelSpecialValueFor("crit_area", ability:GetLevel() - 1) local slowDuration = ability:GetLevelSpecialValueFor("slow_duration", ability:GetLevel() - 1) Units:FindEnemiesInRange({ unit = caster, point = target:GetAbsOrigin(), radius = radius, func = function(enemy) local damage = caster:GetAverageTrueAttackDamage(enemy) ApplyDamage({ victim = enemy, attacker = caster, damage = damage * bonus, damage_type = DAMAGE_TYPE_PHYSICAL}) Particles:CreateTimedParticle("particles/units/heroes/hero_nevermore/nevermore_shadowraze.vpcf", enemy, 0.25) if not enemy:IsMagicImmune() then ability:ApplyDataDrivenModifier(caster, enemy, "modifier_item_nunoboko_no_ken_slow", {duration = slowDuration}) end PopupCriticalDamage(enemy, damage * bonus) end }) end function ShapeTheWorld(event) local caster = event.caster local target = event.target_points[1] local ability = event.ability local radius = ability:GetLevelSpecialValueFor("shape_world_radius", ability:GetLevel() - 1) local paralysisDuration = ability:GetLevelSpecialValueFor("shape_world_duration", ability:GetLevel() - 1) local damageTakenDuration = ability:GetLevelSpecialValueFor("shape_world_damage_taken_duration", ability:GetLevel() - 1) local damage = ability:GetLevelSpecialValueFor("shape_world_damage", ability:GetLevel() - 1) local particle = Particles:CreateTimedParticle("particles/econ/items/enigma/enigma_world_chasm/enigma_blackhole_ti5.vpcf", caster, paralysisDuration) Particles:SetControl(particle, 0, target) Particles:SetControl(particle, 1, radius) Units:FindEnemiesInRange({ unit = caster, point = target, radius = radius, func = function(enemy) ability:ApplyDataDrivenModifier(caster, enemy, "modifier_item_nunoboko_no_ken_paralysis", {duration = paralysisDuration}) ability:ApplyDataDrivenModifier(caster, enemy, "modifier_item_nunoboko_no_ken_damage_taken", {duration = damageTakenDuration}) ApplyDamage({ victim = enemy, attacker = caster, damage = (caster:GetStrength() + caster:GetAgility() + caster:GetIntellect()) * damage, damage_type = DAMAGE_TYPE_MAGICAL}) end }) caster:EmitSound("Hero_Enigma.BlackHole.Cast.Chasm") end
apache-2.0
1yvT0s/luvit
tests/test-fs-readfile-unlink.lua
11
1448
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer local string = require('string') local dirName = Path.join(module.dir, 'fixtures', 'test-readfile-unlink') local fileName = Path.join(dirName, 'test.bin') local bufStr = string.rep(string.char(42), 512 * 1024) local buf = Buffer:new(bufStr) test('fs readfile unlink', function() local ok, err ok, err = pcall(FS.mkdirSync, dirName, '0777') if not ok then assert(err.code == 'EEXIST') end FS.writeFileSync(fileName, buf:toString()) FS.readFile(fileName, function(err, data) assert(err == nil) assert(#data == buf.length) assert(string.byte(data, 1) == 42) FS.unlink(fileName, function() FS.rmdirSync(dirName) end) end) end) end)
apache-2.0
Zero-K-Experiments/Zero-K-Experiments
units/chicken_tiamat.lua
3
8618
unitDef = { unitname = [[chicken_tiamat]], name = [[Tiamat]], description = [[Heavy Assault/Riot]], acceleration = 0.36, autoheal = 20, brakeRate = 0.205, buildCostEnergy = 0, buildCostMetal = 0, builder = false, buildPic = [[chicken_tiamat.png]], buildTime = 350, canAttack = true, canGuard = true, canMove = true, canPatrol = true, category = [[LAND FIREPROOF]], customParams = { description_fr = [[Assault lourd]], description_de = [[Schwere Sturm-/Rioteinheit]], fireproof = 1, helptext = [[The ultimate assault chicken, the Tiamat is a fire-breathing, iron-jawed, spore-spewing monstrosity that knows no fear, no mercy. It even has a mucous shield to protect itself and surrounding chickens from damage.]], helptext_fr = [[L'ultime unit? d'assault pouler, le Tiamat est une monstruosit? crachant des flammes, d?chirant de ses machoires d'acier et lan?ant des spores sur ses victimes. Elle poss?de m?me un bouclier ?nerg?tique r?sultant de sa fureur, lui procurant ? elle et aux unit?s alli?es ? proximit? une protection efficace durant leur progession vers l'adversaire.]], helptext_de = [[Das ultimative Sturmchicken: Tiamat ist eine feuer-, eisenspuckende und Sporenspeiende Monstrosität, die keine Angst oder Furcht kennt, aber auch keine Gnade. Sie besitzt sogar ein schleimiges Schild, welches sie selbst und nahe, verbEdete Einheiten schEzt.]], }, explodeAs = [[NOWEAPON]], footprintX = 4, footprintZ = 4, iconType = [[t3generic]], idleAutoHeal = 20, idleTime = 300, leaveTracks = true, maxDamage = 3650, maxSlope = 37, maxVelocity = 2.3, maxWaterDepth = 5000, minCloakDistance = 75, movementClass = [[AKBOT6]], noAutoFire = false, noChaseCategory = [[TERRAFORM FIXEDWING SATELLITE GUNSHIP SUB STUPIDTARGET MINE]], objectName = [[chickenbroodqueen.s3o]], power = 350, seismicSignature = 4, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:blood_spray]], [[custom:blood_explode]], [[custom:dirt]], [[custom:RAIDMUZZLE]], }, }, sightDistance = 256, trackOffset = 7, trackStrength = 9, trackStretch = 1, trackType = [[ChickenTrack]], trackWidth = 34, turninplace = 0, turnRate = 806, upright = false, workerTime = 0, weapons = { { def = [[JAWS]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, { def = [[SPORES]], badTargetCategory = [[SWIM LAND SHIP HOVER]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, { def = [[FLAMETHROWER]], badTargetCategory = [[FIREPROOF]], mainDir = [[0 0 1]], maxAngleDif = 120, onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP FIXEDWING]], }, { def = [[SHIELD]], }, }, weaponDefs = { FLAMETHROWER = { name = [[Flamethrower]], areaOfEffect = 64, avoidGround = false, avoidFeature = false, avoidFriendly = false, collideFeature = false, collideGround = false, coreThickness = 0, craterBoost = 0, craterMult = 0, cegTag = [[flamer]], customParams = { flamethrower = [[1]], setunitsonfire = "1", burntime = [[450]], }, damage = { default = 12, subs = 0.01, }, duration = 0.01, explosionGenerator = [[custom:SMOKE]], fallOffRate = 1, fireStarter = 100, heightMod = 1, impulseBoost = 0, impulseFactor = 0, intensity = 0.3, interceptedByShieldType = 1, noExplode = true, noSelfDamage = true, --predictBoost = 1, range = 290, reloadtime = 0.16, rgbColor = [[1 1 1]], soundStart = [[weapon/flamethrower]], soundTrigger = true, texture1 = [[flame]], thickness = 0, tolerance = 5000, turret = true, weaponType = [[LaserCannon]], weaponVelocity = 800, }, JAWS = { name = [[Jaws]], areaOfEffect = 8, craterBoost = 0, craterMult = 0, damage = { default = 300, planes = 300, subs = 3, }, explosionGenerator = [[custom:NONE]], impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 0, noSelfDamage = true, range = 160, reloadtime = 1.5, size = 0, soundHit = [[chickens/chickenbig2]], soundStart = [[chickens/chickenbig2]], targetborder = 1, tolerance = 5000, turret = true, waterWeapon = true, weaponType = [[Cannon]], weaponVelocity = 500, }, SHIELD = { name = [[Shield]], craterMult = 0, damage = { default = 10, }, exteriorShield = true, impulseFactor = 0, interceptedByShieldType = 1, shieldAlpha = 0.15, shieldBadColor = [[1.0 1 0.1]], shieldGoodColor = [[0.1 1.0 0.1]], shieldInterceptType = 3, shieldPower = 2500, shieldPowerRegen = 180, shieldPowerRegenEnergy = 0, shieldRadius = 300, shieldRepulser = false, smartShield = true, texture1 = [[wake]], visibleShield = true, visibleShieldHitFrames = 30, visibleShieldRepulse = false, weaponType = [[Shield]], }, SPORES = { name = [[Spores]], areaOfEffect = 24, avoidFriendly = false, burst = 8, burstrate = 0.1, collideFriendly = false, craterBoost = 0, craterMult = 0, customParams = { light_radius = 0, }, damage = { default = 100, planes = 100, subs = 100, }, dance = 60, explosionGenerator = [[custom:NONE]], fireStarter = 0, fixedlauncher = 1, flightTime = 5, groundbounce = 1, heightmod = 0.5, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, metalpershot = 0, model = [[chickeneggpink.s3o]], noSelfDamage = true, range = 600, reloadtime = 6, smokeTrail = true, startVelocity = 100, texture1 = [[]], texture2 = [[sporetrail]], tolerance = 10000, tracks = true, turnRate = 24000, turret = true, waterweapon = true, weaponAcceleration = 100, weaponType = [[MissileLauncher]], weaponVelocity = 500, wobble = 32000, }, }, } return lowerkeys({ chicken_tiamat = unitDef })
gpl-2.0
Scavenge/darkstar
scripts/zones/The_Ashu_Talif/mobs/Ashu_Talif_Crew.lua
10
1189
----------------------------------- -- Area: The Ashu Talif (The Black Coffin) -- MOB: Ashu Talif Crew ----------------------------------- require("scripts/globals/status"); local TheAshuTalif = require("scripts/zones/The_Ashu_Talif/IDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged Action ----------------------------------- function onMobEngaged(mob,target) local allies = mob:getInstance():getAllies(); for i,v in pairs(allies) do if (v:isAlive()) then v:setLocalVar("ready",1); end end local mobs = mob:getInstance():getMobs(); for i,v in pairs(mobs) do if(v:isAlive()) then v:setLocalVar("ready",1); end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) local instance = mob:getInstance(); instance:setProgress(instance:getProgress() + 1); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) end;
gpl-3.0
maksym1221/nlp-rnn
util/CharSplitLMMinibatchLoader.lua
1
9489
local rex = require 'rex_pcre' -- Modified from https://github.com/oxford-cs-ml-2015/practical6 -- the modification included support for train/val/test splits local CharSplitLMMinibatchLoader = {} CharSplitLMMinibatchLoader.__index = CharSplitLMMinibatchLoader function CharSplitLMMinibatchLoader.create(data_dir, batch_size, seq_length, split_fractions, word_level, threshold) -- split_fractions is e.g. {0.9, 0.05, 0.05} if not word_level then threshold = 0 end local self = {} setmetatable(self, CharSplitLMMinibatchLoader) self.word_level = word_level local input_file = path.join(data_dir, 'input.txt') local vocab_file = path.join(data_dir, word_level and 'vocab_w' .. threshold .. '.t7' or 'vocab.t7') local tensor_file = path.join(data_dir, word_level and 'data_w' .. threshold .. '.t7' or 'data.t7') -- fetch file attributes to determine if we need to rerun preprocessing local run_prepro = false if not (path.exists(vocab_file) or path.exists(tensor_file)) then -- prepro files do not exist, generate them print('vocab.t7 and data.t7 do not exist. Running preprocessing...') run_prepro = true else -- check if the input file was modified since last time we -- ran the prepro. if so, we have to rerun the preprocessing local input_attr = lfs.attributes(input_file) local vocab_attr = lfs.attributes(vocab_file) local tensor_attr = lfs.attributes(tensor_file) if input_attr.modification > vocab_attr.modification or input_attr.modification > tensor_attr.modification then print('vocab.t7 or data.t7 detected as stale. Re-running preprocessing...') run_prepro = true end end if run_prepro then -- construct a tensor with all the data, and vocab file print('one-time setup: preprocessing input text file ' .. input_file .. '...') CharSplitLMMinibatchLoader.text_to_tensor(word_level, threshold, input_file, vocab_file, tensor_file) end print('loading data files...') local data = torch.load(tensor_file) self.vocab_mapping = torch.load(vocab_file) -- cut off the end so that it divides evenly local len = data:size(1) if len % (batch_size * seq_length) ~= 0 then print('cutting off end of data so that the batches/sequences divide evenly') data = data:sub(1, batch_size * seq_length * math.floor(len / (batch_size * seq_length))) end -- count vocab self.vocab_size = 0 for _ in pairs(self.vocab_mapping) do self.vocab_size = self.vocab_size + 1 end -- self.batches is a table of tensors print('reshaping tensor...') self.batch_size = batch_size self.seq_length = seq_length local ydata = data:clone() ydata:sub(1,-2):copy(data:sub(2,-1)) ydata[-1] = data[1] self.x_batches = data:view(batch_size, -1):split(seq_length, 2) -- #rows = #batches self.nbatches = #self.x_batches self.y_batches = ydata:view(batch_size, -1):split(seq_length, 2) -- #rows = #batches assert(#self.x_batches == #self.y_batches) -- lets try to be helpful here if self.nbatches < 50 then print('WARNING: less than 50 batches in the data in total? Looks like very small dataset. You probably want to use smaller batch_size and/or seq_length.') end -- perform safety checks on split_fractions assert(split_fractions[1] >= 0 and split_fractions[1] <= 1, 'bad split fraction ' .. split_fractions[1] .. ' for train, not between 0 and 1') assert(split_fractions[2] >= 0 and split_fractions[2] <= 1, 'bad split fraction ' .. split_fractions[2] .. ' for val, not between 0 and 1') assert(split_fractions[3] >= 0 and split_fractions[3] <= 1, 'bad split fraction ' .. split_fractions[3] .. ' for test, not between 0 and 1') if split_fractions[3] == 0 then -- catch a common special case where the user might not want a test set self.ntrain = math.floor(self.nbatches * split_fractions[1]) self.nval = self.nbatches - self.ntrain self.ntest = 0 else -- divide data to train/val and allocate rest to test self.ntrain = math.floor(self.nbatches * split_fractions[1]) self.nval = math.floor(self.nbatches * split_fractions[2]) self.ntest = self.nbatches - self.nval - self.ntrain -- the rest goes to test (to ensure this adds up exactly) end self.split_sizes = {self.ntrain, self.nval, self.ntest} self.batch_ix = {0,0,0} print(string.format('data load done. Number of data batches in train: %d, val: %d, test: %d', self.ntrain, self.nval, self.ntest)) collectgarbage() return self end function CharSplitLMMinibatchLoader:reset_batch_pointer(split_index, batch_index) batch_index = batch_index or 0 self.batch_ix[split_index] = batch_index end function CharSplitLMMinibatchLoader:next_batch(split_index) if self.split_sizes[split_index] == 0 then -- perform a check here to make sure the user isn't screwing something up local split_names = {'train', 'val', 'test'} print('ERROR. Code requested a batch for split ' .. split_names[split_index] .. ', but this split has no data.') os.exit() -- crash violently end -- split_index is integer: 1 = train, 2 = val, 3 = test self.batch_ix[split_index] = self.batch_ix[split_index] + 1 if self.batch_ix[split_index] > self.split_sizes[split_index] then self.batch_ix[split_index] = 1 -- cycle around to beginning end -- pull out the correct next batch local ix = self.batch_ix[split_index] if split_index == 2 then ix = ix + self.ntrain end -- offset by train set size if split_index == 3 then ix = ix + self.ntrain + self.nval end -- offset by train + val return self.x_batches[ix], self.y_batches[ix] end -- *** STATIC method *** function CharSplitLMMinibatchLoader.text_to_tensor(word_level, threshold, in_textfile, out_vocabfile, out_tensorfile) local timer = torch.Timer() print('loading text file...') local f = torch.DiskFile(in_textfile) local rawdata = f:readString('*a') -- NOTE: this reads the whole file at once f:close() -- create vocabulary if it doesn't exist yet print('creating vocabulary mapping...') print('word occurence threshold is ' .. threshold) -- record all characters to a set local unordered = {} --rawdata = re.sub('([%s])' % (re.escape(string.punctuation)+"1234567890"), r" \1 ", rawdata) local numtokens = 0 for token in CharSplitLMMinibatchLoader.tokens(rawdata, word_level) do if not unordered[token] then unordered[token] = 1 else unordered[token] = unordered[token] + 1 end numtokens = numtokens + 1 end -- sort into a table (i.e. keys become 1..N) local ordered = {} for token, count in pairs(unordered) do if count > threshold then ordered[#ordered + 1] = token end end if word_level then ordered[#ordered + 1] = "UNK" --represents unknown words end table.sort(ordered) -- invert `ordered` to create the char->int mapping local vocab_mapping = {} for i, char in ipairs(ordered) do vocab_mapping[char] = i end -- construct a tensor with all the data print('putting data into tensor...') local data = word_level and torch.ShortTensor(numtokens) or torch.ByteTensor(#rawdata) -- store it into 1D first, then rearrange if word_level then local i = 1 for token in CharSplitLMMinibatchLoader.tokens(rawdata, word_level) do data[i] = vocab_mapping[token] or vocab_mapping["UNK"] i = i + 1 end else for i=1, #rawdata do data[i] = vocab_mapping[rawdata:sub(i, i)] -- lua has no string indexing using [] end end -- save output preprocessed files print('saving ' .. out_vocabfile) torch.save(out_vocabfile, vocab_mapping) print('saving ' .. out_tensorfile) torch.save(out_tensorfile, data) end function CharSplitLMMinibatchLoader.tokens(rawstr, word_level) if word_level then --local str, _, _ = rex.gsub(rawstr, '[[:punct:][:digit:]]', ' %0 ') --str, _, _ = rex.gsub(str, '\\n', ' RN ') --return rex.split(str, "\\s+") return word_iter(rawstr) else return rawstr:gmatch'.' end end function word_iter(str) local n = str:len() local punctdigit = rex.new('[[:punct:][:digit:]]') local newline = rex.new('\\n') local whitespace = rex.new('[ \\t]') --dont match newlines local char_iter = str:gmatch'.' local c = char_iter() return function() if c == nil then return nil end while rex.count(c, whitespace) > 0 do c = char_iter() if c == nil then return nil end end if rex.count(c, punctdigit) > 0 then local ret = c c = char_iter() return ret end if rex.count(c, newline) > 0 then c = char_iter() return '\n' end local word = '' repeat word = word .. c c = char_iter() if c == nil then return word end until rex.count(c, whitespace) > 0 or rex.count(c, punctdigit) > 0 or rex.count(c, newline) > 0 return word end end return CharSplitLMMinibatchLoader
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/feature_fx.lua
6
1309
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Feature Effects", desc = "Does effects related to feature life and death", author = "Anarchid", date = "January 2015", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end local spSpawnCEG = Spring.SpawnCEG; local spGetFeaturePosition = Spring.GetFeaturePosition; local spGetFeatureResources = Spring.GetFeatureResources; local spGetFeatureRadius = Spring.GetFeatureRadius; local CEG_SPAWN = [[feature_poof_spawner]]; function gadget:FeatureDestroyed(id, allyTeam) local _,_,_,x,y,z = spGetFeaturePosition(id, true); local r = spGetFeatureRadius(id); spSpawnCEG( CEG_SPAWN, x,y,z, 0,0,0, 2+(r/3), 2+(r/3) ); --This could be used to later play sounds without betraying events or positions of destroyed features --SendToUnsynced("feature_destroyed", x, y, z); end
gpl-2.0
Scavenge/darkstar
scripts/globals/items/serving_of_bass_meuniere_+1.lua
12
1663
----------------------------------------- -- ID: 4346 -- Item: serving_of_bass_meuniere_+1 -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 3 (cap 130) -- Dexterity 3 -- Agility 3 -- Mind -3 -- Ranged ACC % 6 -- Ranged ACC Cap 20 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4346); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 3); target:addMod(MOD_FOOD_HP_CAP, 130); target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_MND, -3); target:addMod(MOD_FOOD_RACCP, 6); target:addMod(MOD_FOOD_RACC_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 3); target:delMod(MOD_FOOD_HP_CAP, 130); target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_MND, -3); target:delMod(MOD_FOOD_RACCP, 6); target:delMod(MOD_FOOD_RACC_CAP, 20); end;
gpl-3.0
xincun/nginx-openresty-windows
luajit-root/luajit/share/luajit-2.1.0-alpha/jit/dis_x86.lua
17
29376
---------------------------------------------------------------------------- -- LuaJIT x86/x64 disassembler module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- This is a helper module used by the LuaJIT machine code dumper module. -- -- Sending small code snippets to an external disassembler and mixing the -- output with our own stuff was too fragile. So I had to bite the bullet -- and write yet another x86 disassembler. Oh well ... -- -- The output format is very similar to what ndisasm generates. But it has -- been developed independently by looking at the opcode tables from the -- Intel and AMD manuals. The supported instruction set is quite extensive -- and reflects what a current generation Intel or AMD CPU implements in -- 32 bit and 64 bit mode. Yes, this includes MMX, SSE, SSE2, SSE3, SSSE3, -- SSE4.1, SSE4.2, SSE4a and even privileged and hypervisor (VMX/SVM) -- instructions. -- -- Notes: -- * The (useless) a16 prefix, 3DNow and pre-586 opcodes are unsupported. -- * No attempt at optimization has been made -- it's fast enough for my needs. -- * The public API may change when more architectures are added. ------------------------------------------------------------------------------ local type = type local sub, byte, format = string.sub, string.byte, string.format local match, gmatch, gsub = string.match, string.gmatch, string.gsub local lower, rep = string.lower, string.rep local bit = require("bit") local tohex = bit.tohex -- Map for 1st opcode byte in 32 bit mode. Ugly? Well ... read on. local map_opc1_32 = { --0x [0]="addBmr","addVmr","addBrm","addVrm","addBai","addVai","push es","pop es", "orBmr","orVmr","orBrm","orVrm","orBai","orVai","push cs","opc2*", --1x "adcBmr","adcVmr","adcBrm","adcVrm","adcBai","adcVai","push ss","pop ss", "sbbBmr","sbbVmr","sbbBrm","sbbVrm","sbbBai","sbbVai","push ds","pop ds", --2x "andBmr","andVmr","andBrm","andVrm","andBai","andVai","es:seg","daa", "subBmr","subVmr","subBrm","subVrm","subBai","subVai","cs:seg","das", --3x "xorBmr","xorVmr","xorBrm","xorVrm","xorBai","xorVai","ss:seg","aaa", "cmpBmr","cmpVmr","cmpBrm","cmpVrm","cmpBai","cmpVai","ds:seg","aas", --4x "incVR","incVR","incVR","incVR","incVR","incVR","incVR","incVR", "decVR","decVR","decVR","decVR","decVR","decVR","decVR","decVR", --5x "pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR","pushUR", "popUR","popUR","popUR","popUR","popUR","popUR","popUR","popUR", --6x "sz*pushaw,pusha","sz*popaw,popa","boundVrm","arplWmr", "fs:seg","gs:seg","o16:","a16", "pushUi","imulVrmi","pushBs","imulVrms", "insb","insVS","outsb","outsVS", --7x "joBj","jnoBj","jbBj","jnbBj","jzBj","jnzBj","jbeBj","jaBj", "jsBj","jnsBj","jpeBj","jpoBj","jlBj","jgeBj","jleBj","jgBj", --8x "arith!Bmi","arith!Vmi","arith!Bmi","arith!Vms", "testBmr","testVmr","xchgBrm","xchgVrm", "movBmr","movVmr","movBrm","movVrm", "movVmg","leaVrm","movWgm","popUm", --9x "nop*xchgVaR|pause|xchgWaR|repne nop","xchgVaR","xchgVaR","xchgVaR", "xchgVaR","xchgVaR","xchgVaR","xchgVaR", "sz*cbw,cwde,cdqe","sz*cwd,cdq,cqo","call farViw","wait", "sz*pushfw,pushf","sz*popfw,popf","sahf","lahf", --Ax "movBao","movVao","movBoa","movVoa", "movsb","movsVS","cmpsb","cmpsVS", "testBai","testVai","stosb","stosVS", "lodsb","lodsVS","scasb","scasVS", --Bx "movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi","movBRi", "movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI","movVRI", --Cx "shift!Bmu","shift!Vmu","retBw","ret","$lesVrm","$ldsVrm","movBmi","movVmi", "enterBwu","leave","retfBw","retf","int3","intBu","into","iretVS", --Dx "shift!Bm1","shift!Vm1","shift!Bmc","shift!Vmc","aamBu","aadBu","salc","xlatb", "fp*0","fp*1","fp*2","fp*3","fp*4","fp*5","fp*6","fp*7", --Ex "loopneBj","loopeBj","loopBj","sz*jcxzBj,jecxzBj,jrcxzBj", "inBau","inVau","outBua","outVua", "callVj","jmpVj","jmp farViw","jmpBj","inBad","inVad","outBda","outVda", --Fx "lock:","int1","repne:rep","rep:","hlt","cmc","testb!Bm","testv!Vm", "clc","stc","cli","sti","cld","std","incb!Bm","incd!Vm", } assert(#map_opc1_32 == 255) -- Map for 1st opcode byte in 64 bit mode (overrides only). local map_opc1_64 = setmetatable({ [0x06]=false, [0x07]=false, [0x0e]=false, [0x16]=false, [0x17]=false, [0x1e]=false, [0x1f]=false, [0x27]=false, [0x2f]=false, [0x37]=false, [0x3f]=false, [0x60]=false, [0x61]=false, [0x62]=false, [0x63]="movsxdVrDmt", [0x67]="a32:", [0x40]="rex*", [0x41]="rex*b", [0x42]="rex*x", [0x43]="rex*xb", [0x44]="rex*r", [0x45]="rex*rb", [0x46]="rex*rx", [0x47]="rex*rxb", [0x48]="rex*w", [0x49]="rex*wb", [0x4a]="rex*wx", [0x4b]="rex*wxb", [0x4c]="rex*wr", [0x4d]="rex*wrb", [0x4e]="rex*wrx", [0x4f]="rex*wrxb", [0x82]=false, [0x9a]=false, [0xc4]=false, [0xc5]=false, [0xce]=false, [0xd4]=false, [0xd5]=false, [0xd6]=false, [0xea]=false, }, { __index = map_opc1_32 }) -- Map for 2nd opcode byte (0F xx). True CISC hell. Hey, I told you. -- Prefix dependent MMX/SSE opcodes: (none)|rep|o16|repne, -|F3|66|F2 local map_opc2 = { --0x [0]="sldt!Dmp","sgdt!Ump","larVrm","lslVrm",nil,"syscall","clts","sysret", "invd","wbinvd",nil,"ud1",nil,"$prefetch!Bm","femms","3dnowMrmu", --1x "movupsXrm|movssXrm|movupdXrm|movsdXrm", "movupsXmr|movssXmr|movupdXmr|movsdXmr", "movhlpsXrm$movlpsXrm|movsldupXrm|movlpdXrm|movddupXrm", "movlpsXmr||movlpdXmr", "unpcklpsXrm||unpcklpdXrm", "unpckhpsXrm||unpckhpdXrm", "movlhpsXrm$movhpsXrm|movshdupXrm|movhpdXrm", "movhpsXmr||movhpdXmr", "$prefetcht!Bm","hintnopVm","hintnopVm","hintnopVm", "hintnopVm","hintnopVm","hintnopVm","hintnopVm", --2x "movUmx$","movUmy$","movUxm$","movUym$","movUmz$",nil,"movUzm$",nil, "movapsXrm||movapdXrm", "movapsXmr||movapdXmr", "cvtpi2psXrMm|cvtsi2ssXrVmt|cvtpi2pdXrMm|cvtsi2sdXrVmt", "movntpsXmr|movntssXmr|movntpdXmr|movntsdXmr", "cvttps2piMrXm|cvttss2siVrXm|cvttpd2piMrXm|cvttsd2siVrXm", "cvtps2piMrXm|cvtss2siVrXm|cvtpd2piMrXm|cvtsd2siVrXm", "ucomissXrm||ucomisdXrm", "comissXrm||comisdXrm", --3x "wrmsr","rdtsc","rdmsr","rdpmc","sysenter","sysexit",nil,"getsec", "opc3*38",nil,"opc3*3a",nil,nil,nil,nil,nil, --4x "cmovoVrm","cmovnoVrm","cmovbVrm","cmovnbVrm", "cmovzVrm","cmovnzVrm","cmovbeVrm","cmovaVrm", "cmovsVrm","cmovnsVrm","cmovpeVrm","cmovpoVrm", "cmovlVrm","cmovgeVrm","cmovleVrm","cmovgVrm", --5x "movmskpsVrXm$||movmskpdVrXm$","sqrtpsXrm|sqrtssXrm|sqrtpdXrm|sqrtsdXrm", "rsqrtpsXrm|rsqrtssXrm","rcppsXrm|rcpssXrm", "andpsXrm||andpdXrm","andnpsXrm||andnpdXrm", "orpsXrm||orpdXrm","xorpsXrm||xorpdXrm", "addpsXrm|addssXrm|addpdXrm|addsdXrm","mulpsXrm|mulssXrm|mulpdXrm|mulsdXrm", "cvtps2pdXrm|cvtss2sdXrm|cvtpd2psXrm|cvtsd2ssXrm", "cvtdq2psXrm|cvttps2dqXrm|cvtps2dqXrm", "subpsXrm|subssXrm|subpdXrm|subsdXrm","minpsXrm|minssXrm|minpdXrm|minsdXrm", "divpsXrm|divssXrm|divpdXrm|divsdXrm","maxpsXrm|maxssXrm|maxpdXrm|maxsdXrm", --6x "punpcklbwPrm","punpcklwdPrm","punpckldqPrm","packsswbPrm", "pcmpgtbPrm","pcmpgtwPrm","pcmpgtdPrm","packuswbPrm", "punpckhbwPrm","punpckhwdPrm","punpckhdqPrm","packssdwPrm", "||punpcklqdqXrm","||punpckhqdqXrm", "movPrVSm","movqMrm|movdquXrm|movdqaXrm", --7x "pshufwMrmu|pshufhwXrmu|pshufdXrmu|pshuflwXrmu","pshiftw!Pmu", "pshiftd!Pmu","pshiftq!Mmu||pshiftdq!Xmu", "pcmpeqbPrm","pcmpeqwPrm","pcmpeqdPrm","emms|", "vmreadUmr||extrqXmuu$|insertqXrmuu$","vmwriteUrm||extrqXrm$|insertqXrm$", nil,nil, "||haddpdXrm|haddpsXrm","||hsubpdXrm|hsubpsXrm", "movVSmMr|movqXrm|movVSmXr","movqMmr|movdquXmr|movdqaXmr", --8x "joVj","jnoVj","jbVj","jnbVj","jzVj","jnzVj","jbeVj","jaVj", "jsVj","jnsVj","jpeVj","jpoVj","jlVj","jgeVj","jleVj","jgVj", --9x "setoBm","setnoBm","setbBm","setnbBm","setzBm","setnzBm","setbeBm","setaBm", "setsBm","setnsBm","setpeBm","setpoBm","setlBm","setgeBm","setleBm","setgBm", --Ax "push fs","pop fs","cpuid","btVmr","shldVmru","shldVmrc",nil,nil, "push gs","pop gs","rsm","btsVmr","shrdVmru","shrdVmrc","fxsave!Dmp","imulVrm", --Bx "cmpxchgBmr","cmpxchgVmr","$lssVrm","btrVmr", "$lfsVrm","$lgsVrm","movzxVrBmt","movzxVrWmt", "|popcntVrm","ud2Dp","bt!Vmu","btcVmr", "bsfVrm","bsrVrm|lzcntVrm|bsrWrm","movsxVrBmt","movsxVrWmt", --Cx "xaddBmr","xaddVmr", "cmppsXrmu|cmpssXrmu|cmppdXrmu|cmpsdXrmu","$movntiVmr|", "pinsrwPrWmu","pextrwDrPmu", "shufpsXrmu||shufpdXrmu","$cmpxchg!Qmp", "bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR","bswapVR", --Dx "||addsubpdXrm|addsubpsXrm","psrlwPrm","psrldPrm","psrlqPrm", "paddqPrm","pmullwPrm", "|movq2dqXrMm|movqXmr|movdq2qMrXm$","pmovmskbVrMm||pmovmskbVrXm", "psubusbPrm","psubuswPrm","pminubPrm","pandPrm", "paddusbPrm","padduswPrm","pmaxubPrm","pandnPrm", --Ex "pavgbPrm","psrawPrm","psradPrm","pavgwPrm", "pmulhuwPrm","pmulhwPrm", "|cvtdq2pdXrm|cvttpd2dqXrm|cvtpd2dqXrm","$movntqMmr||$movntdqXmr", "psubsbPrm","psubswPrm","pminswPrm","porPrm", "paddsbPrm","paddswPrm","pmaxswPrm","pxorPrm", --Fx "|||lddquXrm","psllwPrm","pslldPrm","psllqPrm", "pmuludqPrm","pmaddwdPrm","psadbwPrm","maskmovqMrm||maskmovdquXrm$", "psubbPrm","psubwPrm","psubdPrm","psubqPrm", "paddbPrm","paddwPrm","padddPrm","ud", } assert(map_opc2[255] == "ud") -- Map for three-byte opcodes. Can't wait for their next invention. local map_opc3 = { ["38"] = { -- [66] 0f 38 xx --0x [0]="pshufbPrm","phaddwPrm","phadddPrm","phaddswPrm", "pmaddubswPrm","phsubwPrm","phsubdPrm","phsubswPrm", "psignbPrm","psignwPrm","psigndPrm","pmulhrswPrm", nil,nil,nil,nil, --1x "||pblendvbXrma",nil,nil,nil, "||blendvpsXrma","||blendvpdXrma",nil,"||ptestXrm", nil,nil,nil,nil, "pabsbPrm","pabswPrm","pabsdPrm",nil, --2x "||pmovsxbwXrm","||pmovsxbdXrm","||pmovsxbqXrm","||pmovsxwdXrm", "||pmovsxwqXrm","||pmovsxdqXrm",nil,nil, "||pmuldqXrm","||pcmpeqqXrm","||$movntdqaXrm","||packusdwXrm", nil,nil,nil,nil, --3x "||pmovzxbwXrm","||pmovzxbdXrm","||pmovzxbqXrm","||pmovzxwdXrm", "||pmovzxwqXrm","||pmovzxdqXrm",nil,"||pcmpgtqXrm", "||pminsbXrm","||pminsdXrm","||pminuwXrm","||pminudXrm", "||pmaxsbXrm","||pmaxsdXrm","||pmaxuwXrm","||pmaxudXrm", --4x "||pmulddXrm","||phminposuwXrm", --Fx [0xf0] = "|||crc32TrBmt",[0xf1] = "|||crc32TrVmt", }, ["3a"] = { -- [66] 0f 3a xx --0x [0x00]=nil,nil,nil,nil,nil,nil,nil,nil, "||roundpsXrmu","||roundpdXrmu","||roundssXrmu","||roundsdXrmu", "||blendpsXrmu","||blendpdXrmu","||pblendwXrmu","palignrPrmu", --1x nil,nil,nil,nil, "||pextrbVmXru","||pextrwVmXru","||pextrVmSXru","||extractpsVmXru", nil,nil,nil,nil,nil,nil,nil,nil, --2x "||pinsrbXrVmu","||insertpsXrmu","||pinsrXrVmuS",nil, --4x [0x40] = "||dppsXrmu", [0x41] = "||dppdXrmu", [0x42] = "||mpsadbwXrmu", --6x [0x60] = "||pcmpestrmXrmu",[0x61] = "||pcmpestriXrmu", [0x62] = "||pcmpistrmXrmu",[0x63] = "||pcmpistriXrmu", }, } -- Map for VMX/SVM opcodes 0F 01 C0-FF (sgdt group with register operands). local map_opcvm = { [0xc1]="vmcall",[0xc2]="vmlaunch",[0xc3]="vmresume",[0xc4]="vmxoff", [0xc8]="monitor",[0xc9]="mwait", [0xd8]="vmrun",[0xd9]="vmmcall",[0xda]="vmload",[0xdb]="vmsave", [0xdc]="stgi",[0xdd]="clgi",[0xde]="skinit",[0xdf]="invlpga", [0xf8]="swapgs",[0xf9]="rdtscp", } -- Map for FP opcodes. And you thought stack machines are simple? local map_opcfp = { -- D8-DF 00-BF: opcodes with a memory operand. -- D8 [0]="faddFm","fmulFm","fcomFm","fcompFm","fsubFm","fsubrFm","fdivFm","fdivrFm", "fldFm",nil,"fstFm","fstpFm","fldenvVm","fldcwWm","fnstenvVm","fnstcwWm", -- DA "fiaddDm","fimulDm","ficomDm","ficompDm", "fisubDm","fisubrDm","fidivDm","fidivrDm", -- DB "fildDm","fisttpDm","fistDm","fistpDm",nil,"fld twordFmp",nil,"fstp twordFmp", -- DC "faddGm","fmulGm","fcomGm","fcompGm","fsubGm","fsubrGm","fdivGm","fdivrGm", -- DD "fldGm","fisttpQm","fstGm","fstpGm","frstorDmp",nil,"fnsaveDmp","fnstswWm", -- DE "fiaddWm","fimulWm","ficomWm","ficompWm", "fisubWm","fisubrWm","fidivWm","fidivrWm", -- DF "fildWm","fisttpWm","fistWm","fistpWm", "fbld twordFmp","fildQm","fbstp twordFmp","fistpQm", -- xx C0-FF: opcodes with a pseudo-register operand. -- D8 "faddFf","fmulFf","fcomFf","fcompFf","fsubFf","fsubrFf","fdivFf","fdivrFf", -- D9 "fldFf","fxchFf",{"fnop"},nil, {"fchs","fabs",nil,nil,"ftst","fxam"}, {"fld1","fldl2t","fldl2e","fldpi","fldlg2","fldln2","fldz"}, {"f2xm1","fyl2x","fptan","fpatan","fxtract","fprem1","fdecstp","fincstp"}, {"fprem","fyl2xp1","fsqrt","fsincos","frndint","fscale","fsin","fcos"}, -- DA "fcmovbFf","fcmoveFf","fcmovbeFf","fcmovuFf",nil,{nil,"fucompp"},nil,nil, -- DB "fcmovnbFf","fcmovneFf","fcmovnbeFf","fcmovnuFf", {nil,nil,"fnclex","fninit"},"fucomiFf","fcomiFf",nil, -- DC "fadd toFf","fmul toFf",nil,nil, "fsub toFf","fsubr toFf","fdivr toFf","fdiv toFf", -- DD "ffreeFf",nil,"fstFf","fstpFf","fucomFf","fucompFf",nil,nil, -- DE "faddpFf","fmulpFf",nil,{nil,"fcompp"}, "fsubrpFf","fsubpFf","fdivrpFf","fdivpFf", -- DF nil,nil,nil,nil,{"fnstsw ax"},"fucomipFf","fcomipFf",nil, } assert(map_opcfp[126] == "fcomipFf") -- Map for opcode groups. The subkey is sp from the ModRM byte. local map_opcgroup = { arith = { "add", "or", "adc", "sbb", "and", "sub", "xor", "cmp" }, shift = { "rol", "ror", "rcl", "rcr", "shl", "shr", "sal", "sar" }, testb = { "testBmi", "testBmi", "not", "neg", "mul", "imul", "div", "idiv" }, testv = { "testVmi", "testVmi", "not", "neg", "mul", "imul", "div", "idiv" }, incb = { "inc", "dec" }, incd = { "inc", "dec", "callUmp", "$call farDmp", "jmpUmp", "$jmp farDmp", "pushUm" }, sldt = { "sldt", "str", "lldt", "ltr", "verr", "verw" }, sgdt = { "vm*$sgdt", "vm*$sidt", "$lgdt", "vm*$lidt", "smsw", nil, "lmsw", "vm*$invlpg" }, bt = { nil, nil, nil, nil, "bt", "bts", "btr", "btc" }, cmpxchg = { nil, "sz*,cmpxchg8bQmp,cmpxchg16bXmp", nil, nil, nil, nil, "vmptrld|vmxon|vmclear", "vmptrst" }, pshiftw = { nil, nil, "psrlw", nil, "psraw", nil, "psllw" }, pshiftd = { nil, nil, "psrld", nil, "psrad", nil, "pslld" }, pshiftq = { nil, nil, "psrlq", nil, nil, nil, "psllq" }, pshiftdq = { nil, nil, "psrlq", "psrldq", nil, nil, "psllq", "pslldq" }, fxsave = { "$fxsave", "$fxrstor", "$ldmxcsr", "$stmxcsr", nil, "lfenceDp$", "mfenceDp$", "sfenceDp$clflush" }, prefetch = { "prefetch", "prefetchw" }, prefetcht = { "prefetchnta", "prefetcht0", "prefetcht1", "prefetcht2" }, } ------------------------------------------------------------------------------ -- Maps for register names. local map_regs = { B = { "al", "cl", "dl", "bl", "ah", "ch", "dh", "bh", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, B64 = { "al", "cl", "dl", "bl", "spl", "bpl", "sil", "dil", "r8b", "r9b", "r10b", "r11b", "r12b", "r13b", "r14b", "r15b" }, W = { "ax", "cx", "dx", "bx", "sp", "bp", "si", "di", "r8w", "r9w", "r10w", "r11w", "r12w", "r13w", "r14w", "r15w" }, D = { "eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi", "r8d", "r9d", "r10d", "r11d", "r12d", "r13d", "r14d", "r15d" }, Q = { "rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi", "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15" }, M = { "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7", "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7" }, -- No x64 ext! X = { "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7", "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15" }, } local map_segregs = { "es", "cs", "ss", "ds", "fs", "gs", "segr6", "segr7" } -- Maps for size names. local map_sz2n = { B = 1, W = 2, D = 4, Q = 8, M = 8, X = 16, } local map_sz2prefix = { B = "byte", W = "word", D = "dword", Q = "qword", M = "qword", X = "xword", F = "dword", G = "qword", -- No need for sizes/register names for these two. } ------------------------------------------------------------------------------ -- Output a nicely formatted line with an opcode and operands. local function putop(ctx, text, operands) local code, pos, hex = ctx.code, ctx.pos, "" local hmax = ctx.hexdump if hmax > 0 then for i=ctx.start,pos-1 do hex = hex..format("%02X", byte(code, i, i)) end if #hex > hmax then hex = sub(hex, 1, hmax)..". " else hex = hex..rep(" ", hmax-#hex+2) end end if operands then text = text.." "..operands end if ctx.o16 then text = "o16 "..text; ctx.o16 = false end if ctx.a32 then text = "a32 "..text; ctx.a32 = false end if ctx.rep then text = ctx.rep.." "..text; ctx.rep = false end if ctx.rex then local t = (ctx.rexw and "w" or "")..(ctx.rexr and "r" or "").. (ctx.rexx and "x" or "")..(ctx.rexb and "b" or "") if t ~= "" then text = "rex."..t.." "..text end ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false end if ctx.seg then local text2, n = gsub(text, "%[", "["..ctx.seg..":") if n == 0 then text = ctx.seg.." "..text else text = text2 end ctx.seg = false end if ctx.lock then text = "lock "..text; ctx.lock = false end local imm = ctx.imm if imm then local sym = ctx.symtab[imm] if sym then text = text.."\t->"..sym end end ctx.out(format("%08x %s%s\n", ctx.addr+ctx.start, hex, text)) ctx.mrm = false ctx.start = pos ctx.imm = nil end -- Clear all prefix flags. local function clearprefixes(ctx) ctx.o16 = false; ctx.seg = false; ctx.lock = false; ctx.rep = false ctx.rexw = false; ctx.rexr = false; ctx.rexx = false; ctx.rexb = false ctx.rex = false; ctx.a32 = false end -- Fallback for incomplete opcodes at the end. local function incomplete(ctx) ctx.pos = ctx.stop+1 clearprefixes(ctx) return putop(ctx, "(incomplete)") end -- Fallback for unknown opcodes. local function unknown(ctx) clearprefixes(ctx) return putop(ctx, "(unknown)") end -- Return an immediate of the specified size. local function getimm(ctx, pos, n) if pos+n-1 > ctx.stop then return incomplete(ctx) end local code = ctx.code if n == 1 then local b1 = byte(code, pos, pos) return b1 elseif n == 2 then local b1, b2 = byte(code, pos, pos+1) return b1+b2*256 else local b1, b2, b3, b4 = byte(code, pos, pos+3) local imm = b1+b2*256+b3*65536+b4*16777216 ctx.imm = imm return imm end end -- Process pattern string and generate the operands. local function putpat(ctx, name, pat) local operands, regs, sz, mode, sp, rm, sc, rx, sdisp local code, pos, stop = ctx.code, ctx.pos, ctx.stop -- Chars used: 1DFGIMPQRSTUVWXacdfgijmoprstuwxyz for p in gmatch(pat, ".") do local x = nil if p == "V" or p == "U" then if ctx.rexw then sz = "Q"; ctx.rexw = false elseif ctx.o16 then sz = "W"; ctx.o16 = false elseif p == "U" and ctx.x64 then sz = "Q" else sz = "D" end regs = map_regs[sz] elseif p == "T" then if ctx.rexw then sz = "Q"; ctx.rexw = false else sz = "D" end regs = map_regs[sz] elseif p == "B" then sz = "B" regs = ctx.rex and map_regs.B64 or map_regs.B elseif match(p, "[WDQMXFG]") then sz = p regs = map_regs[sz] elseif p == "P" then sz = ctx.o16 and "X" or "M"; ctx.o16 = false regs = map_regs[sz] elseif p == "S" then name = name..lower(sz) elseif p == "s" then local imm = getimm(ctx, pos, 1); if not imm then return end x = imm <= 127 and format("+0x%02x", imm) or format("-0x%02x", 256-imm) pos = pos+1 elseif p == "u" then local imm = getimm(ctx, pos, 1); if not imm then return end x = format("0x%02x", imm) pos = pos+1 elseif p == "w" then local imm = getimm(ctx, pos, 2); if not imm then return end x = format("0x%x", imm) pos = pos+2 elseif p == "o" then -- [offset] if ctx.x64 then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("[0x%08x%08x]", imm2, imm1) pos = pos+8 else local imm = getimm(ctx, pos, 4); if not imm then return end x = format("[0x%08x]", imm) pos = pos+4 end elseif p == "i" or p == "I" then local n = map_sz2n[sz] if n == 8 and ctx.x64 and p == "I" then local imm1 = getimm(ctx, pos, 4); if not imm1 then return end local imm2 = getimm(ctx, pos+4, 4); if not imm2 then return end x = format("0x%08x%08x", imm2, imm1) else if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "Q" and (imm < 0 or imm > 0x7fffffff) then imm = (0xffffffff+1)-imm x = format(imm > 65535 and "-0x%08x" or "-0x%x", imm) else x = format(imm > 65535 and "0x%08x" or "0x%x", imm) end end pos = pos+n elseif p == "j" then local n = map_sz2n[sz] if n == 8 then n = 4 end local imm = getimm(ctx, pos, n); if not imm then return end if sz == "B" and imm > 127 then imm = imm-256 elseif imm > 2147483647 then imm = imm-4294967296 end pos = pos+n imm = imm + pos + ctx.addr if imm > 4294967295 and not ctx.x64 then imm = imm-4294967296 end ctx.imm = imm if sz == "W" then x = format("word 0x%04x", imm%65536) elseif ctx.x64 then local lo = imm % 0x1000000 x = format("0x%02x%06x", (imm-lo) / 0x1000000, lo) else x = "0x"..tohex(imm) end elseif p == "R" then local r = byte(code, pos-1, pos-1)%8 if ctx.rexb then r = r + 8; ctx.rexb = false end x = regs[r+1] elseif p == "a" then x = regs[1] elseif p == "c" then x = "cl" elseif p == "d" then x = "dx" elseif p == "1" then x = "1" else if not mode then mode = ctx.mrm if not mode then if pos > stop then return incomplete(ctx) end mode = byte(code, pos, pos) pos = pos+1 end rm = mode%8; mode = (mode-rm)/8 sp = mode%8; mode = (mode-sp)/8 sdisp = "" if mode < 3 then if rm == 4 then if pos > stop then return incomplete(ctx) end sc = byte(code, pos, pos) pos = pos+1 rm = sc%8; sc = (sc-rm)/8 rx = sc%8; sc = (sc-rx)/8 if ctx.rexx then rx = rx + 8; ctx.rexx = false end if rx == 4 then rx = nil end end if mode > 0 or rm == 5 then local dsz = mode if dsz ~= 1 then dsz = 4 end local disp = getimm(ctx, pos, dsz); if not disp then return end if mode == 0 then rm = nil end if rm or rx or (not sc and ctx.x64 and not ctx.a32) then if dsz == 1 and disp > 127 then sdisp = format("-0x%x", 256-disp) elseif disp >= 0 and disp <= 0x7fffffff then sdisp = format("+0x%x", disp) else sdisp = format("-0x%x", (0xffffffff+1)-disp) end else sdisp = format(ctx.x64 and not ctx.a32 and not (disp >= 0 and disp <= 0x7fffffff) and "0xffffffff%08x" or "0x%08x", disp) end pos = pos+dsz end end if rm and ctx.rexb then rm = rm + 8; ctx.rexb = false end if ctx.rexr then sp = sp + 8; ctx.rexr = false end end if p == "m" then if mode == 3 then x = regs[rm+1] else local aregs = ctx.a32 and map_regs.D or ctx.aregs local srm, srx = "", "" if rm then srm = aregs[rm+1] elseif not sc and ctx.x64 and not ctx.a32 then srm = "rip" end ctx.a32 = false if rx then if rm then srm = srm.."+" end srx = aregs[rx+1] if sc > 0 then srx = srx.."*"..(2^sc) end end x = format("[%s%s%s]", srm, srx, sdisp) end if mode < 3 and (not match(pat, "[aRrgp]") or match(pat, "t")) then -- Yuck. x = map_sz2prefix[sz].." "..x end elseif p == "r" then x = regs[sp+1] elseif p == "g" then x = map_segregs[sp+1] elseif p == "p" then -- Suppress prefix. elseif p == "f" then x = "st"..rm elseif p == "x" then if sp == 0 and ctx.lock and not ctx.x64 then x = "CR8"; ctx.lock = false else x = "CR"..sp end elseif p == "y" then x = "DR"..sp elseif p == "z" then x = "TR"..sp elseif p == "t" then else error("bad pattern `"..pat.."'") end end if x then operands = operands and operands..", "..x or x end end ctx.pos = pos return putop(ctx, name, operands) end -- Forward declaration. local map_act -- Fetch and cache MRM byte. local function getmrm(ctx) local mrm = ctx.mrm if not mrm then local pos = ctx.pos if pos > ctx.stop then return nil end mrm = byte(ctx.code, pos, pos) ctx.pos = pos+1 ctx.mrm = mrm end return mrm end -- Dispatch to handler depending on pattern. local function dispatch(ctx, opat, patgrp) if not opat then return unknown(ctx) end if match(opat, "%|") then -- MMX/SSE variants depending on prefix. local p if ctx.rep then p = ctx.rep=="rep" and "%|([^%|]*)" or "%|[^%|]*%|[^%|]*%|([^%|]*)" ctx.rep = false elseif ctx.o16 then p = "%|[^%|]*%|([^%|]*)"; ctx.o16 = false else p = "^[^%|]*" end opat = match(opat, p) if not opat then return unknown(ctx) end -- ctx.rep = false; ctx.o16 = false --XXX fails for 66 f2 0f 38 f1 06 crc32 eax,WORD PTR [esi] --XXX remove in branches? end if match(opat, "%$") then -- reg$mem variants. local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end opat = match(opat, mrm >= 192 and "^[^%$]*" or "%$(.*)") if opat == "" then return unknown(ctx) end end if opat == "" then return unknown(ctx) end local name, pat = match(opat, "^([a-z0-9 ]*)(.*)") if pat == "" and patgrp then pat = patgrp end return map_act[sub(pat, 1, 1)](ctx, name, pat) end -- Get a pattern from an opcode map and dispatch to handler. local function dispatchmap(ctx, opcmap) local pos = ctx.pos local opat = opcmap[byte(ctx.code, pos, pos)] pos = pos + 1 ctx.pos = pos return dispatch(ctx, opat) end -- Map for action codes. The key is the first char after the name. map_act = { -- Simple opcodes without operands. [""] = function(ctx, name, pat) return putop(ctx, name) end, -- Operand size chars fall right through. B = putpat, W = putpat, D = putpat, Q = putpat, V = putpat, U = putpat, T = putpat, M = putpat, X = putpat, P = putpat, F = putpat, G = putpat, -- Collect prefixes. [":"] = function(ctx, name, pat) ctx[pat == ":" and name or sub(pat, 2)] = name if ctx.pos - ctx.start > 5 then return unknown(ctx) end -- Limit #prefixes. end, -- Chain to special handler specified by name. ["*"] = function(ctx, name, pat) return map_act[name](ctx, name, sub(pat, 2)) end, -- Use named subtable for opcode group. ["!"] = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end return dispatch(ctx, map_opcgroup[name][((mrm-(mrm%8))/8)%8+1], sub(pat, 2)) end, -- o16,o32[,o64] variants. sz = function(ctx, name, pat) if ctx.o16 then ctx.o16 = false else pat = match(pat, ",(.*)") if ctx.rexw then local p = match(pat, ",(.*)") if p then pat = p; ctx.rexw = false end end end pat = match(pat, "^[^,]*") return dispatch(ctx, pat) end, -- Two-byte opcode dispatch. opc2 = function(ctx, name, pat) return dispatchmap(ctx, map_opc2) end, -- Three-byte opcode dispatch. opc3 = function(ctx, name, pat) return dispatchmap(ctx, map_opc3[pat]) end, -- VMX/SVM dispatch. vm = function(ctx, name, pat) return dispatch(ctx, map_opcvm[ctx.mrm]) end, -- Floating point opcode dispatch. fp = function(ctx, name, pat) local mrm = getmrm(ctx); if not mrm then return incomplete(ctx) end local rm = mrm%8 local idx = pat*8 + ((mrm-rm)/8)%8 if mrm >= 192 then idx = idx + 64 end local opat = map_opcfp[idx] if type(opat) == "table" then opat = opat[rm+1] end return dispatch(ctx, opat) end, -- REX prefix. rex = function(ctx, name, pat) if ctx.rex then return unknown(ctx) end -- Only 1 REX prefix allowed. for p in gmatch(pat, ".") do ctx["rex"..p] = true end ctx.rex = true end, -- Special case for nop with REX prefix. nop = function(ctx, name, pat) return dispatch(ctx, ctx.rex and pat or "nop") end, } ------------------------------------------------------------------------------ -- Disassemble a block of code. local function disass_block(ctx, ofs, len) if not ofs then ofs = 0 end local stop = len and ofs+len or #ctx.code ofs = ofs + 1 ctx.start = ofs ctx.pos = ofs ctx.stop = stop ctx.imm = nil ctx.mrm = false clearprefixes(ctx) while ctx.pos <= stop do dispatchmap(ctx, ctx.map1) end if ctx.pos ~= ctx.start then incomplete(ctx) end end -- Extended API: create a disassembler context. Then call ctx:disass(ofs, len). local function create(code, addr, out) local ctx = {} ctx.code = code ctx.addr = (addr or 0) - 1 ctx.out = out or io.write ctx.symtab = {} ctx.disass = disass_block ctx.hexdump = 16 ctx.x64 = false ctx.map1 = map_opc1_32 ctx.aregs = map_regs.D return ctx end local function create64(code, addr, out) local ctx = create(code, addr, out) ctx.x64 = true ctx.map1 = map_opc1_64 ctx.aregs = map_regs.Q return ctx end -- Simple API: disassemble code (a string) at address and output via out. local function disass(code, addr, out) create(code, addr, out):disass() end local function disass64(code, addr, out) create64(code, addr, out):disass() end -- Return register name for RID. local function regname(r) if r < 8 then return map_regs.D[r+1] end return map_regs.X[r-7] end local function regname64(r) if r < 16 then return map_regs.Q[r+1] end return map_regs.X[r-15] end -- Public module functions. return { create = create, create64 = create64, disass = disass, disass64 = disass64, regname = regname, regname64 = regname64 }
bsd-2-clause
taxler/radish
lua/parse/substitution/charset/cswindows1252.lua
1
1732
local byte = require 'parse.substitution.charset.byte' return byte + { ['\x80'] = '\u{20ac}'; -- euro sign ['\x81'] = require 'parse.substitution.undefined_char'; ['\x82'] = '\u{201a}'; -- single low-9 quotation mark ['\x83'] = '\u{192}'; -- latin small letter f with hook ['\x84'] = '\u{201e}'; -- double low-9 quotation mark ['\x85'] = '\u{2026}'; -- horizontal ellipsis ['\x86'] = '\u{2020}'; -- dagger ['\x87'] = '\u{2021}'; -- double dagger ['\x88'] = '\u{2c6}'; -- modifier letter circumflex accent ['\x89'] = '\u{2030}'; -- per mille sign ['\x8a'] = '\u{160}'; -- latin capital letter s with caron ['\x8b'] = '\u{2039}'; -- single left-pointing angle quotation mark ['\x8c'] = '\u{152}'; -- latin capital ligature oe ['\x8d'] = require 'parse.substitution.undefined_char'; ['\x8e'] = '\u{17d}'; -- latin capital letter z with caron ['\x8f'] = require 'parse.substitution.undefined_char'; ['\x90'] = require 'parse.substitution.undefined_char'; ['\x91'] = '\u{2018}'; -- left single quotation mark ['\x92'] = '\u{2019}'; -- right single quotation mark ['\x93'] = '\u{201c}'; -- left double quotation mark ['\x94'] = '\u{201d}'; -- right double quotation mark ['\x95'] = '\u{2022}'; -- bullet ['\x96'] = '\u{2013}'; -- en dash ['\x97'] = '\u{2014}'; -- em dash ['\x98'] = '\u{2dc}'; -- small tilde ['\x99'] = '\u{2122}'; -- trade mark sign ['\x9a'] = '\u{161}'; -- latin small letter s with caron ['\x9b'] = '\u{203a}'; -- single right-pointing angle quotation mark ['\x9c'] = '\u{153}'; -- latin small ligature oe ['\x9d'] = require 'parse.substitution.undefined_char'; ['\x9e'] = '\u{17e}'; -- latin small letter z with caron ['\x9f'] = '\u{178}'; -- latin capital letter y with diaeresis }
mit
omidtarh/wbot
bot/bot.lua
1
6954
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '0.14.6' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) -- vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) mark_read(receiver, ok_cb, false) end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) -- See plugins/isup.lua as an example for cron _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then print('\27[36mNot valid: Telegram message\27[39m') return false end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "tests", "betoche", "echo", "get", "google", "groupmanager", "help", "images", "img_google", "location", "media", "plugins", "channels", "set", "stats", "time", "version", "weather", "youtube", "media_handler", "moderation"}, sudo_users = {51718050,31639107,128386313}, disabled_channels = {}, moderation = {data = 'data/moderation.json'} } serialize_to_file(config, './data/config.lua') print ('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) --vardump (chat) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 5 mins postpone (cron_plugins, false, 5*60.0) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
scripts/shipskirm.lua
4
4625
--Stupid dumb Bos converted to amazing awesome Lua (see http://packages.springrts.com/bos2lua/index.php) include 'constants.lua' -------------------------------------------------------------------- --pieces -------------------------------------------------------------------- local hull = piece 'hull' local neck = piece 'neck' local turret = piece 'turret' local arml = piece 'arml' local armr = piece 'armr' local flare1 = piece 'flare1' local flare2 = piece 'flare2' local flare3 = piece 'flare3' local flare4 = piece 'flare4' local missile1 = piece 'missile1' local missile2 = piece 'missile2' local missile3 = piece 'missile3' local missile4 = piece 'missile4' local exhaust1 = piece 'exhaust1' local exhaust2 = piece 'exhaust2' local exhaust3 = piece 'exhaust3' local exhaust4 = piece 'exhaust4' local wakel = piece 'wakel' local waker = piece 'waker' local exp1 = piece 'exp1' local exp2 = piece 'exp2' local exp3 = piece 'exp3' local exp4 = piece 'exp4' -------------------------------------------------------------------- --constants -------------------------------------------------------------------- local smokePiece = {hull, turret} -- Signal definitions local SIG_MOVE = 8 --rockz include 'RockPiece.lua' local ROCK_PIECE = hull -- should be negative to alternate rocking direction local ROCK_Z_SPEED = 3 --number of quarter-cycles per second around z-axis local ROCK_Z_DECAY = -1/2 --rocking around z-axis is reduced by this factor each time' local ROCK_Z_MIN = math.rad(3) --if around z-axis rock is not greater than this amount rocking will stop after returning to center local ROCK_Z_MAX = math.rad(15) local SIG_ROCK_Z = 16 --Signal( to prevent multiple rocking local ROCK_Z_FIRE_1 = -5 local ROCK_FORCE = 0.1 -------------------------------------------------------------------- --variables -------------------------------------------------------------------- local gun1 = 0 local restore_delay = 3000 local gun_1_yaw = 0 local dead = false function script.Create() StartThread(SmokeUnit, smokePiece) InitializeRock(ROCK_PIECE, ROCK_Z_SPEED, ROCK_Z_DECAY, ROCK_Z_MIN, ROCK_Z_MAX, SIG_ROCK_Z, z_axis) end local function RestoreAfterDelay() Sleep( restore_delay) if dead then return false end Turn( turret , y_axis, 0, math.rad(35.000000) ) Turn( arml , x_axis, 0, math.rad(20.000000) ) Turn( armr , x_axis, 0, math.rad(20.000000) ) end local function Wake() Signal( SIG_MOVE) SetSignalMask( SIG_MOVE) while true do if not Spring.GetUnitIsCloaked(unitID) then EmitSfx( wakel, 2 ) EmitSfx( waker, 4 ) end Sleep(300) end end function script.StartMoving() StartThread(Wake) end function script.StopMoving() Signal( SIG_MOVE) end function script.AimWeapon(num, heading, pitch) Signal( 2) SetSignalMask( 2) Turn( turret , y_axis, heading, math.rad(70.000000) ) Turn( arml , x_axis, -pitch, math.rad(40.000000) ) Turn( armr , x_axis, -pitch, math.rad(40.000000) ) WaitForTurn(turret, y_axis) WaitForTurn(arml, x_axis) WaitForTurn(armr, x_axis) StartThread(RestoreAfterDelay) gun_1_yaw = heading return (1) end function script.Shot(num) StartThread(Rock, gun_1_yaw, ROCK_FORCE, z_axis) gun1 = gun1 + 1 if gun1 == 4 then gun1 = 0 end if gun1 == 0 then Move( missile1 , z_axis, -4.000000 ) --Sleep( 1500) Move( missile1 , z_axis, 0.000000 , 1.000000 ) end if gun1 == 1 then Move( missile2 , z_axis, -4.000000 ) --Sleep( 1500) Move( missile2 , z_axis, 0.000000 , 1.000000 ) end if gun1 == 2 then Move( missile3 , z_axis, -4.000000 ) --Sleep( 1500) Move( missile3 , z_axis, 0.000000 , 1.000000 ) end if gun1 == 3 then Move( missile4 , z_axis, -4.000000 ) --Sleep( 1500) Move( missile4 , z_axis, 0.000000 , 1.000000 ) end end function script.AimFromWeapon(num) return turret end function script.QueryWeapon(num) if gun1 == 0 then return flare1 end if gun1 == 1 then return flare2 end if gun1 == 2 then return flare3 end if gun1 == 3 then return flare4 end end function script.BlockShot(num, targetID) if GG.OverkillPrevention_CheckBlock(unitID, targetID, 280, 105, false, false, true) then return true end return false end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity <= 0.50 then Explode( turret, sfxShatter) return 1 end Explode( hull, sfxShatter) Explode( neck, sfxShatter) Explode( turret, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) Explode( arml, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) Explode( armr, sfxFall + sfxSmoke + sfxFire + sfxExplodeOnHit) return 2 end
gpl-2.0
TeamFSIModding/FS17_Goweil_LT_Master
src/scripts/hud/hudProgressIcon.lua
1
2703
-- -- HudProgressIcon -- -- @author TyKonKet -- @date 06/04/2017 HudProgressIcon = {}; local HudProgressIcon_mt = Class(HudProgressIcon, Hud); function HudProgressIcon:new(name, overlayFilename, x, y, width, height, parent, custom_mt) if custom_mt == nil then custom_mt = HudProgressIcon_mt; end self.uiScale = g_gameSettings:getValue("uiScale"); width, height = getNormalizedScreenValues(width * self.uiScale, height * self.uiScale); local self = Hud:new(name, x, y, width, height, parent, custom_mt); self.filename = overlayFilename; self.bgOverlayId = 0; self.fgOverlayId = 0; if self.filename ~= nil then self.bgOverlayId = createImageOverlay(self.filename); self.fgOverlayId = createImageOverlay(self.filename); end self.value = 1; return self; end function HudProgressIcon:delete(applyToChilds) if self.bgOverlayId ~= 0 then delete(self.bgOverlayId); self.bgOverlayId = 0; end if self.fgOverlayId ~= 0 then delete(self.fgOverlayId); self.fgOverlayId = 0; end HudProgressIcon:superClass().delete(self, applyToChilds); end function HudProgressIcon:setColor(r, g, b, a, applyToChilds) HudProgressIcon:superClass().setColor(self, r, g, b, a, applyToChilds); if self.fgOverlayId ~= 0 then setOverlayColor(self.fgOverlayId, self.r, self.g, self.b, self.a); end end function HudProgressIcon:setUVs(uvs) if uvs ~= self.uvs then if type(uvs) == "number" then printCallstack(); end self.uvs = uvs; if self.bgOverlayId ~= 0 then setOverlayUVs(self.bgOverlayId, unpack(self.uvs)); end if self.fgOverlayId ~= 0 then setOverlayUVs(self.fgOverlayId, unpack(self.uvs)); end end end function HudProgressIcon:setValue(newValue) if self.value ~= newValue then self.value = newValue; if self.fgOverlayId ~= 0 then local topLeftX = self.uvs[2] + (self.uvs[4] - self.uvs[2]) * self.value; local topRightX = self.uvs[6] + (self.uvs[8] - self.uvs[6]) * self.value; setOverlayUVs(self.fgOverlayId, self.uvs[1], self.uvs[2], self.uvs[3], topLeftX, self.uvs[5], self.uvs[6], self.uvs[7], topRightX); end end end function HudProgressIcon:render() if self.visible then local x, y = self:getRenderPosition(); local w, h = self:getRenderDimension(); if self.bgOverlayId ~= 0 then renderOverlay(self.bgOverlayId, x, y, w, h); end if self.fgOverlayId ~= 0 then renderOverlay(self.fgOverlayId, x, y, w, h * self.value); end end end
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/Kaede.lua
14
2546
----------------------------------- -- Area: Port Bastok -- NPC: Kaede -- Start Quest: Ayame and Kaede -- Involved in Quests: Riding on the Clouds -- @pos 48 -6 67 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 4) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ayameKaede = player:getQuestStatus(BASTOK,AYAME_AND_KAEDE); local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,0) == false) then player:startEvent(0x0160); elseif (ayameKaede == QUEST_AVAILABLE and player:getMainLvl() >= 30) then player:startEvent(0x00f0); elseif (ayameKaede == QUEST_ACCEPTED) then player:startEvent(0x001a); elseif (ayameKaede == QUEST_COMPLETED) then player:startEvent(0x00f8); else player:startEvent(0x001a); 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 == 0x00f0) then if (player:getQuestStatus(BASTOK,AYAME_AND_KAEDE) == QUEST_AVAILABLE) then player:addQuest(BASTOK,AYAME_AND_KAEDE); end elseif (csid == 0x0160) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",0,true); end end;
gpl-3.0
PaulBatchelor/Soundpipe
modules/data/delay.lua
4
1145
sptbl["delay"] = { files = { module = "delay.c", header = "delay.h", example = "ex_delay.c", }, func = { create = "sp_delay_create", destroy = "sp_delay_destroy", init = "sp_delay_init", compute = "sp_delay_compute", }, params = { mandatory = { { name = "time", type = "SPFLOAT", description = "Delay time, in seconds.", default = 1.0 } }, optional = { { name = "feedback", type = "SPFLOAT", description = "Feedback amount. Should be a value between 0-1.", default = 0.0 } } }, modtype = "module", description = [[Adds a delay to an incoming signal with optional feedback.]], ninputs = 1, noutputs = 1, inputs = { { name = "input", description = "Signal input." }, }, outputs = { { name = "out", description = "Signal output." }, } }
mit
Scavenge/darkstar
scripts/zones/Castle_Oztroja/npcs/_47c.lua
14
2120
----------------------------------- -- Area: Castle Oztroja -- NPC: _47c (Handle) -- Notes: Opens Trap Door (_47a) or Brass Door (_470) -- @pos 17.717 -1.087 -14.320 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local X = player:getXPos(); local Z = player:getZPos(); local BrassDoor = npc:getID() - 3; local TrapDoor = npc:getID() - 2; local BrassA = GetNPCByID(BrassDoor):getAnimation(); local TrapA = GetNPCByID(TrapDoor):getAnimation(); if (X < 21.6 and X > 18 and Z > -15.6 and Z < -12.4) then if (VanadielDayOfTheYear() % 2 == 0) then if (BrassA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- wait 1 second delay goes here GetNPCByID(BrassDoor):openDoor(6); end else if (TrapA == 9 and npc:getAnimation() == 9) then npc:openDoor(8); -- wait 1 second delay goes here GetNPCByID(TrapDoor):openDoor(6); end if (player:getCurrentMission(WINDURST) == TO_EACH_HIS_OWN_RIGHT and player:getVar("MissionStatus") == 3) then player:startEvent(0x002B); end end else player:messageSpecial(0); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002B) then player:setVar("MissionStatus",4); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Behemoths_Dominion/npcs/Field_Manual.lua
29
1051
----------------------------------- -- Field Manual -- Area: Behemoth's Dominion ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/fieldsofvalor"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startFov(FOV_EVENT_BEHEMOTH,player); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,menuchoice) updateFov(player,csid,menuchoice,101,102,103,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) finishFov(player,csid,option,101,102,103,0,0,FOV_MSG_BEHEMOTH); end;
gpl-3.0
Kyklas/luci-proto-hso
applications/luci-pbx/luasrc/controller/pbx.lua
144
1448
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- module("luci.controller.pbx", package.seeall) function index() entry({"admin", "services", "pbx"}, cbi("pbx"), "PBX", 80) entry({"admin", "services", "pbx", "pbx-google"}, cbi("pbx-google"), "Google Accounts", 1) entry({"admin", "services", "pbx", "pbx-voip"}, cbi("pbx-voip"), "SIP Accounts", 2) entry({"admin", "services", "pbx", "pbx-users"}, cbi("pbx-users"), "User Accounts", 3) entry({"admin", "services", "pbx", "pbx-calls"}, cbi("pbx-calls"), "Call Routing", 4) entry({"admin", "services", "pbx", "pbx-advanced"}, cbi("pbx-advanced"), "Advanced Settings", 6) end
apache-2.0
Scavenge/darkstar
scripts/globals/effects/dark_arts.lua
65
2045
----------------------------------- -- -- -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:addMod(MOD_BLACK_MAGIC_COST, -bonus); target:addMod(MOD_BLACK_MAGIC_CAST, -bonus); target:addMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:addMod(MOD_BLACK_MAGIC_COST, -10); target:addMod(MOD_BLACK_MAGIC_CAST, -10); target:addMod(MOD_BLACK_MAGIC_RECAST, -10); target:addMod(MOD_WHITE_MAGIC_COST, 20); target:addMod(MOD_WHITE_MAGIC_CAST, 20); target:addMod(MOD_WHITE_MAGIC_RECAST, 20); target:addMod(MOD_HELIX_EFFECT, helix); target:addMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:recalculateAbilitiesTable(); local bonus = effect:getPower(); local helix = effect:getSubPower(); target:delMod(MOD_BLACK_MAGIC_COST, -bonus); target:delMod(MOD_BLACK_MAGIC_CAST, -bonus); target:delMod(MOD_BLACK_MAGIC_RECAST, -bonus); if not (target:hasStatusEffect(EFFECT_TABULA_RASA)) then target:delMod(MOD_BLACK_MAGIC_COST, -10); target:delMod(MOD_BLACK_MAGIC_CAST, -10); target:delMod(MOD_BLACK_MAGIC_RECAST, -10); target:delMod(MOD_WHITE_MAGIC_COST, 20); target:delMod(MOD_WHITE_MAGIC_CAST, 20); target:delMod(MOD_WHITE_MAGIC_RECAST, 20); target:delMod(MOD_HELIX_EFFECT, helix); target:delMod(MOD_HELIX_DURATION, 72); end target:recalculateSkillsTable(); end;
gpl-3.0
jnsbl/dotfiles
neovim/lua/plugins/init.lua
1
2505
vim.cmd [[packadd packer.nvim]] require("packer").startup(function(use) use "savq/paq-nvim" -- Let Packer manage itself -- Appearance use "bradcush/base16-nvim" use "RRethy/nvim-base16" use "kyazdani42/nvim-web-devicons" use "nvim-lualine/lualine.nvim" use "goolord/alpha-nvim" use "lukas-reineke/indent-blankline.nvim" use "kevinhwang91/nvim-bqf" -- Utilities use "nvim-lua/plenary.nvim" use "famiu/bufdelete.nvim" use "jghauser/mkdir.nvim" use "nkakouros-original/numbers.nvim" use "norcalli/nvim-colorizer.lua" -- use "gennaro-tedesco/nvim-peekup" use "numToStr/Comment.nvim" use {"phaazon/hop.nvim", branch = "v2"} use "nacro90/numb.nvim" use "lewis6991/gitsigns.nvim" use "nvim-lua/popup.nvim" use "MunifTanjim/nui.nvim" use "vim-scripts/ReplaceWithRegister" use "kyazdani42/nvim-tree.lua" -- Syntax use {"nvim-treesitter/nvim-treesitter", run = ":TSUpdate"} use "kylechui/nvim-surround" use "m-demare/hlargs.nvim" use "dag/vim-fish" -- Language support use {"roxma/nvim-yarp", { run = "pip install -r requirements.txt" }} -- Fuzzy-finding and searching use "BurntSushi/ripgrep" use {"nvim-telescope/telescope.nvim", branch = "0.1.x"} use "jvgrootveld/telescope-zoxide" use "gelguy/wilder.nvim" use "kevinhwang91/nvim-hlslens" -- File-type specific use "ellisonleao/glow.nvim" -- LSP use "williamboman/mason.nvim" use "williamboman/mason-lspconfig.nvim" use "neovim/nvim-lspconfig" -- Code completion and snippets use "hrsh7th/cmp-nvim-lsp" use "hrsh7th/cmp-buffer" use "hrsh7th/cmp-path" use "hrsh7th/cmp-cmdline" use "L3MON4D3/LuaSnip" use "saadparwaiz1/cmp_luasnip" use "hrsh7th/nvim-cmp" end) -- Appearance require("plugins.base16-nvim") require("plugins.nvim-base16") require("plugins.nvim-web-devicons") require("plugins.lualine-nvim") require("plugins.alpha-nvim") require("plugins.indent-blankline-nvim") -- Utilities require("plugins.numbers-nvim") require("plugins.nvim-colorizer") require("plugins.comment-nvim") require("plugins.hop-nvim") require("plugins.numb-nvim") require("plugins.gitsigns-nvim") require("plugins.nvim-tree") -- Syntax require("plugins.nvim-surround") require("plugins.hlargs-nvim") -- Fuzzy-finding and searching require("plugins.telescope-nvim") require("plugins.wilder-nvim") -- File-type specific require("plugins.glow-nvim") -- LSP require("plugins.lsp-mason-nvim") -- Code completion and snippets require("plugins.nvim-cmp")
unlicense
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/unit_paralysis_damage.lua
4
2516
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Paralysis", desc = "Handels paralysis system and adds extra_damage to lightning weapons", author = "Google Frog", date = "Apr, 2010", license = "GNU GPL, v2 or later", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (not gadgetHandler:IsSyncedCode()) then return false -- no unsynced code end local spGetUnitHealth = Spring.GetUnitHealth local spSetUnitHealth = Spring.SetUnitHealth local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitIsStunned = Spring.GetUnitIsStunned local spGetUnitArmored = Spring.GetUnitArmored local spAddUnitDamage = Spring.AddUnitDamage local normalDamageMult = {} local wantedWeaponList = {} for wdid = 1, #WeaponDefs do local wd = WeaponDefs[wdid] if wd.paralyzer then local rawDamage = tonumber(wd.customParams.raw_damage or 0) if wd.customParams and wd.customParams.extra_damage and rawDamage > 0 then normalDamageMult[wdid] = wd.customParams.extra_damage/rawDamage end wantedWeaponList[#wantedWeaponList + 1] = wdid end end function gadget:UnitPreDamaged_GetWantedWeaponDef() return wantedWeaponList end function gadget:UnitDamaged_GetWantedWeaponDef() return wantedWeaponList end local already_stunned = false function gadget:UnitPreDamaged(unitID, unitDefID, unitTeam, damage, paralyzer, weaponDefID, attackerID, attackerDefID, attackerTeam) if paralyzer then -- the weapon deals paralysis damage already_stunned = spGetUnitIsStunned(unitID) local health, maxHealth = spGetUnitHealth(unitID) if normalDamageMult[weaponDefID] then attackerID = attackerID or -1 local damageMult = normalDamageMult[weaponDefID] -- Don't apply armour twice local armored, mult = spGetUnitArmored(unitID) if armored then damageMult = damageMult/mult end -- be careful; this line can cause recursion! don't make it do paralyzer damage spAddUnitDamage(unitID, damageMult*damage, 0, attackerID, weaponDefID) end if health and maxHealth and health ~= 0 then -- taking no chances. return damage*maxHealth/health end end return damage end
gpl-2.0
Arashbrsh/lifemaic
plugins/invite.lua
15
1046
-- Invite other user to the chat group. -- Use !invite name User_name or !invite id id_number -- The User_name is the print_name (there are no spaces but _) do local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg, matches) local user = matches[2] -- User submitted a user name if matches[1] == "name" then user = string.gsub(user," ","_") end -- User submitted an id if matches[1] == "id" then user = 'user#id'..user end -- The message must come from a chat group if msg.to.type == 'chat' then local chat = 'chat#id'..msg.to.id chat_add_user(chat, user, callback, false) return "Add: "..user.." to "..chat else return 'This isnt a chat group!' end end return { description = "Invite other user to the chat group", usage = { "!invite name [user_name]", "!invite id [user_id]" }, patterns = { "^!invite (id) (%d+)$" "^/invite (id) (%d+)$" "^!invite (%d+)$" }, run = run, moderation = true } end
gpl-2.0
lordporya1/6985
plugins/autoleave.lua
125
1025
--[[ Kicking ourself (bot) from unmanaged groups. When someone invited this bot to a group, the bot then will chek if the group is in its moderations (moderation.json). If not, the bot will exit immediately by kicking itself out of that group. No switch available. You need to turn it on or off using !plugins command. Testing needed. --]] -- suppress '*** lua: attempt to call a nil value' warning local function callback(extra, success, result) vardump(success) vardump(result) end local function run(msg) if msg.service and msg.action.type == 'chat_add_user' then local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)] then print "This is not our group. Leaving..." chat_del_user('chat#id'..msg.to.id, 'user#id'..our_id, callback, false) end end end return { description = "Kicking ourself (bot) from unmanaged groups.", usage = "No switch available. Turn it on or off using !plugins command.", patterns = { "^!!tgservice (.+)$" }, run = run }
gpl-2.0
opencpe/mand
mand/tests/nonunique_index_stresstest.lua
2
2083
require "libluadmconfig" require "luaevent.core" -- open configure session evctx = luaevent.core.new() rc, session = dmconfig.init(evctx) if rc ~= dmconfig.r_ok then error("Couldn't initiate session object or establish a connection to the server") end print "Initiating the session object was successful" if session:start(nil, 20, dmconfig.s_readwrite) ~= dmconfig.r_ok then error("Couldn't start session") end print "Session started successfully." local CNATIPS = 20 local INSLIMIT = 5 local NATIPs = {} math.randomseed(1) for i = 1, CNATIPS do table.insert(NATIPs, { IP = string.format("%d.%d.%d.%d", math.random(1,254), math.random(0,254), math.random(0,254), math.random(1,254)), inst = {} }) print(NATIPs[#NATIPs].IP) end print "----" local path = "InternetGatewayDevice.X_TPLINO_NET_SessionControl.Zone" rc, instance = session:add(path) if rc ~= dmconfig.r_ok then error("add zone") end path = path.."."..instance..".Clients.Client" for i = 1, 1000 do local nat = NATIPs[math.random(1,#NATIPs)] if #nat.inst == INSLIMIT then for i = 1, math.random(1, INSLIMIT) do local ind = math.random(1, #nat.inst) print("DEL", nat.inst[ind], nat.IP) rc = session:delete(path.."."..nat.inst[ind]) if rc ~= dmconfig.r_ok then error("remove client") end table.remove(nat.inst, ind) print("INST", unpack(nat.inst)) end else rc, instance = session:add(path) if rc ~= dmconfig.r_ok then error("add client") end print("ADD", instance, nat.IP) rc = session:set{ {dmconfig.t_address, path.."."..instance..".NATIPAddress", nat.IP} } if rc ~= dmconfig.r_ok then error("set client nat ip") end if next(nat.inst) then table.insert(nat.inst, 2, instance) else table.insert(nat.inst, instance) end print("INST", unpack(nat.inst)) end end if session:terminate() ~= dmconfig.r_ok then error("Couldn't close session") end print "Session closed successfully" if session:shutdown() ~= dmconfig.r_ok then error("Couldn't shutdown the server connection") end print "Shutting down the server connection was successful"
mpl-2.0
Scavenge/darkstar
scripts/globals/spells/bluemagic/saline_coat.lua
26
1336
----------------------------------------- -- Spell: Saline Coat -- Enhances magic defense -- Spell cost: 66 MP -- Monster Type: Luminians -- Spell Type: Magical (Light) -- Blue Magic Points: 3 -- Stat Bonus: VIT+2, AGI+2, MP+10 -- Level: 72 -- Casting Time: 3 seconds -- Recast Time: 60 seconds -- Duration: 60 seconds -- -- Combos: Defense Bonus ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_MAGIC_DEF_BOOST; local power = 40; local duration = 60; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Mount_Zhayolm/npcs/Runic_Portal.lua
24
1758
----------------------------------- -- Area: Mount Zhayolm -- NPC: Runic Portal -- Mount Zhayolm Teleporter Back to Aht Urgan Whitegate -- @pos 688 -23 349 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); require("scripts/globals/teleports"); require("scripts/globals/besieged"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(TOAU) == IMMORTAL_SENTRIES and player:getVar("AhtUrganStatus") == 1) then player:startEvent(111); elseif (player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then if (hasRunicPortal(player,4) == 1) then player:startEvent(109); else player:startEvent(111); end else player:messageSpecial(RESPONSE); 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 == 111 and option == 1) then player:addNationTeleport(AHTURHGAN,16); toChamberOfPassage(player); elseif (csid == 109 and option == 1) then toChamberOfPassage(player); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Upper_Jeuno/npcs/Zekobi-Morokobi.lua
14
1051
----------------------------------- -- Area: Upper Jeuno -- NPC: Zekobi-Morokobi -- Type: Standard NPC -- @zone 244 -- @pos 41.258 -5.999 -74.105 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0057); 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
Scavenge/darkstar
scripts/zones/Abyssea-Vunkerl/npcs/qm1.lua
5
1346
----------------------------------- -- Zone: Abyssea-Vunkerl -- NPC: qm1 (???) -- Spawns Khalkotaur -- @pos ? ? ? 217 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(3098,1) and trade:getItemCount() == 1) then -- Player has all the required items. if (GetMobAction(17666487) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(17666487):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 3098); -- Inform player what items they need. 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
Scavenge/darkstar
scripts/globals/items/deep-fried_shrimp_+1.lua
12
1689
----------------------------------------- -- ID: 6277 -- Item: deep-fried_shrimp -- Food Effect: 60Min, All Races ----------------------------------------- -- VIT +4 -- Fire resistance +21 -- Accuracy +21% (cap 75) -- Ranged Accuracy +21% (cap 75) -- Subtle Blow +9 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,6277); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 4); target:addMod(MOD_FIRERES, 21); target:addMod(MOD_FOOD_ACCP, 21); target:addMod(MOD_FOOD_ACC_CAP, 75); target:addMod(MOD_FOOD_RACCP, 21); target:addMod(MOD_FOOD_RACC_CAP, 75); target:addMod(MOD_SUBTLE_BLOW, 9); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 4); target:delMod(MOD_FIRERES, 21); target:delMod(MOD_FOOD_ACCP, 21); target:delMod(MOD_FOOD_ACC_CAP, 75); target:delMod(MOD_FOOD_RACCP, 21); target:delMod(MOD_FOOD_RACC_CAP, 75); target:delMod(MOD_SUBTLE_BLOW, 9); end;
gpl-3.0
Tkachov/scummvm
devtools/create_ultima/files/ultima6/scripts/u6/magic/circle_07/chain_bolt.lua
18
1582
local caster = magic_get_caster() local actor = select_actor_with_projectile(0x188, caster) if actor == nil then return end local random = math.random local exp = actor_hit(actor, random(1, 0x1e)) if exp ~= 0 then caster.exp = caster.exp + exp end actor_yell_for_help(caster, actor, 1) actor_hit_msg(actor) local i,j for i=0,6 do if g_avatar_died == true then break -- don't keep casting once Avatar is dead end local var_c = 32769 local new_target = nil for j=1,0xff do local tmp_actor = Actor.get(j) if tmp_actor.obj_n ~= 0 and tmp_actor.alive == true and tmp_actor.actor_num ~= actor.actor_num and actor_ok_to_attack(actor, tmp_actor) == true then local target_x = tmp_actor.x local target_y = tmp_actor.y if tmp_actor.z == caster.z and target_x > caster.x - 5 and target_x < caster.x + 5 and target_y > caster.y - 5 and target_y < caster.y + 5 then local val = (target_x - actor.x) * (target_x - actor.x) + (target_y - actor.y) * (target_y - actor.y) dbg("and here val = "..val.."\n") if val > 0 then if val <= var_c then if val == var_c then if random(0, 1) == 0 then new_target = tmp_actor end else var_c = val new_target = tmp_actor end end end end end end if new_target == nil then break end projectile(0x188, actor.x, actor.y, new_target.x, new_target.y, 2, 0) actor = new_target local exp = actor_hit(actor, random(1, 0x1e)) if exp ~= 0 then caster.exp = caster.exp + exp end actor_yell_for_help(caster, actor, 1) actor_hit_msg(actor) end
gpl-3.0
Youka/NyuFX
templates/Fun/3D_cube.lua
2
2434
-- Cube rectangles local cube = {nil, nil, nil, nil, nil, nil} -- Front rectangle (frontface has points clockwise; 1 pixel overhang to fill gaps) cube[1] = { {-101, -101, 100}, {101, -101, 100}, {101, 101, 100}, {-101, 101, 100} } -- Back rectangle cube[2] = { math.rotate(cube[1][1], "y", 180), math.rotate(cube[1][2], "y", 180), math.rotate(cube[1][3], "y", 180), math.rotate(cube[1][4], "y", 180) } -- Left rectangle cube[3] = { math.rotate(cube[1][1], "y", -90), math.rotate(cube[1][2], "y", -90), math.rotate(cube[1][3], "y", -90), math.rotate(cube[1][4], "y", -90) } -- Right rectangle cube[4] = { math.rotate(cube[1][1], "y", 90), math.rotate(cube[1][2], "y", 90), math.rotate(cube[1][3], "y", 90), math.rotate(cube[1][4], "y", 90) } -- Top rectangle cube[5] = { math.rotate(cube[1][1], "x", 90), math.rotate(cube[1][2], "x", 90), math.rotate(cube[1][3], "x", 90), math.rotate(cube[1][4], "x", 90) } -- Bottom rectangle cube[6] = { math.rotate(cube[1][1], "x", -90), math.rotate(cube[1][2], "x", -90), math.rotate(cube[1][3], "x", -90), math.rotate(cube[1][4], "x", -90) } -- Frame-wise cube building (30s, 25 FPS) local line = lines[1] for s, e, i, n in utils.frames(0, 30000, 40) do line.start_time = s line.end_time = e -- Define rotations local x_rotation = i/n * 720 local y_rotation = i/n * 540 local z_rotation = i/n * 360 -- Iterate through cube rectangles (copy) for rect_i, rect in ipairs(table.copy(cube)) do -- Rotate rectangle points for point_i = 1, #rect do rect[point_i] = math.rotate(math.rotate(math.rotate(rect[point_i], "x", x_rotation), "y", y_rotation), "z", z_rotation) end -- Calculate rectangle orthogonal vector local ortho = math.ortho({rect[2][1] - rect[1][1], rect[2][2] - rect[1][2], rect[2][3] - rect[1][3]}, {rect[4][1] - rect[1][1], rect[4][2] - rect[1][2], rect[4][3] - rect[1][3]}) -- Further process only for visible frontface if ortho[3] > 0 then -- Calculate degree light direction <-> rectangle (fixed to 0-90 degree) local deg = math.trim(math.abs(math.degree(ortho, {0, -0.5, 1})), 0, 90) -- Create rectangle dialog line line.text = string.format("{\\an7\\pos(300,200)\\bord0\\1c%s\\p1}m %d %d l %d %d %d %d %d %d" , utils.interpolate(deg / 90, "&HFFFFFF&", "&H000000&") , rect[1][1], rect[1][2], rect[2][1], rect[2][2], rect[3][1], rect[3][2], rect[4][1], rect[4][2]) io.write_line(line) end end end
lgpl-3.0
smanolache/kong
spec/plugins/jwt/hooks_spec.lua
1
5589
local json = require "cjson" local http_client = require "kong.tools.http_client" local spec_helper = require "spec.spec_helpers" local cache = require "kong.tools.database_cache" local jwt_encoder = require "kong.plugins.jwt.jwt_parser" local STUB_GET_URL = spec_helper.STUB_GET_URL local API_URL = spec_helper.API_URL describe("JWT Authentication Hooks", function() setup(function() spec_helper.prepare_db() end) teardown(function() spec_helper.stop_kong() end) before_each(function() spec_helper.restart_kong() spec_helper.drop_db() spec_helper.insert_fixtures { api = { {request_host = "jwt.com", upstream_url = "http://mockbin.com"} }, consumer = { {username = "consumer1"} }, plugin = { {name = "jwt", config = {}, __api = 1} }, jwt_secret = { {key = "key123", secret = "secret123", __consumer = 1} } } end) local PAYLOAD = { iss = nil, nbf = os.time(), iat = os.time(), exp = os.time() + 3600 } local function get_authorization(key, secret) PAYLOAD.iss = key local jwt = jwt_encoder.encode(PAYLOAD, secret) return "Bearer "..jwt end describe("JWT Credentials entity invalidation", function() it("should invalidate when JWT Auth Credential entity is deleted", function() -- It should work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(200, status) -- Check that cache is populated local cache_key = cache.jwtauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Retrieve credential ID local response, status = http_client.get(API_URL.."/consumers/consumer1/jwt/") assert.equals(200, status) local credential_id = json.decode(response).data[1].id assert.truthy(credential_id) -- Delete JWT credential (which triggers invalidation) local _, status = http_client.delete(API_URL.."/consumers/consumer1/jwt/"..credential_id) assert.equals(204, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should not work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(403, status) end) it("should invalidate when JWT Auth Credential entity is updated", function() -- It should work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(200, status) -- It should not work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("keyhello", "secret123")}) assert.equal(403, status) -- Check that cache is populated local cache_key = cache.jwtauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Retrieve credential ID local response, status = http_client.get(API_URL.."/consumers/consumer1/jwt/") assert.equals(200, status) local credential_id = json.decode(response).data[1].id assert.truthy(credential_id) -- Delete JWT credential (which triggers invalidation) local _, status = http_client.patch(API_URL.."/consumers/consumer1/jwt/"..credential_id, {key="keyhello"}) assert.equals(200, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("keyhello", "secret123")}) assert.equal(200, status) -- It should not work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(403, status) end) end) describe("Consumer entity invalidation", function() it("should invalidate when Consumer entity is deleted", function() -- It should work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(200, status) -- Check that cache is populated local cache_key = cache.jwtauth_credential_key("key123") local _, status = http_client.get(API_URL.."/cache/"..cache_key) assert.equals(200, status) -- Delete Consumer (which triggers invalidation) local _, status = http_client.delete(API_URL.."/consumers/consumer1") assert.equals(204, status) -- Wait for cache to be invalidated local exists = true while(exists) do local _, status = http_client.get(API_URL.."/cache/"..cache_key) if status ~= 200 then exists = false end end -- It should not work local _, status = http_client.get(STUB_GET_URL, nil, {host = "jwt.com", authorization = get_authorization("key123", "secret123")}) assert.equal(403, status) end) end) end)
apache-2.0
Scavenge/darkstar
scripts/zones/Apollyon/mobs/Gorynich.lua
17
1531
----------------------------------- -- Area: Apollyon NW -- NPC: Kaiser Behemoth ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16932977) then -- recover GetNPCByID(16932864+179):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+179):setStatus(STATUS_NORMAL); elseif (mobID ==16932978) then -- timer 1 GetNPCByID(16932864+262):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+262):setStatus(STATUS_NORMAL); elseif (mobID ==16932980) then -- timer 2 GetNPCByID(16932864+97):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+97):setStatus(STATUS_NORMAL); elseif (mobID ==16932981) then -- timer 3 GetNPCByID(16932864+98):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+98):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/The_Eldieme_Necropolis_[S]/npcs/Turbulent_Storm.lua
29
1838
----------------------------------- -- Area: The Eldieme Necropolis [S] -- NPC: Turbulent Storm -- Note: Starts Quest "The Fighting Fourth" -- @pos 422.461 -48.000 175 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCampaignAllegiance() > 0) then if (player:getCampaignAllegiance() == 2) then player:startEvent(9); else -- message for other nations missing player:startEvent(9); end elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == true) then player:startEvent(8); elseif (player:hasKeyItem(RED_RECOMMENDATION_LETTER) == false) then player:startEvent(7); 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 == 0x0007 and option == 0) then player:addKeyItem(BLUE_RECOMMENDATION_LETTER); player:messageSpecial(KEYITEM_OBTAINED,BLUE_RECOMMENDATION_LETTER); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_Windurst/npcs/Boronene.lua
14
1049
----------------------------------- -- Area: Port Windurst -- NPC: Boronene -- Type: Moghouse Renter -- @zone 240 -- @pos 201.651 -13 229.584 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x027e); 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
Scavenge/darkstar
scripts/zones/Waughroon_Shrine/bcnms/on_my_way.lua
27
1994
----------------------------------- -- Area: Waughroon Shrine -- Name: Mission Rank 7-2 (Bastok) -- @pos -345 104 -260 144 ----------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Waughroon_Shrine/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(BASTOK,ON_MY_WAY)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then player:addKeyItem(LETTER_FROM_WEREI); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_WEREI); player:setVar("MissionStatus",3); end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Qulun_Dome/npcs/_440.lua
14
1602
----------------------------------- -- Area: Qulun Dome -- NPC: Door -- Involved in Mission: Magicite -- @pos 60 24 -2 148 ----------------------------------- package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Qulun_Dome/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(CORUSCANT_ROSARY) and player:hasKeyItem(BLACK_MATINEE_NECKLACE)) then if (player:getZPos() < -7.2) then player:startEvent(0x0033); else player:startEvent(0x0032); end else player:messageSpecial(IT_SEEMS_TO_BE_LOCKED_BY_POWERFUL_MAGIC); 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 == 0x0032 or csid == 0x0033) and option == 1) then player:messageSpecial(THE_3_ITEMS_GLOW_FAINTLY,SILVER_BELL,CORUSCANT_ROSARY,BLACK_MATINEE_NECKLACE); end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/chili_new/skins/DarkGlass/skin.lua
43
1112
--//============================================================================= --// GlassSkin local skin = { info = { name = "DarkGlass", version = "0.11", author = "jK", depend = { "Glass", }, } } --//============================================================================= --// skin.general = { textColor = {1,1,1,1}, } skin.window = { TileImage = ":cl:glass_.png", tiles = {22, 24, 22, 23}, --// tile widths: left,top,right,bottom padding = {14, 23, 14, 14}, hitpadding = {10, 4, 10, 10}, captionColor = {1, 1, 1, 0.55}, boxes = { resize = {-25, -25, -14, -14}, drag = {0, 0, "100%", 24}, }, NCHitTest = NCHitTestWithPadding, NCMouseDown = WindowNCMouseDown, NCMouseDownPostChildren = WindowNCMouseDownPostChildren, DrawControl = DrawWindow, DrawDragGrip = DrawDragGrip, DrawResizeGrip = DrawResizeGrip, } skin.combobox_window = { clone = "window"; TileImage = ":cl:combobox_wnd.png", padding = {4, 3, 3, 4}; } --//============================================================================= --// return skin
gpl-2.0
Scavenge/darkstar
scripts/zones/Kazham/npcs/Vanono.lua
14
1484
----------------------------------- -- Area: Kazham -- NPC: Vanono -- Type: Standard NPC -- @zone 250 -- @pos -23.140 -5 -23.101 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 3) then player:startEvent(0x0108); elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") > 3) then player:startEvent(0x010C); else player:startEvent(0x0106); 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 == 0x0108) then player:setVar("MissionStatus",4); end end;
gpl-3.0
yohanesyuen/mal
lua/step8_macros.lua
40
5392
#!/usr/bin/env lua local table = require('table') local readline = require('readline') local utils = require('utils') local types = require('types') local reader = require('reader') local printer = require('printer') local Env = require('env') local core = require('core') local List, Vector, HashMap = types.List, types.Vector, types.HashMap -- read function READ(str) return reader.read_str(str) end -- eval function is_pair(x) return types._sequential_Q(x) and #x > 0 end function quasiquote(ast) if not is_pair(ast) then return types.List:new({types.Symbol:new("quote"), ast}) elseif types._symbol_Q(ast[1]) and ast[1].val == 'unquote' then return ast[2] elseif is_pair(ast[1]) and types._symbol_Q(ast[1][1]) and ast[1][1].val == 'splice-unquote' then return types.List:new({types.Symbol:new("concat"), ast[1][2], quasiquote(ast:slice(2))}) else return types.List:new({types.Symbol:new("cons"), quasiquote(ast[1]), quasiquote(ast:slice(2))}) end end function is_macro_call(ast, env) if types._list_Q(ast) and types._symbol_Q(ast[1]) and env:find(ast[1]) then local f = env:get(ast[1]) return types._malfunc_Q(f) and f.ismacro end end function macroexpand(ast, env) while is_macro_call(ast, env) do local mac = env:get(ast[1]) ast = mac.fn(unpack(ast:slice(2))) end return ast end function eval_ast(ast, env) if types._symbol_Q(ast) then return env:get(ast) elseif types._list_Q(ast) then return List:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._vector_Q(ast) then return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast)) elseif types._hash_map_Q(ast) then local new_hm = {} for k,v in pairs(ast) do new_hm[EVAL(k, env)] = EVAL(v, env) end return HashMap:new(new_hm) else return ast end end function EVAL(ast, env) while true do --print("EVAL: "..printer._pr_str(ast,true)) if not types._list_Q(ast) then return eval_ast(ast, env) end -- apply list ast = macroexpand(ast, env) if not types._list_Q(ast) then return ast end local a0,a1,a2,a3 = ast[1], ast[2],ast[3],ast[4] local a0sym = types._symbol_Q(a0) and a0.val or "" if 'def!' == a0sym then return env:set(a1, EVAL(a2, env)) elseif 'let*' == a0sym then local let_env = Env:new(env) for i = 1,#a1,2 do let_env:set(a1[i], EVAL(a1[i+1], let_env)) end env = let_env ast = a2 -- TCO elseif 'quote' == a0sym then return a1 elseif 'quasiquote' == a0sym then ast = quasiquote(a1) -- TCO elseif 'defmacro!' == a0sym then local mac = EVAL(a2, env) mac.ismacro = true return env:set(a1, mac) elseif 'macroexpand' == a0sym then return macroexpand(a1, env) elseif 'do' == a0sym then local el = eval_ast(ast:slice(2,#ast-1), env) ast = ast[#ast] -- TCO elseif 'if' == a0sym then local cond = EVAL(a1, env) if cond == types.Nil or cond == false then if a3 then ast = a3 else return types.Nil end -- TCO else ast = a2 -- TCO end elseif 'fn*' == a0sym then return types.MalFunc:new(function(...) return EVAL(a2, Env:new(env, a1, arg)) end, a2, env, a1) else local args = eval_ast(ast, env) local f = table.remove(args, 1) if types._malfunc_Q(f) then ast = f.ast env = Env:new(f.env, f.params, args) -- TCO else return f(unpack(args)) end end end end -- print function PRINT(exp) return printer._pr_str(exp, true) end -- repl local repl_env = Env:new() function rep(str) return PRINT(EVAL(READ(str),repl_env)) end -- core.lua: defined using Lua for k,v in pairs(core.ns) do repl_env:set(types.Symbol:new(k), v) end repl_env:set(types.Symbol:new('eval'), function(ast) return EVAL(ast, repl_env) end) repl_env:set(types.Symbol:new('*ARGV*'), types.List:new(types.slice(arg,2))) -- core.mal: defined using mal rep("(def! not (fn* (a) (if a false true)))") rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))") rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))") rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))") if #arg > 0 and arg[1] == "--raw" then readline.raw = true table.remove(arg,1) end if #arg > 0 then rep("(load-file \""..arg[1].."\")") os.exit(0) end while true do line = readline.readline("user> ") if not line then break end xpcall(function() print(rep(line)) end, function(exc) if exc then if types._malexception_Q(exc) then exc = printer._pr_str(exc.val, true) end print("Error: " .. exc) print(debug.traceback()) end end) end
mpl-2.0
Scavenge/darkstar
scripts/zones/Windurst_Woods/npcs/Anillah.lua
53
1829
----------------------------------- -- Area: Windurst Woods -- NPC: Anillah -- Type: Clothcraft Image Support -- @pos -34.800 -2.25 -119.950 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,3); local SkillCap = getCraftSkillCap(player,SKILL_CLOTHCRAFT); local SkillLevel = player:getSkillLevel(SKILL_CLOTHCRAFT); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY) == false) then player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(0x271F,SkillCap,SkillLevel,2,511,player:getGil(),7108,0,0); end else player:startEvent(0x271F); -- Standard Dialogue 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 == 0x271F and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,4,2); player:addStatusEffect(EFFECT_CLOTHCRAFT_IMAGERY,1,0,120); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/RuAun_Gardens/npcs/Treasure_Coffer.lua
14
3857
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: Treasure Coffer -- @zone 130 -- @pos ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/RuAun_Gardens/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1058,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1058,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local zone = player:getZoneID(); if (player:hasKeyItem(MAP_OF_THE_RUAUN_GARDENS) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(MAP_OF_THE_RUAUN_GARDENS); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_RUAUN_GARDENS); -- Map of the Ru'Aun Gardens (KI) else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1058); 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
Scavenge/darkstar
scripts/zones/Meriphataud_Mountains/npcs/Daruru_WW.lua
14
3356
----------------------------------- -- Area: Meriphataud Mountains -- NPC: Daruru, W.W. -- Type: Border Conquest Guards -- @pos -120.393 -25.822 -592.604 119 ----------------------------------- package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Meriphataud_Mountains/TextIDs"); local guardnation = NATION_WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ARAGONEU; local csid = 0x7ff6; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Configs/StartBoxes/Iced Coffee v4.3.lua
11
1915
return { [0] = { boxes = { { {2501.6335449219, 753.90344238281}, {2172.1101074219, 430.34170532227}, {2216.1037597656, 386.40158081055}, {2320.662109375, 364.4716796875}, {2398.1352539063, 343.24713134766}, {2467.3872070313, 353.52038574219}, {2566.8725585938, 365.91967773438}, {2673.9050292969, 422.64590454102}, {2751.1005859375, 515.505859375}, {2791.8728027344, 569.54553222656}, {2831.1062011719, 695.322265625}, {2837.7084960938, 802.19329833984}, {2803.5490722656, 917.41650390625}, {2760.369140625, 1006.6159667969}, {2651.283203125, 1082.9749755859}, {2562.3088378906, 1096.3940429688}, {2443.1022949219, 1071.1011962891}, {2318.734375, 938.45056152344}, {2248.4450683594, 887.73516845703}, {2190.3962402344, 759.50305175781}, {2138.2194824219, 593.62145996094}, {2126.8930664063, 450.72381591797}, {2172.1101074219, 430.34170532227}, } }, startpoints = { {2500, 750} }, nameLong = "North", nameShort = "N", }, [1] = { boxes = { { {1591.6123046875, 3369.8693847656}, {1880.6569824219, 3272.8740234375}, {1898.19921875, 3353.2890625}, {1928.2905273438, 3448.7329101563}, {1931.5773925781, 3558.0688476563}, {1929.1245117188, 3653.0739746094}, {1837.5194091797, 3735.1701660156}, {1651.3452148438, 3739.4675292969}, {1503.5988769531, 3710.7878417969}, {1404.1212158203, 3629.3337402344}, {1315.4040527344, 3502.9084472656}, {1281.52734375, 3386.6352539063}, {1291.4721679688, 3206.2275390625}, {1358.7440185547, 3077.8486328125}, {1474.8648681641, 2992.0908203125}, {1600.3682861328, 2979.8671875}, {1732.3284912109, 3042.0065917969}, {1842.0825195313, 3166.4604492188}, {1880.6569824219, 3272.8740234375}, } }, startpoints = { {1590, 3370} }, nameLong = "South", nameShort = "S", }, }, { 2 }
gpl-2.0
Scavenge/darkstar
scripts/zones/Quicksand_Caves/npcs/qm6.lua
27
2110
----------------------------------- -- Area: Quicksand Caves -- NPC: ??? (qm6) -- Bastok Mission 8.1 "The Chains That Bind Us" -- @pos ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Quicksand_Caves/TextIDs"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local missionStatus = player:getVar("MissionStatus"); local timesincelastclear = os.time()-GetServerVariable("Bastok8-1LastClear"); -- how long ago they were last killed. local currentMission = player:getCurrentMission(player:getNation()) if (currentMission == THE_CHAINS_THAT_BIND_US) and (missionStatus == 1) then if (timesincelastclear < QM_RESET_TIME) then player:startEvent(0x0B); elseif (GetMobAction(17629187) == 0) and (GetMobAction(17629188) == 0) and (GetMobAction(17629189) == 0) then SpawnMob(17629187):updateClaim(player); -- Centurio IV-VII SpawnMob(17629188):updateClaim(player); -- Triarius IV-XIV SpawnMob(17629189):updateClaim(player); -- Princeps IV-XLV player:messageSpecial(SENSE_OF_FOREBODING); npc:setStatus(2); -- Disappear SetServerVariable("BastokFight8_1", 3); end else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- print("CSID:",csid); -- print("RESULT:",option); if (csid == 0x0B) then player:setVar("MissionStatus", 2); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Abyssea-Tahrongi/npcs/qm9.lua
14
1378
----------------------------------- -- Zone: Abyssea-Tahrongi -- NPC: qm9 (???) -- Spawns Alectryon -- @pos ? ? ? 45 ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) --[[ if (trade:hasItemQty(2923,1) and trade:hasItemQty(2949,1) and trade:getItemCount() == 2) then -- Player has all the required items. if (GetMobAction(16961925) == ACTION_NONE) then -- Mob not already spawned from this SpawnMob(16961925):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe) player:tradeComplete(); end end ]] end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(1010, 2923 ,2949); -- Inform payer what items they need. 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
cyclonetm/XmakanX
plugins/info.lua
1
1930
do local function action_by_reply(extra, success, result) local user_info = {} local uhash = 'user:'..result.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.from.id..':'..result.to.id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..result.from.id..']' local msgs = '6-messages sent : '..user_info.msgs if result.from.username then user_name = '@'..result.from.username else user_name = '' end local msg = result local user_id = msg.from.id local chat_id = msg.to.id local user = 'user#id'..msg.from.id local chat = 'chat#id'..msg.to.id local data = load_data(_config.moderation.data) if data[tostring('admins')][tostring(user_id)] then who = 'Admim' elseif data[tostring(msg.to.id)]['moderators'][tostring(user_id)] then who = 'Moderator' elseif data[tostring(msg.to.id)]['set_owner'] == tostring(user_id) then who = 'Owner' elseif tonumber(result.from.id) == tonumber(our_id) then who = 'Group creator' else who = 'Member' end for v,user in pairs(_config.sudo_users) do if user == user_id then who = 'Sudo' end end local text = '1-Full name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n' ..'2-First name : '..(result.from.first_name or '')..'\n' ..'3-Last name : '..(result.from.last_name or '')..'\n' ..'4-Username : '..user_name..'\n' ..'5-ID : '..result.from.id..'\n' ..msgs..'\n' ..'7-Position in group : '..who send_large_msg(extra.receiver, text) end local function run(msg) if msg.text == '!info' and msg.reply_id and is_momod(msg) then get_message(msg.reply_id, action_by_reply, {receiver=get_receiver(msg)}) end end return { patterns = { '^!info$', '^[!/#$&@-+.*]info$', '^info$' }, run = run } end
gpl-2.0
swan524/BotOfLegend
MetaBuild/MetaBuild.lua
1
5244
class 'MetaBuild'; function MetaBuild:__init() self:Alerte("MetaBuild loading.."); self.Items = {}; self.Sprite = {}; self.UseMetabuild = false; self:GetData(); self:GetSprite(); self.MetaBuild = scriptConfig(" > MetaBuild", "MetaBuild"); self.MetaBuild:addParam("Enable", "Enable MetaBuild :", SCRIPT_PARAM_ONOFF, true); self.MetaBuild:addParam("n0", "", SCRIPT_PARAM_INFO, ""); self.MetaBuild:addParam("X", "Set X value :", SCRIPT_PARAM_SLICE, 3.2, 0, 5, 0.100); self.MetaBuild:addParam("X2", "Set + X(i) value :", SCRIPT_PARAM_SLICE, 125, 0, 250, 10); self.MetaBuild:addParam("n1", "", SCRIPT_PARAM_INFO, ""); self.MetaBuild:addParam("Y", "Set Y value :", SCRIPT_PARAM_SLICE, 30, 2, 160, 2); self.MetaBuild:addParam("n2", "", SCRIPT_PARAM_INFO, ""); self.MetaBuild:addParam("n3", "By spyk & ThisIsDna (<3)", SCRIPT_PARAM_INFO, ""); AddDrawCallback(function() self:OnDraw(); end); AddRemoveBuffCallback(function(unit, buff) self:OnRemoveBuff(unit, buff); end); AddTickCallback(function() self:OnTick(); end); if self.Items ~= nil then self:Alerte("MetaBuild loaded! ("..myHero.charName..")"); else self:Alerte("Error during loading..? ("..myHero.charName..")"); end end function MetaBuild:Alerte(msg) PrintChat("<b><font color=\"#F62459\">></font></b> <font color=\"#FEFEE2\"> "..msg.."</font>"); end function MetaBuild:Socket(path) self.Socket = require("socket").tcp(); self.Socket:settimeout(5); self.Socket:connect("champion.gg", 80); self.Socket:send("GET "..path.." HTTP/1.0\r\n"..[[Host: champion.gg User-Agent: hDownload Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 Accept-Language: pl,en-US;q=0.7,en;q=0.3 Cookie: 720plan=R1726442047; path=/; Connection: close Cache-Control: max-age=0 ]]); local received_data = self.Socket:receive("*a"); repeat until received_data ~= nil self.Socket:close(); return received_data end function MetaBuild:GetSprite() if not DirectoryExist(SPRITE_PATH.."MetaBuild") then CreateDirectory(SPRITE_PATH.."MetaBuild//"); end local Items = {"1400", "1401", "1402", "1408", "1409", "1410", "1412", "1413", "1414", "1416", "1418", "1419", "2045", "2049", "2301", "2302", "2303", "3001", "3003", "3004", "3006", "3009", "3020", "3022", "3025", "3026", "3027", "3030", "3031", "3033", "3036", "3040", "3041", "3042", "3043", "3046", "3047", "3048", "3050", "3053", "3056", "3060", "3065", "3068", "3069", "3071", "3072", "3074", "3075", "3078", "3083", "3085", "3087", "3089", "3091", "3092", "3094", "3100", "3102", "3110", "3111", "3115", "3116", "3117", "3124", "3135", "3139", "3142", "3143", "3146", "3147", "3151", "3152", "3153", "3157", "3158", "3165", "3174", "3190", "3198", "3222", "3285", "3401", "3504", "3508", "3512", "3742", "3748", "3800", "3812"}; for _, v in pairs(Items) do local l = "MetaBuild\\"..v..".png"; if FileExist(SPRITE_PATH..l) then self.Sprite[v] = createSprite(l); else DownloadFile("https://raw.githubusercontent.com\\spyk1\\BoL\\master\\MetaBuild\\item\\"..v..".png", SPRITE_PATH.."MetaBuild\\"..v..".png", function() self:Alerte("Downloaded Sprite : "..v..".png"); self.Sprite[v] = createSprite(l); end); end end end function MetaBuild:GetData() local data = self:Socket("/champion/"..myHero.charName); local data2 = data:find("Most Frequent Core Build")+58 local real_data = data:sub(data2) local i = 0; local EveryItems = string.gsub(real_data, '/img/item/[0-9][0-9][0-9][0-9].png', function(x) if i == 6 then return end i = i + 1; self.Items[i] = x:match("[0-9][0-9][0-9][0-9]"); end); end function MetaBuild:OnDraw() if self.MetaBuild.Enable and (self.UseMetabuild or myHero.dead) then if self.Items == nil then return end for i = 1, 6 do self.Sprite[self.Items[i]]:Draw(WINDOW_W/self.MetaBuild.X+(i*self.MetaBuild.X2), WINDOW_W/self.MetaBuild.Y, 255); end end end function MetaBuild:OnRemoveBuff(unit, buff) if unit and unit.isMe and buff.name == "recall" and InFountain() and self.MetaBuild.Enable then self.UseMetabuild = true; end end function MetaBuild:OnTick() if self.UseMetabuild == true and not InFountain() then self.UseMetabuild = false; end end function Update() local version = "0.01"; local UPDATE_HOST = "raw.githubusercontent.com"; local UPDATE_PATH = "/spyk1/BoL/master/MetaBuild/MetaBuild.lua".."?rand="..math.random(1,10000); local UPDATE_FILE_PATH = SCRIPT_PATH.._ENV.FILE_NAME; local UPDATE_URL = "https://"..UPDATE_HOST..UPDATE_PATH; local ServerData = GetWebResult(UPDATE_HOST, "/spyk1/BoL/master/MetaBuild/MetaBuild.version"); if ServerData then local ServerVersion = type(tonumber(ServerData)) == "number" and tonumber(ServerData) or nil; if ServerVersion then if tonumber(version) < ServerVersion then MetaBuild:Alerte("New version available "..ServerVersion); MetaBuild:Alerte(">>Updating, please don't press F9<<"); DelayAction(function() DownloadFile(UPDATE_URL, UPDATE_FILE_PATH, function () MetaBuild:Alerte("Successfully updated. ("..version.." => "..ServerVersion.."), press F9 twice to load the updated version.") end) end, 3); else MetaBuild(); end else MetaBuild:Alerte("Error while downloading version info"); end end end Update();
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
units/armjeth.lua
1
4768
unitDef = { unitname = [[armjeth]], name = [[Gremlin]], description = [[Cloaked Anti-Air Bot]], acceleration = 0.5, brakeRate = 0.32, buildCostEnergy = 150, buildCostMetal = 150, buildPic = [[ARMJETH.png]], buildTime = 150, canAttack = true, canGuard = true, canMove = true, canPatrol = true, canstop = [[1]], category = [[LAND]], cloakCost = 0.1, cloakCostMoving = 0.5, collisionVolumeOffsets = [[0 1 0]], collisionVolumeScales = [[22 28 22]], collisionVolumeType = [[cylY]], corpse = [[DEAD]], customParams = { description_de = [[Flugabwehr Roboter]], description_fr = [[Robot Anti-Air]], helptext = [[Fast and fairly sturdy for its price, the Gremlin is good budget mobile anti-air. It can cloak, allowing it to provide unexpected anti-air protection or escape ground forces it's defenseless against.]], helptext_de = [[Durch seine Fähigkeit mobile Kräft vor Luftangriffen zu beschützen, gibt der Gremlin den entsprechenden Einheiten einen wichtigen Vorteil gegenüber Lufteinheiten. Verteidigungslos gegenüber Landeinheiten.]], helptext_fr = [[Se situant entre le Defender et le Razor pour la d?fense a?rienne, en ayant la faiblaisse d'aucun des deux et pouvant offrire un d?fense d?cissive pour les forces mobile, le Gremlin done un avantage d?finis pour les robots. Il est sans d?fense contre les unit?s terriennes.]], modelradius = [[11]], }, explodeAs = [[BIG_UNITEX]], footprintX = 2, footprintZ = 2, iconType = [[kbotaa]], idleAutoHeal = 5, idleTime = 1800, initCloaked = true, leaveTracks = true, maxDamage = 550, maxSlope = 36, maxVelocity = 2.9, maxWaterDepth = 22, minCloakDistance = 140, movementClass = [[KBOT2]], moveState = 0, noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SWIM FLOAT SUB HOVER]], objectName = [[spherejeth.s3o]], script = [[armjeth.lua]], seismicSignature = 4, selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:NONE]], [[custom:NONE]], }, }, sightDistance = 660, trackOffset = 0, trackStrength = 8, trackStretch = 1, trackType = [[ComTrack]], trackWidth = 17, turnRate = 2200, upright = true, weapons = { { def = [[AA_LASER]], --badTargetCategory = [[GUNSHIP]], onlyTargetCategory = [[GUNSHIP FIXEDWING]], }, }, weaponDefs = { AA_LASER = { name = [[Anti-Air Laser]], areaOfEffect = 12, beamDecay = 0.736, beamTime = 1/30, beamttl = 15, canattackground = false, coreThickness = 0.5, craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { isaa = [[1]], light_color = [[0.2 1.2 1.2]], light_radius = 120, }, damage = { default = 1.84, planes = 18.4, subs = 1, }, explosionGenerator = [[custom:flash_teal7]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 3.25, minIntensity = 1, range = 700, reloadtime = 0.3, rgbColor = [[0 1 1]], soundStart = [[weapon/laser/rapid_laser]], soundStartVolume = 4, thickness = 2.3, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], weaponVelocity = 2200, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[spherejeth_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ armjeth = unitDef })
gpl-2.0
tonyli71/kolla
docker/heka/plugins/decoders/os_syslog.lua
6
1710
-- Copyright 2016 Mirantis, Inc. -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -- -- The code in this file was inspired by Heka's rsyslog.lua decoder plugin. -- https://github.com/mozilla-services/heka/blob/master/sandbox/lua/decoders/rsyslog.lua local syslog = require "syslog" local utils = require "os_utils" local msg = { Timestamp = nil, Type = 'log', Hostname = read_config("hostname"), Payload = nil, Pid = nil, Severity = nil, Fields = nil } -- See https://tools.ietf.org/html/rfc3164 local grammar = syslog.build_rsyslog_grammar('<%PRI%>%TIMESTAMP% %syslogtag% %msg%') function process_message () local log = read_message("Payload") local fields = grammar:match(log) if not fields then return -1 end msg.Timestamp = fields.timestamp fields.timestamp = nil msg.Severity = fields.pri.severity fields.syslogfacility = fields.pri.facility fields.pri = nil fields.programname = fields.syslogtag.programname msg.Pid = fields.syslogtag.pid fields.syslogtag = nil msg.Payload = fields.msg fields.msg = nil msg.Fields = fields return utils.safe_inject_message(msg) end
apache-2.0
Scavenge/darkstar
scripts/globals/spells/raiton_san.lua
21
1286
----------------------------------------- -- Spell: Raiton: San -- Deals lightning damage to an enemy and lowers its resistance against earth. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_RAITON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_RAITON_EFFECT); -- T1 mag atk if(caster:getMerit(MERIT_RAITON_SAN) ~= 0) then -- T2 mag atk/mag acc, don't want to give a penalty to entities that can cast this without merits bonusMab = bonusMab + caster:getMerit(MERIT_RAITON_SAN) - 5; -- merit gives 5 power but no bonus with one invest, thus subtract 5 bonusAcc = bonusAcc + caster:getMerit(MERIT_RAITON_SAN) - 5; end local dmg = doNinjutsuNuke(134,1.5,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_EARTHRES); return dmg; end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
scripts/nsaclash.lua
9
3737
include "constants.lua" include "RockPiece.lua" local base = piece 'base' local front = piece 'front' local turret = piece 'turret' local lbarrel = piece 'lbarrel' local rbarrel = piece 'rbarrel' local lflare = piece 'lflare' local rflare = piece 'rflare' local exhaust = piece 'exhaust' local wakes = {} for i = 1, 8 do wakes[i] = piece ('wake' .. i) end local ground1 = piece 'ground1' local random = math.random local shotNum = 1 local flares = { lflare, rflare, } local gunHeading = 0 local ROCKET_SPREAD = 0.4 local SIG_ROCK_X = 8 local SIG_ROCK_Z = 16 local ROCK_FIRE_FORCE = 0.35 local ROCK_SPEED = 10 --Number of half-cycles per second around x-axis. local ROCK_DECAY = -0.85 --Rocking around axis is reduced by this factor each time = piece 'to rock. local ROCK_PIECE = base -- should be negative to alternate rocking direction. local ROCK_MIN = 0.001 --If around axis rock is not greater than this amount, rocking will stop after returning to center. local ROCK_MAX = 1.5 local SIG_MOVE = 1 local SIG_AIM = 2 local RESTORE_DELAY = 3000 local function WobbleUnit() local wobble = true while true do if wobble == true then Move(base, y_axis, 0.9, 1.2) end if wobble == false then Move(base, y_axis, -0.9, 1.2) end wobble = not wobble Sleep(750) end end local sfxNum = 0 function script.setSFXoccupy(num) sfxNum = num end local function MoveScript() while Spring.GetUnitIsStunned(unitID) do Sleep(2000) end while true do if not Spring.GetUnitIsCloaked(unitID) then if (sfxNum == 1 or sfxNum == 2) and select(2, Spring.GetUnitPosition(unitID)) == 0 then for i = 1, 8 do EmitSfx(wakes[i], 3) end else EmitSfx(ground1, 1024) end end Sleep(150) end end function script.Create() Turn(exhaust, y_axis, math.rad(-180)) Turn(lbarrel, y_axis, ROCKET_SPREAD) Turn(rbarrel, y_axis, -ROCKET_SPREAD) StartThread(SmokeUnit, {base}) StartThread(WobbleUnit) StartThread(MoveScript) InitializeRock(ROCK_PIECE, ROCK_SPEED, ROCK_DECAY, ROCK_MIN, ROCK_MAX, SIG_ROCK_X, x_axis) InitializeRock(ROCK_PIECE, ROCK_SPEED, ROCK_DECAY, ROCK_MIN, ROCK_MAX, SIG_ROCK_Z, z_axis) end local function RestoreAfterDelay() Sleep(RESTORE_DELAY) Turn(turret, y_axis, 0, math.rad(90)) Turn(turret, x_axis, 0, math.rad(45)) end function script.AimFromWeapon() return turret end function script.AimWeapon(num, heading, pitch) Signal(SIG_AIM) SetSignalMask(SIG_AIM) Turn(turret, y_axis, heading, math.rad(180)) Turn(turret, x_axis, -pitch, math.rad(100)) Turn(lbarrel, y_axis, ROCKET_SPREAD + 2*pitch, math.rad(300)) Turn(rbarrel, y_axis, -ROCKET_SPREAD - 2*pitch, math.rad(300)) Turn(lbarrel, x_axis, -pitch, math.rad(300)) Turn(rbarrel, x_axis, -pitch, math.rad(300)) gunHeading = heading WaitForTurn(turret, y_axis) WaitForTurn(turret, x_axis) StartThread(RestoreAfterDelay) return (1) end function script.QueryWeapon(piecenum) return flares[shotNum] end function script.FireWeapon() StartThread(Rock, gunHeading, ROCK_FIRE_FORCE, z_axis) StartThread(Rock, gunHeading - hpi, ROCK_FIRE_FORCE*0.4, x_axis) end function script.BlockShot(num, targetID) return GG.OverkillPrevention_CheckBlock(unitID, targetID, 620.1, 70, 0.3) end function script.Shot() EmitSfx(flares[shotNum], UNIT_SFX2) EmitSfx(exhaust, UNIT_SFX3) shotNum = 3 - shotNum end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if severity <= 0.25 then return 1 elseif severity <= 0.50 then Explode(front, sfxNone) Explode(turret, sfxShatter) return 1 elseif severity <= 0.99 then Explode(front, sfxShatter) Explode(turret, sfxShatter) return 2 end Explode(front, sfxShatter) Explode(turret, sfxShatter) return 2 end
gpl-2.0
Scavenge/darkstar
scripts/globals/spells/silencega.lua
6
1124
----------------------------------------- -- Spell: Silence ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effectType = EFFECT_SILENCE; if (target:hasStatusEffect(effectType)) then spell:setMsg(75); -- no effect return effectType; end --Pull base stats. local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND)); --Duration, including resistance. May need more research. local duration = 120; --Resist local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_SILENCE); if (resist >= 0.5) then --Do it! if (target:addStatusEffect(effectType,1,0,duration * resist)) then spell:setMsg(236); else spell:setMsg(75); -- no effect end else spell:setMsg(85); end return effectType; end;
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/Themes/_fallback/Scripts/03 ThemeAndGamePrefs.lua
1
3329
-- sm-ssc Default Theme Preferences Handler function InitGamePrefs() local Prefs = { }; local BPrefs = { { "ComboOnRolls", false }, }; for idx,pref in ipairs(Prefs) do if GetGamePref( pref[1] ) == nil then SetGamePref( pref[1], pref[2] ); end; end; for idx,pref in ipairs(BPrefs) do if GetGamePrefB( pref[1] ) == nil then SetGamePref( pref[1], pref[2] ); end; end; end function InitUserPrefs() if GetUserPrefB("ShowLotsaOptions") == nil then SetUserPref("ShowLotsaOptions", true); end; local Prefs = { { "GameplayShowStepsDisplay", true }, { "GameplayShowScore", false}, --[[ { "ProTimingP1", false}, { "ProTimingP2", false}, --]] }; local BPrefs = { { "AutoSetStyle", false }, { "ComboUnderField", true }, { "LongFail", false}, { "NotePosition", true }, { "UserPrefProtimingP1", false}, { "UserPrefProtimingP2", false}, { "ShowLotsaOptions", true}, { "ComboOnRolls", false}, { "FlashyCombos", false}, { "GameplayFooter", false}, }; for idx,pref in ipairs(Prefs) do if GetUserPref( pref[1] ) == nil then SetUserPref( pref[1], pref[2] ); end; end; -- making sure I don't screw up anything yet... for idx,pref in ipairs(BPrefs) do if GetUserPrefB( pref[1] ) == nil then SetUserPref( pref[1], pref[2] ); end; end; end; --[[ theme option rows ]] -- screen cover function GetProTiming(pn) local pname = ToEnumShortString(pn); if GetUserPref("ProTiming"..pname) then return GetUserPrefB("ProTiming"..pname); else SetUserPref("ProTiming"..pname,false); return false; end; end; function OptionRowProTiming() local t = { Name = "ProTiming"; LayoutType = "ShowAllInRow"; SelectType = "SelectOne"; OneChoiceForAllPlayers = false; ExportOnChange = false; Choices = { 'Off','On' }; LoadSelections = function(self, list, pn) local bShow; if GetUserPrefB("UserPrefProtiming" .. ToEnumShortString(pn) ) then bShow = GetUserPrefB("UserPrefProtiming" .. ToEnumShortString(pn) ); if bShow then list[2] = true; else list[1] = true; end else list[1] = true; end; --[[ local pname = ToEnumShortString(pn); if getenv("ProTiming"..pname) == true then list[2] = true; else list[1] = true; end; --]] end; SaveSelections = function(self, list, pn) local bSave; if list[2] then bSave = true; else bSave = false; end; SetUserPref("UserPrefProtiming" .. ToEnumShortString(pn),bSave); --[[ local val; if list[2] then val = true; else val = false; end; local pname = ToEnumShortString(pn); setenv("ProTiming"..pname, val); --]] end; }; return t; end; function GetDefaultOptionLines() local LineSets = { "1,8,14,2,3,4,5,6,R,7,9,10,11,12,13,15,16,SF,17,18", -- All "1,8,14,2,7,13,16,SF,17,18", -- DDR Essentials ( no turns, fx ) }; local function IsExtra() if GAMESTATE:IsExtraStage() or GAMESTATE:IsExtraStage2() then return true else return false end end if not IsExtra() then if GetUserPrefB("UserPrefShowLotsaOptions") then return GetUserPrefB("UserPrefShowLotsaOptions") and LineSets[1] or LineSets[2]; else return LineSets[2]; -- Just make sure! end else return "1,8,14,2,7,13,16,SF,17,18" -- "failsafe" list end end; --[[ end themeoption rows ]] --[[ game option rows ]]
mit
Scavenge/darkstar
scripts/zones/Bastok_Mines/npcs/Tall_Mountain.lua
29
1820
----------------------------------- -- Area: Bastok Mines -- NPC: Tall Mountain -- Involved in Quest: Stamp Hunt -- Finish Mission: Bastok 6-1 -- @pos 71 7 -7 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local StampHunt = player:getQuestStatus(BASTOK,STAMP_HUNT); if (player:getCurrentMission(BASTOK) == RETURN_OF_THE_TALEKEEPER and player:getVar("MissionStatus") == 3) then player:startEvent(0x00b6); elseif (StampHunt == QUEST_ACCEPTED and player:getMaskBit(player:getVar("StampHunt_Mask"),1) == false) then player:startEvent(0x0055); else player:startEvent(0x0037); end end; -- 0x7fb5 0x0037 0x0055 0x00b0 0x00b4 0x00b6 0x024f 0x0251 ----------------------------------- -- 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 == 0x00b6) then finishMissionTimeline(player,1,csid,option); elseif (csid == 0x0055) then player:setMaskBit(player:getVar("StampHunt_Mask"),"StampHunt_Mask",1,true); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/bowl_of_dhalmel_stew.lua
12
1754
----------------------------------------- -- ID: 4433 -- Item: Bowl of Dhalmel Stew -- Food Effect: 180Min, All Races ----------------------------------------- -- Strength 4 -- Agility 1 -- Vitality 2 -- Intelligence -2 -- Attack % 25 -- Attack Cap 45 -- Ranged ATT % 25 -- Ranged ATT Cap 45 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4433); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 4); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 25); target:addMod(MOD_FOOD_ATT_CAP, 45); target:addMod(MOD_FOOD_RATTP, 25); target:addMod(MOD_FOOD_RATT_CAP, 45); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 4); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 25); target:delMod(MOD_FOOD_ATT_CAP, 45); target:delMod(MOD_FOOD_RATTP, 25); target:delMod(MOD_FOOD_RATT_CAP, 45); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Maze_of_Shakhrami/npcs/qm2.lua
14
1859
----------------------------------- -- Area: Maze of Shakhrami -- NPC: qm2 -- Type: Quest NPC -- @pos 143 9 -219 198 ----------------------------------- package.loaded["scripts/zones/Maze_of_Shakhrami/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Maze_of_Shakhrami/TextIDs"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local wyrm1 = 17588701; local wyrm2 = 17588702; local wyrm3 = 17588703; if (player:getQuestStatus(WINDURST,ECO_WARRIOR_WIN) ~= QUEST_AVAILABLE and player:getVar("ECO_WARRIOR_ACTIVE") == 238 and player:hasStatusEffect(EFFECT_LEVEL_RESTRICTION) and player:hasKeyItem(INDIGESTED_MEAT) == false) then if (player:getVar("ECOR_WAR_WIN-NMs_killed") == 1) then player:addKeyItem(INDIGESTED_MEAT); player:messageSpecial(KEYITEM_OBTAINED,INDIGESTED_MEAT); elseif (GetMobAction(wyrm1) + GetMobAction(wyrm1) + GetMobAction(wyrm1) == 0) then SpawnMob(wyrm1):updateClaim(player); SpawnMob(wyrm2):updateClaim(player); SpawnMob(wyrm3):updateClaim(player); 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
kirubz/Penlight
examples/seesubst.lua
15
1272
-- shows how replacing '@see module' in the Markdown documentation -- can be done more elegantly using PL. -- We either have something like 'pl.config' (a module reference) -- or 'pl.seq.map' (a function reference); these cases must be distinguished -- and a Markdown link generated pointing to the LuaDoc file. require 'pl' local res = {} s = [[ (@see pl.bonzo.dog) remember about @see pl.bonzo ]] local _gsub_patterns = {} function gsub (s,pat,subst,start) local fpat = _gsub_patterns[pat] if not fpat then -- use SIP to generate a proper string pattern. -- the _whole thing_ is a capture, to get the whole match -- and the unnamed capture. fpat = '('..sip.create_pattern(pat)..')' _gsub_patterns[pat] = fpat end return s:gsub(fpat,subst,start) end local mod = sip.compile '$v.$v' local fun = sip.compile '$v.$v.$v' for line in stringx.lines(s) do line = gsub(line,'@see $p',function(see,path) if fun(path,res) or mod(path,res) then local ret = ('[see %s](%s.%s.html'):format(path,res[1],res[2]) if res[3] then return ret..'#'..res[3]..')' else return ret..')' end end end) print(line) end
mit
PredatorMF/Urho3D
bin/Data/LuaScripts/12_PhysicsStressTest.lua
24
12743
-- Physics stress test example. -- This sample demonstrates: -- - Physics and rendering performance with a high (1000) moving object count -- - Using triangle meshes for collision -- - Optimizing physics simulation by leaving out collision event signaling -- - Usage of Lua Coroutine to yield/resume based on time step require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the scene content CreateScene() -- Create the UI content CreateInstructions() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update and render post-update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create octree, use default volume (-1000, -1000, -1000) to (1000, 1000, 1000) -- Create a physics simulation world with default parameters, which will update at 60ps. Like the Octree must -- exist before creating drawable components, the PhysicsWorld must exist before creating physics components. -- Finally, create a DebugRenderer component so that we can draw physics debug geometry scene_:CreateComponent("Octree") scene_:CreateComponent("PhysicsWorld") scene_:CreateComponent("DebugRenderer") -- Create a Zone component for ambient lighting & fog control local zoneNode = scene_:CreateChild("Zone") local zone = zoneNode:CreateComponent("Zone") zone.boundingBox = BoundingBox(-1000.0, 1000.0) zone.ambientColor = Color(0.15, 0.15, 0.15) zone.fogColor = Color(0.5, 0.5, 0.7) zone.fogStart = 100.0 zone.fogEnd = 300.0 -- Create a directional light to the world. Enable cascaded shadows on it local lightNode = scene_:CreateChild("DirectionalLight") lightNode.direction = Vector3(0.6, -1.0, 0.8) local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_DIRECTIONAL light.castShadows = true light.shadowBias = BiasParameters(0.00025, 0.5) -- Set cascade splits at 10, 50 and 200 world units, fade shadows out at 80% of maximum shadow distance light.shadowCascade = CascadeParameters(10.0, 50.0, 200.0, 0.0, 0.8) if true then -- Create a floor object, 500 x 500 world units. Adjust position so that the ground is at zero Y local floorNode = scene_:CreateChild("Floor") floorNode.position = Vector3(0.0, -0.5, 0.0) floorNode.scale = Vector3(500.0, 1.0, 500.0) local floorObject = floorNode:CreateComponent("StaticModel") floorObject.model = cache:GetResource("Model", "Models/Box.mdl") floorObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Make the floor physical by adding RigidBody and CollisionShape components local body = floorNode:CreateComponent("RigidBody") local shape = floorNode:CreateComponent("CollisionShape") -- Set a box shape of size 1 x 1 x 1 for collision. The shape will be scaled with the scene node scale, so the -- rendering and physics representation sizes should match (the box model is also 1 x 1 x 1.) shape:SetBox(Vector3(1.0, 1.0, 1.0)) end -- Create static mushrooms with triangle mesh collision local NUM_MUSHROOMS = 50 for i = 1, NUM_MUSHROOMS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(400.0) - 200.0, 0.0, Random(400.0) - 200.0) mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(5.0 + Random(5.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") mushroomObject.castShadows = true local body = mushroomNode:CreateComponent("RigidBody") local shape = mushroomNode:CreateComponent("CollisionShape") -- By default the highest LOD level will be used, the LOD level can be passed as an optional parameter shape:SetTriangleMesh(mushroomObject.model) end -- Start coroutine to create a large amount of falling physics objects coroutine.start(function() local NUM_OBJECTS = 1000 for i = 1, NUM_OBJECTS do local boxNode = scene_:CreateChild("Box") boxNode.position = Vector3(0.0, 100.0, 0.0) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml") boxObject.castShadows = true -- Give the RigidBody mass to make it movable and also adjust friction local body = boxNode:CreateComponent("RigidBody") body.mass = 1.0 body.friction = 1.0 -- Set linear velocity body.linearVelocity = Vector3(0.0, -50.0, 0.0) -- Disable collision event signaling to reduce CPU load of the physics simulation body.collisionEventMode = COLLISION_NEVER local shape = boxNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) -- sleep coroutine coroutine.sleep(0.1) end end) -- Create the camera. Limit far clip distance to match the fog. Note: now we actually create the camera node outside -- the scene, because we want it to be unaffected by scene load/save cameraNode = Node() local camera = cameraNode:CreateComponent("Camera") camera.farClip = 300.0 -- Set an initial position for the camera scene node above the floor cameraNode.position = Vector3(0.0, 3.0, -20.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move\n".. "LMB to spawn physics objects\n".. "F5 to save scene, F7 to load\n".. "Space to toggle physics debug geometry") instructionText:SetFont(cache:GetResource("Font", "Fonts/Anonymous Pro.ttf"), 15) -- The text has multiple rows. Center them in relation to each other instructionText.textAlignment = HA_CENTER -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") -- Subscribe HandlePostRenderUpdate() function for processing the post-render update event, during which we request -- debug geometry SubscribeToEvent("PostRenderUpdate", "HandlePostRenderUpdate") end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw + MOUSE_SENSITIVITY * mouseMove.x pitch = pitch +MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end -- "Shoot" a physics object with left mousebutton if input:GetMouseButtonPress(MOUSEB_LEFT) then SpawnObject() end -- Check for loading/saving the scene. Save the scene to the file Data/Scenes/Physics.xml relative to the executable -- directory if input:GetKeyPress(KEY_F5) then scene_:SaveXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml") end if input:GetKeyPress(KEY_F7) then scene_:LoadXML(fileSystem:GetProgramDir().."Data/Scenes/PhysicsStressTest.xml") end -- Toggle debug geometry with space if input:GetKeyPress(KEY_SPACE) then drawDebug = not drawDebug end end function SpawnObject() -- Create a smaller box at camera position local boxNode = scene_:CreateChild("SmallBox") boxNode.position = cameraNode.position boxNode.rotation = cameraNode.rotation boxNode:SetScale(0.25) local boxObject = boxNode:CreateComponent("StaticModel") boxObject.model = cache:GetResource("Model", "Models/Box.mdl") boxObject.material = cache:GetResource("Material", "Materials/StoneSmall.xml") boxObject.castShadows = true -- Create physics components, use a smaller mass also local body = boxNode:CreateComponent("RigidBody") body.mass = 0.25 body.friction = 0.75 local shape = boxNode:CreateComponent("CollisionShape") shape:SetBox(Vector3(1.0, 1.0, 1.0)) local OBJECT_VELOCITY = 10.0 -- Set initial velocity for the RigidBody based on camera forward vector. Add also a slight up component -- to overcome gravity better body.linearVelocity = cameraNode.rotation * Vector3(0.0, 0.25, 1.0) * OBJECT_VELOCITY end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end function HandlePostRenderUpdate(eventType, eventData) -- If draw debug mode is enabled, draw physics debug geometry. Use depth test to make the result easier to interpret if drawDebug then scene_:GetComponent("PhysicsWorld"):DrawDebugGeometry(true) end end -- Create XML patch instructions for screen joystick layout specific to this sample app function GetScreenJoystickPatchString() return "<patch>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Spawn</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button0']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"MouseButtonBinding\" />" .. " <attribute name=\"Text\" value=\"LEFT\" />" .. " </element>" .. " </add>" .. " <remove sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/attribute[@name='Is Visible']\" />" .. " <replace sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]/element[./attribute[@name='Name' and @value='Label']]/attribute[@name='Text']/@value\">Debug</replace>" .. " <add sel=\"/element/element[./attribute[@name='Name' and @value='Button1']]\">" .. " <element type=\"Text\">" .. " <attribute name=\"Name\" value=\"KeyBinding\" />" .. " <attribute name=\"Text\" value=\"SPACE\" />" .. " </element>" .. " </add>" .. "</patch>" end
mit
Scavenge/darkstar
scripts/zones/Beaucedine_Glacier/Zone.lua
12
3024
----------------------------------- -- -- Zone: Beaucedine_Glacier (111) -- ----------------------------------- package.loaded[ "scripts/zones/Beaucedine_Glacier/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Beaucedine_Glacier/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/icanheararainbow"); require("scripts/globals/zone"); require("scripts/globals/conquest"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) SetRegionalConquestOverseers(zone:getRegionID()) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (prevZone == 134) then -- warp player to a correct position after dynamis player:setPos(-284.751,-39.923,-422.948,235); end if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -247.911, -82.165, 260.207, 248); end if (player:getCurrentMission( COP) == DESIRES_OF_EMPTINESS and player:getVar( "PromathiaStatus") == 9) then cs = 0x00CE; elseif (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0072; elseif (player:getCurrentMission(WINDURST) == VAIN and player:getVar("MissionStatus") ==1) then cs = 0x0074; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0072) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow elseif (csid == 0x0074) then player:updateEvent(0,0,0,0,0,4); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00CE) then player:setVar("PromathiaStatus",10); elseif (csid == 0x0072) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) local mirrorPond = GetNPCByID(17232198); -- Quest: Love And Ice if (weather == WEATHER_GLOOM or weather == WEATHER_DARKNESS) then mirrorPond:setStatus(STATUS_NORMAL); else mirrorPond:setStatus(STATUS_DISAPPEAR); end end;
gpl-3.0
Scavenge/darkstar
scripts/mixins/abyssea_nm.lua
20
2977
-- Abyssea NM mixin (for non-force popped NMs) -- Customization: require("scripts/globals/mixins") require("scripts/globals/abyssea") g_mixins = g_mixins or {} g_mixins.abyssea_nm = function(mob) mob:addListener("ENGAGE", "ABYSSEA_WEAKNESS_SET", function(mob) mob:setLocalVar("abyssea_magic_weak", getNewYellowWeakness(mob)) mob:setLocalVar("abyssea_ele_ws_weak", getNewRedWeakness(mob)) mob:setLocalVar("abyssea_phys_ws_weak", getNewBlueWeakness(mob)) mob:setLocalVar("abyssea_blue_proc_count", 0) mob:setLocalVar("abyssea_red_proc_count", 0) mob:setLocalVar("abyssea_yellow_proc_count", 0) end) mob:addListener("MAGIC_TAKE", "ABYSSEA_MAGIC_PROC_CHECK", function(mob, caster, spell, action) if mob:canChangeState() then if spell:getID() == mob:getLocalVar("abyssea_magic_weak") then --TODO: weakness trigger message mob:weaknessTrigger(1) mob:addStatusEffect(EFFECT_SILENCE,0,0,30) mob:setLocalVar("abyssea_yellow_proc_count", mob:getLocalVar("abyssea_yellow_proc_count" + 1)) else --discernment end end end) mob:addListener("WEAPONSKILL_TAKE", "ABYSSEA_WS_PROC_CHECK", function(mob, user, wsid) if mob:canChangeState() then if wsid == mob:getLocalVar("abyssea_ele_ws_weak") then --TODO: weakness trigger message mob:weaknessTrigger(2) mob:addStatusEffect(EFFECT_TERROR,0,0,30) mob:setLocalVar("abyssea_blue_proc_count", mob:getLocalVar("abyssea_red_proc_count" + 1)) elseif wsid == mob:getLocalVar("abyssea_phys_ws_weak") then --TODO: weakness trigger message mob:weaknessTrigger(0) mob:addStatusEffect(EFFECT_AMNESIA,0,0,30) mob:setLocalVar("abyssea_blue_proc_count", mob:getLocalVar("abyssea_blue_proc_count" + 1)) else --discernment (figure out if ws is elemental...) end end end) mob:addListener("DEATH", "ABYSSEA_KI_DISTRIBUTION", function(mob, killer) --TODO: message local ki1 = mob:getLocalVar("ABYSSEA_PKI_DROP") local ki2 = mob:getLocalVar("ABYSSEA_TKI_DROP") if ki1 ~= 0 or ki2 ~= 0 then for _,player in killer:getAlliance() do local chance = 100 - ((mob:getLocalVar("abyssea_red_proc_count") - 1) * 10) if mob:getLocalVar("abyssea_red_proc_count") == 0 then chance = 10 end if math.random(0,99) < chance then if ki1 ~= 0 then player:addKeyItem(ki1) end if ki2 ~= 0 then player:addKeyItem(ki2) end end end end end) end return g_mixins.abyssea_nm
gpl-3.0
Scavenge/darkstar
scripts/globals/weaponskills/full_swing.lua
25
1283
----------------------------------- -- 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, tp, primary, action, taChar) 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, wsID, tp, primary, action, taChar, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/NoteSkins/dance/midi-note-3d/NoteSkin.lua
1
2448
-- Haggen Daze local ret = ... or {}; ret.RedirTable = { Up = "Down", Down = "Down", Left = "Down", Right = "Down", UpLeft = "Down", UpRight = "Down", }; local OldRedir = ret.Redir; ret.Redir = function(sButton, sElement) -- sButton, sElement = OldRedir(sButton, sElement); if sElement == "Tap Fake" then sElement = "Tap Note"; end sButton = ret.RedirTable[sButton]; return sButton, sElement; end -- local OldRedir = ret.Redir; -- ret.Redir = function(sButton, sElement) -- sButton = ret.RedirTable[sButton]; -- return sButton, sElement; -- end -- To have separate graphics for each hold part: local OldRedir = ret.Redir; ret.Redir = function(sButton, sElement) -- Redirect non-hold, non-roll parts. if string.find(sElement, "hold") or string.find(sElement, "roll") then return sButton, sElement; end return OldRedir(sButton, sElement); end --[[ local OldFunc = ret.Load; function ret.Load() local t = OldFunc(); -- The main "Explosion" part just loads other actors; don't rotate -- it. The "Hold Explosion" part should not be rotated. if Var "Element" == "Explosion" or Var "Element" == "Roll Explosion" then t.BaseRotationZ = nil; end return t; end ]] local OldFunc = ret.Load; function ret.Load() local t = OldFunc(); --Explosion should not be rotated; it calls other actors. if Var "Element" == "Explosion" then t.BaseRotationZ = nil; end return t; end ret.PartsToRotate = { ["Receptor"] = true, ["Go Receptor"] = true, ["Ready Receptor"] = true, ["Tap Explosion Bright"] = true, ["Tap Explosion Dim"] = true, ["Tap Note"] = true, ["Tap Fake"] = true, ["Tap Lift"] = true, ["Hold Head Active"] = true, ["Hold Head Inactive"] = true, ["Roll Head Active"] = true, ["Roll Head Inactive"] = true, ["Hold Explosion"] = true, ["Roll Explosion"] = true, }; ret.Rotate = { Up = 180, Down = 0, Left = 90, Right = -90, UpLeft = 135, UpRight = 225, }; -- -- If a derived skin wants to have separate UpLeft graphics, -- use this: -- -- ret.RedirTable.UpLeft = "UpLeft"; -- ret.RedirTable.UpRight = "UpLeft"; -- ret.Rotate.UpLeft = 0; -- ret.Rotate.UpRight = 90; -- ret.Blank = { ["Hold Topcap Active"] = true, ["Hold Topcap Inactive"] = true, ["Roll Topcap Active"] = true, ["Roll Topcap Inactive"] = true, ["Hold Tail Active"] = true, ["Hold Tail Inactive"] = true, ["Roll Tail Active"] = true, ["Roll Tail Inactive"] = true, ["Roll Explosion"] = true, }; return ret;
mit
BlockMen/minetest_next
mods/default/nodes/lava.lua
2
2327
minetest.register_node("default:lava_source", { description = "Lava Source", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "liquid", tiles = { { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, special_tiles = { -- New-style lava source material (mostly unused) { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, backface_culling = false, }, }, paramtype = "light", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 192, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, hot = 3, igniter = 1}, }) minetest.register_node("default:lava_flowing", { description = "Flowing Lava", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "flowingliquid", tiles = {"default_lava.png"}, special_tiles = { { name = "default_lava_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, { name = "default_lava_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, }, paramtype = "light", paramtype2 = "flowingliquid", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a = 192, r = 255, g = 64, b = 0}, groups = {lava = 3, liquid = 2, hot = 3, igniter = 1, not_in_creative_inventory = 1}, })
gpl-3.0
smanolache/kong
kong/plugins/rate-limiting/migrations/postgres.lua
1
1069
return { { name = "2015-08-03-132400_init_ratelimiting", up = [[ CREATE TABLE IF NOT EXISTS ratelimiting_metrics( api_id uuid, identifier text, period text, period_date timestamp without time zone, value integer, PRIMARY KEY (api_id, identifier, period_date, period) ); CREATE OR REPLACE FUNCTION increment_rate_limits(a_id uuid, i text, p text, p_date timestamp with time zone, v integer) RETURNS VOID AS $$ BEGIN LOOP UPDATE ratelimiting_metrics SET value = value + v WHERE api_id = a_id AND identifier = i AND period = p AND period_date = p_date; IF found then RETURN; END IF; BEGIN INSERT INTO ratelimiting_metrics(api_id, period, period_date, identifier, value) VALUES(a_id, p, p_date, i, v); RETURN; EXCEPTION WHEN unique_violation THEN END; END LOOP; END; $$ LANGUAGE 'plpgsql'; ]], down = [[ DROP TABLE ratelimiting_metrics; ]] } }
apache-2.0
oceancn/luci-nwan
luci/modules/admin-full/luasrc/model/cbi/admin_system/fstab/mount.lua
3
3240
--[[ LuCI - Lua Configuration Interface Copyright 2010 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 $Id: mount.lua 6562 2010-11-27 04:55:38Z jow $ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local has_extroot = fs.access("/sbin/block") local has_fscheck = fs.access("/usr/sbin/e2fsck") local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Mount Entry")) m.redirect = luci.dispatcher.build_url("admin/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "mount" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "mount", translate("Mount Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this mount")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) o = mount:taboption("general", Value, "target", translate("Mount point"), translate("Specifies the directory the device is attached to")) o:depends("is_rootfs", "") o = mount:taboption("general", Value, "fstype", translate("Filesystem"), translate("The filesystem that was used to format the memory (<abbr title=\"for example\">e.g.</abbr> <samp><abbr title=\"Third Extended Filesystem\">ext3</abbr></samp>)")) local fs for fs in io.lines("/proc/filesystems") do fs = fs:match("%S+") if fs ~= "nodev" then o:value(fs) end end o = mount:taboption("advanced", Value, "options", translate("Mount options"), translate("See \"mount\" manpage for details")) o.placeholder = "defaults" if has_extroot then o = mount:taboption("general", Flag, "is_rootfs", translate("Use as root filesystem"), translate("Configures this mount as overlay storage for block-extroot")) o:depends("fstype", "jffs") o:depends("fstype", "ext2") o:depends("fstype", "ext3") o:depends("fstype", "ext4") end if has_fscheck then o = mount:taboption("general", Flag, "enabled_fsck", translate("Run filesystem check"), translate("Run a filesystem check before mounting the device")) end return m
mit
smanolache/kong
spec/plugins/hmac-auth/access_spec.lua
4
23300
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local crypto = require "crypto" local base64 = require "base64" local PROXY_URL = spec_helper.PROXY_URL local STUB_GET_URL = spec_helper.STUB_GET_URL local STUB_POST_URL = spec_helper.STUB_POST_URL local hmac_sha1_binary = function(secret, data) return crypto.hmac.digest("sha1", data, secret, true) end local SIGNATURE_NOT_VALID = "HMAC signature cannot be verified" describe("Authentication Plugin", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests-hmac-auth", request_host = "hmacauth.com", upstream_url = "http://mockbin.org/"}, {name = "tests-hmac-auth2", request_host = "hmacauth2.com", upstream_url = "http://httpbin.org/"} }, consumer = { {username = "hmacauth_tests_consuser"} }, plugin = { {name = "hmac-auth", config = {clock_skew = 3000}, __api = 1}, {name = "hmac-auth", config = {clock_skew = 3000}, __api = 2} }, hmacauth_credential = { {username = "bob", secret = "secret", __consumer = 1} } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("HMAC Authentication", function() it("should not be authorized when the hmac credentials are missing", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date}) local parsed_response = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", parsed_response.message) end) it("should not be authorized when the HMAC signature is wrong", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not be authorized when date header is missing", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication", body.message) end) it("should not be authorized when the HMAC signature is wrong in proxy-authorization", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = "asd"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass when passing only the digest", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = "hmac :dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass when passing wrong hmac parameters", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = "hmac username=,algorithm,headers,dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass when passing wrong hmac parameters", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = "hmac username=,algorithm=,headers=,signature=dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not be authorized when passing only the username", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = "hmac username"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not be authorized when authorization is missing", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization123 = "hmac username:dXNlcm5hbWU6cGFzc3dvcmQ="}) local body = cjson.decode(response) assert.equal(401, status) assert.equal("Unauthorized", body.message) end) it("should pass with GET", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date)) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, authorization = hmacAuth}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET and proxy-authorization", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date)) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(nil, parsed_response.headers["authorization"]) end) it("should pass with POST", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date)) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date",signature="]]..encodedSignature..[["]] local response, status = http_client.post(STUB_POST_URL, {}, {host = "hmacauth.com", date = date, authorization = hmacAuth}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET and valid authorization and wrong proxy-authorization", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date)) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = "hmac username", authorization = hmacAuth}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET and invalid authorization and valid proxy-authorization", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date)) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization ="hello"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["authorization"]) end) it("should pass with GET with content-md5", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1",headers="date content-md5",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["authorization"]) end) it("should pass with GET with request-line", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1", headers="date content-md5 request-line", signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["authorization"]) end) it("should not pass with GET with wrong username", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bobb", algorithm="hmac-sha1", headers="date content-md5 request-line", signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with username blank", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="", algorithm="hmac-sha1", headers="date content-md5 request-line", signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with username missing", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac algorithm="hmac-sha1", headers="date content-md5 request-line", signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with wrong hmac headers field name", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1", header="date content-md5 request-line", signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with wrong hmac signature field name", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1", headers="date content-md5 request-line", signatures="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with malformed hmac signature field", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1" headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should not pass with GET with malformed hmac headers field", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1" headers=" date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal(SIGNATURE_NOT_VALID, body.message) end) it("should pass with GET with no space or space between hmac signatures fields", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["authorization"]) end) it("should pass with GET with wrong algorithm", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha256", headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal("hello", parsed_response.headers["authorization"]) end) it("should pass the right headers to the upstream server", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /headers? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha256", headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(PROXY_URL.."/headers", {}, {host = "hmacauth2.com", date = date, ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.truthy(parsed_response.headers["X-Consumer-Id"]) assert.truthy(parsed_response.headers["X-Consumer-Username"]) assert.truthy(parsed_response.headers["X-Credential-Username"]) assert.equal("bob", parsed_response.headers["X-Credential-Username"]) end) it("should pass with GET with x-date header", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "x-date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="x-date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = date, authorization = hmacAuth, ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should not pass with GET with both date and x-date missing", function() local encodedSignature = base64.encode(hmac_sha1_binary("secret", "content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob", algorithm="hmac-sha1" headers="content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["proxy-authorization"] = hmacAuth, authorization = "hello", ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication", body.message) end) it("should not pass with GET with x-date malformed", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "x-date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="x-date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = "wrong date", authorization = hmacAuth, ["content-md5"] = "md5"}) local body = cjson.decode(response) assert.equal(403, status) assert.equal("HMAC signature cannot be verified, a valid date or x-date header is required for HMAC Authentication", body.message) end) it("should pass with GET with x-date malformed but date correct", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = "wrong date", date = date, authorization = hmacAuth, ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET with x-date malformed but date correct and used for signature", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: "..date.."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = "wrong date", date = date, authorization = hmacAuth, ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET with x-date malformed and used for signature but skew test pass", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "x-date: ".."wrong date".."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="x-date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = "wrong date", date = date, authorization = hmacAuth, ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) it("should pass with GET with date malformed and used for signature but skew test pass", function() local date = os.date("!%a, %d %b %Y %H:%M:%S GMT") local encodedSignature = base64.encode(hmac_sha1_binary("secret", "date: ".."wrong date".."\n".."content-md5: md5".."\nGET /request? HTTP/1.1")) local hmacAuth = [["hmac username="bob",algorithm="hmac-sha1", headers="date content-md5 request-line",signature="]]..encodedSignature..[["]] local response, status = http_client.get(STUB_GET_URL, {}, {host = "hmacauth.com", ["x-date"] = date, date = "wrong date", authorization = hmacAuth, ["content-md5"] = "md5"}) assert.equal(200, status) local parsed_response = cjson.decode(response) assert.equal(hmacAuth, parsed_response.headers["authorization"]) end) end) end)
apache-2.0
Scavenge/darkstar
scripts/globals/items/remedy.lua
7
1289
----------------------------------------- -- ID: 4155 -- Item: Remedy -- Item Effect: This potion remedies status ailments. -- Works on paralysis, silence, blindness, poison, and disease. ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) return 0; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) if (target:hasStatusEffect(EFFECT_SILENCE) == true) then target:delStatusEffect(EFFECT_SILENCE); end if (target:hasStatusEffect(EFFECT_BLINDNESS) == true) then target:delStatusEffect(EFFECT_BLINDNESS); end if (target:hasStatusEffect(EFFECT_POISON) == true) then target:delStatusEffect(EFFECT_POISON); end if (target:hasStatusEffect(EFFECT_PARALYSIS) == true) then target:delStatusEffect(EFFECT_PARALYSIS); end local rDisease = math.random(1,2) -- Disease is not garunteed to be cured, 1 means removed 2 means fail. 50% chance if (rDisease == 1 and target:hasStatusEffect(EFFECT_DISEASE) == true) then target:delStatusEffect(EFFECT_DISEASE); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/bloody_bolt.lua
26
1410
----------------------------------------- -- ID: 18151 -- Item: Bloody Bolt -- Additional Effect: Drains HP ----------------------------------------- require("scripts/globals/status"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 95; if (target:getMainLvl() > player:getMainLvl()) then chance = chance - 5 * (target:getMainLvl() - player:getMainLvl()) chance = utils.clamp(chance, 5, 95); end if (math.random(0,99) >= chance or target:isUndead()) then return 0,0,0; else local diff = player:getStat(MOD_INT) - target:getStat(MOD_INT); if (diff > 20) then diff = 20 + (diff - 20) / 2; end local drain = diff + (player:getMainLvl() - target:getMainLvl()) + damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; drain = addBonusesAbility(player, ELE_DARK, target, drain, params); drain = drain * applyResistanceAddEffect(player,target,ELE_DARK,0); drain = adjustForTarget(target,drain,ELE_DARK); if (drain < 0) then drain = 0 end drain = finalMagicNonSpellAdjustments(player,target,ELE_DARK,drain); return SUBEFFECT_HP_DRAIN, MSGBASIC_ADD_EFFECT_HP_DRAIN,player:addHP(drain); end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
units/armjamt.lua
3
3084
unitDef = { unitname = [[armjamt]], name = [[Sneaky Pete]], description = [[Area Cloaker/Jammer]], activateWhenBuilt = true, buildCostEnergy = 420, buildCostMetal = 420, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 4, buildingGroundDecalSizeY = 4, buildingGroundDecalType = [[armjamt_aoplane.dds]], buildPic = [[ARMJAMT.png]], buildTime = 420, canAttack = false, category = [[SINK UNARMED]], cloakCost = 1, collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[32 70 32]], collisionVolumeType = [[CylY]], corpse = [[DEAD]], customParams = { description_de = [[Verhüllender Turm / Störsender]], helptext = [[Jammers such as this intefere with enemy radar waves, concealing your units' radar returns. Sneaky Pete is also equipped with a cloak shield to hide nearby units from enemy sight.]], helptext_de = [[Störsender wie diese behindern das feindliche Radar, verschleiern, die von deinen Einheiten ausgelösten, Radarechos. Sneaky Pete bietet außerdem noch ein Deckmantel, um Einheiten in der Nähe vor dem Gegner zu verstecken.]], removewait = 1, morphto = [[spherecloaker]], morphtime = 30, area_cloak = 1, area_cloak_upkeep = 12, area_cloak_radius = 550, area_cloak_decloak_distance = 75, priority_misc = 2, -- High }, energyUse = 1.5, explodeAs = [[BIG_UNITEX]], floater = true, footprintX = 2, footprintZ = 2, iconType = [[staticjammer]], idleAutoHeal = 5, idleTime = 1800, initCloaked = true, levelGround = false, maxDamage = 700, maxSlope = 36, minCloakDistance = 100, noAutoFire = false, objectName = [[radarjammer.dae]], onoffable = true, radarDistanceJam = 550, script = [[armjamt.lua]], seismicSignature = 16, selfDestructAs = [[BIG_UNITEX]], sightDistance = 250, useBuildingGroundDecal = true, yardMap = [[oo oo]], featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[radarjammer_dead.dae]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ armjamt = unitDef })
gpl-2.0
focusworld/antispam
plugins/invite.lua
1111
1195
do local function callbackres(extra, success, result) -- Callback for res_user in line 27 local user = 'user#id'..result.id local chat = 'chat#id'..extra.chatid if is_banned(result.id, extra.chatid) then -- Ignore bans send_large_msg(chat, 'User is banned.') elseif is_gbanned(result.id) then -- Ignore globall bans send_large_msg(chat, 'User is globaly banned.') else chat_add_user(chat, user, ok_cb, false) -- Add user on chat end end function run(msg, matches) local data = load_data(_config.moderation.data) if not is_realm(msg) then if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then return 'Group is private.' end end if msg.to.type ~= 'chat' then return end if not is_momod(msg) then return end --if not is_admin(msg) then -- For admins only ! --return 'Only admins can invite.' --end local cbres_extra = {chatid = msg.to.id} local username = matches[1] local username = username:gsub("@","") res_user(username, callbackres, cbres_extra) end return { patterns = { "^[!/]invite (.*)$" }, run = run } end
gpl-2.0
mamaddeveloper/jjhw
plugins/remind.lua
362
1875
local filename='data/remind.lua' local cronned = load_from_file(filename) local function save_cron(msg, text,date) local origin = get_receiver(msg) if not cronned[date] then cronned[date] = {} end local arr = { origin, text } ; table.insert(cronned[date], arr) serialize_to_file(cronned, filename) return 'Saved!' end local function delete_cron(date) for k,v in pairs(cronned) do if k == date then cronned[k]=nil end end serialize_to_file(cronned, filename) end local function cron() for date, values in pairs(cronned) do if date < os.time() then --time's up send_msg(values[1][1], "Time's up:\n"..values[1][2], ok_cb, false) delete_cron(date) --TODO: Maybe check for something else? Like user end end end local function actually_run(msg, delay,text) if (not delay or not text) then return "Usage: !remind [delay: 2h3m1s] text" end save_cron(msg, text,delay) return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'" end local function run(msg, matches) local sum = 0 for i = 1, #matches-1 do local b,_ = string.gsub(matches[i],"[a-zA-Z]","") if string.find(matches[i], "s") then sum=sum+b end if string.find(matches[i], "m") then sum=sum+b*60 end if string.find(matches[i], "h") then sum=sum+b*3600 end end local date=sum+os.time() local text = matches[#matches] local text = actually_run(msg, date, text) return text end return { description = "remind plugin", usage = { "!remind [delay: 2hms] text", "!remind [delay: 2h3m] text", "!remind [delay: 2h3m1s] text" }, patterns = { "^!remind ([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$", "^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$" }, run = run, cron = cron }
gpl-2.0
Scavenge/darkstar
scripts/zones/Port_Jeuno/npcs/Sagheera.lua
11
10850
----------------------------------- -- Area: Port Jeuno -- NPC: Sagheera -- @pos -3 0.1 -9 246 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Port_Jeuno/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/armor_upgrade"); local ABreward = {15244,14812,14813,15475,15476,15477,15488,14815,15961,2127}; local ABremove = {150,75,75,75,150,75,75, 75, 75,75}; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local CurrentAFupgrade = player:getVar("AFupgrade"); local StoreAncientBeastcoins = player:getCurrency("ancient_beastcoin"); local AvailableCombinationDetected = 0; local cost = 0; local time = os.date("*t"); if (CurrentAFupgrade == 0 and count == 4) then -- RELIC Armor +1 ??? for nb = 2, #Relic_Armor_Plus_one, 2 do --looking for the relic armor --trade base relic armor --trade temenos Item --trade Apollyon item --trade craft item have enought ancien beastcoin ctore ? if (trade:hasItemQty(Relic_Armor_Plus_one[nb][2],1) and trade:hasItemQty(Relic_Armor_Plus_one[nb][3],1) and trade:hasItemQty(Relic_Armor_Plus_one[nb][4],1) and trade:hasItemQty(Relic_Armor_Plus_one[nb][5],1) and Relic_Armor_Plus_one[nb][6] <= StoreAncientBeastcoins) then AvailableCombinationDetected = Relic_Armor_Plus_one[nb-1]; cost = Relic_Armor_Plus_one[nb][6]; printf("detect trade - available relic combination: %u", Relic_Armor_Plus_one[nb][1]); end end elseif (CurrentAFupgrade == 0 and AvailableCombinationDetected == 0) then -- Artfact Armor +1 ??? for nb = 2, #Artifact_Armor_Plus_one, 2 do --looking for the Artifact armor --trade base Artfact armor --- trade Artfact armor -1 trade craft item if (trade:hasItemQty(Artifact_Armor_Plus_one[nb][2],1) and trade:hasItemQty(Artifact_Armor_Plus_one[nb][3],1) and trade:hasItemQty(Artifact_Armor_Plus_one[nb][4],1) and trade:hasItemQty(Artifact_Armor_Plus_one[nb][5],Artifact_Armor_Plus_one[nb][6])) then if (count == 3 + Artifact_Armor_Plus_one[nb][6]) then --check the total number of item trade (base af + af-1 + craft item + number of curency) AvailableCombinationDetected = Artifact_Armor_Plus_one[nb-1]; printf("detect trade - available Artifact combination: %u", Artifact_Armor_Plus_one[nb][1]); end end end end if (trade:hasItemQty(1875, count) and AvailableCombinationDetected == 0) then --- AB storage local total = player:getCurrency("ancient_beastcoin") + count; player:startEvent(0x0137, count, 0, 0, 0, 0, 0, 0, total); if (total < 9999) then -- store max 9999 Ancien beastcoin player:addCurrency("ancient_beastcoin", count); player:tradeComplete(); end elseif (AvailableCombinationDetected ~= 0) then player:setVar("AFupgrade", AvailableCombinationDetected); player:setVar("AFupgradeDay", os.time(t) + (3600 - time.min*60)); -- Current time + Remaining minutes in the hour in seconds (Day Change) player:delCurrency("ancient_beastcoin", cost); -- cost is defined if the relic/af was found above player:tradeComplete(); player:startEvent(0x0138); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); local CurrentAFupgrade = 0; local StoreAB = player:getCurrency("ancient_beastcoin"); local playergils = player:getGil(); local CosmoWaitTime = BETWEEN_2COSMOCLEANSE_WAIT_TIME * 20 * 60 * 60; local lastCosmoTime = player:getVar("Cosmo_Cleanse_TIME"); if (lastCosmoTime ~= 0) then lastCosmoTime = lastCosmoTime + CosmoWaitTime; end; local CosmoTime = 0; local hasCosmoCleanse = 0; if (player:hasKeyItem(COSMOCLEANSE)) then hasCosmoCleanse = 1; else if (lastCosmoTime <= os.time(t)) then CosmoTime = 2147483649; -- BITMASK for the purchase -- printf("CASE: LESSTHAN | BUY COSMOCLEANSE"); elseif (lastCosmoTime > os.time(t)) then CosmoTime = (lastCosmoTime - 1009843200) - 39600; -- (os.time number - BITMASK for the event) - 11 hours in seconds. Only works in this format (strangely). -- printf("CASE: GREATERTHAN | lastCosmoTime: "..lastCosmoTime.." | CosmoTime: "..CosmoTime); end end if (player:getVar("AFupgradeDay") <= os.time(t)) then CurrentAFupgrade = player:getVar("AFupgrade"); end if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno, 19) == false) then player:startEvent(313); else player:startEvent(0x0136, 3, CurrentAFupgrade, 0, playergils, CosmoTime, 1, hasCosmoCleanse, StoreAB); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) local option1 = 0; local option2 = 0; local option3 = 0; local option4 = 0; local option5 = 0; local option6 = 0; local option7 = 0; local option8 = 0; if (csid == 0x0136 and option > 0 and option <101) then for nb = 1, #Relic_Armor_Plus_one, 2 do --looking for the relic armor if (Relic_Armor_Plus_one[nb] == option) then option1 =Relic_Armor_Plus_one[nb+1][1]; --relic +1 option2 = Relic_Armor_Plus_one[nb+1][2]; --relic base option3 = Relic_Armor_Plus_one[nb+1][3]; --item 1 option4 = Relic_Armor_Plus_one[nb+1][4]; --item 2 option5 = Relic_Armor_Plus_one[nb+1][5]; --item 3 option8 = Relic_Armor_Plus_one[nb+1][6]; -- AB cost end end player:updateEvent(option1, option2, option3, option4, option5, option6, option7, option8); -- print("relic"); elseif (csid == 0x0136 and option > 200) then for nb = 1, #Relic_Armor_Plus_one, 2 do --looking for the relic armor if (Relic_Armor_Plus_one[nb] == option) then option1 =Relic_Armor_Plus_one[nb+1][1]; --relic +1 option2 = Relic_Armor_Plus_one[nb+1][2]; --relic base option3 = Relic_Armor_Plus_one[nb+1][3]; --item 1 option4 = Relic_Armor_Plus_one[nb+1][4]; --item 2 option5 = Relic_Armor_Plus_one[nb+1][5]; --item 3 option8 = Relic_Armor_Plus_one[nb+1][6]; -- AB cost end end player:updateEvent(option1, option2, option3, option4, option5, option6, option7, option8); -- print("relic"); elseif (csid == 0x0136 and option > 100 and option <201) then for nb = 1, #Artifact_Armor_Plus_one, 2 do --looking for the artifact armor if (Artifact_Armor_Plus_one[nb] == option) then option1 = Artifact_Armor_Plus_one[nb+1][1]; --af +1 option2 = Artifact_Armor_Plus_one[nb+1][2]; --af base option3 = Artifact_Armor_Plus_one[nb+1][3]; --af -1 option4 = Artifact_Armor_Plus_one[nb+1][4]; -- item option5 = Artifact_Armor_Plus_one[nb+1][5]; --curency ID option6 = Artifact_Armor_Plus_one[nb+1][6]; -- currency cost end end player:updateEvent(option1, option2, option3, option4, option5, option6, option7, option8); -- print("artifact"); end --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) local remainingAB=player:getCurrency("ancient_beastcoin"); local ugrade_armor_Type = 0 ; local ugrade_armor_ID = 0 ; --printf("CSID: %u",csid); --print("event finish"); --printf("RESULT: %u",option); if (csid == 313) then player:setMaskBit(player:getVar("WildcatJeuno"), "WildcatJeuno", 19, true); elseif (csid == 0x0136 and option == 3) then --add keyitem for limbus player:setVar("Cosmo_Cleanse_TIME", os.time(t)); player:addKeyItem(COSMOCLEANSE); player:messageSpecial(KEYITEM_OBTAINED, COSMOCLEANSE); player:delGil(15000); elseif (csid == 0x0136 and option >10 and option < 21) then -- ancient beastcoin reward if (player:getFreeSlotsCount() == 0 or player:hasItem(ABreward[option-10])) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, ABreward[option-10]); else player:delCurrency("ancient_beastcoin", ABremove[option-10]); player:addItem(ABreward[option-10]); player:messageSpecial(ITEM_OBTAINED, ABreward[option-10]); end elseif (csid == 0x0136 and option == 100) then -- upgrade armor reward ugrade_armor_Type = player:getVar("AFupgrade"); --printf("detect type: %u",ugrade_armor); if (ugrade_armor_Type < 101 or ugrade_armor_Type >200) then for nb = 1, #Relic_Armor_Plus_one, 2 do -- looking for the relic armor if (Relic_Armor_Plus_one[nb] == ugrade_armor_Type) then ugrade_armor_ID= Relic_Armor_Plus_one[nb+1][1]; end end else for nb = 1, #Artifact_Armor_Plus_one, 2 do -- looking for the Artifact armor if (Artifact_Armor_Plus_one[nb] == ugrade_armor_Type) then ugrade_armor_ID= Artifact_Armor_Plus_one[nb+1][1]; end end end if (player:getFreeSlotsCount() == 0 and ugrade_armor_ID ~= 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, ugrade_armor_ID); else player:addItem(ugrade_armor_ID); player:messageSpecial(ITEM_OBTAINED, ugrade_armor_ID); player:setVar("AFupgrade", 0); player:setVar("AFupgradeDay", 0); end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Western_Adoulin/npcs/Dewalt.lua
14
2104
----------------------------------- -- Area: Western Adoulin -- NPC: Dewalt -- Type: Standard NPC and Quest NPC -- Involved with Quests: 'Flavors of our Lives' -- 'Dont Ever Leaf Me' -- @zone 256 -- @pos -23 0 28 256 ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DELM = player:getQuestStatus(ADOULIN, DONT_EVER_LEAF_ME); local FOOL = player:getQuestStatus(ADOULIN, FLAVORS_OF_OUR_LIVES); if ((DELM == QUEST_ACCEPTED) and (player:getVar("DELM_Dewalt_Branch") < 1)) then -- Progresses Quest: 'Dont Ever Leaf Me' player:startEvent(0x1395); elseif ((FOOL == QUEST_ACCEPTED) and ((player:getVar("FOOL_Status") == 1) or (player:getVar("FOOL_Status") == 2))) then if (player:getVar("FOOL_Status") == 1) then -- Progresses Quest: 'Flavors of Our Lives' player:startEvent(0x0055); else -- Reminds player of hint for Quest: 'Flavors of Our Lives' player:startEvent(0x0069); end elseif ((DELM == QUEST_ACCEPTED) and (player:getVar("DELM_Dewalt_Branch") < 2)) then -- Reminds player of hint for Quest: 'Dont Ever Leaf Me' player:startEvent(0x1396); else -- Standard dialogue player:startEvent(0x1399); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x1395) then -- Progresses Quest: 'Dont Ever Leaf Me' player:setVar("DELM_Dewalt_Branch", 1); elseif (csid == 0x0055) then -- Progresses Quest: 'Flavors of Our Lives' player:setVar("FOOL_Status", 3); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/rolanberry_pie_+1.lua
12
1285
----------------------------------------- -- ID: 4339 -- Item: rolanberry_pie_+1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Magic 60 -- Intelligence 3 -- MP Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,4339); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 60); target:addMod(MOD_INT, 3); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 60); target:delMod(MOD_INT, 3); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Metalworks/npcs/Kaela.lua
14
1445
----------------------------------- -- Area: Metalworks -- NPC: Kaela -- Type: Adventurer's Assistant -- @pos 40.167 -14.999 16.073 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatBastok = player:getVar("WildcatBastok"); if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,8) == false) then player:startEvent(0x03a6); else player:startEvent(0x02e5); 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 == 0x03a6) then player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",8,true); end end;
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/BackgroundEffects/Checkerboard2File2x2.lua
1
1438
local Color1 = color(Var "Color1"); local Color2 = color(Var "Color2"); local a1 = LoadActor(Var "File1") .. { OnCommand= function(self) self:cropto(SCREEN_WIDTH/2,SCREEN_HEIGHT/2):diffuse(Color1) :effectclock("music") -- Explanation in StretchNoLoop.lua. if self.GetTexture then self:GetTexture():rate(self:GetParent():GetUpdateRate()) end end, GainFocusCommand=cmd(play); LoseFocusCommand=cmd(pause); }; local a2 = LoadActor(Var "File2") .. { OnCommand= function(self) self:cropto(SCREEN_WIDTH/2,SCREEN_HEIGHT/2):diffuse(Color2):effectclock("music") -- Explanation in StretchNoLoop.lua. if self.GetTexture then self:GetTexture():rate(self:GetParent():GetUpdateRate()) end end, GainFocusCommand=cmd(play); LoseFocusCommand=cmd(pause); }; local t = Def.ActorFrame { a1 .. { OnCommand=cmd(x,scale(1,0,4,SCREEN_LEFT,SCREEN_RIGHT);y,scale(1,0,4,SCREEN_TOP,SCREEN_BOTTOM)); }; a2 .. { OnCommand=cmd(x,scale(3,0,4,SCREEN_LEFT,SCREEN_RIGHT);y,scale(1,0,4,SCREEN_TOP,SCREEN_BOTTOM)); }; a2 .. { OnCommand=function(self) self:x(scale(1,0,4,SCREEN_LEFT,SCREEN_RIGHT)):y(scale(3,0,4,SCREEN_TOP,SCREEN_BOTTOM)) if self.SetDecodeMovie then self:SetDecodeMovie(false) end end }; a1 .. { OnCommand=function(self) self:x(scale(3,0,4,SCREEN_LEFT,SCREEN_RIGHT)):y(scale(3,0,4,SCREEN_TOP,SCREEN_BOTTOM)) if self.SetDecodeMovie then self:SetDecodeMovie(false) end end }; }; return t;
mit
1yvT0s/luvit
tests/test-tls-connect-two-client.lua
11
1196
require('tap')(function (test) local fixture = require('./fixture-tls') local tls = require('tls') local options = { cert = fixture.certPem, key = fixture.keyPem } local serverConnected = 0 local clientConnected = 0 test("tls connect simple two client", function() local server server = tls.createServer(options, function(conn) serverConnected = serverConnected + 1 p('accepted',serverConnected) conn:destroy() if (serverConnected == 2) then server:close() p('server closed') end end) server:listen(fixture.commonPort, function() p('listening') local client1, client2 client1 = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) client1:on('connect', function() clientConnected = clientConnected + 1 --client1:destroy() end) client1:on('error',function(err) p(err) end) client2 = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) client2:on('connect', function() clientConnected = clientConnected + 1 --client2:destroy() end) client2:on('error',function(err) p(err) end) end) end) end)
apache-2.0
Scavenge/darkstar
scripts/zones/Bastok_Mines/npcs/Titus.lua
56
1742
----------------------------------- -- Area: Bastok Mines -- NPC: Titus -- Alchemy Synthesis Image Support ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,1); local SkillCap = getCraftSkillCap(player,SKILL_ALCHEMY); local SkillLevel = player:getSkillLevel(SKILL_ALCHEMY); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_ALCHEMY_IMAGERY) == false) then player:startEvent(0x007B,SkillCap,SkillLevel,1,137,player:getGil(),0,0,0); else player:startEvent(0x007B,SkillCap,SkillLevel,1,137,player:getGil(),6758,0,0); end else player:startEvent(0x007B); 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 == 0x007B and option == 1) then player:messageSpecial(ALCHEMY_SUPPORT,0,7,1); player:addStatusEffect(EFFECT_ALCHEMY_IMAGERY,1,0,120); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/RuLude_Gardens/npcs/Goggehn.lua
14
3163
----------------------------------- -- Area: Ru'Lude Gardens -- NPC: Goggehn -- Involved in Mission: Bastok 3-3, 4-1 -- @zone 243 -- @pos 3 9 -76 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) pNation = player:getNation(); currentMission = player:getCurrentMission(BASTOK); missionStatus = player:getVar("MissionStatus"); if (currentMission == JEUNO_MISSION and missionStatus == 1) then player:startEvent(0x0029); elseif (currentMission == JEUNO_MISSION and missionStatus == 2) then player:startEvent(0x0042); elseif (currentMission == JEUNO_MISSION and missionStatus == 3) then player:startEvent(0x0026); elseif (player:getRank() == 4 and player:getCurrentMission(BASTOK) == 255 and getMissionRankPoints(player,13) == 1) then if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then player:startEvent(0x0081,1); else player:startEvent(0x0081); -- Start Mission 4-1 Magicite end elseif (currentMission == MAGICITE_BASTOK and missionStatus == 1) then player:startEvent(0x0084); elseif (currentMission == MAGICITE_BASTOK and missionStatus <= 5) then player:startEvent(0x0087); elseif (currentMission == MAGICITE_BASTOK and missionStatus == 6) then player:startEvent(0x0023); elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK)) then player:startEvent(0x0037); elseif (pNation == NATION_WINDURST) then player:startEvent(0x0004); elseif (pNation == NATION_SANDORIA) then player:startEvent(0x0002); else player:startEvent(0x0065); 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 == 0x0029) then player:setVar("MissionStatus",2); player:delKeyItem(LETTER_TO_THE_AMBASSADOR); elseif (csid == 0x0081 and option == 1) then player:setVar("MissionStatus",1); if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) == false) then player:addKeyItem(ARCHDUCAL_AUDIENCE_PERMIT); player:messageSpecial(KEYITEM_OBTAINED,ARCHDUCAL_AUDIENCE_PERMIT); end elseif (csid == 0x0026 or csid == 0x0023) then finishMissionTimeline(player,1,csid,option); end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
LuaUI/Widgets/gui_icon_sets.lua
6
1827
function widget:GetInfo() return { name = "Icon Sets", desc = "Manages alternate icon/buildpic sets.", author = "Sprung", license = "PD", layer = 1, enabled = true, } end options_path = 'Settings/Graphics/Unit Visibility/Radar Icons' options_order = { 'coniconchassis' } options = { coniconchassis = { name = 'Show constructor chassis', desc = 'Do constructor icons show chassis? Conveys more information but reduces visibility somewhat.', type = 'bool', value = false, noHotkey = true, OnChange = function(self) if not self.value then Spring.SetUnitDefIcon(UnitDefNames["armrectr"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["cornecro"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["corned"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["coracv"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["amphcon"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["corfast"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["arm_spider"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["corch"].id, "builder") Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "builder") else Spring.SetUnitDefIcon(UnitDefNames["armrectr"].id, "kbotbuilder") Spring.SetUnitDefIcon(UnitDefNames["cornecro"].id, "walkerbuilder") Spring.SetUnitDefIcon(UnitDefNames["corned"].id, "vehiclebuilder") Spring.SetUnitDefIcon(UnitDefNames["coracv"].id, "tankbuilder") Spring.SetUnitDefIcon(UnitDefNames["amphcon"].id, "amphbuilder") Spring.SetUnitDefIcon(UnitDefNames["corfast"].id, "jumpjetbuilder") Spring.SetUnitDefIcon(UnitDefNames["arm_spider"].id, "spiderbuilder") Spring.SetUnitDefIcon(UnitDefNames["corch"].id, "hoverbuilder") Spring.SetUnitDefIcon(UnitDefNames["shipcon"].id, "shipbuilder") end end, }, }
gpl-2.0
Scavenge/darkstar
scripts/commands/hide.lua
62
1164
--------------------------------------------------------------------------------------------------- -- func: hide -- desc: Hides the GM from other players. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "s" }; function onTrigger(player, cmd) -- Obtain the players hide status.. local isHidden = player:getVar("GMHidden"); if (cmd ~= nil) then if (cmd == "status") then player:PrintToPlayer(string.format('Current hide status: %s', tostring(isHidden))); return; end end -- Toggle the hide status.. if (isHidden == 0) then isHidden = 1; else isHidden = 0; end -- If hidden animate us beginning our hide.. if (isHidden == 1) then player:setVar( "GMHidden", 1 ); player:setGMHidden(true); player:PrintToPlayer( "You are now GM hidden from other players." ); else player:setVar( "GMHidden", 0 ); player:setGMHidden(false); player:PrintToPlayer( "You are no longer GM hidden from other players." ); end end
gpl-3.0
Promptitude/Badger-Derma
lua/autorun/client/dpoly.lua
1
1602
local meta = FindMetaTable( "Panel" ) function meta:SetVertices( verts ) self.vertices = {} local radiusW = self:GetWide() / 2 local radiusH = self:GetTall() / 2 self.vertices[ #self.vertices + 1 ] = { x = radiusW, y = radiusH } for i = 0, verts do local a = math.rad( i / verts * -360 ) self.vertices[ #self.vertices + 1 ] = { x = radiusW + math.sin( a ) * radiusW, y = radiusH + math.cos( a ) * radiusH } end self.vertices[ #self.vertices + 1 ] = { x = radiusW, y = radiusH } self:SetPaintedManually( true ) self.vParent = vgui.Create( "Panel", self:GetParent() ) self.vParent:SetPos( self:GetPos() ) self.vParent:SetSize( self:GetSize() ) self.vParent.vChild = self function self.vParent:Paint() if !self.vChild or !IsValid( self.vChild ) then return end render.ClearStencil() render.SetStencilEnable( true ) render.SetStencilWriteMask( 1 ) render.SetStencilTestMask( 1 ) render.SetStencilFailOperation( STENCILOPERATION_REPLACE ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilReferenceValue( 1 ) draw.NoTexture() surface.SetDrawColor( color_white ) surface.DrawPoly( self.vChild.vertices ) render.SetStencilFailOperation( STENCILOPERATION_ZERO ) render.SetStencilCompareFunction( STENCILCOMPARISONFUNCTION_EQUAL ) render.SetStencilReferenceValue( 1 ) self.vChild:PaintManual() render.SetStencilEnable( false ) end end --[[ Example: local example = vgui.Create( "DFrame" ) example:SetSize( 100, 100 ) example:SetVertices( 6 ) ]]--
mit
Scavenge/darkstar
scripts/zones/Lower_Jeuno/npcs/Matoaka.lua
17
1146
----------------------------------- -- Area: Lower Jeuno -- NPC: Matoaka -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MATOAKA_SHOP_DIALOG); stock = {0x340F,1250, -- Silver Earring 0x3490,1250, -- Silver Ring 0x3410,4140} -- Mythril Earring 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
Scavenge/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/qm10.lua
14
1037
----------------------------------- -- Area: Phomiuna Aqueducts -- NPC: qm10 (???) -- Notes: Opens south door @ J-7 -- @pos 113.474 -26.000 91.610 27 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 63; if (GetNPCByID(DoorOffset):getAnimation() == 9) then GetNPCByID(DoorOffset):openDoor(7); -- _0rh 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