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
geanux/darkstar
scripts/globals/items/bowl_of_sopa_de_pez_blanco.lua
35
1549
----------------------------------------- -- ID: 4601 -- Item: Bowl of Sopa de Pez Blanco -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 12 -- Dexterity 6 -- Mind -4 -- Accuracy 3 -- Ranged ACC % 7 -- Ranged ACC Cap 10 ----------------------------------------- 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,4601); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 12); target:addMod(MOD_DEX, 6); target:addMod(MOD_MND, -4); target:addMod(MOD_ACC, 3); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 10); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 12); target:delMod(MOD_DEX, 6); target:delMod(MOD_MND, -4); target:delMod(MOD_ACC, 3); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 10); end;
gpl-3.0
bakert0/SuperSuperTux
TestHeuristics.lua
1
7423
function printBoard(board) returnString = "" for y=1,#board,1 do for x=1,#board[1],1 do if isBlock(board[y][x]) then returnString = returnString .. "1" else returnString = returnString .. "0" end end returnString = returnString .."\n" end return returnString end function copyBoard(board) local copy = {} for y=1,#board,1 do copy[y] = {} for x=1,#board[1],1 do if isBlock(board[y][x]) then table.insert(copy[y],1) else table.insert(copy[y],0) end end end return copy end function isBlock(cell) return cell == 1 end function isEmpty(cell) return cell == 0 end function holesInBoard(board) --A hole is an empty space that is under a block. --It does not have to be directly under a block. local holes = {} local block_in_col = false for x = 1,#board[1],1 do for y = 1,#board,1 do if block_in_col and isEmpty(board[y][x]) then table.insert(holes, {x,y}) elseif isBlock(board[y][x]) then block_in_col = true end end block_in_col = false end return holes end function numHoles(board) return #holesInBoard(board) end function numBlocksAboveHoles(board) --Number of blocks that are located on top of a hole --A block does not need to be directly on top of a hold to count. local count = 0 local holes = holesInBoard(board) for i=1,#holes do hole_x = holes[i][1] hole_y = holes[i][2] for y=hole_y-1,1,-1 do if isBlock(board[y][hole_x]) then count = count + 1 else break end end end return count end function numGaps(board) --Like holes but finds gagps horizonally local gaps = {} local sequence = 0 -- 0 = No Progress, 1 = Found Block, 2 = Found Block Gap local boardCopy = copyBoard(board) for y = 1,#board,1 do table.insert(boardCopy[y],1,1) table.insert(boardCopy[y],1) end for y=1,#boardCopy,1 do for x=1,#boardCopy[1],1 do if sequence == 0 and isBlock(boardCopy[y][x]) then sequence = 1 elseif sequence == 1 and isEmpty(boardCopy[y][x]) then sequence = 2 elseif sequence == 2 then if isBlock(boardCopy[y][x]) then table.insert(gaps,boardCopy[y][x-1]) sequence = 1 else sequence = 0 end end end end return #gaps end function maxHeight(board) --return the max height for y=1,#board,1 do for x=1,#board[1],1 do cell = board[y][x] if isBlock(cell) then return #board - y end end end end function avgHeight(board) --return the average height of all block local totalheight = 0 for y=1,#board,1 do currHeight = #board - y for x=1,#board[1],1 do cell = board[y][x] if isBlock(cell) then totalheight = totalheight + currHeight end end end return totalheight / numBlocks(board) end function numBlocks(board) --return number of blocks local count = 0 for y=1,#board,1 do for x=1,#board[1],1 do if isBlock(board[y][x]) then count = count + 1 end end end return count end --Begin Section to find the best move function getMoves(board,piece) allMoves = {} for r=1,numRotations(piece),1 do for x=1,getMaxX(piece[r],board),1 do y = firstCollision(x,piece[r],board) - 1 thisboard = newBoard(x,y,piece[r],board) table.insert(allMoves,{x=x,r=r,board=thisboard}) end end return allMoves end --Returns y value of the first collision point --A block should be therefore be placed at y - 1 function firstCollision(x,piece,board) for y=1,#board,1 do --Loop over all possible y posiitons for cy=1,#piece,1 do -- Loop over all y values of piece for cx=1,#piece[1],1 do --Loop over all x values of piece if isBlock(piece[cy][cx]) and cy+y > #board then return y end if isBlock(piece[cy][cx]) and isBlock(board[y+cy-1][x+cx-1]) then return y end end end end end --Returns a new board with a given piece's rotation placed at (x,y) function newBoard(x,y,piece,board) thisBoard = copyBoard(board) for cy=1,#piece,1 do for cx=1,#piece[1],1 do if isBlock(piece[cy][cx]) then thisBoard[y+cy-1][x+cx-1] = 1 end end end return thisBoard end --Given a piece, return the number rotations it has --Since a piece is a 3D array where the first dimension is rotation, simply return the length to get number of rotations function numRotations(piece) return #piece end --Given a piece in a rotation, determine the x most value it can be placed. function getMaxX(piece,board) maxX = 0 for y=1,#piece,1 do for x=1,#piece[1] do if isBlock(piece[y][x]) and x > maxX then maxX = x end end end return #board[1] - (maxX-1) end --Scores a board based on heurisitic weights function scoreBoard(board,heuritics) local score = 0 score = score + numHoles(board) * heurisitics.holes score = score + numBlocksAboveHoles(board) * heurisitics.aboveHoles score = score + numGaps(board) * heurisitics.gaps score = score + maxHeight(board) * heurisitics.maxHeight score = score + avgHeight(board) * heurisitics.avgHeight score = score + numBlocks(board) * heurisitics.blocks return score end --finds a given board and piece's best move function bestMove(board,piece) allMoves = getMoves(board,piece) best = 0 bestScore = 0 for i=1,#allMoves,1 do local thisScore = scoreBoard(allMoves[i].board) if thisScore > bestScore then best = i bestScore = thisScore end end return allMoves[best] end board = {{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, 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, 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, 0, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 0, 0, 0, 0, 0}, {0, 0, 0, 0, 1, 1, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 1, 0, 0, 0, 0}, {0, 0, 1, 0, 0, 1, 1, 0, 0, 0}, {0, 0, 1, 0, 1, 1, 1, 0, 0, 0}, {0, 0, 1, 0, 0, 0, 1, 1, 0, 0}, {1, 1, 1, 1, 0, 0, 1, 0, 0, 0}, {1, 1, 1, 1, 0, 1, 1, 1, 0, 0}, {1, 0, 0, 1, 1, 0, 1, 1, 0, 0}, {1, 1, 0, 1, 1, 0, 1, 0, 0, 0}, {1, 0, 1, 1, 1, 1, 1, 0, 0, 0}} print(board[1]) print(numHoles(board))--22 print(numBlocksAboveHoles(board) )--25 print(numGaps(board))--7 print(maxHeight(board))--13 local total_height = 13*2 + 12*1 + 11*1 + 10*1 + 9*2 + 8*2 + 7*3 + 6*4 + 5*3 + 4*5 + 3*8 + 2*5 + 1*5 + 0*6 print(avgHeight(board)) print( total_height / numBlocks(board)) print(numBlocks(board)) --48 testpiece1 = {{{0,1,1},{1,1,0},{0,0,0}},{{1,0,0},{1,1,0},{0,1,0}}} testpiece2 = {{{1,1,1},{0,1,0},{0,0,0}}} print(getMaxX(testpiece1[2],board)) -- 9 print(getMaxX(testpiece2,board)) -- 8 print(numRotations(testpiece1)) -- 2 board2 = newBoard(1,1,testpiece1[1],board) --print_r(board2) --print_r(board) print(firstCollision(4,testpiece1[2],board)) -- 8 print(firstCollision(6,testpiece2,board)) -- 10 print(firstCollision(8,testpiece2,board)) -- 18 heurisitics = {} heurisitics.holes = -496 heurisitics.aboveHoles = 897 heurisitics.gaps = 19 heurisitics.maxHeight = -910 heurisitics.avgHeight = -747 heurisitics.blocks = 174 print(scoreBoard(board,heuristics)) -- 11.9416667 best = bestMove(board,testpiece1) print(best.x .. " " .. best.r) print(printBoard(board)) print(printBoard(best.board))
mit
geanux/darkstar
scripts/globals/spells/hojo_ni.lua
18
1160
----------------------------------------- -- Spell: Hojo:Ni -- Description: Inflicts Slow on target. -- Edited from slow.lua ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Power for Hojo is a flat 19.5% reduction local power = 200; --Duration and Resistance calculation local duration = 300 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); --Calculates the resist chance from Resist Blind trait if (math.random(0,100) >= target:getMod(MOD_SLOWRES)) then -- Spell succeeds if a 1 or 1/2 resist check is achieved if (duration >= 150) then if (target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return EFFECT_SLOW; end;
gpl-3.0
evilexecutable/ResourceKeeper
install/Lua/lib/lua/pl/luabalanced.lua
49
8024
--- Extract delimited Lua sequences from strings. -- Inspired by Damian Conway's Text::Balanced in Perl. <br/> -- <ul> -- <li>[1] <a href="http://lua-users.org/wiki/LuaBalanced">Lua Wiki Page</a></li> -- <li>[2] http://search.cpan.org/dist/Text-Balanced/lib/Text/Balanced.pm</li> -- </ul> <br/> -- <pre class=example> -- local lb = require "pl.luabalanced" -- --Extract Lua expression starting at position 4. -- print(lb.match_expression("if x^2 + x > 5 then print(x) end", 4)) -- --> x^2 + x > 5 16 -- --Extract Lua string starting at (default) position 1. -- print(lb.match_string([["test\"123" .. "more"]])) -- --> "test\"123" 12 -- </pre> -- (c) 2008, David Manura, Licensed under the same terms as Lua (MIT license). -- @class module -- @name pl.luabalanced local M = {} local assert = assert local table_concat = table.concat -- map opening brace <-> closing brace. local ends = { ['('] = ')', ['{'] = '}', ['['] = ']' } local begins = {}; for k,v in pairs(ends) do begins[v] = k end -- Match Lua string in string <s> starting at position <pos>. -- Returns <string>, <posnew>, where <string> is the matched -- string (or nil on no match) and <posnew> is the character -- following the match (or <pos> on no match). -- Supports all Lua string syntax: "...", '...', [[...]], [=[...]=], etc. local function match_string(s, pos) pos = pos or 1 local posa = pos local c = s:sub(pos,pos) if c == '"' or c == "'" then pos = pos + 1 while 1 do pos = assert(s:find("[" .. c .. "\\]", pos), 'syntax error') if s:sub(pos,pos) == c then local part = s:sub(posa, pos) return part, pos + 1 else pos = pos + 2 end end else local sc = s:match("^%[(=*)%[", pos) if sc then local _; _, pos = s:find("%]" .. sc .. "%]", pos) assert(pos) local part = s:sub(posa, pos) return part, pos + 1 else return nil, pos end end end M.match_string = match_string -- Match bracketed Lua expression, e.g. "(...)", "{...}", "[...]", "[[...]]", -- [=[...]=], etc. -- Function interface is similar to match_string. local function match_bracketed(s, pos) pos = pos or 1 local posa = pos local ca = s:sub(pos,pos) if not ends[ca] then return nil, pos end local stack = {} while 1 do pos = s:find('[%(%{%[%)%}%]\"\']', pos) assert(pos, 'syntax error: unbalanced') local c = s:sub(pos,pos) if c == '"' or c == "'" then local part; part, pos = match_string(s, pos) assert(part) elseif ends[c] then -- open local mid, posb if c == '[' then mid, posb = s:match('^%[(=*)%[()', pos) end if mid then pos = s:match('%]' .. mid .. '%]()', posb) assert(pos, 'syntax error: long string not terminated') if #stack == 0 then local part = s:sub(posa, pos-1) return part, pos end else stack[#stack+1] = c pos = pos + 1 end else -- close assert(stack[#stack] == assert(begins[c]), 'syntax error: unbalanced') stack[#stack] = nil if #stack == 0 then local part = s:sub(posa, pos) return part, pos+1 end pos = pos + 1 end end end M.match_bracketed = match_bracketed -- Match Lua comment, e.g. "--...\n", "--[[...]]", "--[=[...]=]", etc. -- Function interface is similar to match_string. local function match_comment(s, pos) pos = pos or 1 if s:sub(pos, pos+1) ~= '--' then return nil, pos end pos = pos + 2 local partt, post = match_string(s, pos) if partt then return '--' .. partt, post end local part; part, pos = s:match('^([^\n]*\n?)()', pos) return '--' .. part, pos end -- Match Lua expression, e.g. "a + b * c[e]". -- Function interface is similar to match_string. local wordop = {['and']=true, ['or']=true, ['not']=true} local is_compare = {['>']=true, ['<']=true, ['~']=true} local function match_expression(s, pos) pos = pos or 1 local posa = pos local lastident local poscs, posce while pos do local c = s:sub(pos,pos) if c == '"' or c == "'" or c == '[' and s:find('^[=%[]', pos+1) then local part; part, pos = match_string(s, pos) assert(part, 'syntax error') elseif c == '-' and s:sub(pos+1,pos+1) == '-' then -- note: handle adjacent comments in loop to properly support -- backtracing (poscs/posce). poscs = pos while s:sub(pos,pos+1) == '--' do local part; part, pos = match_comment(s, pos) assert(part) pos = s:match('^%s*()', pos) posce = pos end elseif c == '(' or c == '{' or c == '[' then local part; part, pos = match_bracketed(s, pos) elseif c == '=' and s:sub(pos+1,pos+1) == '=' then pos = pos + 2 -- skip over two-char op containing '=' elseif c == '=' and is_compare[s:sub(pos-1,pos-1)] then pos = pos + 1 -- skip over two-char op containing '=' elseif c:match'^[%)%}%];,=]' then local part = s:sub(posa, pos-1) return part, pos elseif c:match'^[%w_]' then local newident,newpos = s:match('^([%w_]+)()', pos) if pos ~= posa and not wordop[newident] then -- non-first ident local pose = ((posce == pos) and poscs or pos) - 1 while s:match('^%s', pose) do pose = pose - 1 end local ce = s:sub(pose,pose) if ce:match'[%)%}\'\"%]]' or ce:match'[%w_]' and not wordop[lastident] then local part = s:sub(posa, pos-1) return part, pos end end lastident, pos = newident, newpos else pos = pos + 1 end pos = s:find('[%(%{%[%)%}%]\"\';,=%w_%-]', pos) end local part = s:sub(posa, #s) return part, #s+1 end M.match_expression = match_expression -- Match name list (zero or more names). E.g. "a,b,c" -- Function interface is similar to match_string, -- but returns array as match. local function match_namelist(s, pos) pos = pos or 1 local list = {} while 1 do local c = #list == 0 and '^' or '^%s*,%s*' local item, post = s:match(c .. '([%a_][%w_]*)%s*()', pos) if item then pos = post else break end list[#list+1] = item end return list, pos end M.match_namelist = match_namelist -- Match expression list (zero or more expressions). E.g. "a+b,b*c". -- Function interface is similar to match_string, -- but returns array as match. local function match_explist(s, pos) pos = pos or 1 local list = {} while 1 do if #list ~= 0 then local post = s:match('^%s*,%s*()', pos) if post then pos = post else break end end local item; item, pos = match_expression(s, pos) assert(item, 'syntax error') list[#list+1] = item end return list, pos end M.match_explist = match_explist -- Replace snippets of code in Lua code string <s> -- using replacement function f(u,sin) --> sout. -- <u> is the type of snippet ('c' = comment, 's' = string, -- 'e' = any other code). -- Snippet is replaced with <sout> (unless <sout> is nil or false, in -- which case the original snippet is kept) -- This is somewhat analogous to string.gsub . local function gsub(s, f) local pos = 1 local posa = 1 local sret = '' while 1 do pos = s:find('[%-\'\"%[]', pos) if not pos then break end if s:match('^%-%-', pos) then local exp = s:sub(posa, pos-1) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end local comment; comment, pos = match_comment(s, pos) sret = sret .. (f('c', assert(comment)) or comment) posa = pos else local posb = s:find('^[\'\"%[]', pos) local str if posb then str, pos = match_string(s, posb) end if str then local exp = s:sub(posa, posb-1) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end sret = sret .. (f('s', str) or str) posa = pos else pos = pos + 1 end end end local exp = s:sub(posa) if #exp > 0 then sret = sret .. (f('e', exp) or exp) end return sret end M.gsub = gsub return M
gpl-2.0
geanux/darkstar
scripts/zones/Bastok_Markets/npcs/Gwill.lua
17
2884
----------------------------------- -- Area: Bastok Markets -- NPC: Gwill -- Starts & Ends Quest: The Return of the Adventurer -- Involved in Quests: The Cold Light of Day, Riding on the Clouds -- @zone 235 -- @pos 0 0 0 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) returnOfAdven = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER); if (returnOfAdven == QUEST_ACCEPTED and trade:hasItemQty(628,1) and trade:getItemCount() == 1) then player:startEvent(0x00f3); end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 2) 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) pFame = player:getFameLevel(BASTOK); FatherFigure = player:getQuestStatus(BASTOK,FATHER_FIGURE); TheReturn = player:getQuestStatus(BASTOK,THE_RETURN_OF_THE_ADVENTURER); if (FatherFigure == QUEST_COMPLETED and TheReturn == QUEST_AVAILABLE and pFame >= 3) then player:startEvent(0x00f2); elseif (player:getQuestStatus(BASTOK,THE_COLD_LIGHT_OF_DAY) == QUEST_ACCEPTED) then player:startEvent(0x0067); else player:startEvent(0x0071); 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 == 0x00f2) then player:addQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER); elseif (csid == 0x00f3) then if (player:getFreeSlotsCount() >= 1) then player:tradeComplete(); player:addTitle(KULATZ_BRIDGE_COMPANION); player:addItem(12498); player:messageSpecial(ITEM_OBTAINED,12498); player:addFame(BASTOK,BAS_FAME*80); player:completeQuest(BASTOK,THE_RETURN_OF_THE_ADVENTURER); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12498); end end end;
gpl-3.0
geanux/darkstar
scripts/globals/weaponskills/frostbite.lua
30
1231
----------------------------------- -- Frostbite -- Great Sword weapon skill -- Skill Level: 70 -- Delivers an ice elemental attack. Damage varies with TP. -- Aligned with the Snow Gorget. -- Aligned with the Snow Belt. -- Element: Ice -- Modifiers: STR:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_ICE; params.skill = SKILL_GSD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
jiangzhhhh/slua
build/luajit-2.1.0-beta3/dynasm/dasm_x86.lua
32
71256
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2017 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ local x64 = x64 -- Module information: local _info = { arch = x64 and "x64" or "x86", description = "DynASM x86/x64 module", version = "1.4.0", vernum = 10400, release = "2015-10-18", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, unpack, setmetatable = assert, unpack or table.unpack, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local find, match, gmatch, gsub = _s.find, _s.match, _s.gmatch, _s.gsub local concat, sort, remove = table.concat, table.sort, table.remove local bit = bit or require("bit") local band, bxor, shl, shr = bit.band, bit.bxor, bit.lshift, bit.rshift -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { -- int arg, 1 buffer pos: "DISP", "IMM_S", "IMM_B", "IMM_W", "IMM_D", "IMM_WB", "IMM_DB", -- action arg (1 byte), int arg, 1 buffer pos (reg/num): "VREG", "SPACE", -- ptrdiff_t arg, 1 buffer pos (address): !x64 "SETLABEL", "REL_A", -- action arg (1 byte) or int arg, 2 buffer pos (link, offset): "REL_LG", "REL_PC", -- action arg (1 byte) or int arg, 1 buffer pos (link): "IMM_LG", "IMM_PC", -- action arg (1 byte) or int arg, 1 buffer pos (offset): "LABEL_LG", "LABEL_PC", -- action arg (1 byte), 1 buffer pos (offset): "ALIGN", -- action args (2 bytes), no buffer pos. "EXTERN", -- action arg (1 byte), no buffer pos. "ESC", -- no action arg, no buffer pos. "MARK", -- action arg (1 byte), no buffer pos, terminal action: "SECTION", -- no args, no buffer pos, terminal action: "STOP" } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number (dynamically generated below). local map_action = {} -- First action number. Everything below does not need to be escaped. local actfirst = 256-#action_names -- Action list buffer and string (only used to remove dupes). local actlist = {} local actstr = "" -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 -- VREG kind encodings, pre-shifted by 5 bits. local map_vreg = { ["modrm.rm.m"] = 0x00, ["modrm.rm.r"] = 0x20, ["opcode"] = 0x20, ["sib.base"] = 0x20, ["sib.index"] = 0x40, ["modrm.reg"] = 0x80, ["vex.v"] = 0xa0, ["imm.hi"] = 0xc0, } -- Current number of VREG actions contributing to REX/VEX shrinkage. local vreg_shrink_count = 0 ------------------------------------------------------------------------------ -- Compute action numbers for action names. for n,name in ipairs(action_names) do local num = actfirst + n - 1 map_action[name] = num end -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist local last = actlist[nn] or 255 actlist[nn] = nil -- Remove last byte. if nn == 0 then nn = 1 end out:write("static const unsigned char ", name, "[", nn, "] = {\n") local s = " " for n,b in ipairs(actlist) do s = s..b.."," if #s >= 75 then assert(out:write(s, "\n")) s = " " end end out:write(s, last, "\n};\n\n") -- Add last byte back. end ------------------------------------------------------------------------------ -- Add byte to action list. local function wputxb(n) assert(n >= 0 and n <= 255 and n % 1 == 0, "byte out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, a, num) wputxb(assert(map_action[action], "bad action name `"..action.."'")) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Optionally add a VREG action. local function wvreg(kind, vreg, psz, sk, defer) if not vreg then return end waction("VREG", vreg) local b = assert(map_vreg[kind], "bad vreg kind `"..vreg.."'") if b < (sk or 0) then vreg_shrink_count = vreg_shrink_count + 1 end if not defer then b = b + vreg_shrink_count * 8 vreg_shrink_count = 0 end wputxb(b + (psz or 0)) end -- Add call to embedded DynASM C code. local function wcall(func, args) wline(format("dasm_%s(Dst, %s);", func, concat(args, ", ")), true) end -- Delete duplicate action list chunks. A tad slow, but so what. local function dedupechunk(offset) local al, as = actlist, actstr local chunk = char(unpack(al, offset+1, #al)) local orig = find(as, chunk, 1, true) if orig then actargs[1] = orig-1 -- Replace with original offset. for i=offset+1,#al do al[i] = nil end -- Kill dupe. else actstr = as..chunk end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) local offset = actargs[1] if #actlist == offset then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. dedupechunk(offset) wcall("put", actargs) -- Add call to dasm_put(). actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped byte. local function wputb(n) if n >= actfirst then waction("ESC") end -- Need to escape byte. wputxb(n) end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 10 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_@]*$") then werror("bad global label") end local n = next_global if n > 246 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=10,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=10,next_global-1 do out:write(" ", prefix, gsub(t[i], "@.*", ""), ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=10,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = -1 local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n < -256 then werror("too many extern labels") end next_extern = n - 1 t[name] = n return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("Extern labels:\n") for i=1,-next_extern-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) local t = {} for name, n in pairs(map_extern) do t[-n] = name end out:write("static const char *const ", name, "[] = {\n") for i=1,-next_extern-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = {} -- Ext. register name -> int. name. local map_reg_rev = {} -- Int. register name -> ext. name. local map_reg_num = {} -- Int. register name -> register number. local map_reg_opsize = {} -- Int. register name -> operand size. local map_reg_valid_base = {} -- Int. register name -> valid base register? local map_reg_valid_index = {} -- Int. register name -> valid index register? local map_reg_needrex = {} -- Int. register name -> need rex vs. no rex. local reg_list = {} -- Canonical list of int. register names. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for _PTx macros). local addrsize = x64 and "q" or "d" -- Size for address operands. -- Helper functions to fill register maps. local function mkrmap(sz, cl, names) local cname = format("@%s", sz) reg_list[#reg_list+1] = cname map_archdef[cl] = cname map_reg_rev[cname] = cl map_reg_num[cname] = -1 map_reg_opsize[cname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[cname] = true map_reg_valid_index[cname] = true end if names then for n,name in ipairs(names) do local iname = format("@%s%x", sz, n-1) reg_list[#reg_list+1] = iname map_archdef[name] = iname map_reg_rev[iname] = name map_reg_num[iname] = n-1 map_reg_opsize[iname] = sz if sz == "b" and n > 4 then map_reg_needrex[iname] = false end if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end for i=0,(x64 and sz ~= "f") and 15 or 7 do local needrex = sz == "b" and i > 3 local iname = format("@%s%x%s", sz, i, needrex and "R" or "") if needrex then map_reg_needrex[iname] = true end local name if sz == "o" or sz == "y" then name = format("%s%d", cl, i) elseif sz == "f" then name = format("st%d", i) else name = format("r%d%s", i, sz == addrsize and "" or sz) end map_archdef[name] = iname if not map_reg_rev[iname] then reg_list[#reg_list+1] = iname map_reg_rev[iname] = name map_reg_num[iname] = i map_reg_opsize[iname] = sz if sz == addrsize or sz == "d" then map_reg_valid_base[iname] = true map_reg_valid_index[iname] = true end end end reg_list[#reg_list+1] = "" end -- Integer registers (qword, dword, word and byte sized). if x64 then mkrmap("q", "Rq", {"rax", "rcx", "rdx", "rbx", "rsp", "rbp", "rsi", "rdi"}) end mkrmap("d", "Rd", {"eax", "ecx", "edx", "ebx", "esp", "ebp", "esi", "edi"}) mkrmap("w", "Rw", {"ax", "cx", "dx", "bx", "sp", "bp", "si", "di"}) mkrmap("b", "Rb", {"al", "cl", "dl", "bl", "ah", "ch", "dh", "bh"}) map_reg_valid_index[map_archdef.esp] = false if x64 then map_reg_valid_index[map_archdef.rsp] = false end if x64 then map_reg_needrex[map_archdef.Rb] = true end map_archdef["Ra"] = "@"..addrsize -- FP registers (internally tword sized, but use "f" as operand size). mkrmap("f", "Rf") -- SSE registers (oword sized, but qword and dword accessible). mkrmap("o", "xmm") -- AVX registers (yword sized, but oword, qword and dword accessible). mkrmap("y", "ymm") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", yword = "y", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, y = 32, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", y = "yword", t = "tword", f = "fpword", } -- Valid index register scale factors. local map_xsc = { ["1"] = 0, ["2"] = 1, ["4"] = 2, ["8"] = 3, } -- Condition codes. local map_cc = { o = 0, no = 1, b = 2, nb = 3, e = 4, ne = 5, be = 6, nbe = 7, s = 8, ns = 9, p = 10, np = 11, l = 12, nl = 13, le = 14, nle = 15, c = 2, nae = 2, nc = 3, ae = 3, z = 4, nz = 5, na = 6, a = 7, pe = 10, po = 11, nge = 12, ge = 13, ng = 14, g = 15, } -- Reverse defines for registers. function _M.revdef(s) return gsub(s, "@%w+", map_reg_rev) end -- Dump register names and numbers local function dumpregs(out) out:write("Register names, sizes and internal numbers:\n") for _,reg in ipairs(reg_list) do if reg == "" then out:write("\n") else local name = map_reg_rev[reg] local num = map_reg_num[reg] local opsize = map_opsizename[map_reg_opsize[reg]] out:write(format(" %-5s %-8s %s\n", name, opsize, num < 0 and "(variable)" or num)) end end end ------------------------------------------------------------------------------ -- Put action for label arg (IMM_LG, IMM_PC, REL_LG, REL_PC). local function wputlabel(aprefix, imm, num) if type(imm) == "number" then if imm < 0 then waction("EXTERN") wputxb(aprefix == "IMM_" and 0 or 1) imm = -imm-1 else waction(aprefix.."LG", nil, num); end wputxb(imm) else waction(aprefix.."PC", imm, num) end end -- Put signed byte or arg. local function wputsbarg(n) if type(n) == "number" then if n < -128 or n > 127 then werror("signed immediate byte out of range") end if n < 0 then n = n + 256 end wputb(n) else waction("IMM_S", n) end end -- Put unsigned byte or arg. local function wputbarg(n) if type(n) == "number" then if n < 0 or n > 255 then werror("unsigned immediate byte out of range") end wputb(n) else waction("IMM_B", n) end end -- Put unsigned word or arg. local function wputwarg(n) if type(n) == "number" then if shr(n, 16) ~= 0 then werror("unsigned immediate word out of range") end wputb(band(n, 255)); wputb(shr(n, 8)); else waction("IMM_W", n) end end -- Put signed or unsigned dword or arg. local function wputdarg(n) local tn = type(n) if tn == "number" then wputb(band(n, 255)) wputb(band(shr(n, 8), 255)) wputb(band(shr(n, 16), 255)) wputb(shr(n, 24)) elseif tn == "table" then wputlabel("IMM_", n[1], 1) else waction("IMM_D", n) end end -- Put operand-size dependent number or arg (defaults to dword). local function wputszarg(sz, n) if not sz or sz == "d" or sz == "q" then wputdarg(n) elseif sz == "w" then wputwarg(n) elseif sz == "b" then wputbarg(n) elseif sz == "s" then wputsbarg(n) else werror("bad operand size") end end -- Put multi-byte opcode with operand-size dependent modifications. local function wputop(sz, op, rex, vex, vregr, vregxb) local psz, sk = 0, nil if vex then local tail if vex.m == 1 and band(rex, 11) == 0 then if x64 and vregxb then sk = map_vreg["modrm.reg"] else wputb(0xc5) tail = shl(bxor(band(rex, 4), 4), 5) psz = 3 end end if not tail then wputb(0xc4) wputb(shl(bxor(band(rex, 7), 7), 5) + vex.m) tail = shl(band(rex, 8), 4) psz = 4 end local reg, vreg = 0, nil if vex.v then reg = vex.v.reg if not reg then werror("bad vex operand") end if reg < 0 then reg = 0; vreg = vex.v.vreg end end if sz == "y" or vex.l then tail = tail + 4 end wputb(tail + shl(bxor(reg, 15), 3) + vex.p) wvreg("vex.v", vreg) rex = 0 if op >= 256 then werror("bad vex opcode") end else if rex ~= 0 then if not x64 then werror("bad operand size") end elseif (vregr or vregxb) and x64 then rex = 0x10 sk = map_vreg["vex.v"] end end local r if sz == "w" then wputb(102) end -- Needs >32 bit numbers, but only for crc32 eax, word [ebx] if op >= 4294967296 then r = op%4294967296 wputb((op-r)/4294967296) op = r end if op >= 16777216 then wputb(shr(op, 24)); op = band(op, 0xffffff) end if op >= 65536 then if rex ~= 0 then local opc3 = band(op, 0xffff00) if opc3 == 0x0f3a00 or opc3 == 0x0f3800 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end end wputb(shr(op, 16)); op = band(op, 0xffff); psz = psz + 1 end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0; psz = 2 end wputb(b); op = band(op, 255); psz = psz + 1 end if rex ~= 0 then wputb(64 + band(rex, 15)); psz = 2 end if sz == "b" then op = op - 1 end wputb(op) return psz, sk end -- Put ModRM or SIB formatted byte. local function wputmodrm(m, s, rm, vs, vrm) assert(m < 4 and s < 16 and rm < 16, "bad modrm operands") wputb(shl(m, 6) + shl(band(s, 7), 3) + band(rm, 7)) end -- Put ModRM/SIB plus optional displacement. local function wputmrmsib(t, imark, s, vsreg, psz, sk) local vreg, vxreg local reg, xreg = t.reg, t.xreg if reg and reg < 0 then reg = 0; vreg = t.vreg end if xreg and xreg < 0 then xreg = 0; vxreg = t.vxreg end if s < 0 then s = 0 end -- Register mode. if sub(t.mode, 1, 1) == "r" then wputmodrm(3, s, reg) wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.r", vreg, psz+1, sk) return end local disp = t.disp local tdisp = type(disp) -- No base register? if not reg then local riprel = false if xreg then -- Indexed mode with index register only. -- [xreg*xsc+disp] -> (0, s, esp) (xsc, xreg, ebp) wputmodrm(0, s, 4) if imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg) wputmodrm(t.xsc, xreg, 5) wvreg("sib.index", vxreg, psz+2, sk) else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) wvreg("modrm.reg", vsreg, psz+1, sk) if imark == "I" then waction("MARK") end end end if riprel then -- Emit rip-relative displacement. if match("UWSiI", imark) then werror("NYI: rip-relative displacement followed by immediate") end -- The previous byte in the action buffer cannot be 0xe9 or 0x80-0x8f. wputlabel("REL_", disp[1], 2) else wputdarg(disp) end return end local m if tdisp == "number" then -- Check displacement size at assembly time. if disp == 0 and band(reg, 7) ~= 5 then -- [ebp] -> [ebp+0] (in SIB, too) if not vreg then m = 0 end -- Force DISP to allow [Rd(5)] -> [ebp+0] elseif disp >= -128 and disp <= 127 then m = 1 else m = 2 end elseif tdisp == "table" then m = 2 end -- Index register present or esp as base register: need SIB encoding. if xreg or band(reg, 7) == 4 then wputmodrm(m or 2, s, 4) -- ModRM. if m == nil or imark == "I" then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vxreg or vreg) wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. wvreg("sib.index", vxreg, psz+2, sk, vreg) wvreg("sib.base", vreg, psz+2, sk) else wputmodrm(m or 2, s, reg) -- ModRM. if (imark == "I" and (m == 1 or m == 2)) or (m == nil and (vsreg or vreg)) then waction("MARK") end wvreg("modrm.reg", vsreg, psz+1, sk, vreg) wvreg("modrm.rm.m", vreg, psz+1, sk) end -- Put displacement. if m == 1 then wputsbarg(disp) elseif m == 2 then wputdarg(disp) elseif m == nil then waction("DISP", disp) end end ------------------------------------------------------------------------------ -- Return human-readable operand mode string. local function opmodestr(op, args) local m = {} for i=1,#args do local a = args[i] m[#m+1] = sub(a.mode, 1, 1)..(a.opsize or "?") end return op.." "..concat(m, ",") end -- Convert number to valid integer or nil. local function toint(expr) local n = tonumber(expr) if n then if n % 1 ~= 0 or n < -2147483648 or n > 4294967295 then werror("bad integer number `"..expr.."'") end return n end end -- Parse immediate expression. local function immexpr(expr) -- &expr (pointer) if sub(expr, 1, 1) == "&" then return "iPJ", format("(ptrdiff_t)(%s)", sub(expr,2)) end local prefix = sub(expr, 1, 2) -- =>expr (pc label reference) if prefix == "=>" then return "iJ", sub(expr, 3) end -- ->name (global label reference) if prefix == "->" then return "iJ", map_global[sub(expr, 3)] end -- [<>][1-9] (local label reference) local dir, lnum = match(expr, "^([<>])([1-9])$") if dir then -- Fwd: 247-255, Bkwd: 1-9. return "iJ", lnum + (dir == ">" and 246 or 0) end local extname = match(expr, "^extern%s+(%S+)$") if extname then return "iJ", map_extern[extname] end -- expr (interpreted as immediate) return "iI", expr end -- Parse displacement expression: +-num, +-expr, +-opsize*num local function dispexpr(expr) local disp = expr == "" and 0 or toint(expr) if disp then return disp end local c, dispt = match(expr, "^([+-])%s*(.+)$") if c == "+" then expr = dispt elseif not c then werror("bad displacement expression `"..expr.."'") end local opsize, tailops = match(dispt, "^(%w+)%s*%*%s*(.+)$") local ops, imm = map_opsize[opsize], toint(tailops) if ops and imm then if c == "-" then imm = -imm end return imm*map_opsizenum[ops] end local mode, iexpr = immexpr(dispt) if mode == "iJ" then if c == "-" then werror("cannot invert label reference") end return { iexpr } end return expr -- Need to return original signed expression. end -- Parse register or type expression. local function rtexpr(expr) if not expr then return end local tname, ovreg = match(expr, "^([%w_]+):(@[%w_]+)$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg local rnum = map_reg_num[reg] if not rnum then werror("type `"..(tname or expr).."' needs a register override") end if not map_reg_valid_base[reg] then werror("bad base register override `"..(map_reg_rev[reg] or reg).."'") end return reg, rnum, tp end return expr, map_reg_num[expr] end -- Parse operand and return { mode, opsize, reg, xreg, xsc, disp, imm }. local function parseoperand(param) local t = {} local expr = param local opsize, tailops = match(param, "^(%w+)%s*(.+)$") if opsize then t.opsize = map_opsize[opsize] if t.opsize then expr = tailops end end local br = match(expr, "^%[%s*(.-)%s*%]$") repeat if br then t.mode = "xm" -- [disp] t.disp = toint(br) if t.disp then t.mode = x64 and "xm" or "xmO" break end -- [reg...] local tp local reg, tailr = match(br, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if not t.reg then -- [expr] t.mode = x64 and "xm" or "xmO" t.disp = dispexpr("+"..br) break end if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- [xreg*xsc] or [xreg*xsc+-disp] or [xreg*xsc+-expr] local xsc, tailsc = match(tailr, "^%*%s*([1248])%s*(.*)$") if xsc then if not map_reg_valid_index[reg] then werror("bad index register `"..map_reg_rev[reg].."'") end t.xsc = map_xsc[xsc] t.xreg = t.reg t.vxreg = t.vreg t.reg = nil t.vreg = nil t.disp = dispexpr(tailsc) break end if not map_reg_valid_base[reg] then werror("bad base register `"..map_reg_rev[reg].."'") end -- [reg] or [reg+-disp] t.disp = toint(tailr) or (tailr == "" and 0) if t.disp then break end -- [reg+xreg...] local xreg, tailx = match(tailr, "^+%s*([@%w_:]+)%s*(.*)$") xreg, t.xreg, tp = rtexpr(xreg) if not t.xreg then -- [reg+-expr] t.disp = dispexpr(tailr) break end if not map_reg_valid_index[xreg] then werror("bad index register `"..map_reg_rev[xreg].."'") end if t.xreg == -1 then t.vxreg, tailx = match(tailx, "^(%b())(.*)$") if not t.vxreg then werror("bad variable register expression") end end -- [reg+xreg*xsc...] local xsc, tailsc = match(tailx, "^%*%s*([1248])%s*(.*)$") if xsc then t.xsc = map_xsc[xsc] tailx = tailsc end -- [...] or [...+-disp] or [...+-expr] t.disp = dispexpr(tailx) else -- imm or opsize*imm local imm = toint(expr) if not imm and sub(expr, 1, 1) == "*" and t.opsize then imm = toint(sub(expr, 2)) if imm then imm = imm * map_opsizenum[t.opsize] t.opsize = nil end end if imm then if t.opsize then werror("bad operand size override") end local m = "i" if imm == 1 then m = m.."1" end if imm >= 4294967168 and imm <= 4294967295 then imm = imm-4294967296 end if imm >= -128 and imm <= 127 then m = m.."S" end t.imm = imm t.mode = m break end local tp local reg, tailr = match(expr, "^([@%w_:]+)%s*(.*)$") reg, t.reg, tp = rtexpr(reg) if t.reg then if t.reg == -1 then t.vreg, tailr = match(tailr, "^(%b())(.*)$") if not t.vreg then werror("bad variable register expression") end end -- reg if tailr == "" then if t.opsize then werror("bad operand size override") end t.opsize = map_reg_opsize[reg] if t.opsize == "f" then t.mode = t.reg == 0 and "fF" or "f" else if reg == "@w4" or (x64 and reg == "@d4") then wwarn("bad idea, try again with `"..(x64 and "rsp'" or "esp'")) end t.mode = t.reg == 0 and "rmR" or (reg == "@b1" and "rmC" or "rm") end t.needrex = map_reg_needrex[reg] break end -- type[idx], type[idx].field, type->field -> [reg+offset_expr] if not tp then werror("bad operand `"..param.."'") end t.mode = "xm" t.disp = format(tp.ctypefmt, tailr) else t.mode, t.imm = immexpr(expr) if sub(t.mode, -1) == "J" then if t.opsize and t.opsize ~= addrsize then werror("bad operand size override") end t.opsize = addrsize end end end until true return t end ------------------------------------------------------------------------------ -- x86 Template String Description -- =============================== -- -- Each template string is a list of [match:]pattern pairs, -- separated by "|". The first match wins. No match means a -- bad or unsupported combination of operand modes or sizes. -- -- The match part and the ":" is omitted if the operation has -- no operands. Otherwise the first N characters are matched -- against the mode strings of each of the N operands. -- -- The mode string for each operand type is (see parseoperand()): -- Integer register: "rm", +"R" for eax, ax, al, +"C" for cl -- FP register: "f", +"F" for st0 -- Index operand: "xm", +"O" for [disp] (pure offset) -- Immediate: "i", +"S" for signed 8 bit, +"1" for 1, -- +"I" for arg, +"P" for pointer -- Any: +"J" for valid jump targets -- -- So a match character "m" (mixed) matches both an integer register -- and an index operand (to be encoded with the ModRM/SIB scheme). -- But "r" matches only a register and "x" only an index operand -- (e.g. for FP memory access operations). -- -- The operand size match string starts right after the mode match -- characters and ends before the ":". "dwb" or "qdwb" is assumed, if empty. -- The effective data size of the operation is matched against this list. -- -- If only the regular "b", "w", "d", "q", "t" operand sizes are -- present, then all operands must be the same size. Unspecified sizes -- are ignored, but at least one operand must have a size or the pattern -- won't match (use the "byte", "word", "dword", "qword", "tword" -- operand size overrides. E.g.: mov dword [eax], 1). -- -- If the list has a "1" or "2" prefix, the operand size is taken -- from the respective operand and any other operand sizes are ignored. -- If the list contains only ".", all operand sizes are ignored. -- If the list has a "/" prefix, the concatenated (mixed) operand sizes -- are compared to the match. -- -- E.g. "rrdw" matches for either two dword registers or two word -- registers. "Fx2dq" matches an st0 operand plus an index operand -- pointing to a dword (float) or qword (double). -- -- Every character after the ":" is part of the pattern string: -- Hex chars are accumulated to form the opcode (left to right). -- "n" disables the standard opcode mods -- (otherwise: -1 for "b", o16 prefix for "w", rex.w for "q") -- "X" Force REX.W. -- "r"/"R" adds the reg. number from the 1st/2nd operand to the opcode. -- "m"/"M" generates ModRM/SIB from the 1st/2nd operand. -- The spare 3 bits are either filled with the last hex digit or -- the result from a previous "r"/"R". The opcode is restored. -- "u" Use VEX encoding, vvvv unused. -- "v"/"V" Use VEX encoding, vvvv from 1st/2nd operand (the operand is -- removed from the list used by future characters). -- "L" Force VEX.L -- -- All of the following characters force a flush of the opcode: -- "o"/"O" stores a pure 32 bit disp (offset) from the 1st/2nd operand. -- "s" stores a 4 bit immediate from the last register operand, -- followed by 4 zero bits. -- "S" stores a signed 8 bit immediate from the last operand. -- "U" stores an unsigned 8 bit immediate from the last operand. -- "W" stores an unsigned 16 bit immediate from the last operand. -- "i" stores an operand sized immediate from the last operand. -- "I" dito, but generates an action code to optionally modify -- the opcode (+2) for a signed 8 bit immediate. -- "J" generates one of the REL action codes from the last operand. -- ------------------------------------------------------------------------------ -- Template strings for x86 instructions. Ordered by first opcode byte. -- Unimplemented opcodes (deliberate omissions) are marked with *. local map_op = { -- 00-05: add... -- 06: *push es -- 07: *pop es -- 08-0D: or... -- 0E: *push cs -- 0F: two byte opcode prefix -- 10-15: adc... -- 16: *push ss -- 17: *pop ss -- 18-1D: sbb... -- 1E: *push ds -- 1F: *pop ds -- 20-25: and... es_0 = "26", -- 27: *daa -- 28-2D: sub... cs_0 = "2E", -- 2F: *das -- 30-35: xor... ss_0 = "36", -- 37: *aaa -- 38-3D: cmp... ds_0 = "3E", -- 3F: *aas inc_1 = x64 and "m:FF0m" or "rdw:40r|m:FF0m", dec_1 = x64 and "m:FF1m" or "rdw:48r|m:FF1m", push_1 = (x64 and "rq:n50r|rw:50r|mq:nFF6m|mw:FF6m" or "rdw:50r|mdw:FF6m").."|S.:6AS|ib:n6Ai|i.:68i", pop_1 = x64 and "rq:n58r|rw:58r|mq:n8F0m|mw:8F0m" or "rdw:58r|mdw:8F0m", -- 60: *pusha, *pushad, *pushaw -- 61: *popa, *popad, *popaw -- 62: *bound rdw,x -- 63: x86: *arpl mw,rw movsxd_2 = x64 and "rm/qd:63rM", fs_0 = "64", gs_0 = "65", o16_0 = "66", a16_0 = not x64 and "67" or nil, a32_0 = x64 and "67", -- 68: push idw -- 69: imul rdw,mdw,idw -- 6A: push ib -- 6B: imul rdw,mdw,S -- 6C: *insb -- 6D: *insd, *insw -- 6E: *outsb -- 6F: *outsd, *outsw -- 70-7F: jcc lb -- 80: add... mb,i -- 81: add... mdw,i -- 82: *undefined -- 83: add... mdw,S test_2 = "mr:85Rm|rm:85rM|Ri:A9ri|mi:F70mi", -- 86: xchg rb,mb -- 87: xchg rdw,mdw -- 88: mov mb,r -- 89: mov mdw,r -- 8A: mov r,mb -- 8B: mov r,mdw -- 8C: *mov mdw,seg lea_2 = "rx1dq:8DrM", -- 8E: *mov seg,mdw -- 8F: pop mdw nop_0 = "90", xchg_2 = "Rrqdw:90R|rRqdw:90r|rm:87rM|mr:87Rm", cbw_0 = "6698", cwde_0 = "98", cdqe_0 = "4898", cwd_0 = "6699", cdq_0 = "99", cqo_0 = "4899", -- 9A: *call iw:idw wait_0 = "9B", fwait_0 = "9B", pushf_0 = "9C", pushfd_0 = not x64 and "9C", pushfq_0 = x64 and "9C", popf_0 = "9D", popfd_0 = not x64 and "9D", popfq_0 = x64 and "9D", sahf_0 = "9E", lahf_0 = "9F", mov_2 = "OR:A3o|RO:A1O|mr:89Rm|rm:8BrM|rib:nB0ri|ridw:B8ri|mi:C70mi", movsb_0 = "A4", movsw_0 = "66A5", movsd_0 = "A5", cmpsb_0 = "A6", cmpsw_0 = "66A7", cmpsd_0 = "A7", -- A8: test Rb,i -- A9: test Rdw,i stosb_0 = "AA", stosw_0 = "66AB", stosd_0 = "AB", lodsb_0 = "AC", lodsw_0 = "66AD", lodsd_0 = "AD", scasb_0 = "AE", scasw_0 = "66AF", scasd_0 = "AF", -- B0-B7: mov rb,i -- B8-BF: mov rdw,i -- C0: rol... mb,i -- C1: rol... mdw,i ret_1 = "i.:nC2W", ret_0 = "C3", -- C4: *les rdw,mq -- C5: *lds rdw,mq -- C6: mov mb,i -- C7: mov mdw,i -- C8: *enter iw,ib leave_0 = "C9", -- CA: *retf iw -- CB: *retf int3_0 = "CC", int_1 = "i.:nCDU", into_0 = "CE", -- CF: *iret -- D0: rol... mb,1 -- D1: rol... mdw,1 -- D2: rol... mb,cl -- D3: rol... mb,cl -- D4: *aam ib -- D5: *aad ib -- D6: *salc -- D7: *xlat -- D8-DF: floating point ops -- E0: *loopne -- E1: *loope -- E2: *loop -- E3: *jcxz, *jecxz -- E4: *in Rb,ib -- E5: *in Rdw,ib -- E6: *out ib,Rb -- E7: *out ib,Rdw call_1 = x64 and "mq:nFF2m|J.:E8nJ" or "md:FF2m|J.:E8J", jmp_1 = x64 and "mq:nFF4m|J.:E9nJ" or "md:FF4m|J.:E9J", -- short: EB -- EA: *jmp iw:idw -- EB: jmp ib -- EC: *in Rb,dx -- ED: *in Rdw,dx -- EE: *out dx,Rb -- EF: *out dx,Rdw lock_0 = "F0", int1_0 = "F1", repne_0 = "F2", repnz_0 = "F2", rep_0 = "F3", repe_0 = "F3", repz_0 = "F3", -- F4: *hlt cmc_0 = "F5", -- F6: test... mb,i; div... mb -- F7: test... mdw,i; div... mdw clc_0 = "F8", stc_0 = "F9", -- FA: *cli cld_0 = "FC", std_0 = "FD", -- FE: inc... mb -- FF: inc... mdw -- misc ops not_1 = "m:F72m", neg_1 = "m:F73m", mul_1 = "m:F74m", imul_1 = "m:F75m", div_1 = "m:F76m", idiv_1 = "m:F77m", imul_2 = "rmqdw:0FAFrM|rIqdw:69rmI|rSqdw:6BrmS|riqdw:69rmi", imul_3 = "rmIqdw:69rMI|rmSqdw:6BrMS|rmiqdw:69rMi", movzx_2 = "rm/db:0FB6rM|rm/qb:|rm/wb:0FB6rM|rm/dw:0FB7rM|rm/qw:", movsx_2 = "rm/db:0FBErM|rm/qb:|rm/wb:0FBErM|rm/dw:0FBFrM|rm/qw:", bswap_1 = "rqd:0FC8r", bsf_2 = "rmqdw:0FBCrM", bsr_2 = "rmqdw:0FBDrM", bt_2 = "mrqdw:0FA3Rm|miqdw:0FBA4mU", btc_2 = "mrqdw:0FBBRm|miqdw:0FBA7mU", btr_2 = "mrqdw:0FB3Rm|miqdw:0FBA6mU", bts_2 = "mrqdw:0FABRm|miqdw:0FBA5mU", shld_3 = "mriqdw:0FA4RmU|mrC/qq:0FA5Rm|mrC/dd:|mrC/ww:", shrd_3 = "mriqdw:0FACRmU|mrC/qq:0FADRm|mrC/dd:|mrC/ww:", rdtsc_0 = "0F31", -- P1+ rdpmc_0 = "0F33", -- P6+ cpuid_0 = "0FA2", -- P1+ -- floating point ops fst_1 = "ff:DDD0r|xd:D92m|xq:nDD2m", fstp_1 = "ff:DDD8r|xd:D93m|xq:nDD3m|xt:DB7m", fld_1 = "ff:D9C0r|xd:D90m|xq:nDD0m|xt:DB5m", fpop_0 = "DDD8", -- Alias for fstp st0. fist_1 = "xw:nDF2m|xd:DB2m", fistp_1 = "xw:nDF3m|xd:DB3m|xq:nDF7m", fild_1 = "xw:nDF0m|xd:DB0m|xq:nDF5m", fxch_0 = "D9C9", fxch_1 = "ff:D9C8r", fxch_2 = "fFf:D9C8r|Fff:D9C8R", fucom_1 = "ff:DDE0r", fucom_2 = "Fff:DDE0R", fucomp_1 = "ff:DDE8r", fucomp_2 = "Fff:DDE8R", fucomi_1 = "ff:DBE8r", -- P6+ fucomi_2 = "Fff:DBE8R", -- P6+ fucomip_1 = "ff:DFE8r", -- P6+ fucomip_2 = "Fff:DFE8R", -- P6+ fcomi_1 = "ff:DBF0r", -- P6+ fcomi_2 = "Fff:DBF0R", -- P6+ fcomip_1 = "ff:DFF0r", -- P6+ fcomip_2 = "Fff:DFF0R", -- P6+ fucompp_0 = "DAE9", fcompp_0 = "DED9", fldenv_1 = "x.:D94m", fnstenv_1 = "x.:D96m", fstenv_1 = "x.:9BD96m", fldcw_1 = "xw:nD95m", fstcw_1 = "xw:n9BD97m", fnstcw_1 = "xw:nD97m", fstsw_1 = "Rw:n9BDFE0|xw:n9BDD7m", fnstsw_1 = "Rw:nDFE0|xw:nDD7m", fclex_0 = "9BDBE2", fnclex_0 = "DBE2", fnop_0 = "D9D0", -- D9D1-D9DF: unassigned fchs_0 = "D9E0", fabs_0 = "D9E1", -- D9E2: unassigned -- D9E3: unassigned ftst_0 = "D9E4", fxam_0 = "D9E5", -- D9E6: unassigned -- D9E7: unassigned fld1_0 = "D9E8", fldl2t_0 = "D9E9", fldl2e_0 = "D9EA", fldpi_0 = "D9EB", fldlg2_0 = "D9EC", fldln2_0 = "D9ED", fldz_0 = "D9EE", -- D9EF: unassigned f2xm1_0 = "D9F0", fyl2x_0 = "D9F1", fptan_0 = "D9F2", fpatan_0 = "D9F3", fxtract_0 = "D9F4", fprem1_0 = "D9F5", fdecstp_0 = "D9F6", fincstp_0 = "D9F7", fprem_0 = "D9F8", fyl2xp1_0 = "D9F9", fsqrt_0 = "D9FA", fsincos_0 = "D9FB", frndint_0 = "D9FC", fscale_0 = "D9FD", fsin_0 = "D9FE", fcos_0 = "D9FF", -- SSE, SSE2 andnpd_2 = "rmo:660F55rM", andnps_2 = "rmo:0F55rM", andpd_2 = "rmo:660F54rM", andps_2 = "rmo:0F54rM", clflush_1 = "x.:0FAE7m", cmppd_3 = "rmio:660FC2rMU", cmpps_3 = "rmio:0FC2rMU", cmpsd_3 = "rrio:F20FC2rMU|rxi/oq:", cmpss_3 = "rrio:F30FC2rMU|rxi/od:", comisd_2 = "rro:660F2FrM|rx/oq:", comiss_2 = "rro:0F2FrM|rx/od:", cvtdq2pd_2 = "rro:F30FE6rM|rx/oq:", cvtdq2ps_2 = "rmo:0F5BrM", cvtpd2dq_2 = "rmo:F20FE6rM", cvtpd2ps_2 = "rmo:660F5ArM", cvtpi2pd_2 = "rx/oq:660F2ArM", cvtpi2ps_2 = "rx/oq:0F2ArM", cvtps2dq_2 = "rmo:660F5BrM", cvtps2pd_2 = "rro:0F5ArM|rx/oq:", cvtsd2si_2 = "rr/do:F20F2DrM|rr/qo:|rx/dq:|rxq:", cvtsd2ss_2 = "rro:F20F5ArM|rx/oq:", cvtsi2sd_2 = "rm/od:F20F2ArM|rm/oq:F20F2ArXM", cvtsi2ss_2 = "rm/od:F30F2ArM|rm/oq:F30F2ArXM", cvtss2sd_2 = "rro:F30F5ArM|rx/od:", cvtss2si_2 = "rr/do:F30F2DrM|rr/qo:|rxd:|rx/qd:", cvttpd2dq_2 = "rmo:660FE6rM", cvttps2dq_2 = "rmo:F30F5BrM", cvttsd2si_2 = "rr/do:F20F2CrM|rr/qo:|rx/dq:|rxq:", cvttss2si_2 = "rr/do:F30F2CrM|rr/qo:|rxd:|rx/qd:", fxsave_1 = "x.:0FAE0m", fxrstor_1 = "x.:0FAE1m", ldmxcsr_1 = "xd:0FAE2m", lfence_0 = "0FAEE8", maskmovdqu_2 = "rro:660FF7rM", mfence_0 = "0FAEF0", movapd_2 = "rmo:660F28rM|mro:660F29Rm", movaps_2 = "rmo:0F28rM|mro:0F29Rm", movd_2 = "rm/od:660F6ErM|rm/oq:660F6ErXM|mr/do:660F7ERm|mr/qo:", movdqa_2 = "rmo:660F6FrM|mro:660F7FRm", movdqu_2 = "rmo:F30F6FrM|mro:F30F7FRm", movhlps_2 = "rro:0F12rM", movhpd_2 = "rx/oq:660F16rM|xr/qo:n660F17Rm", movhps_2 = "rx/oq:0F16rM|xr/qo:n0F17Rm", movlhps_2 = "rro:0F16rM", movlpd_2 = "rx/oq:660F12rM|xr/qo:n660F13Rm", movlps_2 = "rx/oq:0F12rM|xr/qo:n0F13Rm", movmskpd_2 = "rr/do:660F50rM", movmskps_2 = "rr/do:0F50rM", movntdq_2 = "xro:660FE7Rm", movnti_2 = "xrqd:0FC3Rm", movntpd_2 = "xro:660F2BRm", movntps_2 = "xro:0F2BRm", movq_2 = "rro:F30F7ErM|rx/oq:|xr/qo:n660FD6Rm", movsd_2 = "rro:F20F10rM|rx/oq:|xr/qo:nF20F11Rm", movss_2 = "rro:F30F10rM|rx/od:|xr/do:F30F11Rm", movupd_2 = "rmo:660F10rM|mro:660F11Rm", movups_2 = "rmo:0F10rM|mro:0F11Rm", orpd_2 = "rmo:660F56rM", orps_2 = "rmo:0F56rM", pause_0 = "F390", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nRmU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmovmskb_2 = "rr/do:660FD7rM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", pshufd_3 = "rmio:660F70rMU", pshufhw_3 = "rmio:F30F70rMU", pshuflw_3 = "rmio:F20F70rMU", pslld_2 = "rmo:660FF2rM|rio:660F726mU", pslldq_2 = "rio:660F737mU", psllq_2 = "rmo:660FF3rM|rio:660F736mU", psllw_2 = "rmo:660FF1rM|rio:660F716mU", psrad_2 = "rmo:660FE2rM|rio:660F724mU", psraw_2 = "rmo:660FE1rM|rio:660F714mU", psrld_2 = "rmo:660FD2rM|rio:660F722mU", psrldq_2 = "rio:660F733mU", psrlq_2 = "rmo:660FD3rM|rio:660F732mU", psrlw_2 = "rmo:660FD1rM|rio:660F712mU", rcpps_2 = "rmo:0F53rM", rcpss_2 = "rro:F30F53rM|rx/od:", rsqrtps_2 = "rmo:0F52rM", rsqrtss_2 = "rmo:F30F52rM", sfence_0 = "0FAEF8", shufpd_3 = "rmio:660FC6rMU", shufps_3 = "rmio:0FC6rMU", stmxcsr_1 = "xd:0FAE3m", ucomisd_2 = "rro:660F2ErM|rx/oq:", ucomiss_2 = "rro:0F2ErM|rx/od:", unpckhpd_2 = "rmo:660F15rM", unpckhps_2 = "rmo:0F15rM", unpcklpd_2 = "rmo:660F14rM", unpcklps_2 = "rmo:0F14rM", xorpd_2 = "rmo:660F57rM", xorps_2 = "rmo:0F57rM", -- SSE3 ops fisttp_1 = "xw:nDF1m|xd:DB1m|xq:nDD1m", addsubpd_2 = "rmo:660FD0rM", addsubps_2 = "rmo:F20FD0rM", haddpd_2 = "rmo:660F7CrM", haddps_2 = "rmo:F20F7CrM", hsubpd_2 = "rmo:660F7DrM", hsubps_2 = "rmo:F20F7DrM", lddqu_2 = "rxo:F20FF0rM", movddup_2 = "rmo:F20F12rM", movshdup_2 = "rmo:F30F16rM", movsldup_2 = "rmo:F30F12rM", -- SSSE3 ops pabsb_2 = "rmo:660F381CrM", pabsd_2 = "rmo:660F381ErM", pabsw_2 = "rmo:660F381DrM", palignr_3 = "rmio:660F3A0FrMU", phaddd_2 = "rmo:660F3802rM", phaddsw_2 = "rmo:660F3803rM", phaddw_2 = "rmo:660F3801rM", phsubd_2 = "rmo:660F3806rM", phsubsw_2 = "rmo:660F3807rM", phsubw_2 = "rmo:660F3805rM", pmaddubsw_2 = "rmo:660F3804rM", pmulhrsw_2 = "rmo:660F380BrM", pshufb_2 = "rmo:660F3800rM", psignb_2 = "rmo:660F3808rM", psignd_2 = "rmo:660F380ArM", psignw_2 = "rmo:660F3809rM", -- SSE4.1 ops blendpd_3 = "rmio:660F3A0DrMU", blendps_3 = "rmio:660F3A0CrMU", blendvpd_3 = "rmRo:660F3815rM", blendvps_3 = "rmRo:660F3814rM", dppd_3 = "rmio:660F3A41rMU", dpps_3 = "rmio:660F3A40rMU", extractps_3 = "mri/do:660F3A17RmU|rri/qo:660F3A17RXmU", insertps_3 = "rrio:660F3A41rMU|rxi/od:", movntdqa_2 = "rxo:660F382ArM", mpsadbw_3 = "rmio:660F3A42rMU", packusdw_2 = "rmo:660F382BrM", pblendvb_3 = "rmRo:660F3810rM", pblendw_3 = "rmio:660F3A0ErMU", pcmpeqq_2 = "rmo:660F3829rM", pextrb_3 = "rri/do:660F3A14nRmU|rri/qo:|xri/bo:", pextrd_3 = "mri/do:660F3A16RmU", pextrq_3 = "mri/qo:660F3A16RmU", -- pextrw is SSE2, mem operand is SSE4.1 only phminposuw_2 = "rmo:660F3841rM", pinsrb_3 = "rri/od:660F3A20nrMU|rxi/ob:", pinsrd_3 = "rmi/od:660F3A22rMU", pinsrq_3 = "rmi/oq:660F3A22rXMU", pmaxsb_2 = "rmo:660F383CrM", pmaxsd_2 = "rmo:660F383DrM", pmaxud_2 = "rmo:660F383FrM", pmaxuw_2 = "rmo:660F383ErM", pminsb_2 = "rmo:660F3838rM", pminsd_2 = "rmo:660F3839rM", pminud_2 = "rmo:660F383BrM", pminuw_2 = "rmo:660F383ArM", pmovsxbd_2 = "rro:660F3821rM|rx/od:", pmovsxbq_2 = "rro:660F3822rM|rx/ow:", pmovsxbw_2 = "rro:660F3820rM|rx/oq:", pmovsxdq_2 = "rro:660F3825rM|rx/oq:", pmovsxwd_2 = "rro:660F3823rM|rx/oq:", pmovsxwq_2 = "rro:660F3824rM|rx/od:", pmovzxbd_2 = "rro:660F3831rM|rx/od:", pmovzxbq_2 = "rro:660F3832rM|rx/ow:", pmovzxbw_2 = "rro:660F3830rM|rx/oq:", pmovzxdq_2 = "rro:660F3835rM|rx/oq:", pmovzxwd_2 = "rro:660F3833rM|rx/oq:", pmovzxwq_2 = "rro:660F3834rM|rx/od:", pmuldq_2 = "rmo:660F3828rM", pmulld_2 = "rmo:660F3840rM", ptest_2 = "rmo:660F3817rM", roundpd_3 = "rmio:660F3A09rMU", roundps_3 = "rmio:660F3A08rMU", roundsd_3 = "rrio:660F3A0BrMU|rxi/oq:", roundss_3 = "rrio:660F3A0ArMU|rxi/od:", -- SSE4.2 ops crc32_2 = "rmqd:F20F38F1rM|rm/dw:66F20F38F1rM|rm/db:F20F38F0rM|rm/qb:", pcmpestri_3 = "rmio:660F3A61rMU", pcmpestrm_3 = "rmio:660F3A60rMU", pcmpgtq_2 = "rmo:660F3837rM", pcmpistri_3 = "rmio:660F3A63rMU", pcmpistrm_3 = "rmio:660F3A62rMU", popcnt_2 = "rmqdw:F30FB8rM", -- SSE4a extrq_2 = "rro:660F79rM", extrq_3 = "riio:660F780mUU", insertq_2 = "rro:F20F79rM", insertq_4 = "rriio:F20F78rMUU", lzcnt_2 = "rmqdw:F30FBDrM", movntsd_2 = "xr/qo:nF20F2BRm", movntss_2 = "xr/do:F30F2BRm", -- popcnt is also in SSE4.2 -- AES-NI aesdec_2 = "rmo:660F38DErM", aesdeclast_2 = "rmo:660F38DFrM", aesenc_2 = "rmo:660F38DCrM", aesenclast_2 = "rmo:660F38DDrM", aesimc_2 = "rmo:660F38DBrM", aeskeygenassist_3 = "rmio:660F3ADFrMU", pclmulqdq_3 = "rmio:660F3A44rMU", -- AVX FP ops vaddsubpd_3 = "rrmoy:660FVD0rM", vaddsubps_3 = "rrmoy:F20FVD0rM", vandpd_3 = "rrmoy:660FV54rM", vandps_3 = "rrmoy:0FV54rM", vandnpd_3 = "rrmoy:660FV55rM", vandnps_3 = "rrmoy:0FV55rM", vblendpd_4 = "rrmioy:660F3AV0DrMU", vblendps_4 = "rrmioy:660F3AV0CrMU", vblendvpd_4 = "rrmroy:660F3AV4BrMs", vblendvps_4 = "rrmroy:660F3AV4ArMs", vbroadcastf128_2 = "rx/yo:660F38u1ArM", vcmppd_4 = "rrmioy:660FVC2rMU", vcmpps_4 = "rrmioy:0FVC2rMU", vcmpsd_4 = "rrrio:F20FVC2rMU|rrxi/ooq:", vcmpss_4 = "rrrio:F30FVC2rMU|rrxi/ood:", vcomisd_2 = "rro:660Fu2FrM|rx/oq:", vcomiss_2 = "rro:0Fu2FrM|rx/od:", vcvtdq2pd_2 = "rro:F30FuE6rM|rx/oq:|rm/yo:", vcvtdq2ps_2 = "rmoy:0Fu5BrM", vcvtpd2dq_2 = "rmoy:F20FuE6rM", vcvtpd2ps_2 = "rmoy:660Fu5ArM", vcvtps2dq_2 = "rmoy:660Fu5BrM", vcvtps2pd_2 = "rro:0Fu5ArM|rx/oq:|rm/yo:", vcvtsd2si_2 = "rr/do:F20Fu2DrM|rx/dq:|rr/qo:|rxq:", vcvtsd2ss_3 = "rrro:F20FV5ArM|rrx/ooq:", vcvtsi2sd_3 = "rrm/ood:F20FV2ArM|rrm/ooq:F20FVX2ArM", vcvtsi2ss_3 = "rrm/ood:F30FV2ArM|rrm/ooq:F30FVX2ArM", vcvtss2sd_3 = "rrro:F30FV5ArM|rrx/ood:", vcvtss2si_2 = "rr/do:F30Fu2DrM|rxd:|rr/qo:|rx/qd:", vcvttpd2dq_2 = "rmo:660FuE6rM|rm/oy:660FuLE6rM", vcvttps2dq_2 = "rmoy:F30Fu5BrM", vcvttsd2si_2 = "rr/do:F20Fu2CrM|rx/dq:|rr/qo:|rxq:", vcvttss2si_2 = "rr/do:F30Fu2CrM|rxd:|rr/qo:|rx/qd:", vdppd_4 = "rrmio:660F3AV41rMU", vdpps_4 = "rrmioy:660F3AV40rMU", vextractf128_3 = "mri/oy:660F3AuL19RmU", vextractps_3 = "mri/do:660F3Au17RmU", vhaddpd_3 = "rrmoy:660FV7CrM", vhaddps_3 = "rrmoy:F20FV7CrM", vhsubpd_3 = "rrmoy:660FV7DrM", vhsubps_3 = "rrmoy:F20FV7DrM", vinsertf128_4 = "rrmi/yyo:660F3AV18rMU", vinsertps_4 = "rrrio:660F3AV21rMU|rrxi/ood:", vldmxcsr_1 = "xd:0FuAE2m", vmaskmovps_3 = "rrxoy:660F38V2CrM|xrroy:660F38V2ERm", vmaskmovpd_3 = "rrxoy:660F38V2DrM|xrroy:660F38V2FRm", vmovapd_2 = "rmoy:660Fu28rM|mroy:660Fu29Rm", vmovaps_2 = "rmoy:0Fu28rM|mroy:0Fu29Rm", vmovd_2 = "rm/od:660Fu6ErM|rm/oq:660FuX6ErM|mr/do:660Fu7ERm|mr/qo:", vmovq_2 = "rro:F30Fu7ErM|rx/oq:|xr/qo:660FuD6Rm", vmovddup_2 = "rmy:F20Fu12rM|rro:|rx/oq:", vmovhlps_3 = "rrro:0FV12rM", vmovhpd_2 = "xr/qo:660Fu17Rm", vmovhpd_3 = "rrx/ooq:660FV16rM", vmovhps_2 = "xr/qo:0Fu17Rm", vmovhps_3 = "rrx/ooq:0FV16rM", vmovlhps_3 = "rrro:0FV16rM", vmovlpd_2 = "xr/qo:660Fu13Rm", vmovlpd_3 = "rrx/ooq:660FV12rM", vmovlps_2 = "xr/qo:0Fu13Rm", vmovlps_3 = "rrx/ooq:0FV12rM", vmovmskpd_2 = "rr/do:660Fu50rM|rr/dy:660FuL50rM", vmovmskps_2 = "rr/do:0Fu50rM|rr/dy:0FuL50rM", vmovntpd_2 = "xroy:660Fu2BRm", vmovntps_2 = "xroy:0Fu2BRm", vmovsd_2 = "rx/oq:F20Fu10rM|xr/qo:F20Fu11Rm", vmovsd_3 = "rrro:F20FV10rM", vmovshdup_2 = "rmoy:F30Fu16rM", vmovsldup_2 = "rmoy:F30Fu12rM", vmovss_2 = "rx/od:F30Fu10rM|xr/do:F30Fu11Rm", vmovss_3 = "rrro:F30FV10rM", vmovupd_2 = "rmoy:660Fu10rM|mroy:660Fu11Rm", vmovups_2 = "rmoy:0Fu10rM|mroy:0Fu11Rm", vorpd_3 = "rrmoy:660FV56rM", vorps_3 = "rrmoy:0FV56rM", vpermilpd_3 = "rrmoy:660F38V0DrM|rmioy:660F3Au05rMU", vpermilps_3 = "rrmoy:660F38V0CrM|rmioy:660F3Au04rMU", vperm2f128_4 = "rrmiy:660F3AV06rMU", vptestpd_2 = "rmoy:660F38u0FrM", vptestps_2 = "rmoy:660F38u0ErM", vrcpps_2 = "rmoy:0Fu53rM", vrcpss_3 = "rrro:F30FV53rM|rrx/ood:", vrsqrtps_2 = "rmoy:0Fu52rM", vrsqrtss_3 = "rrro:F30FV52rM|rrx/ood:", vroundpd_3 = "rmioy:660F3AV09rMU", vroundps_3 = "rmioy:660F3AV08rMU", vroundsd_4 = "rrrio:660F3AV0BrMU|rrxi/ooq:", vroundss_4 = "rrrio:660F3AV0ArMU|rrxi/ood:", vshufpd_4 = "rrmioy:660FVC6rMU", vshufps_4 = "rrmioy:0FVC6rMU", vsqrtps_2 = "rmoy:0Fu51rM", vsqrtss_2 = "rro:F30Fu51rM|rx/od:", vsqrtpd_2 = "rmoy:660Fu51rM", vsqrtsd_2 = "rro:F20Fu51rM|rx/oq:", vstmxcsr_1 = "xd:0FuAE3m", vucomisd_2 = "rro:660Fu2ErM|rx/oq:", vucomiss_2 = "rro:0Fu2ErM|rx/od:", vunpckhpd_3 = "rrmoy:660FV15rM", vunpckhps_3 = "rrmoy:0FV15rM", vunpcklpd_3 = "rrmoy:660FV14rM", vunpcklps_3 = "rrmoy:0FV14rM", vxorpd_3 = "rrmoy:660FV57rM", vxorps_3 = "rrmoy:0FV57rM", vzeroall_0 = "0FuL77", vzeroupper_0 = "0Fu77", -- AVX2 FP ops vbroadcastss_2 = "rx/od:660F38u18rM|rx/yd:|rro:|rr/yo:", vbroadcastsd_2 = "rx/yq:660F38u19rM|rr/yo:", -- *vgather* (!vsib) vpermpd_3 = "rmiy:660F3AuX01rMU", vpermps_3 = "rrmy:660F38V16rM", -- AVX, AVX2 integer ops -- In general, xmm requires AVX, ymm requires AVX2. vaesdec_3 = "rrmo:660F38VDErM", vaesdeclast_3 = "rrmo:660F38VDFrM", vaesenc_3 = "rrmo:660F38VDCrM", vaesenclast_3 = "rrmo:660F38VDDrM", vaesimc_2 = "rmo:660F38uDBrM", vaeskeygenassist_3 = "rmio:660F3AuDFrMU", vlddqu_2 = "rxoy:F20FuF0rM", vmaskmovdqu_2 = "rro:660FuF7rM", vmovdqa_2 = "rmoy:660Fu6FrM|mroy:660Fu7FRm", vmovdqu_2 = "rmoy:F30Fu6FrM|mroy:F30Fu7FRm", vmovntdq_2 = "xroy:660FuE7Rm", vmovntdqa_2 = "rxoy:660F38u2ArM", vmpsadbw_4 = "rrmioy:660F3AV42rMU", vpabsb_2 = "rmoy:660F38u1CrM", vpabsd_2 = "rmoy:660F38u1ErM", vpabsw_2 = "rmoy:660F38u1DrM", vpackusdw_3 = "rrmoy:660F38V2BrM", vpalignr_4 = "rrmioy:660F3AV0FrMU", vpblendvb_4 = "rrmroy:660F3AV4CrMs", vpblendw_4 = "rrmioy:660F3AV0ErMU", vpclmulqdq_4 = "rrmio:660F3AV44rMU", vpcmpeqq_3 = "rrmoy:660F38V29rM", vpcmpestri_3 = "rmio:660F3Au61rMU", vpcmpestrm_3 = "rmio:660F3Au60rMU", vpcmpgtq_3 = "rrmoy:660F38V37rM", vpcmpistri_3 = "rmio:660F3Au63rMU", vpcmpistrm_3 = "rmio:660F3Au62rMU", vpextrb_3 = "rri/do:660F3Au14nRmU|rri/qo:|xri/bo:", vpextrw_3 = "rri/do:660FuC5rMU|xri/wo:660F3Au15nRmU", vpextrd_3 = "mri/do:660F3Au16RmU", vpextrq_3 = "mri/qo:660F3Au16RmU", vphaddw_3 = "rrmoy:660F38V01rM", vphaddd_3 = "rrmoy:660F38V02rM", vphaddsw_3 = "rrmoy:660F38V03rM", vphminposuw_2 = "rmo:660F38u41rM", vphsubw_3 = "rrmoy:660F38V05rM", vphsubd_3 = "rrmoy:660F38V06rM", vphsubsw_3 = "rrmoy:660F38V07rM", vpinsrb_4 = "rrri/ood:660F3AV20rMU|rrxi/oob:", vpinsrw_4 = "rrri/ood:660FVC4rMU|rrxi/oow:", vpinsrd_4 = "rrmi/ood:660F3AV22rMU", vpinsrq_4 = "rrmi/ooq:660F3AVX22rMU", vpmaddubsw_3 = "rrmoy:660F38V04rM", vpmaxsb_3 = "rrmoy:660F38V3CrM", vpmaxsd_3 = "rrmoy:660F38V3DrM", vpmaxuw_3 = "rrmoy:660F38V3ErM", vpmaxud_3 = "rrmoy:660F38V3FrM", vpminsb_3 = "rrmoy:660F38V38rM", vpminsd_3 = "rrmoy:660F38V39rM", vpminuw_3 = "rrmoy:660F38V3ArM", vpminud_3 = "rrmoy:660F38V3BrM", vpmovmskb_2 = "rr/do:660FuD7rM|rr/dy:660FuLD7rM", vpmovsxbw_2 = "rroy:660F38u20rM|rx/oq:|rx/yo:", vpmovsxbd_2 = "rroy:660F38u21rM|rx/od:|rx/yq:", vpmovsxbq_2 = "rroy:660F38u22rM|rx/ow:|rx/yd:", vpmovsxwd_2 = "rroy:660F38u23rM|rx/oq:|rx/yo:", vpmovsxwq_2 = "rroy:660F38u24rM|rx/od:|rx/yq:", vpmovsxdq_2 = "rroy:660F38u25rM|rx/oq:|rx/yo:", vpmovzxbw_2 = "rroy:660F38u30rM|rx/oq:|rx/yo:", vpmovzxbd_2 = "rroy:660F38u31rM|rx/od:|rx/yq:", vpmovzxbq_2 = "rroy:660F38u32rM|rx/ow:|rx/yd:", vpmovzxwd_2 = "rroy:660F38u33rM|rx/oq:|rx/yo:", vpmovzxwq_2 = "rroy:660F38u34rM|rx/od:|rx/yq:", vpmovzxdq_2 = "rroy:660F38u35rM|rx/oq:|rx/yo:", vpmuldq_3 = "rrmoy:660F38V28rM", vpmulhrsw_3 = "rrmoy:660F38V0BrM", vpmulld_3 = "rrmoy:660F38V40rM", vpshufb_3 = "rrmoy:660F38V00rM", vpshufd_3 = "rmioy:660Fu70rMU", vpshufhw_3 = "rmioy:F30Fu70rMU", vpshuflw_3 = "rmioy:F20Fu70rMU", vpsignb_3 = "rrmoy:660F38V08rM", vpsignw_3 = "rrmoy:660F38V09rM", vpsignd_3 = "rrmoy:660F38V0ArM", vpslldq_3 = "rrioy:660Fv737mU", vpsllw_3 = "rrmoy:660FVF1rM|rrioy:660Fv716mU", vpslld_3 = "rrmoy:660FVF2rM|rrioy:660Fv726mU", vpsllq_3 = "rrmoy:660FVF3rM|rrioy:660Fv736mU", vpsraw_3 = "rrmoy:660FVE1rM|rrioy:660Fv714mU", vpsrad_3 = "rrmoy:660FVE2rM|rrioy:660Fv724mU", vpsrldq_3 = "rrioy:660Fv733mU", vpsrlw_3 = "rrmoy:660FVD1rM|rrioy:660Fv712mU", vpsrld_3 = "rrmoy:660FVD2rM|rrioy:660Fv722mU", vpsrlq_3 = "rrmoy:660FVD3rM|rrioy:660Fv732mU", vptest_2 = "rmoy:660F38u17rM", -- AVX2 integer ops vbroadcasti128_2 = "rx/yo:660F38u5ArM", vinserti128_4 = "rrmi/yyo:660F3AV38rMU", vextracti128_3 = "mri/oy:660F3AuL39RmU", vpblendd_4 = "rrmioy:660F3AV02rMU", vpbroadcastb_2 = "rro:660F38u78rM|rx/ob:|rr/yo:|rx/yb:", vpbroadcastw_2 = "rro:660F38u79rM|rx/ow:|rr/yo:|rx/yw:", vpbroadcastd_2 = "rro:660F38u58rM|rx/od:|rr/yo:|rx/yd:", vpbroadcastq_2 = "rro:660F38u59rM|rx/oq:|rr/yo:|rx/yq:", vpermd_3 = "rrmy:660F38V36rM", vpermq_3 = "rmiy:660F3AuX00rMU", -- *vpgather* (!vsib) vperm2i128_4 = "rrmiy:660F3AV46rMU", vpmaskmovd_3 = "rrxoy:660F38V8CrM|xrroy:660F38V8ERm", vpmaskmovq_3 = "rrxoy:660F38VX8CrM|xrroy:660F38VX8ERm", vpsllvd_3 = "rrmoy:660F38V47rM", vpsllvq_3 = "rrmoy:660F38VX47rM", vpsravd_3 = "rrmoy:660F38V46rM", vpsrlvd_3 = "rrmoy:660F38V45rM", vpsrlvq_3 = "rrmoy:660F38VX45rM", -- Intel ADX adcx_2 = "rmqd:660F38F6rM", adox_2 = "rmqd:F30F38F6rM", } ------------------------------------------------------------------------------ -- Arithmetic ops. for name,n in pairs{ add = 0, ["or"] = 1, adc = 2, sbb = 3, ["and"] = 4, sub = 5, xor = 6, cmp = 7 } do local n8 = shl(n, 3) map_op[name.."_2"] = format( "mr:%02XRm|rm:%02XrM|mI1qdw:81%XmI|mS1qdw:83%XmS|Ri1qdwb:%02Xri|mi1qdwb:81%Xmi", 1+n8, 3+n8, n, n, 5+n8, n) end -- Shift ops. for name,n in pairs{ rol = 0, ror = 1, rcl = 2, rcr = 3, shl = 4, shr = 5, sar = 7, sal = 4 } do map_op[name.."_2"] = format("m1:D1%Xm|mC1qdwb:D3%Xm|mi:C1%XmU", n, n, n) end -- Conditional ops. for cc,n in pairs(map_cc) do map_op["j"..cc.."_1"] = format("J.:n0F8%XJ", n) -- short: 7%X map_op["set"..cc.."_1"] = format("mb:n0F9%X2m", n) map_op["cmov"..cc.."_2"] = format("rmqdw:0F4%XrM", n) -- P6+ end -- FP arithmetic ops. for name,n in pairs{ add = 0, mul = 1, com = 2, comp = 3, sub = 4, subr = 5, div = 6, divr = 7 } do local nc = 0xc0 + shl(n, 3) local nr = nc + (n < 4 and 0 or (n % 2 == 0 and 8 or -8)) local fn = "f"..name map_op[fn.."_1"] = format("ff:D8%02Xr|xd:D8%Xm|xq:nDC%Xm", nc, n, n) if n == 2 or n == 3 then map_op[fn.."_2"] = format("Fff:D8%02XR|Fx2d:D8%XM|Fx2q:nDC%XM", nc, n, n) else map_op[fn.."_2"] = format("Fff:D8%02XR|fFf:DC%02Xr|Fx2d:D8%XM|Fx2q:nDC%XM", nc, nr, n, n) map_op[fn.."p_1"] = format("ff:DE%02Xr", nr) map_op[fn.."p_2"] = format("fFf:DE%02Xr", nr) end map_op["fi"..name.."_1"] = format("xd:DA%Xm|xw:nDE%Xm", n, n) end -- FP conditional moves. for cc,n in pairs{ b=0, e=1, be=2, u=3, nb=4, ne=5, nbe=6, nu=7 } do local nc = 0xdac0 + shl(band(n, 3), 3) + shl(band(n, 4), 6) map_op["fcmov"..cc.."_1"] = format("ff:%04Xr", nc) -- P6+ map_op["fcmov"..cc.."_2"] = format("Fff:%04XR", nc) -- P6+ end -- SSE / AVX FP arithmetic ops. for name,n in pairs{ sqrt = 1, add = 8, mul = 9, sub = 12, min = 13, div = 14, max = 15 } do map_op[name.."ps_2"] = format("rmo:0F5%XrM", n) map_op[name.."ss_2"] = format("rro:F30F5%XrM|rx/od:", n) map_op[name.."pd_2"] = format("rmo:660F5%XrM", n) map_op[name.."sd_2"] = format("rro:F20F5%XrM|rx/oq:", n) if n ~= 1 then map_op["v"..name.."ps_3"] = format("rrmoy:0FV5%XrM", n) map_op["v"..name.."ss_3"] = format("rrro:F30FV5%XrM|rrx/ood:", n) map_op["v"..name.."pd_3"] = format("rrmoy:660FV5%XrM", n) map_op["v"..name.."sd_3"] = format("rrro:F20FV5%XrM|rrx/ooq:", n) end end -- SSE2 / AVX / AVX2 integer arithmetic ops (66 0F leaf). for name,n in pairs{ paddb = 0xFC, paddw = 0xFD, paddd = 0xFE, paddq = 0xD4, paddsb = 0xEC, paddsw = 0xED, packssdw = 0x6B, packsswb = 0x63, packuswb = 0x67, paddusb = 0xDC, paddusw = 0xDD, pand = 0xDB, pandn = 0xDF, pavgb = 0xE0, pavgw = 0xE3, pcmpeqb = 0x74, pcmpeqd = 0x76, pcmpeqw = 0x75, pcmpgtb = 0x64, pcmpgtd = 0x66, pcmpgtw = 0x65, pmaddwd = 0xF5, pmaxsw = 0xEE, pmaxub = 0xDE, pminsw = 0xEA, pminub = 0xDA, pmulhuw = 0xE4, pmulhw = 0xE5, pmullw = 0xD5, pmuludq = 0xF4, por = 0xEB, psadbw = 0xF6, psubb = 0xF8, psubw = 0xF9, psubd = 0xFA, psubq = 0xFB, psubsb = 0xE8, psubsw = 0xE9, psubusb = 0xD8, psubusw = 0xD9, punpckhbw = 0x68, punpckhwd = 0x69, punpckhdq = 0x6A, punpckhqdq = 0x6D, punpcklbw = 0x60, punpcklwd = 0x61, punpckldq = 0x62, punpcklqdq = 0x6C, pxor = 0xEF } do map_op[name.."_2"] = format("rmo:660F%02XrM", n) map_op["v"..name.."_3"] = format("rrmoy:660FV%02XrM", n) end ------------------------------------------------------------------------------ local map_vexarg = { u = false, v = 1, V = 2 } -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin, vex local opcode = 0 local szov = sz local narg = 1 local rex = 0 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 6 positions. if secpos+6 > maxsecpos then wflush() end -- Process each character. for c in gmatch(pat.."|", ".") do if match(c, "%x") then -- Hex digit. digit = byte(c) - 48 if digit > 48 then digit = digit - 39 elseif digit > 16 then digit = digit - 7 end opcode = opcode*16 + digit addin = nil elseif c == "n" then -- Disable operand size mods for opcode. szov = nil elseif c == "X" then -- Force REX.W. rex = 8 elseif c == "L" then -- Force VEX.L. vex.l = true elseif c == "r" then -- Merge 1st operand regno. into opcode. addin = args[1]; opcode = opcode + (addin.reg % 8) if narg < 2 then narg = 2 end elseif c == "R" then -- Merge 2nd operand regno. into opcode. addin = args[2]; opcode = opcode + (addin.reg % 8) narg = 3 elseif c == "m" or c == "M" then -- Encode ModRM/SIB. local s if addin then s = addin.reg opcode = opcode - band(s, 7) -- Undo regno opcode merge. else s = band(opcode, 15) -- Undo last digit. opcode = shr(opcode, 4) end local nn = c == "m" and 1 or 2 local t = args[nn] if narg <= nn then narg = nn + 1 end if szov == "q" and rex == 0 then rex = rex + 8 end if t.reg and t.reg > 7 then rex = rex + 1 end if t.xreg and t.xreg > 7 then rex = rex + 2 end if s > 7 then rex = rex + 4 end if needrex then rex = rex + 16 end local psz, sk = wputop(szov, opcode, rex, vex, s < 0, t.vreg or t.vxreg) opcode = nil local imark = sub(pat, -1) -- Force a mark (ugly). -- Put ModRM/SIB with regno/last digit as spare. wputmrmsib(t, imark, s, addin and addin.vreg, psz, sk) addin = nil elseif map_vexarg[c] ~= nil then -- Encode using VEX prefix local b = band(opcode, 255); opcode = shr(opcode, 8) local m = 1 if b == 0x38 then m = 2 elseif b == 0x3a then m = 3 end if m ~= 1 then b = band(opcode, 255); opcode = shr(opcode, 8) end if b ~= 0x0f then werror("expected `0F', `0F38', or `0F3A' to precede `"..c.. "' in pattern `"..pat.."' for `"..op.."'") end local v = map_vexarg[c] if v then v = remove(args, v) end b = band(opcode, 255) local p = 0 if b == 0x66 then p = 1 elseif b == 0xf3 then p = 2 elseif b == 0xf2 then p = 3 end if p ~= 0 then opcode = shr(opcode, 8) end if opcode ~= 0 then wputop(nil, opcode, 0); opcode = 0 end vex = { m = m, p = p, v = v } else if opcode then -- Flush opcode. if szov == "q" and rex == 0 then rex = rex + 8 end if needrex then rex = rex + 16 end if addin and addin.reg == -1 then local psz, sk = wputop(szov, opcode - 7, rex, vex, true) wvreg("opcode", addin.vreg, psz, sk) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex, vex) end opcode = nil end if c == "|" then break end if c == "o" then -- Offset (pure 32 bit displacement). wputdarg(args[1].disp); if narg < 2 then narg = 2 end elseif c == "O" then wputdarg(args[2].disp); narg = 3 else -- Anything else is an immediate operand. local a = args[narg] narg = narg + 1 local mode, imm = a.mode, a.imm if mode == "iJ" and not match("iIJ", c) then werror("bad operand size for label") end if c == "S" then wputsbarg(imm) elseif c == "U" then wputbarg(imm) elseif c == "W" then wputwarg(imm) elseif c == "i" or c == "I" then if mode == "iJ" then wputlabel("IMM_", imm, 1) elseif mode == "iI" and c == "I" then waction(sz == "w" and "IMM_WB" or "IMM_DB", imm) else wputszarg(sz, imm) end elseif c == "J" then if mode == "iPJ" then waction("REL_A", imm) -- !x64 (secpos) else wputlabel("REL_", imm, 2) end elseif c == "s" then local reg = a.reg if reg < 0 then wputb(0) wvreg("imm.hi", a.vreg) else wputb(shl(reg, 4)) end else werror("bad char `"..c.."' in pattern `"..pat.."' for `"..op.."'") end end end end end ------------------------------------------------------------------------------ -- Mapping of operand modes to short names. Suppress output with '#'. local map_modename = { r = "reg", R = "eax", C = "cl", x = "mem", m = "mrm", i = "imm", f = "stx", F = "st0", J = "lbl", ["1"] = "1", I = "#", S = "#", O = "#", } -- Return a table/string showing all possible operand modes. local function templatehelp(template, nparams) if nparams == 0 then return "" end local t = {} for tm in gmatch(template, "[^%|]+") do local s = map_modename[sub(tm, 1, 1)] s = s..gsub(sub(tm, 2, nparams), ".", function(c) return ", "..map_modename[c] end) if not match(s, "#") then t[#t+1] = s end end return t end -- Match operand modes against mode match part of template. local function matchtm(tm, args) for i=1,#args do if not match(args[i].mode, sub(tm, i, i)) then return end end return true end -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return templatehelp(template, nparams) end local args = {} -- Zero-operand opcodes have no match part. if #params == 0 then dopattern(template, args, "d", params.op, nil) return end -- Determine common operand size (coerce undefined size) or flag as mixed. local sz, szmix, needrex for i,p in ipairs(params) do args[i] = parseoperand(p) local nsz = args[i].opsize if nsz then if sz and sz ~= nsz then szmix = true else sz = nsz end end local nrex = args[i].needrex if nrex ~= nil then if needrex == nil then needrex = nrex elseif needrex ~= nrex then werror("bad mix of byte-addressable registers") end end end -- Try all match:pattern pairs (separated by '|'). local gotmatch, lastpat for tm in gmatch(template, "[^%|]+") do -- Split off size match (starts after mode match) and pattern string. local szm, pat = match(tm, "^(.-):(.*)$", #args+1) if pat == "" then pat = lastpat else lastpat = pat end if matchtm(tm, args) then local prefix = sub(szm, 1, 1) if prefix == "/" then -- Exactly match leading operand sizes. for i = #szm,1,-1 do if i == 1 then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return elseif args[i-1].opsize ~= sub(szm, i, i) then break end end else -- Match common operand size. local szp = sz if szm == "" then szm = x64 and "qdwb" or "dwb" end -- Default sizes. if prefix == "1" then szp = args[1].opsize; szmix = nil elseif prefix == "2" then szp = args[2].opsize; szmix = nil end if not szmix and (prefix == "." or match(szm, szp or "#")) then dopattern(pat, args, szp, params.op, needrex) -- Process pattern. return end end gotmatch = true end end local msg = "bad operand mode" if gotmatch then if szmix then msg = "mixed operand size" else msg = sz and "bad operand size" or "missing operand size" end end werror(msg.." in `"..opmodestr(params.op, args).."'") end ------------------------------------------------------------------------------ -- x64-specific opcode for 64 bit immediates and displacements. if x64 then function map_op.mov64_2(params) if not params then return { "reg, imm", "reg, [disp]", "[disp], reg" } end if secpos+2 > maxsecpos then wflush() end local opcode, op64, sz, rex, vreg local op64 = match(params[1], "^%[%s*(.-)%s*%]$") if op64 then local a = parseoperand(params[2]) if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa3 else op64 = match(params[2], "^%[%s*(.-)%s*%]$") local a = parseoperand(params[1]) if op64 then if a.mode ~= "rmR" then werror("bad operand mode") end sz = a.opsize rex = sz == "q" and 8 or 0 opcode = 0xa1 else if sub(a.mode, 1, 1) ~= "r" or a.opsize ~= "q" then werror("bad operand mode") end op64 = params[2] if a.reg == -1 then vreg = a.vreg opcode = 0xb8 else opcode = 0xb8 + band(a.reg, 7) end rex = a.reg > 7 and 9 or 8 end end local psz, sk = wputop(sz, opcode, rex, nil, vreg) wvreg("opcode", vreg, psz, sk) waction("IMM_D", format("(unsigned int)(%s)", op64)) waction("IMM_D", format("(unsigned int)((%s)>>32)", op64)) end end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. local function op_data(params) if not params then return "imm..." end local sz = sub(params.op, 2, 2) if sz == "a" then sz = addrsize end for _,p in ipairs(params) do local a = parseoperand(p) if sub(a.mode, 1, 1) ~= "i" or (a.opsize and a.opsize ~= sz) then werror("bad mode or size in `"..p.."'") end if a.mode == "iJ" then wputlabel("IMM_", a.imm, 1) else wputszarg(sz, a.imm) end if secpos+2 > maxsecpos then wflush() end end end map_op[".byte_*"] = op_data map_op[".sbyte_*"] = op_data map_op[".word_*"] = op_data map_op[".dword_*"] = op_data map_op[".aword_*"] = op_data ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_2"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr [, addr]" end if secpos+2 > maxsecpos then wflush() end local a = parseoperand(params[1]) local mode, imm = a.mode, a.imm if type(imm) == "number" and (mode == "iJ" or (imm >= 1 and imm <= 9)) then -- Local label (1: ... 9:) or global label (->global:). waction("LABEL_LG", nil, 1) wputxb(imm) elseif mode == "iJ" then -- PC label (=>pcexpr:). waction("LABEL_PC", imm) else werror("bad label definition") end -- SETLABEL must immediately follow LABEL_LG/LABEL_PC. local addr = params[2] if addr then local a = parseoperand(addr) if a.mode == "iPJ" then waction("SETLABEL", a.imm) else werror("bad label assignment") end end end map_op[".label_1"] = map_op[".label_2"] ------------------------------------------------------------------------------ -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) or map_opsizenum[map_opsize[params[1]]] if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", nil, 1) wputxb(align-1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end -- Spacing pseudo-opcode. map_op[".space_2"] = function(params) if not params then return "num [, filler]" end if secpos+1 > maxsecpos then wflush() end waction("SPACE", params[1]) local fill = params[2] if fill then fill = tonumber(fill) if not fill or fill < 0 or fill > 255 then werror("bad filler") end end wputxb(fill or 0) end map_op[".space_1"] = map_op[".space_2"] ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end if reg and not map_reg_valid_base[reg] then werror("bad base register `"..(map_reg_rev[reg] or reg).."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg and map_reg_rev[tp.reg] or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION") wputxb(num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpregs(out) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
mit
kaen/Zero-K
effects/gundam_vert_explosion.lua
26
3091
-- vert_explosion return { ["vert_explosion"] = { groundflash = { air = true, alwaysvisible = true, circlealpha = 0.9, circlegrowth = 25, flashalpha = 0.9, flashsize = 500, ground = true, ttl = 30, water = true, color = { [1] = 1, [2] = 0.10000000149012, [3] = 0, }, }, pillar0 = { air = true, class = [[heatcloud]], count = 8, ground = true, water = true, properties = { alwaysvisible = true, heat = 15, heatfalloff = 1.5, maxheat = 15, pos = [[0,-100 i18, 0]], size = 90, sizegrowth = -11, speed = [[0, 25, 0]], texture = [[bigexplo]], }, }, poof01 = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, properties = { airdrag = 0.8, alwaysvisible = true, colormap = [[1.0 1.0 1.0 0.04 0.9 0.5 0.2 0.01 0.8 0.1 0.1 0.01]], directional = true, emitrot = 45, emitrotspread = 32, emitvector = [[0, 1, 0]], gravity = [[0, -0.05, 0]], numparticles = 8, particlelife = 15, particlelifespread = 0, particlesize = 20, particlesizespread = 0, particlespeed = 5, particlespeedspread = 5, pos = [[0, 2, 0]], sizegrowth = 1, sizemod = 1.0, texture = [[flashside1]], useairlos = false, }, }, pop1 = { air = true, class = [[heatcloud]], count = 2, ground = true, water = true, properties = { alwaysvisible = true, heat = 10, heatfalloff = 1.1, maxheat = 15, pos = [[r-2 r2, 5, r-2 r2]], size = 30, sizegrowth = 10, speed = [[0, 0, 0]], texture = [[uglynovaexplo]], }, }, smoke = { air = true, count = 8, ground = true, water = true, properties = { agespeed = 0.02, alwaysvisible = true, color = 0.3, pos = [[r-60 r60, 15, r-60 r60]], size = 50, sizeexpansion = 0.6, sizegrowth = 15, speed = [[r-3 r3, 2.5 r1.3, r-3 r3]], startsize = 10, }, }, }, }
gpl-2.0
geanux/darkstar
scripts/globals/items/boiled_crayfish.lua
35
1248
----------------------------------------- -- ID: 4535 -- Item: Boiled Crayfish -- Food Effect: 30Min, All Races ----------------------------------------- -- defense % 30 -- defense % 25 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4535); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_DEFP, 30); target:addMod(MOD_FOOD_DEF_CAP, 25); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_DEFP, 30); target:delMod(MOD_FOOD_DEF_CAP, 25); end;
gpl-3.0
geanux/darkstar
scripts/zones/Beadeaux/TextIDs.lua
7
1373
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6383; -- Obtained: <item>. GIL_OBTAINED = 6384; -- Obtained <number> gil. KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6389; -- You obtain <param2 number> <param1 item>! -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7350; -- You unlock the chest! CHEST_FAIL = 7351; -- Fails to open the chest. CHEST_TRAP = 7352; -- The chest was trapped! CHEST_WEAK = 7353; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7354; -- The chest was a mimic! CHEST_MOOGLE = 7355; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7356; -- The chest was but an illusion... CHEST_LOCKED = 7357; -- The chest appears to be locked. -- Quest Dialog LOCKED_DOOR_QUADAV_HAS_KEY = 7203; -- It is locked tight, but has what looks like a keyhole. Maybe one of the Quadav here has the key. NOTHING_OUT_OF_ORDINARY = 7688; -- There is nothing out of the ordinary here. YOU_CAN_NOW_BECOME_A_DARK_KNIGHT = 7340; -- You can now become a dark knight! -- conquest Base CONQUEST_BASE = 7040; -- Tallying conquest results...
gpl-3.0
geanux/darkstar
scripts/zones/Mhaura/npcs/Kotan-Purutan.lua
19
2416
----------------------------------- -- Area: Mhaura -- NPC: Kotan-Purutan -- Involved in Quest: Overnight Delivery -- @pos 40.323 -8.999 44.242 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local OvernightDelivery = player:getQuestStatus(WINDURST,OVERNIGHT_DELIVERY); local KenapaOvernight = player:getVar("Kenapa_Overnight_var"); -- Variable to track progress for Overnight Delivery local KenapaOvernightDay = player:getVar("Kenapa_Overnight_Day_var"); -- Variable to track the day the quest is started. local KenapaOvernightHour = player:getVar("Kenapa_Overnight_Hour_var"); -- Variable to track the hour the quest is started. local HourOfTheDay = VanadielHour(); if (OvernightDelivery == QUEST_ACCEPTED and player:hasKeyItem(SMALL_BAG) == false and (KenapaOvernight >= 4 and KenapaOvernight <= 7) and (HourOfTheDay < 6 or HourOfTheDay >= 18)) then player:startEvent(0x008d); -- Gives Key Item at correct times of night elseif (OvernightDelivery == QUEST_ACCEPTED and player:hasKeyItem(SMALL_BAG) == false and (KenapaOvernight >= 4 and KenapaOvernight <= 7) and (HourOfTheDay >= 6 or HourOfTheDay < 18)) then player:startEvent(0x0090); -- Only at night elseif (player:hasKeyItem(SMALL_BAG) == true) then player:startEvent(0x008e); -- Reminder Dialogue elseif (OvernightDelivery == QUEST_COMPLETED) then player:startEvent(0x008f); -- Post quest else player:startEvent(0x008c); -- Standard 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 == 0x008d) then player:addKeyItem(SMALL_BAG); player:setVar("Kenapa_Overnight_Day_var",VanadielDayOfTheYear()); player:setVar("Kenapa_Overnight_Hour_var",VanadielHour()); player:messageSpecial(KEYITEM_OBTAINED,SMALL_BAG); end end;
gpl-3.0
geanux/darkstar
scripts/globals/weaponskills/numbing_shot.lua
18
1513
----------------------------------- -- Numbing Shot -- Marksmanship weapon skill -- Skill level: 290 -- Main of sub must be Ranger or Corsair -- Aligned with the Thunder & Breeze Gorget. -- Aligned with the Thunder Belt & Breeze Belt. -- Element: Ice -- Modifiers: AGI 80% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.6; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.agi_wsc = 0.8; end local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60) if (target:hasStatusEffect(EFFECT_PARALYSIS) == false) then target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
geanux/darkstar
scripts/zones/Arrapago_Reef/npcs/qm1.lua
16
1170
----------------------------------- -- Area: Arrapago Reef -- NPC: ??? (Spawn Lil'Apkallu(ZNM T1)) -- @pos 488 -1 166 54 ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Arrapago_Reef/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2601,1) and trade:getItemCount() == 1) then -- Trade Greenling player:tradeComplete(); SpawnMob(16998871,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
tonylauCN/tutorials
openresty/debugger/lualibs/lexers/lexer.lua
2
71168
-- Copyright 2006-2016 Mitchell mitchell.att.foicica.com. See LICENSE. local M = {} --[=[ This comment is for LuaDoc. --- -- Lexes Scintilla documents with Lua and LPeg. -- -- ## Overview -- -- Lexers highlight the syntax of source code. Scintilla (the editing component -- behind [Textadept][] and [SciTE][]) traditionally uses static, compiled C++ -- lexers which are notoriously difficult to create and/or extend. On the other -- hand, Lua makes it easy to to rapidly create new lexers, extend existing -- ones, and embed lexers within one another. Lua lexers tend to be more -- readable than C++ lexers too. -- -- Lexers are Parsing Expression Grammars, or PEGs, composed with the Lua -- [LPeg library][]. The following table comes from the LPeg documentation and -- summarizes all you need to know about constructing basic LPeg patterns. This -- module provides convenience functions for creating and working with other -- more advanced patterns and concepts. -- -- Operator | Description -- ---------------------|------------ -- `lpeg.P(string)` | Matches `string` literally. -- `lpeg.P(`_`n`_`)` | Matches exactly _`n`_ characters. -- `lpeg.S(string)` | Matches any character in set `string`. -- `lpeg.R("`_`xy`_`")` | Matches any character between range `x` and `y`. -- `patt^`_`n`_ | Matches at least _`n`_ repetitions of `patt`. -- `patt^-`_`n`_ | Matches at most _`n`_ repetitions of `patt`. -- `patt1 * patt2` | Matches `patt1` followed by `patt2`. -- `patt1 + patt2` | Matches `patt1` or `patt2` (ordered choice). -- `patt1 - patt2` | Matches `patt1` if `patt2` does not match. -- `-patt` | Equivalent to `("" - patt)`. -- `#patt` | Matches `patt` but consumes no input. -- -- The first part of this document deals with rapidly constructing a simple -- lexer. The next part deals with more advanced techniques, such as custom -- coloring and embedding lexers within one another. Following that is a -- discussion about code folding, or being able to tell Scintilla which code -- blocks are "foldable" (temporarily hideable from view). After that are -- instructions on how to use LPeg lexers with the aforementioned Textadept and -- SciTE editors. Finally there are comments on lexer performance and -- limitations. -- -- [LPeg library]: http://www.inf.puc-rio.br/~roberto/lpeg/lpeg.html -- [Textadept]: http://foicica.com/textadept -- [SciTE]: http://scintilla.org/SciTE.html -- -- ## Lexer Basics -- -- The *lexers/* directory contains all lexers, including your new one. Before -- attempting to write one from scratch though, first determine if your -- programming language is similar to any of the 80+ languages supported. If so, -- you may be able to copy and modify that lexer, saving some time and effort. -- The filename of your lexer should be the name of your programming language in -- lower case followed by a *.lua* extension. For example, a new Lua lexer has -- the name *lua.lua*. -- -- Note: Try to refrain from using one-character language names like "c", "d", -- or "r". For example, Scintillua uses "ansi_c", "dmd", and "rstats", -- respectively. -- -- ### New Lexer Template -- -- There is a *lexers/template.txt* file that contains a simple template for a -- new lexer. Feel free to use it, replacing the '?'s with the name of your -- lexer: -- -- -- ? LPeg lexer. -- -- local l = require('lexer') -- local token, word_match = l.token, l.word_match -- local P, R, S = lpeg.P, lpeg.R, lpeg.S -- -- local M = {_NAME = '?'} -- -- -- Whitespace. -- local ws = token(l.WHITESPACE, l.space^1) -- -- M._rules = { -- {'whitespace', ws}, -- } -- -- M._tokenstyles = { -- -- } -- -- return M -- -- The first 3 lines of code simply define often used convenience variables. The -- 5th and last lines define and return the lexer object Scintilla uses; they -- are very important and must be part of every lexer. The sixth line defines -- something called a "token", an essential building block of lexers. You will -- learn about tokens shortly. The rest of the code defines a set of grammar -- rules and token styles. You will learn about those later. Note, however, the -- `M.` prefix in front of `_rules` and `_tokenstyles`: not only do these tables -- belong to their respective lexers, but any non-local variables need the `M.` -- prefix too so-as not to affect Lua's global environment. All in all, this is -- a minimal, working lexer that you can build on. -- -- ### Tokens -- -- Take a moment to think about your programming language's structure. What kind -- of key elements does it have? In the template shown earlier, one predefined -- element all languages have is whitespace. Your language probably also has -- elements like comments, strings, and keywords. Lexers refer to these elements -- as "tokens". Tokens are the fundamental "building blocks" of lexers. Lexers -- break down source code into tokens for coloring, which results in the syntax -- highlighting familiar to you. It is up to you how specific your lexer is when -- it comes to tokens. Perhaps only distinguishing between keywords and -- identifiers is necessary, or maybe recognizing constants and built-in -- functions, methods, or libraries is desirable. The Lua lexer, for example, -- defines 11 tokens: whitespace, comments, strings, numbers, keywords, built-in -- functions, constants, built-in libraries, identifiers, labels, and operators. -- Even though constants, built-in functions, and built-in libraries are subsets -- of identifiers, Lua programmers find it helpful for the lexer to distinguish -- between them all. It is perfectly acceptable to just recognize keywords and -- identifiers. -- -- In a lexer, tokens consist of a token name and an LPeg pattern that matches a -- sequence of characters recognized as an instance of that token. Create tokens -- using the [`lexer.token()`]() function. Let us examine the "whitespace" token -- defined in the template shown earlier: -- -- local ws = token(l.WHITESPACE, l.space^1) -- -- At first glance, the first argument does not appear to be a string name and -- the second argument does not appear to be an LPeg pattern. Perhaps you -- expected something like: -- -- local ws = token('whitespace', S('\t\v\f\n\r ')^1) -- -- The `lexer` (`l`) module actually provides a convenient list of common token -- names and common LPeg patterns for you to use. Token names include -- [`lexer.DEFAULT`](), [`lexer.WHITESPACE`](), [`lexer.COMMENT`](), -- [`lexer.STRING`](), [`lexer.NUMBER`](), [`lexer.KEYWORD`](), -- [`lexer.IDENTIFIER`](), [`lexer.OPERATOR`](), [`lexer.ERROR`](), -- [`lexer.PREPROCESSOR`](), [`lexer.CONSTANT`](), [`lexer.VARIABLE`](), -- [`lexer.FUNCTION`](), [`lexer.CLASS`](), [`lexer.TYPE`](), [`lexer.LABEL`](), -- [`lexer.REGEX`](), and [`lexer.EMBEDDED`](). Patterns include -- [`lexer.any`](), [`lexer.ascii`](), [`lexer.extend`](), [`lexer.alpha`](), -- [`lexer.digit`](), [`lexer.alnum`](), [`lexer.lower`](), [`lexer.upper`](), -- [`lexer.xdigit`](), [`lexer.cntrl`](), [`lexer.graph`](), [`lexer.print`](), -- [`lexer.punct`](), [`lexer.space`](), [`lexer.newline`](), -- [`lexer.nonnewline`](), [`lexer.nonnewline_esc`](), [`lexer.dec_num`](), -- [`lexer.hex_num`](), [`lexer.oct_num`](), [`lexer.integer`](), -- [`lexer.float`](), and [`lexer.word`](). You may use your own token names if -- none of the above fit your language, but an advantage to using predefined -- token names is that your lexer's tokens will inherit the universal syntax -- highlighting color theme used by your text editor. -- -- #### Example Tokens -- -- So, how might you define other tokens like comments, strings, and keywords? -- Here are some examples. -- -- **Comments** -- -- Line-style comments with a prefix character(s) are easy to express with LPeg: -- -- local shell_comment = token(l.COMMENT, '#' * l.nonnewline^0) -- local c_line_comment = token(l.COMMENT, '//' * l.nonnewline_esc^0) -- -- The comments above start with a '#' or "//" and go to the end of the line. -- The second comment recognizes the next line also as a comment if the current -- line ends with a '\' escape character. -- -- C-style "block" comments with a start and end delimiter are also easy to -- express: -- -- local c_comment = token(l.COMMENT, '/*' * (l.any - '*/')^0 * P('*/')^-1) -- -- This comment starts with a "/\*" sequence and contains anything up to and -- including an ending "\*/" sequence. The ending "\*/" is optional so the lexer -- can recognize unfinished comments as comments and highlight them properly. -- -- **Strings** -- -- It is tempting to think that a string is not much different from the block -- comment shown above in that both have start and end delimiters: -- -- local dq_str = '"' * (l.any - '"')^0 * P('"')^-1 -- local sq_str = "'" * (l.any - "'")^0 * P("'")^-1 -- local simple_string = token(l.STRING, dq_str + sq_str) -- -- However, most programming languages allow escape sequences in strings such -- that a sequence like "\\&quot;" in a double-quoted string indicates that the -- '&quot;' is not the end of the string. The above token incorrectly matches -- such a string. Instead, use the [`lexer.delimited_range()`]() convenience -- function. -- -- local dq_str = l.delimited_range('"') -- local sq_str = l.delimited_range("'") -- local string = token(l.STRING, dq_str + sq_str) -- -- In this case, the lexer treats '\' as an escape character in a string -- sequence. -- -- **Keywords** -- -- Instead of matching _n_ keywords with _n_ `P('keyword_`_`n`_`')` ordered -- choices, use another convenience function: [`lexer.word_match()`](). It is -- much easier and more efficient to write word matches like: -- -- local keyword = token(l.KEYWORD, l.word_match{ -- 'keyword_1', 'keyword_2', ..., 'keyword_n' -- }) -- -- local case_insensitive_keyword = token(l.KEYWORD, l.word_match({ -- 'KEYWORD_1', 'keyword_2', ..., 'KEYword_n' -- }, nil, true)) -- -- local hyphened_keyword = token(l.KEYWORD, l.word_match({ -- 'keyword-1', 'keyword-2', ..., 'keyword-n' -- }, '-')) -- -- By default, characters considered to be in keywords are in the set of -- alphanumeric characters and underscores. The last token demonstrates how to -- allow '-' (hyphen) characters to be in keywords as well. -- -- **Numbers** -- -- Most programming languages have the same format for integer and float tokens, -- so it might be as simple as using a couple of predefined LPeg patterns: -- -- local number = token(l.NUMBER, l.float + l.integer) -- -- However, some languages allow postfix characters on integers. -- -- local integer = P('-')^-1 * (l.dec_num * S('lL')^-1) -- local number = token(l.NUMBER, l.float + l.hex_num + integer) -- -- Your language may need other tweaks, but it is up to you how fine-grained you -- want your highlighting to be. After all, you are not writing a compiler or -- interpreter! -- -- ### Rules -- -- Programming languages have grammars, which specify valid token structure. For -- example, comments usually cannot appear within a string. Grammars consist of -- rules, which are simply combinations of tokens. Recall from the lexer -- template the `_rules` table, which defines all the rules used by the lexer -- grammar: -- -- M._rules = { -- {'whitespace', ws}, -- } -- -- Each entry in a lexer's `_rules` table consists of a rule name and its -- associated pattern. Rule names are completely arbitrary and serve only to -- identify and distinguish between different rules. Rule order is important: if -- text does not match the first rule, the lexer tries the second rule, and so -- on. This simple grammar says to match whitespace tokens under a rule named -- "whitespace". -- -- To illustrate the importance of rule order, here is an example of a -- simplified Lua grammar: -- -- M._rules = { -- {'whitespace', ws}, -- {'keyword', keyword}, -- {'identifier', identifier}, -- {'string', string}, -- {'comment', comment}, -- {'number', number}, -- {'label', label}, -- {'operator', operator}, -- } -- -- Note how identifiers come after keywords. In Lua, as with most programming -- languages, the characters allowed in keywords and identifiers are in the same -- set (alphanumerics plus underscores). If the lexer specified the "identifier" -- rule before the "keyword" rule, all keywords would match identifiers and thus -- incorrectly highlight as identifiers instead of keywords. The same idea -- applies to function, constant, etc. tokens that you may want to distinguish -- between: their rules should come before identifiers. -- -- So what about text that does not match any rules? For example in Lua, the '!' -- character is meaningless outside a string or comment. Normally the lexer -- skips over such text. If instead you want to highlight these "syntax errors", -- add an additional end rule: -- -- M._rules = { -- {'whitespace', ws}, -- {'error', token(l.ERROR, l.any)}, -- } -- -- This identifies and highlights any character not matched by an existing -- rule as an `lexer.ERROR` token. -- -- Even though the rules defined in the examples above contain a single token, -- rules may consist of multiple tokens. For example, a rule for an HTML tag -- could consist of a tag token followed by an arbitrary number of attribute -- tokens, allowing the lexer to highlight all tokens separately. The rule might -- look something like this: -- -- {'tag', tag_start * (ws * attributes)^0 * tag_end^-1} -- -- Note however that lexers with complex rules like these are more prone to lose -- track of their state. -- -- ### Summary -- -- Lexers primarily consist of tokens and grammar rules. At your disposal are a -- number of convenience patterns and functions for rapidly creating a lexer. If -- you choose to use predefined token names for your tokens, you do not have to -- define how the lexer highlights them. The tokens will inherit the default -- syntax highlighting color theme your editor uses. -- -- ## Advanced Techniques -- -- ### Styles and Styling -- -- The most basic form of syntax highlighting is assigning different colors to -- different tokens. Instead of highlighting with just colors, Scintilla allows -- for more rich highlighting, or "styling", with different fonts, font sizes, -- font attributes, and foreground and background colors, just to name a few. -- The unit of this rich highlighting is called a "style". Styles are simply -- strings of comma-separated property settings. By default, lexers associate -- predefined token names like `lexer.WHITESPACE`, `lexer.COMMENT`, -- `lexer.STRING`, etc. with particular styles as part of a universal color -- theme. These predefined styles include [`lexer.STYLE_CLASS`](), -- [`lexer.STYLE_COMMENT`](), [`lexer.STYLE_CONSTANT`](), -- [`lexer.STYLE_ERROR`](), [`lexer.STYLE_EMBEDDED`](), -- [`lexer.STYLE_FUNCTION`](), [`lexer.STYLE_IDENTIFIER`](), -- [`lexer.STYLE_KEYWORD`](), [`lexer.STYLE_LABEL`](), [`lexer.STYLE_NUMBER`](), -- [`lexer.STYLE_OPERATOR`](), [`lexer.STYLE_PREPROCESSOR`](), -- [`lexer.STYLE_REGEX`](), [`lexer.STYLE_STRING`](), [`lexer.STYLE_TYPE`](), -- [`lexer.STYLE_VARIABLE`](), and [`lexer.STYLE_WHITESPACE`](). Like with -- predefined token names and LPeg patterns, you may define your own styles. At -- their core, styles are just strings, so you may create new ones and/or modify -- existing ones. Each style consists of the following comma-separated settings: -- -- Setting | Description -- ---------------|------------ -- font:_name_ | The name of the font the style uses. -- size:_int_ | The size of the font the style uses. -- [not]bold | Whether or not the font face is bold. -- weight:_int_ | The weight or boldness of a font, between 1 and 999. -- [not]italics | Whether or not the font face is italic. -- [not]underlined| Whether or not the font face is underlined. -- fore:_color_ | The foreground color of the font face. -- back:_color_ | The background color of the font face. -- [not]eolfilled | Does the background color extend to the end of the line? -- case:_char_ | The case of the font ('u': upper, 'l': lower, 'm': normal). -- [not]visible | Whether or not the text is visible. -- [not]changeable| Whether the text is changeable or read-only. -- -- Specify font colors in either "#RRGGBB" format, "0xBBGGRR" format, or the -- decimal equivalent of the latter. As with token names, LPeg patterns, and -- styles, there is a set of predefined color names, but they vary depending on -- the current color theme in use. Therefore, it is generally not a good idea to -- manually define colors within styles in your lexer since they might not fit -- into a user's chosen color theme. Try to refrain from even using predefined -- colors in a style because that color may be theme-specific. Instead, the best -- practice is to either use predefined styles or derive new color-agnostic -- styles from predefined ones. For example, Lua "longstring" tokens use the -- existing `lexer.STYLE_STRING` style instead of defining a new one. -- -- #### Example Styles -- -- Defining styles is pretty straightforward. An empty style that inherits the -- default theme settings is simply an empty string: -- -- local style_nothing = '' -- -- A similar style but with a bold font face looks like this: -- -- local style_bold = 'bold' -- -- If you want the same style, but also with an italic font face, define the new -- style in terms of the old one: -- -- local style_bold_italic = style_bold..',italics' -- -- This allows you to derive new styles from predefined ones without having to -- rewrite them. This operation leaves the old style unchanged. Thus if you -- had a "static variable" token whose style you wanted to base off of -- `lexer.STYLE_VARIABLE`, it would probably look like: -- -- local style_static_var = l.STYLE_VARIABLE..',italics' -- -- The color theme files in the *lexers/themes/* folder give more examples of -- style definitions. -- -- ### Token Styles -- -- Lexers use the `_tokenstyles` table to assign tokens to particular styles. -- Recall the token definition and `_tokenstyles` table from the lexer template: -- -- local ws = token(l.WHITESPACE, l.space^1) -- -- ... -- -- M._tokenstyles = { -- -- } -- -- Why is a style not assigned to the `lexer.WHITESPACE` token? As mentioned -- earlier, lexers automatically associate tokens that use predefined token -- names with a particular style. Only tokens with custom token names need -- manual style associations. As an example, consider a custom whitespace token: -- -- local ws = token('custom_whitespace', l.space^1) -- -- Assigning a style to this token looks like: -- -- M._tokenstyles = { -- custom_whitespace = l.STYLE_WHITESPACE -- } -- -- Do not confuse token names with rule names. They are completely different -- entities. In the example above, the lexer assigns the "custom_whitespace" -- token the existing style for `WHITESPACE` tokens. If instead you want to -- color the background of whitespace a shade of grey, it might look like: -- -- local custom_style = l.STYLE_WHITESPACE..',back:$(color.grey)' -- M._tokenstyles = { -- custom_whitespace = custom_style -- } -- -- Notice that the lexer peforms Scintilla/SciTE-style "$()" property expansion. -- You may also use "%()". Remember to refrain from assigning specific colors in -- styles, but in this case, all user color themes probably define the -- "color.grey" property. -- -- ### Line Lexers -- -- By default, lexers match the arbitrary chunks of text passed to them by -- Scintilla. These chunks may be a full document, only the visible part of a -- document, or even just portions of lines. Some lexers need to match whole -- lines. For example, a lexer for the output of a file "diff" needs to know if -- the line started with a '+' or '-' and then style the entire line -- accordingly. To indicate that your lexer matches by line, use the -- `_LEXBYLINE` field: -- -- M._LEXBYLINE = true -- -- Now the input text for the lexer is a single line at a time. Keep in mind -- that line lexers do not have the ability to look ahead at subsequent lines. -- -- ### Embedded Lexers -- -- Lexers embed within one another very easily, requiring minimal effort. In the -- following sections, the lexer being embedded is called the "child" lexer and -- the lexer a child is being embedded in is called the "parent". For example, -- consider an HTML lexer and a CSS lexer. Either lexer stands alone for styling -- their respective HTML and CSS files. However, CSS can be embedded inside -- HTML. In this specific case, the CSS lexer is the "child" lexer with the HTML -- lexer being the "parent". Now consider an HTML lexer and a PHP lexer. This -- sounds a lot like the case with CSS, but there is a subtle difference: PHP -- _embeds itself_ into HTML while CSS is _embedded in_ HTML. This fundamental -- difference results in two types of embedded lexers: a parent lexer that -- embeds other child lexers in it (like HTML embedding CSS), and a child lexer -- that embeds itself within a parent lexer (like PHP embedding itself in HTML). -- -- #### Parent Lexer -- -- Before embedding a child lexer into a parent lexer, the parent lexer needs to -- load the child lexer. This is done with the [`lexer.load()`]() function. For -- example, loading the CSS lexer within the HTML lexer looks like: -- -- local css = l.load('css') -- -- The next part of the embedding process is telling the parent lexer when to -- switch over to the child lexer and when to switch back. The lexer refers to -- these indications as the "start rule" and "end rule", respectively, and are -- just LPeg patterns. Continuing with the HTML/CSS example, the transition from -- HTML to CSS is when the lexer encounters a "style" tag with a "type" -- attribute whose value is "text/css": -- -- local css_tag = P('<style') * P(function(input, index) -- if input:find('^[^>]+type="text/css"', index) then -- return index -- end -- end) -- -- This pattern looks for the beginning of a "style" tag and searches its -- attribute list for the text "`type="text/css"`". (In this simplified example, -- the Lua pattern does not consider whitespace between the '=' nor does it -- consider that using single quotes is valid.) If there is a match, the -- functional pattern returns a value instead of `nil`. In this case, the value -- returned does not matter because we ultimately want to style the "style" tag -- as an HTML tag, so the actual start rule looks like this: -- -- local css_start_rule = #css_tag * tag -- -- Now that the parent knows when to switch to the child, it needs to know when -- to switch back. In the case of HTML/CSS, the switch back occurs when the -- lexer encounters an ending "style" tag, though the lexer should still style -- the tag as an HTML tag: -- -- local css_end_rule = #P('</style>') * tag -- -- Once the parent loads the child lexer and defines the child's start and end -- rules, it embeds the child with the [`lexer.embed_lexer()`]() function: -- -- l.embed_lexer(M, css, css_start_rule, css_end_rule) -- -- The first parameter is the parent lexer object to embed the child in, which -- in this case is `M`. The other three parameters are the child lexer object -- loaded earlier followed by its start and end rules. -- -- #### Child Lexer -- -- The process for instructing a child lexer to embed itself into a parent is -- very similar to embedding a child into a parent: first, load the parent lexer -- into the child lexer with the [`lexer.load()`]() function and then create -- start and end rules for the child lexer. However, in this case, swap the -- lexer object arguments to [`lexer.embed_lexer()`](). For example, in the PHP -- lexer: -- -- local html = l.load('html') -- local php_start_rule = token('php_tag', '<?php ') -- local php_end_rule = token('php_tag', '?>') -- l.embed_lexer(html, M, php_start_rule, php_end_rule) -- -- ### Lexers with Complex State -- -- A vast majority of lexers are not stateful and can operate on any chunk of -- text in a document. However, there may be rare cases where a lexer does need -- to keep track of some sort of persistent state. Rather than using `lpeg.P` -- function patterns that set state variables, it is recommended to make use of -- Scintilla's built-in, per-line state integers via [`lexer.line_state`](). It -- was designed to accommodate up to 32 bit flags for tracking state. -- [`lexer.line_from_position()`]() will return the line for any position given -- to an `lpeg.P` function pattern. (Any positions derived from that position -- argument will also work.) -- -- Writing stateful lexers is beyond the scope of this document. -- -- ## Code Folding -- -- When reading source code, it is occasionally helpful to temporarily hide -- blocks of code like functions, classes, comments, etc. This is the concept of -- "folding". In the Textadept and SciTE editors for example, little indicators -- in the editor margins appear next to code that can be folded at places called -- "fold points". When the user clicks an indicator, the editor hides the code -- associated with the indicator until the user clicks the indicator again. The -- lexer specifies these fold points and what code exactly to fold. -- -- The fold points for most languages occur on keywords or character sequences. -- Examples of fold keywords are "if" and "end" in Lua and examples of fold -- character sequences are '{', '}', "/\*", and "\*/" in C for code block and -- comment delimiters, respectively. However, these fold points cannot occur -- just anywhere. For example, lexers should not recognize fold keywords that -- appear within strings or comments. The lexer's `_foldsymbols` table allows -- you to conveniently define fold points with such granularity. For example, -- consider C: -- -- M._foldsymbols = { -- [l.OPERATOR] = {['{'] = 1, ['}'] = -1}, -- [l.COMMENT] = {['/*'] = 1, ['*/'] = -1}, -- _patterns = {'[{}]', '/%*', '%*/'} -- } -- -- The first assignment states that any '{' or '}' that the lexer recognized as -- an `lexer.OPERATOR` token is a fold point. The integer `1` indicates the -- match is a beginning fold point and `-1` indicates the match is an ending -- fold point. Likewise, the second assignment states that any "/\*" or "\*/" -- that the lexer recognizes as part of a `lexer.COMMENT` token is a fold point. -- The lexer does not consider any occurences of these characters outside their -- defined tokens (such as in a string) as fold points. Finally, every -- `_foldsymbols` table must have a `_patterns` field that contains a list of -- [Lua patterns][] that match fold points. If the lexer encounters text that -- matches one of those patterns, the lexer looks up the matched text in its -- token's table in order to determine whether or not the text is a fold point. -- In the example above, the first Lua pattern matches any '{' or '}' -- characters. When the lexer comes across one of those characters, it checks if -- the match is an `lexer.OPERATOR` token. If so, the lexer identifies the match -- as a fold point. The same idea applies for the other patterns. (The '%' is in -- the other patterns because '\*' is a special character in Lua patterns that -- needs escaping.) How do you specify fold keywords? Here is an example for -- Lua: -- -- M._foldsymbols = { -- [l.KEYWORD] = { -- ['if'] = 1, ['do'] = 1, ['function'] = 1, -- ['end'] = -1, ['repeat'] = 1, ['until'] = -1 -- }, -- _patterns = {'%l+'} -- } -- -- Any time the lexer encounters a lower case word, if that word is a -- `lexer.KEYWORD` token and in the associated list of fold points, the lexer -- identifies the word as a fold point. -- -- If your lexer has case-insensitive keywords as fold points, simply add a -- `_case_insensitive = true` option to the `_foldsymbols` table and specify -- keywords in lower-case. -- -- If your lexer needs to do some additional processing to determine if a match -- is a fold point, assign a function that returns an integer. Returning `1` or -- `-1` indicates the match is a fold point. Returning `0` indicates it is not. -- For example: -- -- local function fold_strange_token(text, pos, line, s, match) -- if ... then -- return 1 -- beginning fold point -- elseif ... then -- return -1 -- ending fold point -- end -- return 0 -- end -- -- M._foldsymbols = { -- ['strange_token'] = {['|'] = fold_strange_token}, -- _patterns = {'|'} -- } -- -- Any time the lexer encounters a '|' that is a "strange_token", it calls the -- `fold_strange_token` function to determine if '|' is a fold point. The lexer -- calls these functions with the following arguments: the text to identify fold -- points in, the beginning position of the current line in the text to fold, -- the current line's text, the position in the current line the matched text -- starts at, and the matched text itself. -- -- [Lua patterns]: http://www.lua.org/manual/5.2/manual.html#6.4.1 -- -- ### Fold by Indentation -- -- Some languages have significant whitespace and/or no delimiters that indicate -- fold points. If your lexer falls into this category and you would like to -- mark fold points based on changes in indentation, use the -- `_FOLDBYINDENTATION` field: -- -- M._FOLDBYINDENTATION = true -- -- ## Using Lexers -- -- ### Textadept -- -- Put your lexer in your *~/.textadept/lexers/* directory so you do not -- overwrite it when upgrading Textadept. Also, lexers in this directory -- override default lexers. Thus, Textadept loads a user *lua* lexer instead of -- the default *lua* lexer. This is convenient for tweaking a default lexer to -- your liking. Then add a [file type][] for your lexer if necessary. -- -- [file type]: _M.textadept.file_types.html -- -- ### SciTE -- -- Create a *.properties* file for your lexer and `import` it in either your -- *SciTEUser.properties* or *SciTEGlobal.properties*. The contents of the -- *.properties* file should contain: -- -- file.patterns.[lexer_name]=[file_patterns] -- lexer.$(file.patterns.[lexer_name])=[lexer_name] -- -- where `[lexer_name]` is the name of your lexer (minus the *.lua* extension) -- and `[file_patterns]` is a set of file extensions to use your lexer for. -- -- Please note that Lua lexers ignore any styling information in *.properties* -- files. Your theme file in the *lexers/themes/* directory contains styling -- information. -- -- ## Considerations -- -- ### Performance -- -- There might be some slight overhead when initializing a lexer, but loading a -- file from disk into Scintilla is usually more expensive. On modern computer -- systems, I see no difference in speed between LPeg lexers and Scintilla's C++ -- ones. Optimize lexers for speed by re-arranging rules in the `_rules` table -- so that the most common rules match first. Do keep in mind that order matters -- for similar rules. -- -- ### Limitations -- -- Embedded preprocessor languages like PHP cannot completely embed in their -- parent languages in that the parent's tokens do not support start and end -- rules. This mostly goes unnoticed, but code like -- -- <div id="<?php echo $id; ?>"> -- -- or -- -- <div <?php if ($odd) { echo 'class="odd"'; } ?>> -- -- will not style correctly. -- -- ### Troubleshooting -- -- Errors in lexers can be tricky to debug. Lexers print Lua errors to -- `io.stderr` and `_G.print()` statements to `io.stdout`. Running your editor -- from a terminal is the easiest way to see errors as they occur. -- -- ### Risks -- -- Poorly written lexers have the ability to crash Scintilla (and thus its -- containing application), so unsaved data might be lost. However, I have only -- observed these crashes in early lexer development, when syntax errors or -- pattern errors are present. Once the lexer actually starts styling text -- (either correctly or incorrectly, it does not matter), I have not observed -- any crashes. -- -- ### Acknowledgements -- -- Thanks to Peter Odding for his [lexer post][] on the Lua mailing list -- that inspired me, and thanks to Roberto Ierusalimschy for LPeg. -- -- [lexer post]: http://lua-users.org/lists/lua-l/2007-04/msg00116.html -- @field LEXERPATH (string) -- The path used to search for a lexer to load. -- Identical in format to Lua's `package.path` string. -- The default value is `package.path`. -- @field DEFAULT (string) -- The token name for default tokens. -- @field WHITESPACE (string) -- The token name for whitespace tokens. -- @field COMMENT (string) -- The token name for comment tokens. -- @field STRING (string) -- The token name for string tokens. -- @field NUMBER (string) -- The token name for number tokens. -- @field KEYWORD (string) -- The token name for keyword tokens. -- @field IDENTIFIER (string) -- The token name for identifier tokens. -- @field OPERATOR (string) -- The token name for operator tokens. -- @field ERROR (string) -- The token name for error tokens. -- @field PREPROCESSOR (string) -- The token name for preprocessor tokens. -- @field CONSTANT (string) -- The token name for constant tokens. -- @field VARIABLE (string) -- The token name for variable tokens. -- @field FUNCTION (string) -- The token name for function tokens. -- @field CLASS (string) -- The token name for class tokens. -- @field TYPE (string) -- The token name for type tokens. -- @field LABEL (string) -- The token name for label tokens. -- @field REGEX (string) -- The token name for regex tokens. -- @field STYLE_CLASS (string) -- The style typically used for class definitions. -- @field STYLE_COMMENT (string) -- The style typically used for code comments. -- @field STYLE_CONSTANT (string) -- The style typically used for constants. -- @field STYLE_ERROR (string) -- The style typically used for erroneous syntax. -- @field STYLE_FUNCTION (string) -- The style typically used for function definitions. -- @field STYLE_KEYWORD (string) -- The style typically used for language keywords. -- @field STYLE_LABEL (string) -- The style typically used for labels. -- @field STYLE_NUMBER (string) -- The style typically used for numbers. -- @field STYLE_OPERATOR (string) -- The style typically used for operators. -- @field STYLE_REGEX (string) -- The style typically used for regular expression strings. -- @field STYLE_STRING (string) -- The style typically used for strings. -- @field STYLE_PREPROCESSOR (string) -- The style typically used for preprocessor statements. -- @field STYLE_TYPE (string) -- The style typically used for static types. -- @field STYLE_VARIABLE (string) -- The style typically used for variables. -- @field STYLE_WHITESPACE (string) -- The style typically used for whitespace. -- @field STYLE_EMBEDDED (string) -- The style typically used for embedded code. -- @field STYLE_IDENTIFIER (string) -- The style typically used for identifier words. -- @field STYLE_DEFAULT (string) -- The style all styles are based off of. -- @field STYLE_LINENUMBER (string) -- The style used for all margins except fold margins. -- @field STYLE_BRACELIGHT (string) -- The style used for highlighted brace characters. -- @field STYLE_BRACEBAD (string) -- The style used for unmatched brace characters. -- @field STYLE_CONTROLCHAR (string) -- The style used for control characters. -- Color attributes are ignored. -- @field STYLE_INDENTGUIDE (string) -- The style used for indentation guides. -- @field STYLE_CALLTIP (string) -- The style used by call tips if [`buffer.call_tip_use_style`]() is set. -- Only the font name, size, and color attributes are used. -- @field any (pattern) -- A pattern that matches any single character. -- @field ascii (pattern) -- A pattern that matches any ASCII character (codes 0 to 127). -- @field extend (pattern) -- A pattern that matches any ASCII extended character (codes 0 to 255). -- @field alpha (pattern) -- A pattern that matches any alphabetic character ('A'-'Z', 'a'-'z'). -- @field digit (pattern) -- A pattern that matches any digit ('0'-'9'). -- @field alnum (pattern) -- A pattern that matches any alphanumeric character ('A'-'Z', 'a'-'z', -- '0'-'9'). -- @field lower (pattern) -- A pattern that matches any lower case character ('a'-'z'). -- @field upper (pattern) -- A pattern that matches any upper case character ('A'-'Z'). -- @field xdigit (pattern) -- A pattern that matches any hexadecimal digit ('0'-'9', 'A'-'F', 'a'-'f'). -- @field cntrl (pattern) -- A pattern that matches any control character (ASCII codes 0 to 31). -- @field graph (pattern) -- A pattern that matches any graphical character ('!' to '~'). -- @field print (pattern) -- A pattern that matches any printable character (' ' to '~'). -- @field punct (pattern) -- A pattern that matches any punctuation character ('!' to '/', ':' to '@', -- '[' to ''', '{' to '~'). -- @field space (pattern) -- A pattern that matches any whitespace character ('\t', '\v', '\f', '\n', -- '\r', space). -- @field newline (pattern) -- A pattern that matches any set of end of line characters. -- @field nonnewline (pattern) -- A pattern that matches any single, non-newline character. -- @field nonnewline_esc (pattern) -- A pattern that matches any single, non-newline character or any set of end -- of line characters escaped with '\'. -- @field dec_num (pattern) -- A pattern that matches a decimal number. -- @field hex_num (pattern) -- A pattern that matches a hexadecimal number. -- @field oct_num (pattern) -- A pattern that matches an octal number. -- @field integer (pattern) -- A pattern that matches either a decimal, hexadecimal, or octal number. -- @field float (pattern) -- A pattern that matches a floating point number. -- @field word (pattern) -- A pattern that matches a typical word. Words begin with a letter or -- underscore and consist of alphanumeric and underscore characters. -- @field FOLD_BASE (number) -- The initial (root) fold level. -- @field FOLD_BLANK (number) -- Flag indicating that the line is blank. -- @field FOLD_HEADER (number) -- Flag indicating the line is fold point. -- @field fold_level (table, Read-only) -- Table of fold level bit-masks for line numbers starting from zero. -- Fold level masks are composed of an integer level combined with any of the -- following bits: -- -- * `lexer.FOLD_BASE` -- The initial fold level. -- * `lexer.FOLD_BLANK` -- The line is blank. -- * `lexer.FOLD_HEADER` -- The line is a header, or fold point. -- @field indent_amount (table, Read-only) -- Table of indentation amounts in character columns, for line numbers -- starting from zero. -- @field line_state (table) -- Table of integer line states for line numbers starting from zero. -- Line states can be used by lexers for keeping track of persistent states. -- @field property (table) -- Map of key-value string pairs. -- @field property_expanded (table, Read-only) -- Map of key-value string pairs with `$()` and `%()` variable replacement -- performed in values. -- @field property_int (table, Read-only) -- Map of key-value pairs with values interpreted as numbers, or `0` if not -- found. -- @field style_at (table, Read-only) -- Table of style names at positions in the buffer starting from 1. module('lexer')]=] local lpeg = require('lpeg') local lpeg_P, lpeg_R, lpeg_S, lpeg_V = lpeg.P, lpeg.R, lpeg.S, lpeg.V local lpeg_Ct, lpeg_Cc, lpeg_Cp = lpeg.Ct, lpeg.Cc, lpeg.Cp local lpeg_Cmt, lpeg_C = lpeg.Cmt, lpeg.C local lpeg_match = lpeg.match M.LEXERPATH = package.path -- Table of loaded lexers. local lexers = {} -- Keep track of the last parent lexer loaded. This lexer's rules are used for -- proxy lexers (those that load parent and child lexers to embed) that do not -- declare a parent lexer. local parent_lexer if not package.searchpath then -- Searches for the given *name* in the given *path*. -- This is an implementation of Lua 5.2's `package.searchpath()` function for -- Lua 5.1. function package.searchpath(name, path) local tried = {} for part in path:gmatch('[^;]+') do local filename = part:gsub('%?', name) local f = io.open(filename, 'r') if f then f:close() return filename end tried[#tried + 1] = ("no file '%s'"):format(filename) end return nil, table.concat(tried, '\n') end end -- Adds a rule to a lexer's current ordered list of rules. -- @param lexer The lexer to add the given rule to. -- @param name The name associated with this rule. It is used for other lexers -- to access this particular rule from the lexer's `_RULES` table. It does not -- have to be the same as the name passed to `token`. -- @param rule The LPeg pattern of the rule. local function add_rule(lexer, id, rule) if not lexer._RULES then lexer._RULES = {} -- Contains an ordered list (by numerical index) of rule names. This is used -- in conjunction with lexer._RULES for building _TOKENRULE. lexer._RULEORDER = {} end lexer._RULES[id] = rule lexer._RULEORDER[#lexer._RULEORDER + 1] = id end -- Adds a new Scintilla style to Scintilla. -- @param lexer The lexer to add the given style to. -- @param token_name The name of the token associated with this style. -- @param style A Scintilla style created from `style()`. -- @see style local function add_style(lexer, token_name, style) local num_styles = lexer._numstyles if num_styles == 32 then num_styles = num_styles + 8 end -- skip predefined if num_styles >= 255 then print('Too many styles defined (255 MAX)') end lexer._TOKENSTYLES[token_name], lexer._numstyles = num_styles, num_styles + 1 lexer._EXTRASTYLES[token_name] = style end -- (Re)constructs `lexer._TOKENRULE`. -- @param parent The parent lexer. local function join_tokens(lexer) local patterns, order = lexer._RULES, lexer._RULEORDER local token_rule = patterns[order[1]] for i = 2, #order do token_rule = token_rule + patterns[order[i]] end lexer._TOKENRULE = token_rule + M.token(M.DEFAULT, M.any) return lexer._TOKENRULE end -- Adds a given lexer and any of its embedded lexers to a given grammar. -- @param grammar The grammar to add the lexer to. -- @param lexer The lexer to add. local function add_lexer(grammar, lexer, token_rule) local token_rule = join_tokens(lexer) local lexer_name = lexer._NAME for i = 1, #lexer._CHILDREN do local child = lexer._CHILDREN[i] if child._CHILDREN then add_lexer(grammar, child) end local child_name = child._NAME local rules = child._EMBEDDEDRULES[lexer_name] local rules_token_rule = grammar['__'..child_name] or rules.token_rule grammar[child_name] = (-rules.end_rule * rules_token_rule)^0 * rules.end_rule^-1 * lpeg_V(lexer_name) local embedded_child = '_'..child_name grammar[embedded_child] = rules.start_rule * (-rules.end_rule * rules_token_rule)^0 * rules.end_rule^-1 token_rule = lpeg_V(embedded_child) + token_rule end grammar['__'..lexer_name] = token_rule -- can contain embedded lexer rules grammar[lexer_name] = token_rule^0 end -- (Re)constructs `lexer._GRAMMAR`. -- @param lexer The parent lexer. -- @param initial_rule The name of the rule to start lexing with. The default -- value is `lexer._NAME`. Multilang lexers use this to start with a child -- rule if necessary. local function build_grammar(lexer, initial_rule) local children = lexer._CHILDREN if children then local lexer_name = lexer._NAME if not initial_rule then initial_rule = lexer_name end local grammar = {initial_rule} add_lexer(grammar, lexer) lexer._INITIALRULE = initial_rule lexer._GRAMMAR = lpeg_Ct(lpeg_P(grammar)) else lexer._GRAMMAR = lpeg_Ct(join_tokens(lexer)^0) end end local string_upper = string.upper -- Default styles. local default = { 'nothing', 'whitespace', 'comment', 'string', 'number', 'keyword', 'identifier', 'operator', 'error', 'preprocessor', 'constant', 'variable', 'function', 'class', 'type', 'label', 'regex', 'embedded' } for i = 1, #default do local name, upper_name = default[i], string_upper(default[i]) M[upper_name], M['STYLE_'..upper_name] = name, '$(style.'..name..')' end -- Predefined styles. local predefined = { 'default', 'linenumber', 'bracelight', 'bracebad', 'controlchar', 'indentguide', 'calltip' } for i = 1, #predefined do local name, upper_name = predefined[i], string_upper(predefined[i]) M[upper_name], M['STYLE_'..upper_name] = name, '$(style.'..name..')' end --- -- Initializes or loads and returns the lexer of string name *name*. -- Scintilla calls this function in order to load a lexer. Parent lexers also -- call this function in order to load child lexers and vice-versa. The user -- calls this function in order to load a lexer when using Scintillua as a Lua -- library. -- @param name The name of the lexing language. -- @param alt_name The alternate name of the lexing language. This is useful for -- embedding the same child lexer with multiple sets of start and end tokens. -- @return lexer object -- @name load function M.load(name, alt_name) if lexers[alt_name or name] then return lexers[alt_name or name] end parent_lexer = nil -- reset -- When using Scintillua as a stand-alone module, the `property` and -- `property_int` tables do not exist (they are not useful). Create them to -- prevent errors from occurring. if not M.property then M.property, M.property_int = {}, setmetatable({}, { __index = function(t, k) return tonumber(M.property[k]) or 0 end, __newindex = function() error('read-only property') end }) end -- Load the language lexer with its rules, styles, etc. M.WHITESPACE = (alt_name or name)..'_whitespace' local lexer_file, error = package.searchpath(name, M.LEXERPATH) if not lexer_file then return nil, "Can't find lexer file" end local ok, lexer = pcall(dofile, lexer_file) if not ok then return nil, "Can't load lexer file" end if alt_name then lexer._NAME = alt_name end -- Create the initial maps for token names to style numbers and styles. local token_styles = {} for i = 1, #default do token_styles[default[i]] = i - 1 end for i = 1, #predefined do token_styles[predefined[i]] = i + 31 end lexer._TOKENSTYLES, lexer._numstyles = token_styles, #default lexer._EXTRASTYLES = {} -- If the lexer is a proxy (loads parent and child lexers to embed) and does -- not declare a parent, try and find one and use its rules. if not lexer._rules and not lexer._lexer then lexer._lexer = parent_lexer end -- If the lexer is a proxy or a child that embedded itself, add its rules and -- styles to the parent lexer. Then set the parent to be the main lexer. if lexer._lexer then local l, _r, _s = lexer._lexer, lexer._rules, lexer._tokenstyles if not l._tokenstyles then l._tokenstyles = {} end if _r then for i = 1, #_r do -- Prevent rule id clashes. l._rules[#l._rules + 1] = {lexer._NAME..'_'.._r[i][1], _r[i][2]} end end if _s then for token, style in pairs(_s) do l._tokenstyles[token] = style end end lexer = l end -- Add the lexer's styles and build its grammar. if lexer._rules then if lexer._tokenstyles then for token, style in pairs(lexer._tokenstyles) do add_style(lexer, token, style) end end for i = 1, #lexer._rules do add_rule(lexer, lexer._rules[i][1], lexer._rules[i][2]) end build_grammar(lexer) end -- Add the lexer's unique whitespace style. add_style(lexer, lexer._NAME..'_whitespace', M.STYLE_WHITESPACE) -- Process the lexer's fold symbols. if lexer._foldsymbols and lexer._foldsymbols._patterns then local patterns = lexer._foldsymbols._patterns for i = 1, #patterns do patterns[i] = '()('..patterns[i]..')' end end lexer.lex, lexer.fold = M.lex, M.fold lexers[alt_name or name] = lexer return lexer end --- -- Lexes a chunk of text *text* (that has an initial style number of -- *init_style*) with lexer *lexer*. -- If *lexer* has a `_LEXBYLINE` flag set, the text is lexed one line at a time. -- Otherwise the text is lexed as a whole. -- @param lexer The lexer object to lex with. -- @param text The text in the buffer to lex. -- @param init_style The current style. Multiple-language lexers use this to -- determine which language to start lexing in. -- @return table of token names and positions. -- @name lex function M.lex(lexer, text, init_style) if not lexer._GRAMMAR then return {M.DEFAULT, #text + 1} end if not lexer._LEXBYLINE then -- For multilang lexers, build a new grammar whose initial_rule is the -- current language. if lexer._CHILDREN then for style, style_num in pairs(lexer._TOKENSTYLES) do if style_num == init_style then local lexer_name = style:match('^(.+)_whitespace') or lexer._NAME if lexer._INITIALRULE ~= lexer_name then build_grammar(lexer, lexer_name) end break end end end return lpeg_match(lexer._GRAMMAR, text) else local tokens = {} local function append(tokens, line_tokens, offset) for i = 1, #line_tokens, 2 do tokens[#tokens + 1] = line_tokens[i] tokens[#tokens + 1] = line_tokens[i + 1] + offset end end local offset = 0 local grammar = lexer._GRAMMAR for line in text:gmatch('[^\r\n]*\r?\n?') do local line_tokens = lpeg_match(grammar, line) if line_tokens then append(tokens, line_tokens, offset) end offset = offset + #line -- Use the default style to the end of the line if none was specified. if tokens[#tokens] ~= offset then tokens[#tokens + 1], tokens[#tokens + 2] = 'default', offset + 1 end end return tokens end end --- -- Determines fold points in a chunk of text *text* with lexer *lexer*. -- *text* starts at position *start_pos* on line number *start_line* with a -- beginning fold level of *start_level* in the buffer. If *lexer* has a `_fold` -- function or a `_foldsymbols` table, that field is used to perform folding. -- Otherwise, if *lexer* has a `_FOLDBYINDENTATION` field set, or if a -- `fold.by.indentation` property is set, folding by indentation is done. -- @param lexer The lexer object to fold with. -- @param text The text in the buffer to fold. -- @param start_pos The position in the buffer *text* starts at, starting at -- zero. -- @param start_line The line number *text* starts on. -- @param start_level The fold level *text* starts on. -- @return table of fold levels. -- @name fold function M.fold(lexer, text, start_pos, start_line, start_level) local folds = {} if text == '' then return folds end local fold = M.property_int['fold'] > 0 local FOLD_BASE = M.FOLD_BASE local FOLD_HEADER, FOLD_BLANK = M.FOLD_HEADER, M.FOLD_BLANK if fold and lexer._fold then return lexer._fold(text, start_pos, start_line, start_level) elseif fold and lexer._foldsymbols then local lines = {} for p, l in (text..'\n'):gmatch('()(.-)\r?\n') do lines[#lines + 1] = {p, l} end local fold_zero_sum_lines = M.property_int['fold.on.zero.sum.lines'] > 0 local fold_symbols = lexer._foldsymbols local fold_symbols_patterns = fold_symbols._patterns local fold_symbols_case_insensitive = fold_symbols._case_insensitive local style_at, fold_level = M.style_at, M.fold_level local line_num, prev_level = start_line, start_level local current_level = prev_level for i = 1, #lines do local pos, line = lines[i][1], lines[i][2] if line ~= '' then if fold_symbols_case_insensitive then line = line:lower() end local level_decreased = false for j = 1, #fold_symbols_patterns do for s, match in line:gmatch(fold_symbols_patterns[j]) do local symbols = fold_symbols[style_at[start_pos + pos + s - 1]] local l = symbols and symbols[match] if type(l) == 'function' then l = l(text, pos, line, s, match) end if type(l) == 'number' then current_level = current_level + l if l < 0 and current_level < prev_level then -- Potential zero-sum line. If the level were to go back up on -- the same line, the line may be marked as a fold header. level_decreased = true end end end end folds[line_num] = prev_level if current_level > prev_level then folds[line_num] = prev_level + FOLD_HEADER elseif level_decreased and current_level == prev_level and fold_zero_sum_lines then if line_num > start_line then folds[line_num] = prev_level - 1 + FOLD_HEADER else -- Typing within a zero-sum line. local level = fold_level[line_num - 1] - 1 if level > FOLD_HEADER then level = level - FOLD_HEADER end if level > FOLD_BLANK then level = level - FOLD_BLANK end folds[line_num] = level + FOLD_HEADER current_level = current_level + 1 end end if current_level < FOLD_BASE then current_level = FOLD_BASE end prev_level = current_level else folds[line_num] = prev_level + FOLD_BLANK end line_num = line_num + 1 end elseif fold and (lexer._FOLDBYINDENTATION or M.property_int['fold.by.indentation'] > 0) then -- Indentation based folding. -- Calculate indentation per line. local indentation = {} for indent, line in (text..'\n'):gmatch('([\t ]*)([^\r\n]*)\r?\n') do indentation[#indentation + 1] = line ~= '' and #indent end -- Find the first non-blank line before start_line. If the current line is -- indented, make that previous line a header and update the levels of any -- blank lines inbetween. If the current line is blank, match the level of -- the previous non-blank line. local current_level = start_level for i = start_line - 1, 0, -1 do local level = M.fold_level[i] if level >= FOLD_HEADER then level = level - FOLD_HEADER end if level < FOLD_BLANK then local indent = M.indent_amount[i] if indentation[1] and indentation[1] > indent then folds[i] = FOLD_BASE + indent + FOLD_HEADER for j = i + 1, start_line - 1 do folds[j] = start_level + FOLD_BLANK end elseif not indentation[1] then current_level = FOLD_BASE + indent end break end end -- Iterate over lines, setting fold numbers and fold flags. for i = 1, #indentation do if indentation[i] then current_level = FOLD_BASE + indentation[i] folds[start_line + i - 1] = current_level for j = i + 1, #indentation do if indentation[j] then if FOLD_BASE + indentation[j] > current_level then folds[start_line + i - 1] = current_level + FOLD_HEADER current_level = FOLD_BASE + indentation[j] -- for any blanks below end break end end else folds[start_line + i - 1] = current_level + FOLD_BLANK end end else -- No folding, reset fold levels if necessary. local current_line = start_line for _ in text:gmatch('\r?\n') do folds[current_line] = start_level current_line = current_line + 1 end end return folds end -- The following are utility functions lexers will have access to. -- Common patterns. M.any = lpeg_P(1) M.ascii = lpeg_R('\000\127') M.extend = lpeg_R('\000\255') M.alpha = lpeg_R('AZ', 'az') M.digit = lpeg_R('09') M.alnum = lpeg_R('AZ', 'az', '09') M.lower = lpeg_R('az') M.upper = lpeg_R('AZ') M.xdigit = lpeg_R('09', 'AF', 'af') M.cntrl = lpeg_R('\000\031') M.graph = lpeg_R('!~') M.print = lpeg_R(' ~') M.punct = lpeg_R('!/', ':@', '[\'', '{~') M.space = lpeg_S('\t\v\f\n\r ') M.newline = lpeg_S('\r\n\f')^1 M.nonnewline = 1 - M.newline M.nonnewline_esc = 1 - (M.newline + '\\') + '\\' * M.any M.dec_num = M.digit^1 M.hex_num = '0' * lpeg_S('xX') * M.xdigit^1 M.oct_num = '0' * lpeg_R('07')^1 M.integer = lpeg_S('+-')^-1 * (M.hex_num + M.oct_num + M.dec_num) M.float = lpeg_S('+-')^-1 * ((M.digit^0 * '.' * M.digit^1 + M.digit^1 * '.' * M.digit^0) * (lpeg_S('eE') * lpeg_S('+-')^-1 * M.digit^1)^-1 + (M.digit^1 * lpeg_S('eE') * lpeg_S('+-')^-1 * M.digit^1)) M.word = (M.alpha + '_') * (M.alnum + '_')^0 --- -- Creates and returns a token pattern with token name *name* and pattern -- *patt*. -- If *name* is not a predefined token name, its style must be defined in the -- lexer's `_tokenstyles` table. -- @param name The name of token. If this name is not a predefined token name, -- then a style needs to be assiciated with it in the lexer's `_tokenstyles` -- table. -- @param patt The LPeg pattern associated with the token. -- @return pattern -- @usage local ws = token(l.WHITESPACE, l.space^1) -- @usage local annotation = token('annotation', '@' * l.word) -- @name token function M.token(name, patt) return lpeg_Cc(name) * patt * lpeg_Cp() end --- -- Creates and returns a pattern that matches a range of text bounded by -- *chars* characters. -- This is a convenience function for matching more complicated delimited ranges -- like strings with escape characters and balanced parentheses. *single_line* -- indicates whether or not the range must be on a single line, *no_escape* -- indicates whether or not to ignore '\' as an escape character, and *balanced* -- indicates whether or not to handle balanced ranges like parentheses and -- requires *chars* to be composed of two characters. -- @param chars The character(s) that bound the matched range. -- @param single_line Optional flag indicating whether or not the range must be -- on a single line. -- @param no_escape Optional flag indicating whether or not the range end -- character may be escaped by a '\\' character. -- @param balanced Optional flag indicating whether or not to match a balanced -- range, like the "%b" Lua pattern. This flag only applies if *chars* -- consists of two different characters (e.g. "()"). -- @return pattern -- @usage local dq_str_escapes = l.delimited_range('"') -- @usage local dq_str_noescapes = l.delimited_range('"', false, true) -- @usage local unbalanced_parens = l.delimited_range('()') -- @usage local balanced_parens = l.delimited_range('()', false, false, true) -- @see nested_pair -- @name delimited_range function M.delimited_range(chars, single_line, no_escape, balanced) local s = chars:sub(1, 1) local e = #chars == 2 and chars:sub(2, 2) or s local range local b = balanced and s or '' local n = single_line and '\n' or '' if no_escape then local invalid = lpeg_S(e..n..b) range = M.any - invalid else local invalid = lpeg_S(e..n..b) + '\\' range = M.any - invalid + '\\' * M.any end if balanced and s ~= e then return lpeg_P{s * (range + lpeg_V(1))^0 * e} else return s * range^0 * lpeg_P(e)^-1 end end --- -- Creates and returns a pattern that matches pattern *patt* only at the -- beginning of a line. -- @param patt The LPeg pattern to match on the beginning of a line. -- @return pattern -- @usage local preproc = token(l.PREPROCESSOR, l.starts_line('#') * -- l.nonnewline^0) -- @name starts_line function M.starts_line(patt) return lpeg_Cmt(lpeg_C(patt), function(input, index, match, ...) local pos = index - #match if pos == 1 then return index, ... end local char = input:sub(pos - 1, pos - 1) if char == '\n' or char == '\r' or char == '\f' then return index, ... end end) end --- -- Creates and returns a pattern that verifies that string set *s* contains the -- first non-whitespace character behind the current match position. -- @param s String character set like one passed to `lpeg.S()`. -- @return pattern -- @usage local regex = l.last_char_includes('+-*!%^&|=,([{') * -- l.delimited_range('/') -- @name last_char_includes function M.last_char_includes(s) s = '['..s:gsub('[-%%%[]', '%%%1')..']' return lpeg_P(function(input, index) if index == 1 then return index end local i = index while input:sub(i - 1, i - 1):match('[ \t\r\n\f]') do i = i - 1 end if input:sub(i - 1, i - 1):match(s) then return index end end) end --- -- Returns a pattern that matches a balanced range of text that starts with -- string *start_chars* and ends with string *end_chars*. -- With single-character delimiters, this function is identical to -- `delimited_range(start_chars..end_chars, false, true, true)`. -- @param start_chars The string starting a nested sequence. -- @param end_chars The string ending a nested sequence. -- @return pattern -- @usage local nested_comment = l.nested_pair('/*', '*/') -- @see delimited_range -- @name nested_pair function M.nested_pair(start_chars, end_chars) local s, e = start_chars, lpeg_P(end_chars)^-1 return lpeg_P{s * (M.any - s - end_chars + lpeg_V(1))^0 * e} end --- -- Creates and returns a pattern that matches any single word in list *words*. -- Words consist of alphanumeric and underscore characters, as well as the -- characters in string set *word_chars*. *case_insensitive* indicates whether -- or not to ignore case when matching words. -- This is a convenience function for simplifying a set of ordered choice word -- patterns. -- @param words A table of words. -- @param word_chars Optional string of additional characters considered to be -- part of a word. By default, word characters are alphanumerics and -- underscores ("%w_" in Lua). This parameter may be `nil` or the empty string -- in order to indicate no additional word characters. -- @param case_insensitive Optional boolean flag indicating whether or not the -- word match is case-insensitive. The default is `false`. -- @return pattern -- @usage local keyword = token(l.KEYWORD, word_match{'foo', 'bar', 'baz'}) -- @usage local keyword = token(l.KEYWORD, word_match({'foo-bar', 'foo-baz', -- 'bar-foo', 'bar-baz', 'baz-foo', 'baz-bar'}, '-', true)) -- @name word_match function M.word_match(words, word_chars, case_insensitive) local word_list = {} for i = 1, #words do word_list[case_insensitive and words[i]:lower() or words[i]] = true end local chars = M.alnum + '_' if word_chars then chars = chars + lpeg_S(word_chars) end return lpeg_Cmt(chars^1, function(input, index, word) if case_insensitive then word = word:lower() end return word_list[word] and index or nil end) end --- -- Embeds child lexer *child* in parent lexer *parent* using patterns -- *start_rule* and *end_rule*, which signal the beginning and end of the -- embedded lexer, respectively. -- @param parent The parent lexer. -- @param child The child lexer. -- @param start_rule The pattern that signals the beginning of the embedded -- lexer. -- @param end_rule The pattern that signals the end of the embedded lexer. -- @usage l.embed_lexer(M, css, css_start_rule, css_end_rule) -- @usage l.embed_lexer(html, M, php_start_rule, php_end_rule) -- @usage l.embed_lexer(html, ruby, ruby_start_rule, ruby_end_rule) -- @name embed_lexer function M.embed_lexer(parent, child, start_rule, end_rule) -- Add child rules. if not child._EMBEDDEDRULES then child._EMBEDDEDRULES = {} end if not child._RULES then -- creating a child lexer to be embedded if not child._rules then error('Cannot embed language with no rules') end for i = 1, #child._rules do add_rule(child, child._rules[i][1], child._rules[i][2]) end end child._EMBEDDEDRULES[parent._NAME] = { ['start_rule'] = start_rule, token_rule = join_tokens(child), ['end_rule'] = end_rule } if not parent._CHILDREN then parent._CHILDREN = {} end local children = parent._CHILDREN children[#children + 1] = child -- Add child styles. if not parent._tokenstyles then parent._tokenstyles = {} end local tokenstyles = parent._tokenstyles tokenstyles[child._NAME..'_whitespace'] = M.STYLE_WHITESPACE if child._tokenstyles then for token, style in pairs(child._tokenstyles) do tokenstyles[token] = style end end -- Add child fold symbols. if not parent._foldsymbols then parent._foldsymbols = {} end if child._foldsymbols then for token, symbols in pairs(child._foldsymbols) do if not parent._foldsymbols[token] then parent._foldsymbols[token] = {} end for k, v in pairs(symbols) do if type(k) == 'number' then parent._foldsymbols[token][#parent._foldsymbols[token] + 1] = v elseif not parent._foldsymbols[token][k] then parent._foldsymbols[token][k] = v end end end end child._lexer = parent -- use parent's tokens if child is embedding itself parent_lexer = parent -- use parent's tokens if the calling lexer is a proxy end -- Determines if the previous line is a comment. -- This is used for determining if the current comment line is a fold point. -- @param prefix The prefix string defining a comment. -- @param text The text passed to a fold function. -- @param pos The pos passed to a fold function. -- @param line The line passed to a fold function. -- @param s The s passed to a fold function. local function prev_line_is_comment(prefix, text, pos, line, s) local start = line:find('%S') if start < s and not line:find(prefix, start, true) then return false end local p = pos - 1 if text:sub(p, p) == '\n' then p = p - 1 if text:sub(p, p) == '\r' then p = p - 1 end if text:sub(p, p) ~= '\n' then while p > 1 and text:sub(p - 1, p - 1) ~= '\n' do p = p - 1 end while text:sub(p, p):find('^[\t ]$') do p = p + 1 end return text:sub(p, p + #prefix - 1) == prefix end end return false end -- Determines if the next line is a comment. -- This is used for determining if the current comment line is a fold point. -- @param prefix The prefix string defining a comment. -- @param text The text passed to a fold function. -- @param pos The pos passed to a fold function. -- @param line The line passed to a fold function. -- @param s The s passed to a fold function. local function next_line_is_comment(prefix, text, pos, line, s) local p = text:find('\n', pos + s) if p then p = p + 1 while text:sub(p, p):find('^[\t ]$') do p = p + 1 end return text:sub(p, p + #prefix - 1) == prefix end return false end --- -- Returns a fold function (to be used within the lexer's `_foldsymbols` table) -- that folds consecutive line comments that start with string *prefix*. -- @param prefix The prefix string defining a line comment. -- @usage [l.COMMENT] = {['--'] = l.fold_line_comments('--')} -- @usage [l.COMMENT] = {['//'] = l.fold_line_comments('//')} -- @name fold_line_comments function M.fold_line_comments(prefix) local property_int = M.property_int return function(text, pos, line, s) if property_int['fold.line.comments'] == 0 then return 0 end if s > 1 and line:match('^%s*()') < s then return 0 end local prev_line_comment = prev_line_is_comment(prefix, text, pos, line, s) local next_line_comment = next_line_is_comment(prefix, text, pos, line, s) if not prev_line_comment and next_line_comment then return 1 end if prev_line_comment and not next_line_comment then return -1 end return 0 end end M.property_expanded = setmetatable({}, { -- Returns the string property value associated with string property *key*, -- replacing any "$()" and "%()" expressions with the values of their keys. __index = function(t, key) return M.property[key]:gsub('[$%%]%b()', function(key) return t[key:sub(3, -2)] end) end, __newindex = function() error('read-only property') end }) --[[ The functions and fields below were defined in C. --- -- Returns the line number of the line that contains position *pos*, which -- starts from 1. -- @param pos The position to get the line number of. -- @return number local function line_from_position(pos) end --- -- Individual fields for a lexer instance. -- @field _NAME The string name of the lexer. -- @field _rules An ordered list of rules for a lexer grammar. -- Each rule is a table containing an arbitrary rule name and the LPeg pattern -- associated with the rule. The order of rules is important, as rules are -- matched sequentially. -- Child lexers should not use this table to access and/or modify their -- parent's rules and vice-versa. Use the `_RULES` table instead. -- @field _tokenstyles A map of non-predefined token names to styles. -- Remember to use token names, not rule names. It is recommended to use -- predefined styles or color-agnostic styles derived from predefined styles -- to ensure compatibility with user color themes. -- @field _foldsymbols A table of recognized fold points for the lexer. -- Keys are token names with table values defining fold points. Those table -- values have string keys of keywords or characters that indicate a fold -- point whose values are integers. A value of `1` indicates a beginning fold -- point and a value of `-1` indicates an ending fold point. Values can also -- be functions that return `1`, `-1`, or `0` (indicating no fold point) for -- keys which need additional processing. -- There is also a required `_pattern` key whose value is a table containing -- Lua pattern strings that match all fold points (the string keys contained -- in token name table values). When the lexer encounters text that matches -- one of those patterns, the matched text is looked up in its token's table -- to determine whether or not it is a fold point. -- @field _fold If this function exists in the lexer, it is called for folding -- the document instead of using `_foldsymbols` or indentation. -- @field _lexer The parent lexer object whose rules should be used. This field -- is only necessary to disambiguate a proxy lexer that loaded parent and -- child lexers for embedding and ended up having multiple parents loaded. -- @field _RULES A map of rule name keys with their associated LPeg pattern -- values for the lexer. -- This is constructed from the lexer's `_rules` table and accessible to other -- lexers for embedded lexer applications like modifying parent or child -- rules. -- @field _LEXBYLINE Indicates the lexer can only process one whole line of text -- (instead of an arbitrary chunk of text) at a time. -- The default value is `false`. Line lexers cannot look ahead to subsequent -- lines. -- @field _FOLDBYINDENTATION Declares the lexer does not define fold points and -- that fold points should be calculated based on changes in indentation. -- @class table -- @name lexer local lexer ]] return M
apache-2.0
kaen/Zero-K
LuaRules/Configs/MetalSpots/Grts_Messa_008.lua
17
1312
return { spots = { -- Four metal spots in center {x = 6162, z = 6750, metal = 3}, {x = 5546, z = 6128, metal = 3}, {x = 6138, z = 5562, metal = 3}, {x = 6747, z = 6152, metal = 3}, -- 12 starting spots (2x3 on each side) {x = 1093, z = 9286, metal = 3}, {x = 1174, z = 7125, metal = 3}, {x = 1208, z = 3882, metal = 3}, {x = 1801, z = 1770, metal = 3}, {x = 11211, z = 3015, metal = 3}, {x = 11127, z = 5179, metal = 3}, {x = 11097, z = 8424, metal = 3}, {x = 10505, z = 10535, metal = 3}, {x = 1110, z = 8144, metal = 3}, {x = 1488, z = 2740, metal = 3}, {x = 11178, z = 4078, metal = 3}, {x = 10853, z = 9452, metal = 3}, -- 8 "pairs" of metal spots -- they are close, but not right next to one another {x = 2734, z = 9944, metal = 3}, {x = 2871, z = 10981, metal = 3}, {x = 5140, z = 8906, metal = 3}, {x = 4199, z = 7650, metal = 3}, {x = 7151, z = 3406, metal = 3}, {x = 8069, z = 4661, metal = 3}, {x = 3010, z = 2775, metal = 3}, {x = 3718, z = 1396, metal = 3}, {x = 8607, z = 10905, metal = 3}, {x = 9275, z = 9512, metal = 3}, {x = 2911, z = 5460, metal = 3}, {x = 4391, z = 4782, metal = 3}, {x = 7771, z = 7617, metal = 3}, {x = 9411, z = 6824, metal = 3}, {x = 9522, z = 2360, metal = 3}, {x = 9419, z = 1328, metal = 3}, } }
gpl-2.0
kaen/Zero-K
LuaUI/Widgets/unit_auto_reclaim_heal_assist.lua
10
3191
----------------------------------- -- Author: Johan Hanssen Seferidis -- -- Comments: Sets all idle units that are not selected to fight. That has as effect to reclaim if there is low metal -- , repair nearby units and assist in building if they have the possibility. -- If you select the unit while it is being idle the widget is not going to take effect on the selected unit. -- ------------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Auto Reclaim/Heal/Assist", desc = "Makes idle unselected builders/rez/com/nanos to reclaim metal if metal bar is not full, repair nearby units and assist in building", author = "Pithikos", date = "Nov 21, 2010", --Nov 7, 2013 license = "GPLv3", layer = 0, enabled = false } end -------------------------------------------------------------------------------------- local echo = Spring.Echo local getUnitPos = Spring.GetUnitPosition local orderUnit = Spring.GiveOrderToUnit local getUnitTeam = Spring.GetUnitTeam local isUnitSelected = Spring.IsUnitSelected local gameInSecs = 0 local lastOrderGivenInSecs= 0 local idleReclaimers={} --reclaimers because they all can reclaim myTeamID=-1; local reverseCompatibility = (Game.version:find('91.0') == 1) or (Game.version:find('94') and not Game.version:find('94.1.1')) -- for UnitDef Tag -------------------------------------------------------------------------------------- --Initializer function widget:Initialize() --disable widget if I am a spec local _, _, spec = Spring.GetPlayerInfo(Spring.GetMyPlayerID()) if spec then widgetHandler:RemoveWidget() return false end myTeamID = Spring.GetMyTeamID() --get my team ID end --Give reclaimers the FIGHT command every second function widget:GameFrame(n) if n%30 == 0 then if WG.Cutscene and WG.Cutscene.IsInCutscene() then return end for unitID in pairs(idleReclaimers) do local x, y, z = getUnitPos(unitID) --get unit's position if (not isUnitSelected(unitID)) then --if unit is not selected orderUnit(unitID, CMD.FIGHT, { x, y, z }, {}) --command unit to reclaim end end end end --Add reclaimer to the register function widget:UnitIdle(unitID, unitDefID, unitTeam) if (myTeamID==getUnitTeam(unitID)) then --check if unit is mine local factoryType = (reverseCompatibility and UnitDefs[unitDefID].type == "Factory") or UnitDefs[unitDefID].isFactory --*** if factoryType then return end --no factories *** if (UnitDefs[unitDefID]["canReclaim"]) then --check if unit can reclaim idleReclaimers[unitID]=true --add unit to register --echo("<auto_reclaim_heal_assist>: registering unit "..unitID.." as idle") end end end --Unregister reclaimer once it is given a command function widget:UnitCommand(unitID) --echo("<auto_reclaim_heal_assist>: unit "..unitID.." got a command") --¤debug for reclaimerID in pairs(idleReclaimers) do if (reclaimerID==unitID) then idleReclaimers[reclaimerID]=nil --echo("<auto_reclaim_heal_assist>: unregistering unit "..reclaimerID.." as idle") end end end
gpl-2.0
girishramnani/Algorithm-Implementations
Hamming_Weight/Lua/Yonaba/numberlua.lua
115
13399
--[[ LUA MODULE bit.numberlua - Bitwise operations implemented in pure Lua as numbers, with Lua 5.2 'bit32' and (LuaJIT) LuaBitOp 'bit' compatibility interfaces. SYNOPSIS local bit = require 'bit.numberlua' print(bit.band(0xff00ff00, 0x00ff00ff)) --> 0xffffffff -- Interface providing strong Lua 5.2 'bit32' compatibility local bit32 = require 'bit.numberlua'.bit32 assert(bit32.band(-1) == 0xffffffff) -- Interface providing strong (LuaJIT) LuaBitOp 'bit' compatibility local bit = require 'bit.numberlua'.bit assert(bit.tobit(0xffffffff) == -1) DESCRIPTION This library implements bitwise operations entirely in Lua. This module is typically intended if for some reasons you don't want to or cannot install a popular C based bit library like BitOp 'bit' [1] (which comes pre-installed with LuaJIT) or 'bit32' (which comes pre-installed with Lua 5.2) but want a similar interface. This modules represents bit arrays as non-negative Lua numbers. [1] It can represent 32-bit bit arrays when Lua is compiled with lua_Number as double-precision IEEE 754 floating point. The module is nearly the most efficient it can be but may be a few times slower than the C based bit libraries and is orders or magnitude slower than LuaJIT bit operations, which compile to native code. Therefore, this library is inferior in performane to the other modules. The `xor` function in this module is based partly on Roberto Ierusalimschy's post in http://lua-users.org/lists/lua-l/2002-09/msg00134.html . The included BIT.bit32 and BIT.bit sublibraries aims to provide 100% compatibility with the Lua 5.2 "bit32" and (LuaJIT) LuaBitOp "bit" library. This compatbility is at the cost of some efficiency since inputted numbers are normalized and more general forms (e.g. multi-argument bitwise operators) are supported. STATUS WARNING: Not all corner cases have been tested and documented. Some attempt was made to make these similar to the Lua 5.2 [2] and LuaJit BitOp [3] libraries, but this is not fully tested and there are currently some differences. Addressing these differences may be improved in the future but it is not yet fully determined how to resolve these differences. The BIT.bit32 library passes the Lua 5.2 test suite (bitwise.lua) http://www.lua.org/tests/5.2/ . The BIT.bit library passes the LuaBitOp test suite (bittest.lua). However, these have not been tested on platforms with Lua compiled with 32-bit integer numbers. API BIT.tobit(x) --> z Similar to function in BitOp. BIT.tohex(x, n) Similar to function in BitOp. BIT.band(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bxor(x, y) --> z Similar to function in Lua 5.2 and BitOp but requires two arguments. BIT.bnot(x) --> z Similar to function in Lua 5.2 and BitOp. BIT.lshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.rshift(x, disp) --> z Similar to function in Lua 5.2 (warning: BitOp uses unsigned lower 5 bits of shift), BIT.extract(x, field [, width]) --> z Similar to function in Lua 5.2. BIT.replace(x, v, field, width) --> z Similar to function in Lua 5.2. BIT.bswap(x) --> z Similar to function in Lua 5.2. BIT.rrotate(x, disp) --> z BIT.ror(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.lrotate(x, disp) --> z BIT.rol(x, disp) --> z Similar to function in Lua 5.2 and BitOp. BIT.arshift Similar to function in Lua 5.2 and BitOp. BIT.btest Similar to function in Lua 5.2 with requires two arguments. BIT.bit32 This table contains functions that aim to provide 100% compatibility with the Lua 5.2 "bit32" library. bit32.arshift (x, disp) --> z bit32.band (...) --> z bit32.bnot (x) --> z bit32.bor (...) --> z bit32.btest (...) --> true | false bit32.bxor (...) --> z bit32.extract (x, field [, width]) --> z bit32.replace (x, v, field [, width]) --> z bit32.lrotate (x, disp) --> z bit32.lshift (x, disp) --> z bit32.rrotate (x, disp) --> z bit32.rshift (x, disp) --> z BIT.bit This table contains functions that aim to provide 100% compatibility with the LuaBitOp "bit" library (from LuaJIT). bit.tobit(x) --> y bit.tohex(x [,n]) --> y bit.bnot(x) --> y bit.bor(x1 [,x2...]) --> y bit.band(x1 [,x2...]) --> y bit.bxor(x1 [,x2...]) --> y bit.lshift(x, n) --> y bit.rshift(x, n) --> y bit.arshift(x, n) --> y bit.rol(x, n) --> y bit.ror(x, n) --> y bit.bswap(x) --> y DEPENDENCIES None (other than Lua 5.1 or 5.2). DOWNLOAD/INSTALLATION If using LuaRocks: luarocks install lua-bit-numberlua Otherwise, download <https://github.com/davidm/lua-bit-numberlua/zipball/master>. Alternately, if using git: git clone git://github.com/davidm/lua-bit-numberlua.git cd lua-bit-numberlua Optionally unpack: ./util.mk or unpack and install in LuaRocks: ./util.mk install REFERENCES [1] http://lua-users.org/wiki/FloatingPoint [2] http://www.lua.org/manual/5.2/ [3] http://bitop.luajit.org/ LICENSE (c) 2008-2011 David Manura. Licensed under the same terms as Lua (MIT). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. (end license) --]] local M = {_TYPE='module', _NAME='bit.numberlua', _VERSION='0.3.1.20120131'} local floor = math.floor local MOD = 2^32 local MODM = MOD-1 local function memoize(f) local mt = {} local t = setmetatable({}, mt) function mt:__index(k) local v = f(k); t[k] = v return v end return t end local function make_bitop_uncached(t, m) local function bitop(a, b) local res,p = 0,1 while a ~= 0 and b ~= 0 do local am, bm = a%m, b%m res = res + t[am][bm]*p a = (a - am) / m b = (b - bm) / m p = p*m end res = res + (a+b)*p return res end return bitop end local function make_bitop(t) local op1 = make_bitop_uncached(t,2^1) local op2 = memoize(function(a) return memoize(function(b) return op1(a, b) end) end) return make_bitop_uncached(op2, 2^(t.n or 1)) end -- ok? probably not if running on a 32-bit int Lua number type platform function M.tobit(x) return x % 2^32 end M.bxor = make_bitop {[0]={[0]=0,[1]=1},[1]={[0]=1,[1]=0}, n=4} local bxor = M.bxor function M.bnot(a) return MODM - a end local bnot = M.bnot function M.band(a,b) return ((a+b) - bxor(a,b))/2 end local band = M.band function M.bor(a,b) return MODM - band(MODM - a, MODM - b) end local bor = M.bor local lshift, rshift -- forward declare function M.rshift(a,disp) -- Lua5.2 insipred if disp < 0 then return lshift(a,-disp) end return floor(a % 2^32 / 2^disp) end rshift = M.rshift function M.lshift(a,disp) -- Lua5.2 inspired if disp < 0 then return rshift(a,-disp) end return (a * 2^disp) % 2^32 end lshift = M.lshift function M.tohex(x, n) -- BitOp style n = n or 8 local up if n <= 0 then if n == 0 then return '' end up = true n = - n end x = band(x, 16^n-1) return ('%0'..n..(up and 'X' or 'x')):format(x) end local tohex = M.tohex function M.extract(n, field, width) -- Lua5.2 inspired width = width or 1 return band(rshift(n, field), 2^width-1) end local extract = M.extract function M.replace(n, v, field, width) -- Lua5.2 inspired width = width or 1 local mask1 = 2^width-1 v = band(v, mask1) -- required by spec? local mask = bnot(lshift(mask1, field)) return band(n, mask) + lshift(v, field) end local replace = M.replace function M.bswap(x) -- BitOp style local a = band(x, 0xff); x = rshift(x, 8) local b = band(x, 0xff); x = rshift(x, 8) local c = band(x, 0xff); x = rshift(x, 8) local d = band(x, 0xff) return lshift(lshift(lshift(a, 8) + b, 8) + c, 8) + d end local bswap = M.bswap function M.rrotate(x, disp) -- Lua5.2 inspired disp = disp % 32 local low = band(x, 2^disp-1) return rshift(x, disp) + lshift(low, 32-disp) end local rrotate = M.rrotate function M.lrotate(x, disp) -- Lua5.2 inspired return rrotate(x, -disp) end local lrotate = M.lrotate M.rol = M.lrotate -- LuaOp inspired M.ror = M.rrotate -- LuaOp insipred function M.arshift(x, disp) -- Lua5.2 inspired local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end local arshift = M.arshift function M.btest(x, y) -- Lua5.2 inspired return band(x, y) ~= 0 end -- -- Start Lua 5.2 "bit32" compat section. -- M.bit32 = {} -- Lua 5.2 'bit32' compatibility local function bit32_bnot(x) return (-1 - x) % MOD end M.bit32.bnot = bit32_bnot local function bit32_bxor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = bxor(a, b) if c then z = bit32_bxor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bxor = bit32_bxor local function bit32_band(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = ((a+b) - bxor(a,b)) / 2 if c then z = bit32_band(z, c, ...) end return z elseif a then return a % MOD else return MODM end end M.bit32.band = bit32_band local function bit32_bor(a, b, c, ...) local z if b then a = a % MOD b = b % MOD z = MODM - band(MODM - a, MODM - b) if c then z = bit32_bor(z, c, ...) end return z elseif a then return a % MOD else return 0 end end M.bit32.bor = bit32_bor function M.bit32.btest(...) return bit32_band(...) ~= 0 end function M.bit32.lrotate(x, disp) return lrotate(x % MOD, disp) end function M.bit32.rrotate(x, disp) return rrotate(x % MOD, disp) end function M.bit32.lshift(x,disp) if disp > 31 or disp < -31 then return 0 end return lshift(x % MOD, disp) end function M.bit32.rshift(x,disp) if disp > 31 or disp < -31 then return 0 end return rshift(x % MOD, disp) end function M.bit32.arshift(x,disp) x = x % MOD if disp >= 0 then if disp > 31 then return (x >= 0x80000000) and MODM or 0 else local z = rshift(x, disp) if x >= 0x80000000 then z = z + lshift(2^disp-1, 32-disp) end return z end else return lshift(x, -disp) end end function M.bit32.extract(x, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD return extract(x, field, ...) end function M.bit32.replace(x, v, field, ...) local width = ... or 1 if field < 0 or field > 31 or width < 0 or field+width > 32 then error 'out of range' end x = x % MOD v = v % MOD return replace(x, v, field, ...) end -- -- Start LuaBitOp "bit" compat section. -- M.bit = {} -- LuaBitOp "bit" compatibility function M.bit.tobit(x) x = x % MOD if x >= 0x80000000 then x = x - MOD end return x end local bit_tobit = M.bit.tobit function M.bit.tohex(x, ...) return tohex(x % MOD, ...) end function M.bit.bnot(x) return bit_tobit(bnot(x % MOD)) end local function bit_bor(a, b, c, ...) if c then return bit_bor(bit_bor(a, b), c, ...) elseif b then return bit_tobit(bor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bor = bit_bor local function bit_band(a, b, c, ...) if c then return bit_band(bit_band(a, b), c, ...) elseif b then return bit_tobit(band(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.band = bit_band local function bit_bxor(a, b, c, ...) if c then return bit_bxor(bit_bxor(a, b), c, ...) elseif b then return bit_tobit(bxor(a % MOD, b % MOD)) else return bit_tobit(a) end end M.bit.bxor = bit_bxor function M.bit.lshift(x, n) return bit_tobit(lshift(x % MOD, n % 32)) end function M.bit.rshift(x, n) return bit_tobit(rshift(x % MOD, n % 32)) end function M.bit.arshift(x, n) return bit_tobit(arshift(x % MOD, n % 32)) end function M.bit.rol(x, n) return bit_tobit(lrotate(x % MOD, n % 32)) end function M.bit.ror(x, n) return bit_tobit(rrotate(x % MOD, n % 32)) end function M.bit.bswap(x) return bit_tobit(bswap(x % MOD)) end return M
mit
kobreu/compiler
testinput/lua5.1-tests/events.lua
10
8646
print('testing metatables') X = 20; B = 30 setfenv(1, setmetatable({}, {__index=_G})) collectgarbage() X = X+10 assert(X == 30 and _G.X == 20) B = false assert(B == false) B = nil assert(B == 30) assert(getmetatable{} == nil) assert(getmetatable(4) == nil) assert(getmetatable(nil) == nil) a={}; setmetatable(a, {__metatable = "xuxu", __tostring=function(x) return x.name end}) assert(getmetatable(a) == "xuxu") assert(tostring(a) == nil) -- cannot change a protected metatable assert(pcall(setmetatable, a, {}) == false) a.name = "gororoba" assert(tostring(a) == "gororoba") local a, t = {10,20,30; x="10", y="20"}, {} assert(setmetatable(a,t) == a) assert(getmetatable(a) == t) assert(setmetatable(a,nil) == a) assert(getmetatable(a) == nil) assert(setmetatable(a,t) == a) function f (t, i, e) assert(not e) local p = rawget(t, "parent") return (p and p[i]+3), "dummy return" end t.__index = f a.parent = {z=25, x=12, [4] = 24} assert(a[1] == 10 and a.z == 28 and a[4] == 27 and a.x == "10") collectgarbage() a = setmetatable({}, t) function f(t, i, v) rawset(t, i, v-3) end t.__newindex = f a[1] = 30; a.x = "101"; a[5] = 200 assert(a[1] == 27 and a.x == 98 and a[5] == 197) local c = {} a = setmetatable({}, t) t.__newindex = c a[1] = 10; a[2] = 20; a[3] = 90 assert(c[1] == 10 and c[2] == 20 and c[3] == 90) do local a; a = setmetatable({}, {__index = setmetatable({}, {__index = setmetatable({}, {__index = function (_,n) return a[n-3]+4, "lixo" end})})}) a[0] = 20 for i=0,10 do assert(a[i*3] == 20 + i*4) end end do -- newindex local foi local a = {} for i=1,10 do a[i] = 0; a['a'..i] = 0; end setmetatable(a, {__newindex = function (t,k,v) foi=true; rawset(t,k,v) end}) foi = false; a[1]=0; assert(not foi) foi = false; a['a1']=0; assert(not foi) foi = false; a['a11']=0; assert(foi) foi = false; a[11]=0; assert(foi) foi = false; a[1]=nil; assert(not foi) foi = false; a[1]=nil; assert(foi) end function f (t, ...) return t, {...} end t.__call = f do local x,y = a(unpack{'a', 1}) assert(x==a and y[1]=='a' and y[2]==1 and y[3]==nil) x,y = a() assert(x==a and y[1]==nil) end local b = setmetatable({}, t) setmetatable(b,t) function f(op) return function (...) cap = {[0] = op, ...} ; return (...) end end t.__add = f("add") t.__sub = f("sub") t.__mul = f("mul") t.__div = f("div") t.__mod = f("mod") t.__unm = f("unm") t.__pow = f("pow") assert(b+5 == b) assert(cap[0] == "add" and cap[1] == b and cap[2] == 5 and cap[3]==nil) assert(b+'5' == b) assert(cap[0] == "add" and cap[1] == b and cap[2] == '5' and cap[3]==nil) assert(5+b == 5) assert(cap[0] == "add" and cap[1] == 5 and cap[2] == b and cap[3]==nil) assert('5'+b == '5') assert(cap[0] == "add" and cap[1] == '5' and cap[2] == b and cap[3]==nil) b=b-3; assert(getmetatable(b) == t) assert(5-a == 5) assert(cap[0] == "sub" and cap[1] == 5 and cap[2] == a and cap[3]==nil) assert('5'-a == '5') assert(cap[0] == "sub" and cap[1] == '5' and cap[2] == a and cap[3]==nil) assert(a*a == a) assert(cap[0] == "mul" and cap[1] == a and cap[2] == a and cap[3]==nil) assert(a/0 == a) assert(cap[0] == "div" and cap[1] == a and cap[2] == 0 and cap[3]==nil) assert(a%2 == a) assert(cap[0] == "mod" and cap[1] == a and cap[2] == 2 and cap[3]==nil) assert(-a == a) assert(cap[0] == "unm" and cap[1] == a) assert(a^4 == a) assert(cap[0] == "pow" and cap[1] == a and cap[2] == 4 and cap[3]==nil) assert(a^'4' == a) assert(cap[0] == "pow" and cap[1] == a and cap[2] == '4' and cap[3]==nil) assert(4^a == 4) assert(cap[0] == "pow" and cap[1] == 4 and cap[2] == a and cap[3]==nil) assert('4'^a == '4') assert(cap[0] == "pow" and cap[1] == '4' and cap[2] == a and cap[3]==nil) t = {} t.__lt = function (a,b,c) collectgarbage() assert(c == nil) if type(a) == 'table' then a = a.x end if type(b) == 'table' then b = b.x end return a<b, "dummy" end function Op(x) return setmetatable({x=x}, t) end local function test () assert(not(Op(1)<Op(1)) and (Op(1)<Op(2)) and not(Op(2)<Op(1))) assert(not(Op('a')<Op('a')) and (Op('a')<Op('b')) and not(Op('b')<Op('a'))) assert((Op(1)<=Op(1)) and (Op(1)<=Op(2)) and not(Op(2)<=Op(1))) assert((Op('a')<=Op('a')) and (Op('a')<=Op('b')) and not(Op('b')<=Op('a'))) assert(not(Op(1)>Op(1)) and not(Op(1)>Op(2)) and (Op(2)>Op(1))) assert(not(Op('a')>Op('a')) and not(Op('a')>Op('b')) and (Op('b')>Op('a'))) assert((Op(1)>=Op(1)) and not(Op(1)>=Op(2)) and (Op(2)>=Op(1))) assert((Op('a')>=Op('a')) and not(Op('a')>=Op('b')) and (Op('b')>=Op('a'))) end test() t.__le = function (a,b,c) assert(c == nil) if type(a) == 'table' then a = a.x end if type(b) == 'table' then b = b.x end return a<=b, "dummy" end test() -- retest comparisons, now using both `lt' and `le' -- test `partial order' local function Set(x) local y = {} for _,k in pairs(x) do y[k] = 1 end return setmetatable(y, t) end t.__lt = function (a,b) for k in pairs(a) do if not b[k] then return false end b[k] = nil end return next(b) ~= nil end t.__le = nil assert(Set{1,2,3} < Set{1,2,3,4}) assert(not(Set{1,2,3,4} < Set{1,2,3,4})) assert((Set{1,2,3,4} <= Set{1,2,3,4})) assert((Set{1,2,3,4} >= Set{1,2,3,4})) assert((Set{1,3} <= Set{3,5})) -- wrong!! model needs a `le' method ;-) t.__le = function (a,b) for k in pairs(a) do if not b[k] then return false end end return true end assert(not (Set{1,3} <= Set{3,5})) -- now its OK! assert(not(Set{1,3} <= Set{3,5})) assert(not(Set{1,3} >= Set{3,5})) t.__eq = function (a,b) for k in pairs(a) do if not b[k] then return false end b[k] = nil end return next(b) == nil end local s = Set{1,3,5} assert(s == Set{3,5,1}) assert(not rawequal(s, Set{3,5,1})) assert(rawequal(s, s)) assert(Set{1,3,5,1} == Set{3,5,1}) assert(Set{1,3,5} ~= Set{3,5,1,6}) t[Set{1,3,5}] = 1 assert(t[Set{1,3,5}] == nil) -- `__eq' is not valid for table accesses t.__concat = function (a,b,c) assert(c == nil) if type(a) == 'table' then a = a.val end if type(b) == 'table' then b = b.val end if A then return a..b else return setmetatable({val=a..b}, t) end end c = {val="c"}; setmetatable(c, t) d = {val="d"}; setmetatable(d, t) A = true assert(c..d == 'cd') assert(0 .."a".."b"..c..d.."e".."f"..(5+3).."g" == "0abcdef8g") A = false x = c..d assert(getmetatable(x) == t and x.val == 'cd') x = 0 .."a".."b"..c..d.."e".."f".."g" assert(x.val == "0abcdefg") -- test comparison compatibilities local t1, t2, c, d t1 = {}; c = {}; setmetatable(c, t1) d = {} t1.__eq = function () return true end t1.__lt = function () return true end assert(c ~= d and not pcall(function () return c < d end)) setmetatable(d, t1) assert(c == d and c < d and not(d <= c)) t2 = {} t2.__eq = t1.__eq t2.__lt = t1.__lt setmetatable(d, t2) assert(c == d and c < d and not(d <= c)) -- test for several levels of calls local i local tt = { __call = function (t, ...) i = i+1 if t.f then return t.f(...) else return {...} end end } local a = setmetatable({}, tt) local b = setmetatable({f=a}, tt) local c = setmetatable({f=b}, tt) i = 0 x = c(3,4,5) assert(i == 3 and x[1] == 3 and x[3] == 5) assert(_G.X == 20) assert(_G == getfenv(0)) print'+' local _g = _G setfenv(1, setmetatable({}, {__index=function (_,k) return _g[k] end})) -- testing proxies assert(getmetatable(newproxy()) == nil) assert(getmetatable(newproxy(false)) == nil) local u = newproxy(true) getmetatable(u).__newindex = function (u,k,v) getmetatable(u)[k] = v end getmetatable(u).__index = function (u,k) return getmetatable(u)[k] end for i=1,10 do u[i] = i end for i=1,10 do assert(u[i] == i) end local k = newproxy(u) assert(getmetatable(k) == getmetatable(u)) a = {} rawset(a, "x", 1, 2, 3) assert(a.x == 1 and rawget(a, "x", 3) == 1) print '+' -- testing metatables for basic types mt = {} debug.setmetatable(10, mt) assert(getmetatable(-2) == mt) mt.__index = function (a,b) return a+b end assert((10)[3] == 13) assert((10)["3"] == 13) debug.setmetatable(23, nil) assert(getmetatable(-2) == nil) debug.setmetatable(true, mt) assert(getmetatable(false) == mt) mt.__index = function (a,b) return a or b end assert((true)[false] == true) assert((false)[false] == false) debug.setmetatable(false, nil) assert(getmetatable(true) == nil) debug.setmetatable(nil, mt) assert(getmetatable(nil) == mt) mt.__add = function (a,b) return (a or 0) + (b or 0) end assert(10 + nil == 10) assert(nil + 23 == 23) assert(nil + nil == 0) debug.setmetatable(nil, nil) assert(getmetatable(nil) == nil) debug.setmetatable(nil, {}) print 'OK' return 12
gpl-3.0
SurenaTeam/TeleSurena
plugins/msg_checks.lua
6
11264
--Begin msg_checks.lua --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = '🔐' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = '🔐' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = '🔐' end if settings.lock_link then lock_link = settings.lock_link else lock_link = '🔐' end if settings.lock_member then lock_member = settings.lock_member else lock_member = '🔐' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = '🔐' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = '🔐' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = '🔐' end if settings.strict then strict = settings.strict else strict = '🔐' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "🔒" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "🔒" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "🔒" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_caption and lock_link == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "🔒" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "🔒" then delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == '🔒' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] joined and kicked (#spam name)") kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "🔒" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if lock_member == '🔒' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] joined and kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == '🔒' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: Service Msg deleted (#spam name)") delete_msg(msg.id, ok_cb, false) if strict == "🔒" or to_chat then savelog(msg.to.id, name_log.." ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#spam name) ") delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "🔒" then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#RTL char in name)") kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == '🔒' then savelog(msg.to.id, name_log.." User ["..msg.from.id.."] added ["..user_id.."]: added user kicked (#lockmember)") kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end end -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function return { patterns = {}, pre_process = pre_process } --End msg_checks.lua --By @Rondoozle
agpl-3.0
forward619/luci
applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/interface.lua
29
2536
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.statistics.rrdtool.definitions.interface", package.seeall) function rrdargs( graph, plugin, plugin_instance ) -- -- traffic diagram -- local traffic = { -- draw this diagram for each plugin instance per_instance = true, title = "%H: Transfer on %pi", vlabel = "Bytes/s", -- diagram data description data = { -- defined sources for data types, if ommitted assume a single DS named "value" (optional) sources = { if_octets = { "tx", "rx" } }, -- special options for single data lines options = { if_octets__tx = { total = true, -- report total amount of bytes color = "00ff00", -- tx is green title = "Bytes (TX)" }, if_octets__rx = { flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- rx is blue title = "Bytes (RX)" } } } } -- -- packet diagram -- local packets = { -- draw this diagram for each plugin instance per_instance = true, title = "%H: Packets on %pi", vlabel = "Packets/s", -- diagram data description data = { -- data type order types = { "if_packets", "if_errors" }, -- defined sources for data types sources = { if_packets = { "tx", "rx" }, if_errors = { "tx", "rx" } }, -- special options for single data lines options = { -- processed packets (tx DS) if_packets__tx = { overlay = true, -- don't summarize total = true, -- report total amount of bytes color = "00ff00", -- processed tx is green title = "Processed (tx)" }, -- processed packets (rx DS) if_packets__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of bytes color = "0000ff", -- processed rx is blue title = "Processed (rx)" }, -- packet errors (tx DS) if_errors__tx = { overlay = true, -- don't summarize total = true, -- report total amount of packets color = "ff5500", -- tx errors are orange title = "Errors (tx)" }, -- packet errors (rx DS) if_errors__rx = { overlay = true, -- don't summarize flip = true, -- flip rx line total = true, -- report total amount of packets color = "ff0000", -- rx errors are red title = "Errors (rx)" } } } } return { traffic, packets } end
apache-2.0
tonylauCN/tutorials
lua/debugger/lualibs/dist/constraints.lua
6
9241
-- Note: the code of this module is borrowed from the original LuaDist project --- LuaDist version constraints functions -- Peter Drahoš, LuaDist Project, 2010 -- Original Code borrowed from LuaRocks Project --- Version constraints handling functions. -- Dependencies are represented in LuaDist through strings with -- a dist name followed by a comma-separated list of constraints. -- Each constraint consists of an operator and a version number. -- In this string format, version numbers are represented as -- naturally as possible, like they are used by upstream projects -- (e.g. "2.0beta3"). Internally, LuaDist converts them to a purely -- numeric representation, allowing comparison following some -- "common sense" heuristics. The precise specification of the -- comparison criteria is the source code of this module, but the -- test/test_deps.lua file included with LuaDist provides some -- insights on what these criteria are. module ("dist.constraints", package.seeall) local operators = { ["=="] = "==", ["~="] = "~=", [">"] = ">", ["<"] = "<", [">="] = ">=", ["<="] = "<=", ["~>"] = "~>", -- plus some convenience translations [""] = "==", ["-"] = "==", ["="] = "==", ["!="] = "~=" } local deltas = { scm = -100, rc = -1000, pre = -10000, beta = -100000, alpha = -1000000, work = -10000000, } local version_mt = { --- Equality comparison for versions. -- All version numbers must be equal. -- If both versions have revision numbers, they must be equal; -- otherwise the revision number is ignored. -- @param v1 table: version table to compare. -- @param v2 table: version table to compare. -- @return boolean: true if they are considered equivalent. __eq = function(v1, v2) if #v1 ~= #v2 then return false end for i = 1, #v1 do if v1[i] ~= v2[i] then return false end end if v1.revision and v2.revision then return (v1.revision == v2.revision) end return true end, --- Size comparison for versions. -- All version numbers are compared. -- If both versions have revision numbers, they are compared; -- otherwise the revision number is ignored. -- @param v1 table: version table to compare. -- @param v2 table: version table to compare. -- @return boolean: true if v1 is considered lower than v2. __lt = function(v1, v2) for i = 1, math.max(#v1, #v2) do local v1i, v2i = v1[i] or 0, v2[i] or 0 if v1i ~= v2i then return (v1i < v2i) end end if v1.revision and v2.revision then return (v1.revision < v2.revision) end return false end } local version_cache = {} setmetatable(version_cache, { __mode = "kv" }) --- Parse a version string, converting to table format. -- A version table contains all components of the version string -- converted to numeric format, stored in the array part of the table. -- If the version contains a revision, it is stored numerically -- in the 'revision' field. The original string representation of -- the string is preserved in the 'string' field. -- Returned version tables use a metatable -- allowing later comparison through relational operators. -- @param vstring string: A version number in string format. -- @return table or nil: A version table or nil -- if the input string contains invalid characters. function parseVersion(vstring) if not vstring then return nil end assert(type(vstring) == "string") local cached = version_cache[vstring] if cached then return cached end local version = {} local i = 1 local function add_token(number) version[i] = version[i] and version[i] + number/100000 or number i = i + 1 end -- trim leading and trailing spaces vstring = vstring:match("^%s*(.*)%s*$") version.string = vstring -- store revision separately if any local main, revision = vstring:match("(.*)%-(%d+)$") if revision then vstring = main version.revision = tonumber(revision) end while #vstring > 0 do -- extract a number local token, rest = vstring:match("^(%d+)[%.%-%_]*(.*)") if token then add_token(tonumber(token)) else -- extract a word token, rest = vstring:match("^(%a+)[%.%-%_]*(.*)") if not token then return nil end local last = #version version[i] = deltas[token] or (token:byte() / 1000) end vstring = rest end setmetatable(version, version_mt) version_cache[vstring] = version return version end --- Utility function to compare version numbers given as strings. -- @param a string: one version. -- @param b string: another version. -- @return boolean: True if a > b. function compareVersions(a, b) return parseVersion(a) > parseVersion(b) end --- Consumes a constraint from a string, converting it to table format. -- For example, a string ">= 1.0, > 2.0" is converted to a table in the -- format {op = ">=", version={1,0}} and the rest, "> 2.0", is returned -- back to the caller. -- @param input string: A list of constraints in string format. -- @return (table, string) or nil: A table representing the same -- constraints and the string with the unused input, or nil if the -- input string is invalid. local function parseConstraint(input) assert(type(input) == "string") local op, version, rest = input:match("^([<>=~!]*)%s*([%w%.%_%-]+)[%s,]*(.*)") op = operators[op] version = parseVersion(version) if not op or not version then return nil end return { op = op, version = version }, rest end --- Convert a list of constraints from string to table format. -- For example, a string ">= 1.0, < 2.0" is converted to a table in the format -- {{op = ">=", version={1,0}}, {op = "<", version={2,0}}}. -- Version tables use a metatable allowing later comparison through -- relational operators. -- @param input string: A list of constraints in string format. -- @return table or nil: A table representing the same constraints, -- or nil if the input string is invalid. function parseConstraints(input) assert(type(input) == "string") local constraints, constraint = {}, nil while #input > 0 do constraint, input = parseConstraint(input) if constraint then table.insert(constraints, constraint) else return nil end end return constraints end --- A more lenient check for equivalence between versions. -- This returns true if the requested components of a version -- match and ignore the ones that were not given. For example, -- when requesting "2", then "2", "2.1", "2.3.5-9"... all match. -- When requesting "2.1", then "2.1", "2.1.3" match, but "2.2" -- doesn't. -- @param version string or table: Version to be tested; may be -- in string format or already parsed into a table. -- @param requested string or table: Version requested; may be -- in string format or already parsed into a table. -- @return boolean: True if the tested version matches the requested -- version, false otherwise. local function partialMatch(version, requested) assert(type(version) == "string" or type(version) == "table") assert(type(requested) == "string" or type(version) == "table") if type(version) ~= "table" then version = parseVersion(version) end if type(requested) ~= "table" then requested = parseVersion(requested) end if not version or not requested then return false end for i = 1, #requested do if requested[i] ~= version[i] then return false end end if requested.revision then return requested.revision == version.revision end return true end --- Check if a version satisfies a set of constraints. -- @param version table: A version in table format -- @param constraints table: An array of constraints in table format. -- @return boolean: True if version satisfies all constraints, -- false otherwise. function matchConstraints(version, constraints) assert(type(version) == "table") assert(type(constraints) == "table") local ok = true setmetatable(version, version_mt) for _, constr in pairs(constraints) do local constr_version = constr.version setmetatable(constr.version, version_mt) if constr.op == "==" then ok = version == constr_version elseif constr.op == "~=" then ok = version ~= constr_version elseif constr.op == ">" then ok = version > constr_version elseif constr.op == "<" then ok = version < constr_version elseif constr.op == ">=" then ok = version >= constr_version elseif constr.op == "<=" then ok = version <= constr_version elseif constr.op == "~>" then ok = partialMatch(version, constr_version) end if not ok then break end end return ok end --- Check if a version string is satisfied by a constraint string. -- @param version string: A version in string format -- @param constraints string: Constraints in string format. -- @return boolean: True if version satisfies all constraints, -- false otherwise. function constraint_satisfied(version, constraints) local const = parseConstraints(constraints) local ver = parseVersion(version) if const and ver then return matchConstraints(ver, const) end return nil, "Error parsing versions." end
apache-2.0
kaen/Zero-K
LuaRules/Gadgets/unit_script.lua
4
24595
-- Author: Tobi Vollebregt --[[ Please, think twice before editing this file. Compared to most gadgets, there are some complex things going on. A good understanding of Lua's coroutines is required to make nontrivial modifications to this file. In other words, HERE BE DRAGONS =) Known issues: - {Query,AimFrom,Aim,Fire}{Primary,Secondary,Tertiary} are not handled. (use {Query,AimFrom,Aim,Fire}{Weapon1,Weapon2,Weapon3} instead!) - Errors in callins which aren't wrapped in a thread do not show a traceback. - Which callins are wrapped in a thread and which aren't is a bit arbitrary. - MoveFinished, TurnFinished and Destroy are overwritten by the framework. - There is no way to reload the script of a single unit. (use /luarules reload) - Error checking is lacking. (In particular for incorrect unitIDs.) To do: - Test real world performance (compared to COB) ]]-- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "LUS", desc = "Manages Lua unit scripts", author = "Tobi Vollebregt", date = "2 September 2009", license = "GPL v2", layer = 0, enabled = true -- loaded by default? } end if (not gadgetHandler:IsSyncedCode()) then return false end local reverseCompat = (not Spring.Utilities.IsCurrentVersionNewerThan(94, 0)) and 1 or 0 -- This lists all callins which may be wrapped in a coroutine (thread). -- The ones which should not be thread-wrapped are commented out. -- Create, Killed, AimWeapon and AimShield callins are always wrapped. local thread_wrap = { --"StartMoving", --"StopMoving", --"Activate", --"Deactivate", --"WindChanged", --"ExtractionRateChanged", "RockUnit", --"HitByWeapon", --"MoveRate", --"setSFXoccupy", --"QueryLandingPad", "Falling", "Landed", "BeginTransport", --"QueryTransport", "TransportPickup", "StartUnload", "EndTransport", "TransportDrop", "StartBuilding", "StopBuilding", --"QueryNanoPiece", --"QueryBuildInfo", --"QueryWeapon", --"AimFromWeapon", "FireWeapon", --"EndBurst", --"Shot", --"BlockShot", --"TargetWeight", } local weapon_funcs = { "QueryWeapon", "AimFromWeapon", "AimWeapon", "AimShield", "FireWeapon", "Shot", "EndBurst", "BlockShot", "TargetWeight", } local default_return_values = { QueryWeapon = -1, AimFromWeapon = -1, AimWeapon = false, AimShield = false, BlockShot = false, TargetWeight = 1, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Localize often used methods. local pairs = pairs local table_remove = table.remove local co_create = coroutine.create local co_resume = coroutine.resume local co_yield = coroutine.yield local co_running = coroutine.running local bit_and = math.bit_and local floor = math.floor local sp_GetGameFrame = Spring.GetGameFrame local sp_GetUnitWeaponState = Spring.GetUnitWeaponState local sp_SetUnitWeaponState = Spring.SetUnitWeaponState local sp_SetUnitShieldState = Spring.SetUnitShieldState -- Keep local reference to engine's CallAsUnit/WaitForMove/WaitForTurn, -- as we overwrite them with (safer) framework version later on. local sp_CallAsUnit = Spring.UnitScript.CallAsUnit local sp_WaitForMove = Spring.UnitScript.WaitForMove local sp_WaitForTurn = Spring.UnitScript.WaitForTurn local sp_SetPieceVisibility = Spring.UnitScript.SetPieceVisibility local sp_SetDeathScriptFinished = Spring.UnitScript.SetDeathScriptFinished local LUA_WEAPON_MIN_INDEX = 1 - reverseCompat local LUA_WEAPON_MAX_INDEX = LUA_WEAPON_MIN_INDEX + 31 local UNITSCRIPT_DIR = (UNITSCRIPT_DIR or "scripts/"):lower() local VFSMODE = VFS.ZIP_ONLY if (Spring.IsDevLuaEnabled()) then VFSMODE = VFS.RAW_ONLY end -- needed here too, and gadget handler doesn't expose it VFS.Include('LuaGadgets/system.lua', nil, VFSMODE) VFS.Include('gamedata/VFSUtils.lua', nil, VFSMODE) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --[[ Data structure to administrate the threads of each managed unit. We store a set of all threads for each unit, and in two separate tables the threads which are waiting for a turn or move animation to finish. The 'thread' stored in waitingForMove/waitingForTurn/sleepers is the table wrapping the actual coroutine object. This way the signal_mask etc. is available too. The threads table is a weak table. This saves us from having to manually clean up dead threads: any thread which is not sleeping or waiting is in none of (sleepers,waitingForMove,waitingForTurn) => it is only in the threads table => garbage collector will harvest it because the table is weak. Beware the threads are indexed by thread (coroutine), so careless iteration of threads WILL cause desync! Format: { [unitID] = { env = {}, -- the unit's environment table waitingForMove = { [piece*3+axis] = thread, ... }, waitingForTurn = { [piece*3+axis] = thread, ... }, threads = { [thread] = { thread = thread, -- the coroutine object signal_mask = object, -- see Signal/SetSignalMask unitID = number, -- 'owner' of the thread onerror = function, -- called after thread died due to an error }, ... }, }, } --]] local units = {} -- this keeps track of the unit that is active (ie. -- running a script) at the time a callin triggers -- -- the _current_ active unit (ID) is always at the -- top of the stack (index #activeUnitStack) local activeUnitStack = {} local function PushActiveUnitID(unitID) activeUnitStack[#activeUnitStack + 1] = unitID end local function PopActiveUnitID() activeUnitStack[#activeUnitStack] = nil end local function GetActiveUnitID() return activeUnitStack[#activeUnitStack] end local function GetActiveUnit() return units[GetActiveUnitID()] end --[[ This is the bed, it stores all the sleeping threads, indexed by the frame in which they need to be woken up. Format: { [framenum] = { [1] = thread1, [2] = thread2, ... }, } (inner tables are in order the calls to Sleep were made) --]] local sleepers = {} local section = 'unit_script.lua' -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Helper for Destroy and Signal. -- NOTE: -- Must not change the relative order of all other elements! -- Also must not break the #-operator, so removal must leave -- no holes --> uses table.remove() instead of tab[i] = nil. local function RemoveTableElement(tab, item) local n = #tab for i = 1,n do if (tab[i] == item) then table_remove(tab, i) return end end end -- This is put in every script to clean up if the script gets destroyed. local function Destroy() local activeUnit = GetActiveUnit() if (activeUnit ~= nil) then for _,thread in pairs(activeUnit.threads) do if thread.container then RemoveTableElement(thread.container, thread) end end units[activeUnit.unitID] = nil end end -- Pcalls thread.onerror, if present. local function RunOnError(thread) local fun = thread.onerror if fun then local good, err = pcall(fun, err) if (not good) then Spring.Log(section, LOG.ERROR, "error in error handler: " .. err) end end end -- Helper for AnimFinished, StartThread and gadget:GameFrame. -- Resumes a sleeping or waiting thread; displays any errors. local function WakeUp(thread, ...) thread.container = nil local co = thread.thread local good, err = co_resume(co, ...) if (not good) then Spring.Log(section, LOG.ERROR, err) Spring.Log(section, LOG.ERROR, debug.traceback(co)) RunOnError(thread) end end -- Helper for MoveFinished and TurnFinished local function AnimFinished(waitingForAnim, piece, axis) local index = piece * 3 + axis local wthreads = waitingForAnim[index] local wthread = nil if wthreads then waitingForAnim[index] = {} while (#wthreads > 0) do wthread = wthreads[#wthreads] wthreads[#wthreads] = nil WakeUp(wthread) end end end -- MoveFinished and TurnFinished are put in every script by the framework. -- They resume the threads which were waiting for the move/turn. local function MoveFinished(piece, axis) local activeUnit = GetActiveUnit() local activeAnim = activeUnit.waitingForMove return AnimFinished(activeAnim, piece, axis) end local function TurnFinished(piece, axis) local activeUnit = GetActiveUnit() local activeAnim = activeUnit.waitingForTurn return AnimFinished(activeAnim, piece, axis) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- overwrites engine's CallAsUnit function Spring.UnitScript.CallAsUnit(unitID, fun, ...) PushActiveUnitID(unitID) local ret = {sp_CallAsUnit(unitID, fun, ...)} PopActiveUnitID() return unpack(ret) end local function CallAsUnitNoReturn(unitID, fun, ...) PushActiveUnitID(unitID) sp_CallAsUnit(unitID, fun, ...) PopActiveUnitID() end -- Helper for WaitForMove and WaitForTurn -- Unsafe, because it does not check whether the animation to wait for actually exists. local function WaitForAnim(threads, waitingForAnim, piece, axis) local index = piece * 3 + axis local wthreads = waitingForAnim[index] if (not wthreads) then wthreads = {} waitingForAnim[index] = wthreads end local thread = threads[co_running() or error("not in a thread", 2)] wthreads[#wthreads+1] = thread thread.container = wthreads -- yield the running thread: -- it will be resumed once the wait finished (in AnimFinished). co_yield() end -- overwrites engine's WaitForMove function Spring.UnitScript.WaitForMove(piece, axis) if sp_WaitForMove(piece, axis) then local activeUnit = GetActiveUnit() return WaitForAnim(activeUnit.threads, activeUnit.waitingForMove, piece, axis) end end -- overwrites engine's WaitForTurn function Spring.UnitScript.WaitForTurn(piece, axis) if sp_WaitForTurn(piece, axis) then local activeUnit = GetActiveUnit() return WaitForAnim(activeUnit.threads, activeUnit.waitingForTurn, piece, axis) end end function Spring.UnitScript.Sleep(milliseconds) local n = floor(milliseconds / 33) if (n <= 0) then n = 1 end n = n + sp_GetGameFrame() local zzz = sleepers[n] if (not zzz) then zzz = {} sleepers[n] = zzz end local activeUnit = GetActiveUnit() or error("[Sleep] no active unit on stack?", 2) local activeThread = activeUnit.threads[co_running() or error("[Sleep] not in a thread?", 2)] zzz[#zzz+1] = activeThread activeThread.container = zzz -- yield the running thread: -- it will be resumed in frame #n (in gadget:GameFrame). co_yield() end function Spring.UnitScript.StartThread(fun, ...) local activeUnit = GetActiveUnit() local co = co_create(fun) -- signal_mask is inherited from current thread, if any local thd = co_running() and activeUnit.threads[co_running()] local sigmask = thd and thd.signal_mask or 0 local thread = { thread = co, signal_mask = sigmask, unitID = activeUnit.unitID, } -- add the new thread to activeUnit's registry activeUnit.threads[co] = thread -- COB doesn't start thread immediately: it only sets up stack and -- pushes parameters on it for first time the thread is scheduled. -- Here it is easier however to start thread immediately, so we don't need -- to remember the parameters for the first co_resume call somewhere. -- I think in practice the difference in behavior isn't an issue. return WakeUp(thread, ...) end local function SetOnError(fun) local activeUnit = GetActiveUnit() local activeThread = activeUnit.threads[co_running()] if activeThread then activeThread.onerror = fun end end function Spring.UnitScript.SetSignalMask(mask) local activeUnit = GetActiveUnit() local activeThread = activeUnit.threads[co_running() or error("[SetSignalMask] not in a thread", 2)] if (activeThread.signal_mask_set) then local ud = UnitDefs[Spring.GetUnitDefID(activeUnit.unitID)] Spring.Log(gadget:GetInfo().name, LOG.WARNING, "Warning: Spring.UnitScript.SetSignalMask called second time for the same thread (possible lack of StartThread?)") Spring.Log(gadget:GetInfo().name, LOG.WARNING, "UnitDef: " .. ud.name .. " Old mask: " .. activeThread.signal_mask .. " New mask: " .. mask) end activeThread.signal_mask = mask activeThread.signal_mask_set = true end function Spring.UnitScript.Signal(mask) local activeUnit = GetActiveUnit() -- beware, unsynced loop order -- (doesn't matter here as long as all threads get removed) if type(mask) == "number" then for _,thread in pairs(activeUnit.threads) do local signal_mask = thread.signal_mask if (type(signal_mask) == "number" and bit_and(signal_mask, mask) ~= 0 and thread.container) then RemoveTableElement(thread.container, thread) end end else for _,thread in pairs(activeUnit.threads) do if (thread.signal_mask == mask and thread.container) then RemoveTableElement(thread.container, thread) end end end end function Spring.UnitScript.Hide(piece) return sp_SetPieceVisibility(piece, false) end function Spring.UnitScript.Show(piece) return sp_SetPieceVisibility(piece, true) end -- may be useful to other gadgets function Spring.UnitScript.GetScriptEnv(unitID) local unit = units[unitID] if unit then return unit.env end return nil end function Spring.UnitScript.GetLongestReloadTime(unitID) local longest = 0 for i = LUA_WEAPON_MIN_INDEX, LUA_WEAPON_MAX_INDEX do local reloadTime = sp_GetUnitWeaponState(unitID, i, "reloadTime") if (not reloadTime) then break end if (reloadTime > longest) then longest = reloadTime end end return 1000 * longest end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local scriptHeader = VFS.LoadFile("gamedata/unit_script_header.lua", VFSMODE) -- Newlines (and comments) are stripped to not change line numbers in stacktraces. scriptHeader = scriptHeader:gsub("%-%-[^\r\n]*", ""):gsub("[\r\n]", " ") --[[ Dictionary mapping script name (without path or extension) to a Lua chunk which returns a new closure (read; instance) of this unitscript. Format: { [unitID] = chunk, } --]] local scripts = {} -- Creates a new prototype environment for a unit script. -- This environment is used as prototype for the unit script instances. -- (To save on time copying and space for a copy for each and every unit.) local prototypeEnv do local script = {} for k,v in pairs(System) do script[k] = v end --script._G = _G -- the global table. (Update: _G points to unit environment now) script.GG = GG -- the shared table (shared with gadgets!) prototypeEnv = script end local function Basename(filename) return filename:match("[^\\/:]*$") or filename end local function LoadChunk(filename) local text = VFS.LoadFile(filename, VFSMODE) if (text == nil) then Spring.Log(section, LOG.ERROR, "Failed to load: " .. filename) return nil end local chunk, err = loadstring(scriptHeader .. text, filename) if (chunk == nil) then Spring.Log(section, LOG.ERROR, "Failed to load: " .. Basename(filename) .. " (" .. err .. ")") return nil end return chunk end local function LoadScript(scriptName, filename) local chunk = LoadChunk(filename) scripts[scriptName] = chunk return chunk end function gadget:Initialize() Spring.Log(section, LOG.INFO, string.format("Loading gadget: %-18s <%s>", ghInfo.name, ghInfo.basename)) -- This initialization code has following properties: -- * all used scripts are loaded => early syntax error detection -- * unused scripts aren't loaded -- * files can be arbitrarily ordered in subdirs (like defs) -- * exact path doesn't need to be specified -- * exact path can be specified to resolve ambiguous basenames -- * engine default scriptName (with .cob extension) works -- Recursively collect files below UNITSCRIPT_DIR. local scriptFiles = {} for _,filename in ipairs(RecursiveFileSearch(UNITSCRIPT_DIR, "*.lua", VFSMODE)) do local basename = Basename(filename) scriptFiles[filename] = filename -- for exact match scriptFiles[basename] = filename -- for basename match end -- Go through all UnitDefs and load scripts. -- Names are tested in following order: -- * exact match -- * basename match -- * exact match where .cob->.lua -- * basename match where .cob->.lua for i=1,#UnitDefs do local unitDef = UnitDefs[i] if (unitDef and not scripts[unitDef.scriptName]) then local fn = UNITSCRIPT_DIR .. unitDef.scriptName:lower() local bn = Basename(fn) local cfn = fn:gsub("%.cob$", "%.lua") local cbn = bn:gsub("%.cob$", "%.lua") local filename = scriptFiles[fn] or scriptFiles[bn] or scriptFiles[cfn] or scriptFiles[cbn] if filename then Spring.Log(section, LOG.INFO, " Loading unit script: " .. filename) LoadScript(unitDef.scriptName, filename) end end end -- Fake UnitCreated events for existing units. (for '/luarules reload') local allUnits = Spring.GetAllUnits() for i=1,#allUnits do local unitID = allUnits[i] gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID)) end end -------------------------------------------------------------------------------- local StartThread = Spring.UnitScript.StartThread local function Wrap_AimWeapon(unitID, callins) local AimWeapon = callins["AimWeapon"] if (not AimWeapon) then return end -- SetUnitShieldState wants true or false, while -- SetUnitWeaponState wants 1.0 or 0.0, niiice =) local function AimWeaponThread(weaponNum, heading, pitch) local bAimReady = AimWeapon(weaponNum, heading, pitch) or false local fAimReady = (bAimReady and 1.0) or 0.0 return sp_SetUnitWeaponState(unitID, weaponNum, "aimReady", fAimReady) end callins["AimWeapon"] = function(weaponNum, heading, pitch) return StartThread(AimWeaponThread, weaponNum, heading, pitch) end end local function Wrap_AimShield(unitID, callins) local AimShield = callins["AimShield"] if (not AimShield) then return end -- SetUnitShieldState wants true or false, while -- SetUnitWeaponState wants 1 or 0, niiice =) local function AimShieldThread(weaponNum) local enabled = AimShield(weaponNum) and true or false return sp_SetUnitShieldState(unitID, weaponNum, enabled) end callins["AimShield"] = function(weaponNum) return StartThread(AimShieldThread, weaponNum) end end local function Wrap_Killed(unitID, callins) local Killed = callins["Killed"] if (not Killed) then return end local function KilledThread(recentDamage, maxHealth) -- It is *very* important the sp_SetDeathScriptFinished is executed, even on error. SetOnError(sp_SetDeathScriptFinished) local wreckLevel = Killed(recentDamage, maxHealth) sp_SetDeathScriptFinished(wreckLevel) end callins["Killed"] = function(recentDamage, maxHealth) StartThread(KilledThread, recentDamage, maxHealth) return -- no return value signals Spring to wait for SetDeathScriptFinished call. end end local function Wrap(callins, name) local fun = callins[name] if (not fun) then return end callins[name] = function(...) return StartThread(fun, ...) end end -------------------------------------------------------------------------------- --[[ Storage for MemoizedInclude. Format: { [filename] = chunk } --]] local include_cache = {} -- core of include() function for unit scripts local function ScriptInclude(filename) --Spring.Echo(" Loading include: " .. UNITSCRIPT_DIR .. filename) local chunk = LoadChunk(UNITSCRIPT_DIR .. filename) if chunk then include_cache[filename] = chunk return chunk end end -- memoize it so we don't need to decompress and parse the .lua file everytime.. local function MemoizedInclude(filename, env) local chunk = include_cache[filename] or ScriptInclude(filename) if chunk then --overwrite environment so it access environment of current unit setfenv(chunk, env) return chunk() end end -------------------------------------------------------------------------------- function gadget:UnitCreated(unitID, unitDefID) local ud = UnitDefs[unitDefID] local chunk = scripts[ud.scriptName] if (not chunk) then return end -- Global variables in the script are still per unit. -- Set up a new environment that is an instance of the prototype -- environment, so we don't need to copy all globals for every unit. -- This means of course, that global variable accesses are a bit more -- expensive inside unit scripts, but this can be worked around easily -- by localizing the necessary globals. local pieces = Spring.GetUnitPieceMap(unitID) local env = { unitID = unitID, unitDefID = unitDefID, script = {}, -- will store the callins } -- easy self-referencing (Note: use of _G differs from _G in gadgets & widgets) env._G = env env.include = function(f) return MemoizedInclude(f, env) end env.piece = function(...) local p = {} for _,name in ipairs{...} do p[#p+1] = pieces[name] or error("piece not found: " .. tostring(name), 2) end return unpack(p) end setmetatable(env, { __index = prototypeEnv }) setfenv(chunk, env) -- Execute the chunk. This puts the callins in env.script CallAsUnitNoReturn(unitID, chunk) local callins = env.script -- Add framework callins. callins.MoveFinished = MoveFinished callins.TurnFinished = TurnFinished callins.Destroy = Destroy -- AimWeapon/AimShield is required for a functional weapon/shield, -- so it doesn't hurt to not check other weapons. if ((not callins.AimWeapon and callins.AimWeapon1) or (not callins.AimShield and callins.AimShield1)) then for j=1,#weapon_funcs do local name = weapon_funcs[j] local dispatch = {} local n = 0 for i=1,#ud.weapons do local fun = callins[name .. i] if fun then dispatch[i] = fun n = n + 1 end end if (n == #ud.weapons) then -- optimized case callins[name] = function(w, ...) return dispatch[w](...) end elseif (n > 0) then -- needed for QueryWeapon / AimFromWeapon to return -1 -- while AimWeapon / AimShield should return false, etc. local ret = default_return_values[name] callins[name] = function(w, ...) local fun = dispatch[w] if fun then return fun(...) end return ret end end end end -- Wrap certain callins in a thread and/or safety net. for i=1,#thread_wrap do Wrap(callins, thread_wrap[i]) end Wrap_AimWeapon(unitID, callins) Wrap_AimShield(unitID, callins) Wrap_Killed(unitID, callins) -- Wrap everything so activeUnit get's set properly. for k,v in pairs(callins) do local fun = callins[k] callins[k] = function(...) PushActiveUnitID(unitID) ret = fun(...) PopActiveUnitID() return ret end end -- Register the callins with Spring. Spring.UnitScript.CreateScript(unitID, callins) -- Register (must be last: it shouldn't be done in case of error.) units[unitID] = { env = env, unitID = unitID, waitingForMove = {}, waitingForTurn = {}, threads = setmetatable({}, {__mode = "kv"}), -- weak table } -- Now it's safe to start a thread which will run Create(). -- (Spring doesn't run it, and if it did, it would do so too early to be useful.) if callins.Create then CallAsUnitNoReturn(unitID, StartThread, callins.Create) end end function gadget:GameFrame() local n = sp_GetGameFrame() local zzz = sleepers[n] if zzz then sleepers[n] = nil -- Wake up the lazy bastards for this frame (in reverse order). -- NOTE: -- 1. during WakeUp() a thread t1 might Signal (kill) another thread t2 -- 2. t2 might also be registered in sleepers[n] and not yet woken up -- 3. if so, t1's signal would cause t2 to be removed from sleepers[n] -- via Signal --> RemoveTableElement -- 4. therefore we cannot use the "for i = 1, #zzz" pattern since the -- container size/contents might change while we are iterating over -- it (and a Lua for-loop range expression is only evaluated once) while (#zzz > 0) do local sleeper = zzz[#zzz] local unitID = sleeper.unitID zzz[#zzz] = nil PushActiveUnitID(unitID) sp_CallAsUnit(unitID, WakeUp, sleeper) PopActiveUnitID() end end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
geanux/darkstar
scripts/zones/FeiYin/npcs/Treasure_Chest.lua
19
3069
----------------------------------- -- Area: Fei'Yin -- NPC: Treasure Chest -- @zone 204 ----------------------------------- package.loaded["scripts/zones/FeiYin/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/FeiYin/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1037,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(1037,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: Sorcery of the North QUEST ----------- if (player:getQuestStatus(SANDORIA,SORCERY_OF_THE_NORTH) == QUEST_ACCEPTED and player:hasKeyItem(FEIYIN_MAGIC_TOME) == 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(FEIYIN_MAGIC_TOME); player:messageSpecial(KEYITEM_OBTAINED,FEIYIN_MAGIC_TOME); -- Fei'yin Magic Tome else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]); player:messageSpecial(GIL_OBTAINED,loot[2]); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1037); 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
h0tw1r3/mame
3rdparty/genie/tests/base/test_api.lua
54
11362
-- -- tests/base/test_api.lua -- Automated test suite for the project API support functions. -- Copyright (c) 2008-2011 Jason Perkins and the Premake project -- T.api = { } local suite = T.api local sln function suite.setup() sln = solution "MySolution" end -- -- premake.getobject() tests -- function suite.getobject_RaisesError_OnNoContainer() premake.CurrentContainer = nil c, err = premake.getobject("container") test.istrue(c == nil) test.isequal("no active solution or project", err) end function suite.getobject_RaisesError_OnNoActiveSolution() premake.CurrentContainer = { } c, err = premake.getobject("solution") test.istrue(c == nil) test.isequal("no active solution", err) end function suite.getobject_RaisesError_OnNoActiveConfig() premake.CurrentConfiguration = nil c, err = premake.getobject("config") test.istrue(c == nil) test.isequal("no active solution, project, or configuration", err) end -- -- premake.setarray() tests -- function suite.setarray_Inserts_OnStringValue() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { } premake.setarray("config", "myfield", "hello") test.isequal("hello", premake.CurrentConfiguration.myfield[1]) end function suite.setarray_Inserts_OnTableValue() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { } premake.setarray("config", "myfield", { "hello", "goodbye" }) test.isequal("hello", premake.CurrentConfiguration.myfield[1]) test.isequal("goodbye", premake.CurrentConfiguration.myfield[2]) end function suite.setarray_Appends_OnNewValues() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { "hello" } premake.setarray("config", "myfield", "goodbye") test.isequal("hello", premake.CurrentConfiguration.myfield[1]) test.isequal("goodbye", premake.CurrentConfiguration.myfield[2]) end function suite.setarray_FlattensTables() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { } premake.setarray("config", "myfield", { {"hello"}, {"goodbye"} }) test.isequal("hello", premake.CurrentConfiguration.myfield[1]) test.isequal("goodbye", premake.CurrentConfiguration.myfield[2]) end function suite.setarray_RaisesError_OnInvalidValue() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { } ok, err = pcall(function () premake.setarray("config", "myfield", "bad", { "Good", "Better", "Best" }) end) test.isfalse(ok) end function suite.setarray_CorrectsCase_OnConstrainedValue() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = { } premake.setarray("config", "myfield", "better", { "Good", "Better", "Best" }) test.isequal("Better", premake.CurrentConfiguration.myfield[1]) end -- -- premake.setstring() tests -- function suite.setstring_Sets_OnNewProperty() premake.CurrentConfiguration = { } premake.setstring("config", "myfield", "hello") test.isequal("hello", premake.CurrentConfiguration.myfield) end function suite.setstring_Overwrites_OnExistingProperty() premake.CurrentConfiguration = { } premake.CurrentConfiguration.myfield = "hello" premake.setstring("config", "myfield", "goodbye") test.isequal("goodbye", premake.CurrentConfiguration.myfield) end function suite.setstring_RaisesError_OnInvalidValue() premake.CurrentConfiguration = { } ok, err = pcall(function () premake.setstring("config", "myfield", "bad", { "Good", "Better", "Best" }) end) test.isfalse(ok) end function suite.setstring_CorrectsCase_OnConstrainedValue() premake.CurrentConfiguration = { } premake.setstring("config", "myfield", "better", { "Good", "Better", "Best" }) test.isequal("Better", premake.CurrentConfiguration.myfield) end -- -- premake.setkeyvalue() tests -- function suite.setkeyvalue_Inserts_OnStringValue() premake.CurrentConfiguration = { } premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" }) test.isequal({"*.h"}, premake.CurrentConfiguration.vpaths["Headers"]) end function suite.setkeyvalue_Inserts_OnTableValue() premake.CurrentConfiguration = { } premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h","*.hpp"} }) test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"]) end function suite.setkeyvalue_Inserts_OnEmptyStringKey() premake.CurrentConfiguration = { } premake.setkeyvalue("config", "vpaths", { [""] = "src" }) test.isequal({"src"}, premake.CurrentConfiguration.vpaths[""]) end function suite.setkeyvalue_RaisesError_OnString() premake.CurrentConfiguration = { } ok, err = pcall(function () premake.setkeyvalue("config", "vpaths", "Headers") end) test.isfalse(ok) end function suite.setkeyvalue_InsertsString_IntoExistingKey() premake.CurrentConfiguration = { } premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.h" }) premake.setkeyvalue("config", "vpaths", { ["Headers"] = "*.hpp" }) test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"]) end function suite.setkeyvalue_InsertsTable_IntoExistingKey() premake.CurrentConfiguration = { } premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.h"} }) premake.setkeyvalue("config", "vpaths", { ["Headers"] = {"*.hpp"} }) test.isequal({"*.h","*.hpp"}, premake.CurrentConfiguration.vpaths["Headers"]) end -- -- accessor tests -- function suite.accessor_CanRetrieveString() sln.blocks[1].kind = "ConsoleApp" test.isequal("ConsoleApp", kind()) end -- -- solution() tests -- function suite.solution_SetsCurrentContainer_OnName() test.istrue(sln == premake.CurrentContainer) end function suite.solution_CreatesNewObject_OnNewName() solution "MySolution2" test.isfalse(sln == premake.CurrentContainer) end function suite.solution_ReturnsPrevious_OnExistingName() solution "MySolution2" local sln2 = solution "MySolution" test.istrue(sln == sln2) end function suite.solution_SetsCurrentContainer_OnExistingName() solution "MySolution2" solution "MySolution" test.istrue(sln == premake.CurrentContainer) end function suite.solution_ReturnsNil_OnNoActiveSolutionAndNoName() premake.CurrentContainer = nil test.isnil(solution()) end function suite.solution_ReturnsCurrentSolution_OnActiveSolutionAndNoName() test.istrue(sln == solution()) end function suite.solution_ReturnsCurrentSolution_OnActiveProjectAndNoName() project "MyProject" test.istrue(sln == solution()) end function suite.solution_LeavesProjectActive_OnActiveProjectAndNoName() local prj = project "MyProject" solution() test.istrue(prj == premake.CurrentContainer) end function suite.solution_LeavesConfigActive_OnActiveSolutionAndNoName() local cfg = configuration "windows" solution() test.istrue(cfg == premake.CurrentConfiguration) end function suite.solution_LeavesConfigActive_OnActiveProjectAndNoName() project "MyProject" local cfg = configuration "windows" solution() test.istrue(cfg == premake.CurrentConfiguration) end function suite.solution_SetsName_OnNewName() test.isequal("MySolution", sln.name) end function suite.solution_AddsNewConfig_OnNewName() test.istrue(#sln.blocks == 1) end function suite.solution_AddsNewConfig_OnName() local num = #sln.blocks solution "MySolution" test.istrue(#sln.blocks == num + 1) end -- -- configuration() tests -- function suite.configuration_RaisesError_OnNoContainer() premake.CurrentContainer = nil local fn = function() configuration{"Debug"} end ok, err = pcall(fn) test.isfalse(ok) end function suite.configuration_SetsCurrentConfiguration_OnKeywords() local cfg = configuration {"Debug"} test.istrue(premake.CurrentConfiguration == cfg) end function suite.configuration_AddsToContainer_OnKeywords() local cfg = configuration {"Debug"} test.istrue(cfg == sln.blocks[#sln.blocks]) end function suite.configuration_ReturnsCurrent_OnNoKeywords() local cfg = configuration() test.istrue(cfg == sln.blocks[1]) end function suite.configuration_SetsTerms() local cfg = configuration {"aa", "bb"} test.isequal({"aa", "bb"}, cfg.terms) end function suite.configuration_SetsTermsWithNestedTables() local cfg = configuration { {"aa", "bb"}, "cc" } test.isequal({"aa", "bb", "cc"}, cfg.terms) end function suite.configuration_CanReuseTerms() local cfg = configuration { "aa", "bb" } local cfg2 = configuration { cfg.terms, "cc" } test.isequal({"aa", "bb", "cc"}, cfg2.terms) end -- -- project() tests -- function suite.project_RaisesError_OnNoSolution() premake.CurrentContainer = nil local fn = function() project("MyProject") end ok, err = pcall(fn) test.isfalse(ok) end function suite.project_SetsCurrentContainer_OnName() local prj = project "MyProject" test.istrue(prj == premake.CurrentContainer) end function suite.project_CreatesNewObject_OnNewName() local prj = project "MyProject" local pr2 = project "MyProject2" test.isfalse(prj == premake.CurrentContainer) end function suite.project_AddsToSolution_OnNewName() local prj = project "MyProject" test.istrue(prj == sln.projects[1]) end function suite.project_ReturnsPrevious_OnExistingName() local prj = project "MyProject" local pr2 = project "MyProject2" local pr3 = project "MyProject" test.istrue(prj == pr3) end function suite.project_SetsCurrentContainer_OnExistingName() local prj = project "MyProject" local pr2 = project "MyProject2" local pr3 = project "MyProject" test.istrue(prj == premake.CurrentContainer) end function suite.project_ReturnsNil_OnNoActiveProjectAndNoName() test.isnil(project()) end function suite.project_ReturnsCurrentProject_OnActiveProjectAndNoName() local prj = project "MyProject" test.istrue(prj == project()) end function suite.project_LeavesProjectActive_OnActiveProjectAndNoName() local prj = project "MyProject" project() test.istrue(prj == premake.CurrentContainer) end function suite.project_LeavesConfigActive_OnActiveProjectAndNoName() local prj = project "MyProject" local cfg = configuration "Windows" project() test.istrue(cfg == premake.CurrentConfiguration) end function suite.project_SetsName_OnNewName() prj = project("MyProject") test.isequal("MyProject", prj.name) end function suite.project_SetsSolution_OnNewName() prj = project("MyProject") test.istrue(sln == prj.solution) end function suite.project_SetsConfiguration() prj = project("MyProject") test.istrue(premake.CurrentConfiguration == prj.blocks[1]) end function suite.project_SetsUUID() local prj = project "MyProject" test.istrue(prj.uuid) end -- -- uuid() tests -- function suite.uuid_makes_uppercase() premake.CurrentContainer = {} uuid "7CBB5FC2-7449-497f-947F-129C5129B1FB" test.isequal(premake.CurrentContainer.uuid, "7CBB5FC2-7449-497F-947F-129C5129B1FB") end -- -- Fields with allowed value lists should be case-insensitive. -- function suite.flags_onCaseMismatch() premake.CurrentConfiguration = {} flags "symbols" test.isequal(premake.CurrentConfiguration.flags[1], "Symbols") end function suite.flags_onCaseMismatchAndAlias() premake.CurrentConfiguration = {} flags "optimisespeed" test.isequal(premake.CurrentConfiguration.flags[1], "OptimizeSpeed") end
gpl-2.0
geanux/darkstar
scripts/globals/mobskills/Benthic_Typhoon.lua
25
1031
--------------------------------------------- -- Benthic Typhoon -- -- Description: Delivers an area attack that lowers target's defense and magic defense. Damage varies with TP. -- Type: Physical (Piercing) -- -- --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.3; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_PIERCE,info.hitslanded); target:delHP(dmg); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_MAGIC_DEF_DOWN, 30, 0, 60); MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_DEFENSE_DOWN, 30, 0, 60); return dmg; end;
gpl-3.0
geanux/darkstar
scripts/globals/items/plate_of_tentacle_sushi.lua
14
1878
----------------------------------------- -- ID: 5215 -- Item: plate_of_tentacle_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 20 -- Dexterity 3 -- Agility 3 -- Mind -1 -- Accuracy % 19 (cap 18) -- Ranged Accuracy % 19 (cap 18) -- Double Attack 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5215); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_AGI, 3); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_ACCP, 20); target:addMod(MOD_FOOD_ACC_CAP, 18); target:addMod(MOD_FOOD_RACCP, 20); target:addMod(MOD_FOOD_RACC_CAP, 18); target:addMod(MOD_DOUBLE_ATTACK, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_AGI, 3); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_ACCP, 20); target:delMod(MOD_FOOD_ACC_CAP, 18); target:delMod(MOD_FOOD_RACCP, 20); target:delMod(MOD_FOOD_RACC_CAP, 18); target:delMod(MOD_DOUBLE_ATTACK, 1); end;
gpl-3.0
kaen/Zero-K
LuaUI/Widgets/gfx_BloomShader.lua
6
15267
-- $Id: BloomShader.lua 3171 2008-11-06 09:06:29Z det $ function widget:GetInfo() return { name = "BloomShader (v0.31a)", desc = "Sets Spring In Bloom (do not use with < 7xxx geforce series or non-latest ATI cards!)", author = "Kloot", --Updated by Shadowfury333 date = "28-5-2008", license = "", layer = 9, enabled = false } end -- CarRepairer: v0.31 has configurable settings in the menu. options_path = 'Settings/Graphics/Effects/Bloom' options = { dbgDraw = { type='bool', name='Draw Only Bloom Mask', value=false, }, maxBrightness = { type='number', name='Maximum Highlight Brightness', value=0.47, min=0.001, max=3,step=0.001, }, illumThreshold = { type='number', name='Illumination Threshold', value=0.7, min=0, max=1,step=0.001, }, blurPasses = { type='number', name='Blur Passes', value=2, min=0, max=10,step=1, }, } -- config params local dbgDraw = 0 -- draw only the bloom-mask? [0 | 1] local maxBrightness = 0.47 -- maximum brightness of bloom additions [1, n] local illumThreshold = 0.7 -- how bright does a fragment need to be before being considered a glow source? [0, 1] local blurPasses = 2 -- how many iterations of Gaussian blur should be applied to the glow sources? local function OnchangeFunc() dbgDraw = options.dbgDraw.value and 1 or 0 maxBrightness = options.maxBrightness.value illumThreshold = options.illumThreshold.value blurPasses = options.blurPasses.value end for key,option in pairs(options) do option.OnChange = OnchangeFunc end OnchangeFunc() -- non-editables local vsx = 1 -- current viewport width local vsy = 1 -- current viewport height local ivsx = 1.0 / vsx local ivsy = 1.0 / vsy local kernelRadius = vsx / 36.0 --30 at 1080 px high -- shader and texture handles local blurShaderH71 = nil local blurShaderV71 = nil local brightShader = nil local brightTexture1 = nil local brightTexture2 = nil local combineShader = nil local screenTexture = nil local screenTextureQuarter = nil local screenTextureSixteenth = nil -- speedups local glGetSun = gl.GetSun local glCreateTexture = gl.CreateTexture local glDeleteTexture = gl.DeleteTexture local glActiveTexture = gl.ActiveTexture local glCopyToTexture = gl.CopyToTexture local glRenderToTexture = gl.RenderToTexture local glTexture = gl.Texture local glTexRect = gl.TexRect local glGenerateMipmaps = gl.GenerateMipmap local glGetShaderLog = gl.GetShaderLog local glCreateShader = gl.CreateShader local glDeleteShader = gl.DeleteShader local glUseShader = gl.UseShader local glUniformInt = gl.UniformInt local glUniform = gl.Uniform local glGetUniformLocation = gl.GetUniformLocation local glGetActiveUniforms = gl.GetActiveUniforms local GL_RGBA32F_ARB = 0x8814 local GL_RGB32F_ARB = 0x8815 local GL_ALPHA32F_ARB = 0x8816 local GL_INTENSITY32F_ARB = 0x8817 local GL_LUMINANCE32F_ARB = 0x8818 local GL_LUMINANCE_ALPHA32F_ARB = 0x8819 local GL_RGBA16F_ARB = 0x881A local GL_RGB16F_ARB = 0x881B local GL_ALPHA16F_ARB = 0x881C local GL_INTENSITY16F_ARB = 0x881D local GL_LUMINANCE16F_ARB = 0x881E local GL_LUMINANCE_ALPHA16F_ARB = 0x881F local GL_TEXTURE_RED_TYPE_ARB = 0x8C10 local GL_TEXTURE_GREEN_TYPE_ARB = 0x8C11 local GL_TEXTURE_BLUE_TYPE_ARB = 0x8C12 local GL_TEXTURE_ALPHA_TYPE_ARB = 0x8C13 local GL_TEXTURE_LUMINANCE_TYPE_ARB = 0x8C14 local GL_TEXTURE_INTENSITY_TYPE_ARB = 0x8C15 local GL_TEXTURE_DEPTH_TYPE_ARB = 0x8C16 local GL_UNSIGNED_NORMALIZED_ARB = 0x8C17 -- shader uniform locations local brightShaderText0Loc = nil local brightShaderInvRXLoc = nil local brightShaderInvRYLoc = nil local brightShaderIllumLoc = nil local blurShaderH51Text0Loc = nil local blurShaderH51InvRXLoc = nil local blurShaderH51FragLoc = nil local blurShaderV51Text0Loc = nil local blurShaderV51InvRYLoc = nil local blurShaderV51FragLoc = nil local blurShaderH71Text0Loc = nil local blurShaderH71InvRXLoc = nil local blurShaderH71FragLoc = nil local blurShaderV71Text0Loc = nil local blurShaderV71InvRYLoc = nil local blurShaderV71FragLoc = nil local combineShaderDebgDrawLoc = nil local combineShaderTexture0Loc = nil local combineShaderTexture1Loc = nil local combineShaderIllumLoc = nil local combineShaderFragLoc = nil local function SetIllumThreshold() local ra, ga, ba = glGetSun("ambient") local rd, gd, bd = glGetSun("diffuse") local rs, gs, bs = glGetSun("specular") local ambientIntensity = ra * 0.299 + ga * 0.587 + ba * 0.114 local diffuseIntensity = rd * 0.299 + gd * 0.587 + bd * 0.114 local specularIntensity = rs * 0.299 + gs * 0.587 + bs * 0.114 -- illumThreshold = (0.8 * ambientIntensity) + (0.1 * diffuseIntensity) + (0.1 * specularIntensity) print("[BloomShader::SetIllumThreshold] sun ambient color: ", ra .. ", " .. ga .. ", " .. ba .. " (intensity: " .. ambientIntensity .. ")") print("[BloomShader::SetIllumThreshold] sun diffuse color: ", rd .. ", " .. gd .. ", " .. bd .. " (intensity: " .. diffuseIntensity .. ")") print("[BloomShader::SetIllumThreshold] sun specular color: ", rs .. ", " .. gs .. ", " .. bs .. " (intensity: " .. specularIntensity .. ")") print("[BloomShader::SetIllumThreshold] illumination threshold: " .. illumThreshold) end local function RemoveMe(msg) Spring.Echo(msg) widgetHandler:RemoveWidget() end function widget:ViewResize(viewSizeX, viewSizeY) vsx = viewSizeX; ivsx = 1.0 / vsx vsy = viewSizeY; ivsy = 1.0 / vsy kernelRadius = vsy / 36.0 glDeleteTexture(brightTexture1 or "") glDeleteTexture(brightTexture2 or "") glDeleteTexture(screenTexture or "") brightTexture1 = glCreateTexture(vsx/4, vsy/4, { fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP, }) brightTexture2 = glCreateTexture(vsx/4, vsy/4, { fbo = true, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, format = GL_RGB16F_ARB, wrap_s = GL.CLAMP, wrap_t = GL.CLAMP, }) screenTexture = glCreateTexture(vsx, vsy, { min_filter = GL.LINEAR, mag_filter = GL.LINEAR, }) screenTextureQuarter = glCreateTexture(vsx/2, vsy/2, { min_filter = GL.LINEAR, mag_filter = GL.LINEAR, }) screenTextureSixteenth = glCreateTexture(vsx/4, vsy/4, { min_filter = GL.LINEAR, mag_filter = GL.LINEAR, }) if (brightTexture1 == nil or brightTexture2 == nil or screenTexture == nil or screenTextureQuarter == nil or screenTextureSixteenth == nil) then RemoveMe("[BloomShader::ViewResize] removing widget, bad texture target") return end end widget:ViewResize(widgetHandler:GetViewSizes()) function widget:Initialize() if (glCreateShader == nil) then RemoveMe("[BloomShader::Initialize] removing widget, no shader support") return end SetIllumThreshold() combineShader = glCreateShader({ fragment = [[ uniform sampler2D texture0; uniform sampler2D texture1; uniform float illuminationThreshold; uniform float fragMaxBrightness; uniform int debugDraw; void main(void) { vec2 C0 = vec2(gl_TexCoord[0]); vec4 S0 = texture2D(texture0, C0); vec4 S1 = texture2D(texture1, C0); S1 = vec4(S1.rgb * fragMaxBrightness/max(1.0 - illuminationThreshold, 0.0001), 1.0); gl_FragColor = bool(debugDraw) ? S1 : S0 + S1; } ]], uniformInt = { texture0 = 0, texture1 = 1, debugDraw = 0}, uniformFloat = {illuminationThreshold, fragMaxBrightness} }) if (combineShader == nil) then RemoveMe("[BloomShader::Initialize] combineShader compilation failed"); print(glGetShaderLog()); return end blurShaderH71 = glCreateShader({ fragment = [[ uniform sampler2D texture0; uniform float inverseRX; uniform float fragKernelRadius; float bloomSigma = fragKernelRadius / 2.0; void main(void) { vec2 C0 = vec2(gl_TexCoord[0]); vec4 S = texture2D(texture0, C0); float weight = 1.0 / (2.50663 * bloomSigma); float total_weight = weight; S *= weight; for (float r = 1.5; r < fragKernelRadius; r += 2.0) { weight = exp(-((r*r)/(2.0 * bloomSigma * bloomSigma)))/(2.50663 * bloomSigma); S += texture2D(texture0, C0 - vec2(r * inverseRX, 0.0)) * weight; S += texture2D(texture0, C0 + vec2(r * inverseRX, 0.0)) * weight; total_weight += 2*weight; } gl_FragColor = vec4(S.rgb/total_weight, 1.0); } ]], uniformInt = {texture0 = 0}, uniformFloat = {inverseRX, fragKernelRadius} }) if (blurShaderH71 == nil) then RemoveMe("[BloomShader::Initialize] blurShaderH71 compilation failed"); print(glGetShaderLog()); return end blurShaderV71 = glCreateShader({ fragment = [[ uniform sampler2D texture0; uniform float inverseRY; uniform float fragKernelRadius; float bloomSigma = fragKernelRadius / 2.0; void main(void) { vec2 C0 = vec2(gl_TexCoord[0]); vec4 S = texture2D(texture0, C0); float weight = 1.0 / (2.50663 * bloomSigma); float total_weight = weight; S *= weight; for (float r = 1.5; r < fragKernelRadius; r += 2.0) { weight = exp(-((r*r)/(2.0 * bloomSigma * bloomSigma)))/(2.50663 * bloomSigma); S += texture2D(texture0, C0 - vec2(0.0, r * inverseRY)) * weight; S += texture2D(texture0, C0 + vec2(0.0, r * inverseRY)) * weight; total_weight += 2*weight; } gl_FragColor = vec4(S.rgb/total_weight, 1.0); } ]], uniformInt = {texture0 = 0}, uniformFloat = {inverseRY, fragKernelRadius} }) if (blurShaderV71 == nil) then RemoveMe("[BloomShader::Initialize] blurShaderV71 compilation failed"); print(glGetShaderLog()); return end brightShader = glCreateShader({ fragment = [[ uniform sampler2D texture0; uniform float illuminationThreshold; uniform float inverseRX; uniform float inverseRY; void main(void) { vec2 C0 = vec2(gl_TexCoord[0]); vec3 color = vec3(texture2D(texture0, C0)); float illum = dot(color, vec3(0.2990, 0.5870, 0.1140)); if (illum > illuminationThreshold) { gl_FragColor = vec4((color - color*(illuminationThreshold/max(illum, 0.00001))), 1.0); } else { gl_FragColor = vec4(0.0, 0.0, 0.0, 1.0); } } ]], uniformInt = {texture0 = 0}, uniformFloat = {illuminationThreshold, inverseRX, inverseRY} }) if (brightShader == nil) then RemoveMe("[BloomShader::Initialize] brightShader compilation failed"); print(glGetShaderLog()); return end brightShaderText0Loc = glGetUniformLocation(brightShader, "texture0") brightShaderInvRXLoc = glGetUniformLocation(brightShader, "inverseRX") brightShaderInvRYLoc = glGetUniformLocation(brightShader, "inverseRY") brightShaderIllumLoc = glGetUniformLocation(brightShader, "illuminationThreshold") blurShaderH71Text0Loc = glGetUniformLocation(blurShaderH71, "texture0") blurShaderH71InvRXLoc = glGetUniformLocation(blurShaderH71, "inverseRX") blurShaderH71FragLoc = glGetUniformLocation(blurShaderH71, "fragKernelRadius") blurShaderV71Text0Loc = glGetUniformLocation(blurShaderV71, "texture0") blurShaderV71InvRYLoc = glGetUniformLocation(blurShaderV71, "inverseRY") blurShaderV71FragLoc = glGetUniformLocation(blurShaderV71, "fragKernelRadius") combineShaderDebgDrawLoc = glGetUniformLocation(combineShader, "debugDraw") combineShaderTexture0Loc = glGetUniformLocation(combineShader, "texture0") combineShaderTexture1Loc = glGetUniformLocation(combineShader, "texture1") combineShaderIllumLoc = glGetUniformLocation(combineShader, "illuminationThreshold") combineShaderFragLoc = glGetUniformLocation(combineShader, "fragMaxBrightness") end function widget:Shutdown() glDeleteTexture(brightTexture1 or "") glDeleteTexture(brightTexture2 or "") glDeleteTexture(screenTexture or "") if (glDeleteShader) then glDeleteShader(brightShader or 0) glDeleteShader(blurShaderH71 or 0) glDeleteShader(blurShaderV71 or 0) glDeleteShader(combineShader or 0) end end local function mglDrawTexture(texUnit, tex, w, h, flipS, flipT) glTexture(texUnit, tex) glTexRect(0, 0, w, h, flipS, flipT) glTexture(texUnit, false) end local function mglDrawFBOTexture(tex) glTexture(tex) glTexRect(-1, -1, 1, 1) glTexture(false) end local function activeTextureFunc(texUnit, tex, w, h, flipS, flipT) glTexture(texUnit, tex) glTexRect(0, 0, w, h, flipS, flipT) glTexture(texUnit, false) end local function mglActiveTexture(texUnit, tex, w, h, flipS, flipT) glActiveTexture(texUnit, activeTextureFunc, texUnit, tex, w, h, flipS, flipT) end local function renderToTextureFunc(tex, s, t) glTexture(tex) glTexRect(-1 * s, -1 * t, 1 * s, 1 * t) glTexture(false) end local function mglRenderToTexture(FBOTex, tex, s, t) glRenderToTexture(FBOTex, renderToTextureFunc, tex, s, t) end local function Bloom() gl.Color(1, 1, 1, 1) glCopyToTexture(screenTexture, 0, 0, 0, 0, vsx, vsy) glUseShader(brightShader) glUniformInt(brightShaderText0Loc, 0) glUniform( brightShaderInvRXLoc, ivsx) glUniform( brightShaderInvRYLoc, ivsy) glUniform( brightShaderIllumLoc, illumThreshold) mglRenderToTexture(brightTexture1, screenTexture, 1, -1) glUseShader(0) for i = 1, blurPasses do glUseShader(blurShaderH71) glUniformInt(blurShaderH71Text0Loc, 0) glUniform( blurShaderH71InvRXLoc, ivsx) glUniform( blurShaderH71FragLoc, kernelRadius) mglRenderToTexture(brightTexture2, brightTexture1, 1, -1) glUseShader(0) glUseShader(blurShaderV71) glUniformInt(blurShaderV71Text0Loc, 0) glUniform( blurShaderV71InvRYLoc, ivsy) glUniform( blurShaderV71FragLoc, kernelRadius) mglRenderToTexture(brightTexture1, brightTexture2, 1, -1) glUseShader(0) end glUseShader(combineShader) glUniformInt(combineShaderDebgDrawLoc, dbgDraw) glUniformInt(combineShaderTexture0Loc, 0) glUniformInt(combineShaderTexture1Loc, 1) glUniform( combineShaderIllumLoc, illumThreshold) glUniform( combineShaderFragLoc, maxBrightness) mglActiveTexture(0, screenTexture, vsx, vsy, false, true) mglActiveTexture(1, brightTexture1, vsx, vsy, false, true) glUseShader(0) end function widget:DrawScreenEffects() Bloom() end --[[ function widget:TextCommand(command) if (string.find(command, "+illumthres") == 1) then illumThreshold = illumThreshold + 0.02 end if (string.find(command, "-illumthres") == 1) then illumThreshold = illumThreshold - 0.02 end if (string.find(command, "+glowamplif") == 1) then maxBrightness = maxBrightness + 0.05 end if (string.find(command, "-glowamplif") == 1) then maxBrightness = maxBrightness - 0.05 end if (string.find(command, "+blurpasses") == 1) then blurPasses = blurPasses + 1 end if (string.find(command, "-blurpasses") == 1) then blurPasses = blurPasses - 1 end if (string.find(command, "+bloomdebug") == 1) then dbgDraw = 1 end if (string.find(command, "-bloomdebug") == 1) then dbgDraw = 0 end illumThreshold = math.max(0.0, math.min(1.0, illumThreshold)) blurPasses = math.max(0, blurPasses) Spring.Echo("[BloomShader::TextCommand]") Spring.Echo(" illumThreshold: " .. illumThreshold) Spring.Echo(" maxBrightness: " .. maxBrightness) Spring.Echo(" blurAmplifier: " .. blurAmplifier) Spring.Echo(" blurPasses: " .. blurPasses) Spring.Echo(" dilatePass: " .. dilatePass) end --]]
gpl-2.0
geanux/darkstar
scripts/zones/Bastok_Markets/npcs/Yafafa.lua
36
1619
----------------------------------- -- Area: Bastok Markets -- NPC: Yafafa -- Only sells when Bastok controls Kolshushu -- -- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(KOLSHUSHU); if (RegionOwner ~= BASTOK) then player:showText(npc,YAFAFA_CLOSED_DIALOG); else player:showText(npc,YAFAFA_OPEN_DIALOG); stock = { 0x1197, 184, --Buburimu Grape 0x0460,1620, --Casablanca 0x1107, 220, --Dhalmel Meat 0x0266, 72, --Mhaura Garlic 0x115d, 40 --Yagudo Cherry } showShop(player,BASTOK,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
vgire/rnn
LinearNoBias.lua
11
1886
------------------------------------------------------------------------ --[[ LinearNoBias ]]-- -- Subclass of nn.Linear with no bias term ------------------------------------------------------------------------ nn = require 'nn' local LinearNoBias, Linear = torch.class('nn.LinearNoBias', 'nn.Linear') function LinearNoBias:__init(inputSize, outputSize) nn.Module.__init(self) self.weight = torch.Tensor(outputSize, inputSize) self.gradWeight = torch.Tensor(outputSize, inputSize) self:reset() end function LinearNoBias:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.weight:size(2)) end if nn.oldSeed then for i=1,self.weight:size(1) do self.weight:select(1, i):apply(function() return torch.uniform(-stdv, stdv) end) end else self.weight:uniform(-stdv, stdv) end return self end function LinearNoBias:updateOutput(input) if input:dim() == 1 then self.output:resize(self.weight:size(1)) self.output:mv(self.weight, input) elseif input:dim() == 2 then local nframe = input:size(1) local nElement = self.output:nElement() self.output:resize(nframe, self.weight:size(1)) if self.output:nElement() ~= nElement then self.output:zero() end if not self.addBuffer or self.addBuffer:nElement() ~= nframe then self.addBuffer = input.new(nframe):fill(1) end self.output:addmm(0, self.output, 1, input, self.weight:t()) else error('input must be vector or matrix') end return self.output end function LinearNoBias:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 1 then self.gradWeight:addr(scale, gradOutput, input) elseif input:dim() == 2 then self.gradWeight:addmm(scale, gradOutput:t(), input) end end
bsd-3-clause
geanux/darkstar
scripts/zones/Chateau_dOraguille/npcs/_6h4.lua
17
3614
----------------------------------- -- Area: Chateau d'Oraguille -- Door: Great Hall -- Involved in Missions: 3-3, 5-2, 6-1, 8-2, 9-1 -- @pos 0 -1 13 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); -- Mission San D'Oria 9-2 The Heir to the Light if (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 5) then player:startEvent(0x0008); -- Mission San D'Oria 9-1 Breaking Barriers elseif (currentMission == BREAKING_BARRIERS and MissionStatus == 4) then if (player:hasKeyItem(FIGURE_OF_TITAN) and player:hasKeyItem(FIGURE_OF_GARUDA) and player:hasKeyItem(FIGURE_OF_LEVIATHAN)) then player:startEvent(0x004c); end elseif (currentMission == BREAKING_BARRIERS and MissionStatus == 0) then player:startEvent(0x0020); -- Mission San D'Oria 8-2 Lightbringer elseif (currentMission == LIGHTBRINGER and MissionStatus == 6) then player:startEvent(0x0068); elseif (currentMission == LIGHTBRINGER and MissionStatus == 0) then player:startEvent(0x0064); -- Mission San D'Oria 6-1 Leaute's Last Wishes elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 1) then player:startEvent(87); -- Mission San D'Oria 5-2 The Shadow Lord elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 5) then player:startEvent(0x003D); -- Mission San D'Oria 3-3 Appointment to Jeuno elseif (currentMission == APPOINTMENT_TO_JEUNO and MissionStatus == 2) then player:startEvent(0x0219); else player:startEvent(0x202); 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 == 0x0219) then player:setVar("MissionStatus",3); player:addKeyItem(LETTER_TO_THE_AMBASSADOR); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_AMBASSADOR); elseif (csid == 0x003D) then finishMissionTimeline(player,3,csid,option); elseif (csid == 87) then player:setVar('MissionStatus',2); elseif (csid == 0x0064) then player:setVar("Mission8-1Completed",0) -- dont need this var anymore. JP midnight is done and prev mission completed. player:setVar("MissionStatus",1); elseif (csid == 0x0068) then player:setVar("Mission8-2Kills",0); finishMissionTimeline(player,3,csid,option); elseif (csid == 0x0008) then player:setVar("MissionStatus",6); elseif (csid == 0x0020) then player:setVar("Cutscenes_8-2",0); -- dont need this var now that mission is flagged and cs have been triggered to progress player:setVar("MissionStatus",1); elseif (csid == 0x004c) then finishMissionTimeline(player,3,csid,option); end end;
gpl-3.0
geanux/darkstar
scripts/globals/items/reishi_mushroom.lua
35
1195
----------------------------------------- -- ID: 4449 -- Item: reishi_mushroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -6 -- Mind 4 ----------------------------------------- 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,300,4449); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -6); target:addMod(MOD_MND, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -6); target:delMod(MOD_MND, 4); end;
gpl-3.0
kaen/Zero-K
LuaUI/utility_two.lua
17
1410
-- Utility function for ZK -- Will try to read LUA content from target file and create BACKUP if have a successful read (in user's Spring folder) OR DELETE them if have a failure read -- This prevent corrupted file from being used. -- Note: currently only a "table" is considered a valid file function CheckLUAFileAndBackup(filePath, headerString) local chunk, err = loadfile(filePath) local success = false if (chunk) then --if original content is LUA OK: local tmp = {} setfenv(chunk, tmp) local tab = chunk() if tab and type(tab) == "table" then table.save(chunk(),filePath..".bak",headerString) --write to backup success = true end end if (not success) then --if original content is not LUA OK: Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Now will find backup file)") chunk, err = loadfile(filePath..".bak") if (chunk) then --if backup content is LUA OK: local tmp = {} setfenv(chunk, tmp) local tab = chunk() if tab and type(tab) == "table" then table.save(chunk(),filePath,headerString) --overwrite original success = true end end if (not success) then --if backup content is also not LUA OK: Spring.Log("CheckLUAFileAndBackup","warning", tostring(err) .. " (Backup file not available)") Spring.Echo(os.remove (filePath)) --delete original Spring.Echo(os.remove (filePath..".bak")) --delete backup end end end
gpl-2.0
forward619/luci
libs/luci-lib-json/luasrc/json.lua
47
11035
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local nixio = require "nixio" local util = require "luci.util" local table = require "table" local string = require "string" local coroutine = require "coroutine" local assert = assert local tonumber = tonumber local tostring = tostring local error = error local type = type local pairs = pairs local ipairs = ipairs local next = next local pcall = pcall local band = nixio.bit.band local bor = nixio.bit.bor local rshift = nixio.bit.rshift local char = string.char local getmetatable = getmetatable module "luci.json" function decode(json, ...) local a = ActiveDecoder(function() return nil end, ...) a.chunk = json local s, obj = pcall(a.get, a) return s and obj or nil end function encode(obj, ...) local out = {} local e = Encoder(obj, 1, ...):source() local chnk, err repeat chnk, err = e() out[#out+1] = chnk until not chnk return not err and table.concat(out) or nil end function null() return null end Encoder = util.class() function Encoder.__init__(self, data, buffersize, fastescape) self.data = data self.buffersize = buffersize or 512 self.buffer = "" self.fastescape = fastescape getmetatable(self).__call = Encoder.source end function Encoder.source(self) local source = coroutine.create(self.dispatch) return function() local res, data = coroutine.resume(source, self, self.data, true) if res then return data else return nil, data end end end function Encoder.dispatch(self, data, start) local parser = self.parsers[type(data)] parser(self, data) if start then if #self.buffer > 0 then coroutine.yield(self.buffer) end coroutine.yield() end end function Encoder.put(self, chunk) if self.buffersize < 2 then coroutine.yield(chunk) else if #self.buffer + #chunk > self.buffersize then local written = 0 local fbuffer = self.buffersize - #self.buffer coroutine.yield(self.buffer .. chunk:sub(written + 1, fbuffer)) written = fbuffer while #chunk - written > self.buffersize do fbuffer = written + self.buffersize coroutine.yield(chunk:sub(written + 1, fbuffer)) written = fbuffer end self.buffer = chunk:sub(written + 1) else self.buffer = self.buffer .. chunk end end end function Encoder.parse_nil(self) self:put("null") end function Encoder.parse_bool(self, obj) self:put(obj and "true" or "false") end function Encoder.parse_number(self, obj) self:put(tostring(obj)) end function Encoder.parse_string(self, obj) if self.fastescape then self:put('"' .. obj:gsub('\\', '\\\\'):gsub('"', '\\"') .. '"') else self:put('"' .. obj:gsub('[%c\\"]', function(char) return '\\u00%02x' % char:byte() end ) .. '"') end end function Encoder.parse_iter(self, obj) if obj == null then return self:put("null") end if type(obj) == "table" and (#obj == 0 and next(obj)) then self:put("{") local first = true for key, entry in pairs(obj) do if key ~= null then first = first or self:put(",") first = first and false self:parse_string(tostring(key)) self:put(":") self:dispatch(entry) end end self:put("}") else self:put("[") local first = true if type(obj) == "table" then for i=1, #obj do first = first or self:put(",") first = first and nil self:dispatch(obj[i]) end else for entry in obj do first = first or self:put(",") first = first and nil self:dispatch(entry) end end self:put("]") end end Encoder.parsers = { ['nil'] = Encoder.parse_nil, ['table'] = Encoder.parse_iter, ['number'] = Encoder.parse_number, ['string'] = Encoder.parse_string, ['boolean'] = Encoder.parse_bool, ['function'] = Encoder.parse_iter } Decoder = util.class() function Decoder.__init__(self, customnull) self.cnull = customnull getmetatable(self).__call = Decoder.sink end function Decoder.sink(self) local sink = coroutine.create(self.dispatch) return function(...) return coroutine.resume(sink, self, ...) end end function Decoder.get(self) return self.data end function Decoder.dispatch(self, chunk, src_err, strict) local robject, object local oset = false while chunk do while chunk and #chunk < 1 do chunk = self:fetch() end assert(not strict or chunk, "Unexpected EOS") if not chunk then break end local char = chunk:sub(1, 1) local parser = self.parsers[char] or (char:match("%s") and self.parse_space) or (char:match("[0-9-]") and self.parse_number) or error("Unexpected char '%s'" % char) chunk, robject = parser(self, chunk) if parser ~= self.parse_space then assert(not oset, "Scope violation: Too many objects") object = robject oset = true if strict then return chunk, object end end end assert(not src_err, src_err) assert(oset, "Unexpected EOS") self.data = object end function Decoder.fetch(self) local tself, chunk, src_err = coroutine.yield() assert(chunk or not src_err, src_err) return chunk end function Decoder.fetch_atleast(self, chunk, bytes) while #chunk < bytes do local nchunk = self:fetch() assert(nchunk, "Unexpected EOS") chunk = chunk .. nchunk end return chunk end function Decoder.fetch_until(self, chunk, pattern) local start = chunk:find(pattern) while not start do local nchunk = self:fetch() assert(nchunk, "Unexpected EOS") chunk = chunk .. nchunk start = chunk:find(pattern) end return chunk, start end function Decoder.parse_space(self, chunk) local start = chunk:find("[^%s]") while not start do chunk = self:fetch() if not chunk then return nil end start = chunk:find("[^%s]") end return chunk:sub(start) end function Decoder.parse_literal(self, chunk, literal, value) chunk = self:fetch_atleast(chunk, #literal) assert(chunk:sub(1, #literal) == literal, "Invalid character sequence") return chunk:sub(#literal + 1), value end function Decoder.parse_null(self, chunk) return self:parse_literal(chunk, "null", self.cnull and null) end function Decoder.parse_true(self, chunk) return self:parse_literal(chunk, "true", true) end function Decoder.parse_false(self, chunk) return self:parse_literal(chunk, "false", false) end function Decoder.parse_number(self, chunk) local chunk, start = self:fetch_until(chunk, "[^0-9eE.+-]") local number = tonumber(chunk:sub(1, start - 1)) assert(number, "Invalid number specification") return chunk:sub(start), number end function Decoder.parse_string(self, chunk) local str = "" local object = nil assert(chunk:sub(1, 1) == '"', 'Expected "') chunk = chunk:sub(2) while true do local spos = chunk:find('[\\"]') if spos then str = str .. chunk:sub(1, spos - 1) local char = chunk:sub(spos, spos) if char == '"' then -- String end chunk = chunk:sub(spos + 1) break elseif char == "\\" then -- Escape sequence chunk, object = self:parse_escape(chunk:sub(spos)) str = str .. object end else str = str .. chunk chunk = self:fetch() assert(chunk, "Unexpected EOS while parsing a string") end end return chunk, str end function Decoder.utf8_encode(self, s1, s2) local n = s1 * 256 + s2 if n >= 0 and n <= 0x7F then return char(n) elseif n >= 0 and n <= 0x7FF then return char( bor(band(rshift(n, 6), 0x1F), 0xC0), bor(band(n, 0x3F), 0x80) ) elseif n >= 0 and n <= 0xFFFF then return char( bor(band(rshift(n, 12), 0x0F), 0xE0), bor(band(rshift(n, 6), 0x3F), 0x80), bor(band(n, 0x3F), 0x80) ) elseif n >= 0 and n <= 0x10FFFF then return char( bor(band(rshift(n, 18), 0x07), 0xF0), bor(band(rshift(n, 12), 0x3F), 0x80), bor(band(rshift(n, 6), 0x3F), 0x80), bor(band(n, 0x3F), 0x80) ) else return "?" end end function Decoder.parse_escape(self, chunk) local str = "" chunk = self:fetch_atleast(chunk:sub(2), 1) local char = chunk:sub(1, 1) chunk = chunk:sub(2) if char == '"' then return chunk, '"' elseif char == "\\" then return chunk, "\\" elseif char == "u" then chunk = self:fetch_atleast(chunk, 4) local s1, s2 = chunk:sub(1, 2), chunk:sub(3, 4) s1, s2 = tonumber(s1, 16), tonumber(s2, 16) assert(s1 and s2, "Invalid Unicode character") return chunk:sub(5), self:utf8_encode(s1, s2) elseif char == "/" then return chunk, "/" elseif char == "b" then return chunk, "\b" elseif char == "f" then return chunk, "\f" elseif char == "n" then return chunk, "\n" elseif char == "r" then return chunk, "\r" elseif char == "t" then return chunk, "\t" else error("Unexpected escaping sequence '\\%s'" % char) end end function Decoder.parse_array(self, chunk) chunk = chunk:sub(2) local array = {} local nextp = 1 local chunk, object = self:parse_delimiter(chunk, "%]") if object then return chunk, array end repeat chunk, object = self:dispatch(chunk, nil, true) table.insert(array, nextp, object) nextp = nextp + 1 chunk, object = self:parse_delimiter(chunk, ",%]") assert(object, "Delimiter expected") until object == "]" return chunk, array end function Decoder.parse_object(self, chunk) chunk = chunk:sub(2) local array = {} local name local chunk, object = self:parse_delimiter(chunk, "}") if object then return chunk, array end repeat chunk = self:parse_space(chunk) assert(chunk, "Unexpected EOS") chunk, name = self:parse_string(chunk) chunk, object = self:parse_delimiter(chunk, ":") assert(object, "Separator expected") chunk, object = self:dispatch(chunk, nil, true) array[name] = object chunk, object = self:parse_delimiter(chunk, ",}") assert(object, "Delimiter expected") until object == "}" return chunk, array end function Decoder.parse_delimiter(self, chunk, delimiter) while true do chunk = self:fetch_atleast(chunk, 1) local char = chunk:sub(1, 1) if char:match("%s") then chunk = self:parse_space(chunk) assert(chunk, "Unexpected EOS") elseif char:match("[%s]" % delimiter) then return chunk:sub(2), char else return chunk, nil end end end Decoder.parsers = { ['"'] = Decoder.parse_string, ['t'] = Decoder.parse_true, ['f'] = Decoder.parse_false, ['n'] = Decoder.parse_null, ['['] = Decoder.parse_array, ['{'] = Decoder.parse_object } ActiveDecoder = util.class(Decoder) function ActiveDecoder.__init__(self, source, customnull) Decoder.__init__(self, customnull) self.source = source self.chunk = nil getmetatable(self).__call = self.get end function ActiveDecoder.get(self) local chunk, src_err, object if not self.chunk then chunk, src_err = self.source() else chunk = self.chunk end self.chunk, object = self:dispatch(chunk, src_err, true) return object end function ActiveDecoder.fetch(self) local chunk, src_err = self.source() assert(chunk or not src_err, src_err) return chunk end
apache-2.0
geanux/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Chemioue.lua
38
1044
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Chemioue -- Type: NPC Quest -- @zone: 26 -- @pos 82.041 -34.964 67.636 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0118); 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
PhearNet/scanner
bin/nmap-openshift/nselib/dns.lua
3
53327
--- -- Simple DNS library supporting packet creation, encoding, decoding, -- and querying. -- -- The most common interface to this module are the <code>query</code> and -- <code>reverse</code> functions. <code>query</code> performs a DNS query, -- and <code>reverse</code> prepares an ip address to have a reverse query -- performed. -- -- <code>query</code> takes two options - a domain name to look up and an -- optional table of options. For more information on the options table, -- see the documentation for <code>query</code>. -- -- Example usage: -- <code> -- -- After this call, <code>status</code> is <code>true</code> and <code>result</code> is <code>"72.14.204.104"</code> -- local status, result = dns.query('www.google.ca') -- -- -- After this call, <code>status</code> is <code>false</code> and <code>result</code> is <code>"No such name"</code> -- local status, result = dns.query('www.google.abc') -- -- -- After this call, <code>status</code> is <code>true</code> and <code>result</code> is the table <code>{"72.14.204.103", "72.14.204.104", "72.14.204.147", "72.14.204.99"}</code> -- local status, result = dns.query('www.google.ca', {retAll=true}) -- -- -- After this call, <code>status</code> is <code>true</code> and <code>result</code> is the <code>"2001:19f0:0:0:0:dead:beef:cafe"</code> -- local status, result = dns.query('irc.ipv6.efnet.org', {dtype='AAAA'}) --</code> -- -- -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html local bin = require "bin" local bit = require "bit" local coroutine = require "coroutine" local ipOps = require "ipOps" local nmap = require "nmap" local stdnse = require "stdnse" local string = require "string" local table = require "table" local base32 = require "base32" local unittest = require "unittest" _ENV = stdnse.module("dns", stdnse.seeall) get_servers = nmap.get_dns_servers --- -- Table of DNS resource types. -- @name types -- @class table types = { A = 1, NS = 2, SOA = 6, CNAME = 5, PTR = 12, HINFO = 13, MX = 15, TXT = 16, AAAA = 28, SRV = 33, OPT = 41, SSHFP = 44, NSEC = 47, NSEC3 = 50, AXFR = 252, ANY = 255 } CLASS = { IN = 1, CH = 3, ANY = 255 } --- -- Repeatedly sends UDP packets to host, waiting for an answer. -- @param data Data to be sent. -- @param host Host to connect to. -- @param port Port to connect to. -- @param timeout Number of ms to wait for a response. -- @param cnt Number of tries. -- @param multiple If true, keep reading multiple responses until timeout. -- @return Status (true or false). -- @return Response (if status is true). local function sendPacketsUDP(data, host, port, timeout, cnt, multiple) local socket = nmap.new_socket("udp") local responses = {} socket:set_timeout(timeout) if ( not(multiple) ) then socket:connect( host, port, "udp" ) end for i = 1, cnt do local status, err if ( multiple ) then status, err = socket:sendto(host, port, data) else status, err = socket:send(data) end if (not(status)) then return false, err end local response if ( multiple ) then while(true) do status, response = socket:receive() if( not(status) ) then break end local status, _, _, ip, _ = socket:get_info() table.insert(responses, { data = response, peer = ip } ) end else status, response = socket:receive() if ( status ) then local status, _, _, ip, _ = socket:get_info() table.insert(responses, { data = response, peer = ip } ) end end if (#responses>0) then socket:close() return true, responses end end socket:close() return false end --- -- Send TCP DNS query -- @param data Data to be sent. -- @param host Host to connect to. -- @param port Port to connect to. -- @param timeout Number of ms to wait for a response. -- @return Status (true or false). -- @return Response (if status is true). local function sendPacketsTCP(data, host, port, timeout) local socket = nmap.new_socket() local response local responses = {} socket:set_timeout(timeout) socket:connect(host, port) -- add payload size we are assuming a minimum size here of 256? local send_data = '\000' .. string.char(#data) .. data socket:send(send_data) local response = '' local got_response = false while true do local status, recv_data = socket:receive_bytes(1) if not status then break end got_response = true response = response .. recv_data end local status, _, _, ip, _ = socket:get_info() socket:close() if not got_response then return false end -- remove payload size table.insert(responses, { data = string.sub(response,3), peer = ip } ) return true, responses end --- -- Call appropriate protocol handler -- @param data Data to be sent. -- @param host Host to connect to. -- @param port Port to connect to. -- @param timeout Number of ms to wait for a response. -- @param cnt Number of tries. -- @param multiple If true, keep reading multiple responses until timeout. -- @return Status (true or false). local function sendPackets(data, host, port, timeout, cnt, multiple, proto) if proto == nil or proto == 'udp' then return sendPacketsUDP(data, host, port, timeout, cnt, multiple) else return sendPacketsTCP(data, host, port, timeout) end end --- -- Checks if a DNS response packet contains a useful answer. -- @param rPkt Decoded DNS response packet. -- @return True if useful, false if not. local function gotAnswer(rPkt) -- have we even got answers? if #rPkt.answers > 0 then -- some MDNS implementation incorrectly return an empty question section -- if this is the case return true if rPkt.questions[1] == nil then return true end -- are those answers not just cnames? if rPkt.questions[1].dtype == types.A then for _, v in ipairs(rPkt.answers) do -- if at least one answer is an A record, it's an answer if v.dtype == types.A then return true end end -- if none was an A record, it's not really an answer return false else -- there was no A request, CNAMEs are not of interest return true end -- no such name is the answer elseif rPkt.flags.RC3 and rPkt.flags.RC4 then return true -- really no answer else return false end end --- -- Tries to find the next nameserver with authority to get a result for -- query. -- @param rPkt Decoded DNS response packet -- @return String or table of next server(s) to query, or false. local function getAuthDns(rPkt) if #rPkt.auth == 0 then if #rPkt.answers == 0 then return false else if rPkt.answers[1].dtype == types.CNAME then return {cname = rPkt.answers[1].domain} end end end if rPkt.auth[1].dtype == types.NS then if #rPkt.add > 0 then local hosts = {} for _, v in ipairs(rPkt.add) do if v.dtype == types.A then table.insert(hosts, v.ip) end end if #hosts > 0 then return hosts end end local status, next = query(rPkt.auth[1].domain, {dtype = "A" }) return next end return false end local function processResponse( response, dname, dtype, options ) local rPkt = decode(response) -- is it a real answer? if gotAnswer(rPkt) then if (options.retPkt) then return true, rPkt else return findNiceAnswer(dtype, rPkt, options.retAll) end elseif ( not(options.noauth) ) then -- if not, ask the next server in authority local next_server = getAuthDns(rPkt) -- if we got a CNAME, ask for the CNAME if type(next_server) == 'table' and next_server.cname then options.tries = options.tries - 1 return query(next_server.cname, options) end -- only ask next server in authority, if -- we got an auth dns and -- it isn't the one we just asked if next_server and next_server ~= options.host and options.tries > 1 then options.host = next_server options.tries = options.tries - 1 return query(dname, options) end elseif ( options.retPkt ) then return true, rPkt end -- nothing worked stdnse.debug1("dns.query() failed to resolve the requested query%s%s", dname and ": " or ".", dname or "") return false, "No Answers" end --- -- Query DNS servers for a DNS record. -- @param dname Desired domain name entry. -- @param options A table containing any of the following fields: -- * <code>dtype</code>: Desired DNS record type (default: <code>"A"</code>). -- * <code>host</code>: DNS server to be queried (default: DNS servers known to Nmap). -- * <code>port</code>: Port of DNS server to connect to (default: <code>53</code>). -- * <code>tries</code>: How often should <code>query</code> try to contact another server (for non-recursive queries). -- * <code>retAll</code>: Return all answers, not just the first. -- * <code>retPkt</code>: Return the packet instead of using the answer-fetching mechanism. -- * <code>norecurse</code>: If true, do not set the recursion (RD) flag. -- * <code>noauth</code>: If true, do not try to find authoritative server -- * <code>multiple</code>: If true, expects multiple hosts to respond to multicast request -- * <code>flags</code>: numeric value to set flags in the DNS query to a specific value -- * <code>id</code>: numeric value to use for the DNS transaction id -- * <code>nsid</code>: If true, queries the server for the nameserver identifier (RFC 5001) -- * <code>subnet</code>: table, if set perform a edns-client-subnet lookup. The table should contain the fields: -- <code>family</code> - string can be either inet or inet6 -- <code>address</code> - string containing the originating subnet IP address -- <code>mask</code> - number containing the number of subnet bits -- @return <code>true</code> if a dns response was received and contained an answer of the requested type, -- or the decoded dns response was requested (retPkt) and is being returned - or <code>false</code> otherwise. -- @return String answer of the requested type, table of answers or a String error message of one of the following: -- "No Such Name", "No Servers", "No Answers", "Unable to handle response" function query(dname, options) if not options then options = {} end local dtype, host, port, proto = options.dtype, options.host, options.port, options.proto if proto == nil then proto = 'udp' end if port == nil then port = '53' end local class = options.class or CLASS.IN if not options.tries then options.tries = 10 end -- don't get into an infinite loop if not options.sendCount then options.sendCount = 2 end if type( options.timeout ) ~= "number" then options.timeout = get_default_timeout() end if type(dtype) == "string" then dtype = types[dtype] end if not dtype then dtype = types.A end local srv local srvI = 1 if not port then port = 53 end if not host then srv = get_servers() if srv and srv[1] then host = srv[1] else return false, "No Servers" end elseif type(host) == "table" then srv = host host = srv[1] end local pkt = newPacket() addQuestion(pkt, dname, dtype, class) if options.norecurse then pkt.flags.RD = false end local dnssec = {} if ( options.dnssec ) then dnssec = { DO = true } end if ( options.nsid ) then addNSID(pkt, dnssec) elseif ( options.subnet ) then local family = { ["inet"] = 1, ["inet6"] = 2 } assert( family[options.subnet.family], "Unsupported subnet family") options.subnet.family = family[options.subnet.family] addClientSubnet(pkt, dnssec, options.subnet ) elseif ( dnssec.DO ) then addOPT(pkt, {DO = true}) end if ( options.flags ) then pkt.flags.raw = options.flags end if ( options.id ) then pkt.id = options.id end local data = encode(pkt) local status, response = sendPackets(data, host, port, options.timeout, options.sendCount, options.multiple, proto) -- if working with know nameservers, try the others while((not status) and srv and srvI < #srv) do srvI = srvI + 1 host = srv[srvI] status, response = sendPackets(data, host, port, options.timeout, options.sendCount) end -- if we got any response: if status then if ( options.multiple ) then local multiresponse = {} for _, r in ipairs( response ) do local status, presponse = processResponse( r.data, dname, dtype, options ) if( status ) then table.insert( multiresponse, { ['output']=presponse, ['peer']=r.peer } ) end end return true, multiresponse else return processResponse( response[1].data, dname, dtype, options) end else stdnse.debug1("dns.query() got zero responses attempting to resolve query%s%s", dname and ": " or ".", dname or "") return false, "No Answers" end end --- -- Formats an IP address for reverse lookup. -- @param ip IP address string. -- @return "Domain"-style representation of IP as subdomain of in-addr.arpa or -- ip6.arpa. function reverse(ip) ip = ipOps.expand_ip(ip) if type(ip) ~= "string" then return nil end local delim = "%." local arpa = ".in-addr.arpa" if ip:match(":") then delim = ":" arpa = ".ip6.arpa" end local ipParts = stdnse.strsplit(delim, ip) if #ipParts == 8 then -- padding local mask = "0000" for i, part in ipairs(ipParts) do ipParts[i] = mask:sub(1, #mask - #part) .. part end -- 32 parts from 8 local temp = {} for i, hdt in ipairs(ipParts) do for part in hdt:gmatch("%x") do temp[#temp+1] = part end end ipParts = temp end local ipReverse = {} for i = #ipParts, 1, -1 do table.insert(ipReverse, ipParts[i]) end return table.concat(ipReverse, ".") .. arpa end -- Table for answer fetching functions. local answerFetcher = {} -- Answer fetcher for TXT records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns TXT record or Table of TXT records or String Error message. answerFetcher[types.TXT] = function(dec, retAll) local answers = {} if not retAll and dec.answers[1].data then return true, string.sub(dec.answers[1].data, 2) elseif not retAll then stdnse.debug1("dns.answerFetcher found no records of the required type: TXT") return false, "No Answers" else for _, v in ipairs(dec.answers) do if v.TXT and v.TXT.text then for _, v in ipairs( v.TXT.text ) do table.insert(answers, v) end end end end if #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: TXT") return false, "No Answers" end return true, answers end -- Answer fetcher for A records -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns A record or Table of A records or String Error message. answerFetcher[types.A] = function(dec, retAll) local answers = {} for _, ans in ipairs(dec.answers) do if ans.dtype == types.A then if not retAll then return true, ans.ip end table.insert(answers, ans.ip) end end if not retAll or #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: A") return false, "No Answers" end return true, answers end -- Answer fetcher for CNAME records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first Domain entry or Table of domain entries or String Error message. answerFetcher[types.CNAME] = function(dec, retAll) local answers = {} if not retAll and dec.answers[1].domain then return true, dec.answers[1].domain elseif not retAll then stdnse.debug1("dns.answerFetcher found no records of the required type: NS, PTR or CNAME") return false, "No Answers" else for _, v in ipairs(dec.answers) do if v.domain then table.insert(answers, v.domain) end end end if #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: NS, PTR or CNAME") return false, "No Answers" end return true, answers end -- Answer fetcher for MX records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns MX record or Table of MX records or String Error message. -- Note that the format of a returned MX answer is "preference:hostname:IPaddress" where zero -- or more IP addresses may be present. answerFetcher[types.MX] = function(dec, retAll) local mx, ip, answers = {}, {}, {} for _, ans in ipairs(dec.answers) do if ans.MX then mx[#mx+1] = ans.MX end if not retAll then break end end if #mx == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: MX") return false, "No Answers" end for _, add in ipairs(dec.add) do if ip[add.dname] then table.insert(ip[add.dname], add.ip) else ip[add.dname] = {add.ip} end end for _, mxrec in ipairs(mx) do if ip[mxrec.server] then table.insert( answers, ("%s:%s:%s"):format(mxrec.pref or "-", mxrec.server or "-", table.concat(ip[mxrec.server], ":")) ) if not retAll then return true, answers[1] end else -- no IP ? table.insert( answers, ("%s:%s"):format(mxrec.pref or "-", mxrec.server or "-") ) if not retAll then return true, answers[1] end end end return true, answers end -- Answer fetcher for SRV records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns SRV record or Table of SRV records or String Error message. -- Note that the format of a returned SRV answer is "priority:weight:port:target" where zero -- or more IP addresses may be present. answerFetcher[types.SRV] = function(dec, retAll) local srv, ip, answers = {}, {}, {} for _, ans in ipairs(dec.answers) do if ans.dtype == types.SRV then if not retAll then return true, ("%s:%s:%s:%s"):format( ans.SRV.prio, ans.SRV.weight, ans.SRV.port, ans.SRV.target ) end table.insert( answers, ("%s:%s:%s:%s"):format( ans.SRV.prio, ans.SRV.weight, ans.SRV.port, ans.SRV.target ) ) end end if #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: SRV") return false, "No Answers" end return true, answers end -- Answer fetcher for NSEC records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns NSEC record or Table of NSEC records or String Error message. -- Note that the format of a returned NSEC answer is "name:dname:types". answerFetcher[types.NSEC] = function(dec, retAll) local nsec, answers = {}, {} for _, auth in ipairs(dec.auth) do if auth.NSEC then nsec[#nsec+1] = auth.NSEC end if not retAll then break end end if #nsec == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: NSEC") return false, "No Answers" end for _, nsecrec in ipairs(nsec) do table.insert( answers, ("%s:%s:%s"):format(nsecrec.name or "-", nsecrec.dname or "-", stdnse.strjoin(":", nsecrec.types) or "-")) end if not retAll then return true, answers[1] end return true, answers end -- Answer fetcher for NS records. -- @name answerFetcher[types.NS] -- @class function -- @param dec Decoded DNS response. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first Domain entry or Table of domain entries or String Error message. answerFetcher[types.NS] = answerFetcher[types.CNAME] -- Answer fetcher for PTR records. -- @name answerFetcher[types.PTR] -- @class function -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first Domain entry or Table of domain entries or String Error message. answerFetcher[types.PTR] = answerFetcher[types.CNAME] -- Answer fetcher for AAAA records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns AAAA record or Table of AAAA records or String Error message. answerFetcher[types.AAAA] = function(dec, retAll) local answers = {} for _, ans in ipairs(dec.answers) do if ans.dtype == types.AAAA then if not retAll then return true, ans.ipv6 end table.insert(answers, ans.ipv6) end end if not retAll or #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: AAAA") return false, "No Answers" end return true, answers end ---Calls the answer fetcher for <code>dtype</code> or returns an error code in -- case of a "no such name" error. -- -- @param dtype DNS resource record type. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return Answer according to the answer fetcher for <code>dtype</code> or an Error message. function findNiceAnswer(dtype, dec, retAll) if (#dec.answers > 0) then if answerFetcher[dtype] then return answerFetcher[dtype](dec, retAll) else stdnse.debug1("dns.findNiceAnswer() does not have an answerFetcher for dtype %s", tostring(dtype)) return false, "Unable to handle response" end elseif (dec.flags.RC3 and dec.flags.RC4) then return false, "No Such Name" else stdnse.debug1("dns.findNiceAnswer() found zero answers in a response, but got an unexpected flags.replycode") return false, "No Answers" end end -- Table for additional fetching functions. -- Some servers return their answers in the additional section. The -- findNiceAdditional function with its relevant additionalFetcher functions -- addresses this. This unfortunately involved some code duplication (because -- of current design of the dns library) from the answerFetchers to the -- additionalFetchers. local additionalFetcher = {} -- Additional fetcher for TXT records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns TXT record or Table of TXT records or String Error message. additionalFetcher[types.TXT] = function(dec, retAll) local answers = {} if not retAll and dec.add[1].data then return true, string.sub(dec.add[1].data, 2) elseif not retAll then stdnse.debug1("dns.additionalFetcher found no records of the required type: TXT") return false, "No Answers" else for _, v in ipairs(dec.add) do if v.TXT and v.TXT.text then for _, v in ipairs( v.TXT.text ) do table.insert(answers, v) end end end end if #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: TXT") return false, "No Answers" end return true, answers end -- Additional fetcher for A records -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns A record or Table of A records or String Error message. additionalFetcher[types.A] = function(dec, retAll) local answers = {} for _, ans in ipairs(dec.add) do if ans.dtype == types.A then if not retAll then return true, ans.ip end table.insert(answers, ans.ip) end end if not retAll or #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: A") return false, "No Answers" end return true, answers end -- Additional fetcher for SRV records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns SRV record or Table of SRV records or String Error message. -- Note that the format of a returned SRV answer is "priority:weight:port:target" where zero -- or more IP addresses may be present. additionalFetcher[types.SRV] = function(dec, retAll) local srv, ip, answers = {}, {}, {} for _, ans in ipairs(dec.add) do if ans.dtype == types.SRV then if not retAll then return true, ("%s:%s:%s:%s"):format( ans.SRV.prio, ans.SRV.weight, ans.SRV.port, ans.SRV.target ) end table.insert( answers, ("%s:%s:%s:%s"):format( ans.SRV.prio, ans.SRV.weight, ans.SRV.port, ans.SRV.target ) ) end end if #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: SRV") return false, "No Answers" end return true, answers end -- Additional fetcher for AAAA records. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return String first dns AAAA record or Table of AAAA records or String Error message. additionalFetcher[types.AAAA] = function(dec, retAll) local answers = {} for _, ans in ipairs(dec.add) do if ans.dtype == types.AAAA then if not retAll then return true, ans.ipv6 end table.insert(answers, ans.ipv6) end end if not retAll or #answers == 0 then stdnse.debug1("dns.answerFetcher found no records of the required type: AAAA") return false, "No Answers" end return true, answers end --- -- Calls the answer fetcher for <code>dtype</code> or returns an error code in -- case of a "no such name" error. -- @param dtype DNS resource record type. -- @param dec Decoded DNS response. -- @param retAll If true, return all entries, not just the first. -- @return True if one or more answers of the required type were found - otherwise false. -- @return Answer according to the answer fetcher for <code>dtype</code> or an Error message. function findNiceAdditional(dtype, dec, retAll) if (#dec.add > 0) then if additionalFetcher[dtype] then return additionalFetcher[dtype](dec, retAll) else stdnse.debug1("dns.findNiceAdditional() does not have an additionalFetcher for dtype %s", (type(dtype) == 'string' and dtype) or type(dtype) or "nil") return false, "Unable to handle response" end elseif (dec.flags.RC3 and dec.flags.RC4) then return false, "No Such Name" else stdnse.debug1("dns.findNiceAdditional() found zero answers in a response, but got an unexpected flags.replycode") return false, "No Answers" end end -- -- Encodes a FQDN -- @param fqdn containing the fully qualified domain name -- @return encQ containing the encoded value local function encodeFQDN(fqdn) if ( not(fqdn) or #fqdn == 0 ) then return "\0" end local encQ = {} for part in string.gmatch(fqdn, "[^%.]+") do encQ[#encQ+1] = bin.pack("p", part) end encQ[#encQ+1] = "\0" return table.concat(encQ) end --- -- Encodes the question part of a DNS request. -- @param questions Table of questions. -- @return Encoded question string. local function encodeQuestions(questions) if type(questions) ~= "table" then return nil end local encQ = {} for _, v in ipairs(questions) do encQ[#encQ+1] = encodeFQDN(v.dname) encQ[#encQ+1] = bin.pack(">SS", v.dtype, v.class) end return table.concat(encQ) end --- -- Encodes the zone part of a DNS request. -- @param questions Table of questions. -- @return Encoded question string. local function encodeZones(zones) return encodeQuestions(zones) end local function encodeUpdates(updates) if type(updates) ~= "table" then return nil end local encQ = {} for _, v in ipairs(updates) do encQ[#encQ+1] = encodeFQDN(v.dname) encQ[#encQ+1] = bin.pack(">SSISA", v.dtype, v.class, v.ttl, #v.data, v.data) end return table.concat(encQ) end --- -- Encodes the additional part of a DNS request. -- @param additional Table of additional records. Each must have the keys -- <code>type</code>, <code>class</code>, <code>ttl</code>, <code>rdlen</code>, -- and <code>rdata</code>. -- @return Encoded additional string. local function encodeAdditional(additional) if type(additional) ~= "table" then return nil end local encA = {} for _, v in ipairs(additional) do encA[#encA+1] = bin.pack(">xSSISA", v.type, v.class, v.ttl, v.rdlen, v.rdata) end return table.concat(encA) end --- -- Encodes DNS flags to a binary digit string. -- @param flags Flag table, each entry representing a flag (QR, OCx, AA, TC, RD, -- RA, RCx). -- @return Binary digit string representing flags. local function encodeFlags(flags) if type(flags) == "string" then return flags end if type(flags) ~= "table" then return nil end local fb = "" if flags.QR then fb = fb .. "1" else fb = fb .. "0" end if flags.OC1 then fb = fb .. "1" else fb = fb .. "0" end if flags.OC2 then fb = fb .. "1" else fb = fb .. "0" end if flags.OC3 then fb = fb .. "1" else fb = fb .. "0" end if flags.OC4 then fb = fb .. "1" else fb = fb .. "0" end if flags.AA then fb = fb .. "1" else fb = fb .. "0" end if flags.TC then fb = fb .. "1" else fb = fb .. "0" end if flags.RD then fb = fb .. "1" else fb = fb .. "0" end if flags.RA then fb = fb .. "1" else fb = fb .. "0" end fb = fb .. "000" if flags.RC1 then fb = fb .. "1" else fb = fb .. "0" end if flags.RC2 then fb = fb .. "1" else fb = fb .. "0" end if flags.RC3 then fb = fb .. "1" else fb = fb .. "0" end if flags.RC4 then fb = fb .. "1" else fb = fb .. "0" end return fb end --- -- Encode a DNS packet. -- -- Caution: doesn't encode answer and authority part. -- @param pkt Table representing DNS packet, initialized by -- <code>newPacket</code>. -- @return Encoded DNS packet. function encode(pkt) if type(pkt) ~= "table" then return nil end local encFlags = encodeFlags(pkt.flags) local additional = encodeAdditional(pkt.additional) local aorplen = #pkt.answers local data, qorzlen, aorulen if ( #pkt.questions > 0 ) then data = encodeQuestions( pkt.questions ) qorzlen = #pkt.questions aorulen = 0 else -- The packet has no questions, assume we're dealing with an update data = encodeZones( pkt.zones ) .. encodeUpdates( pkt.updates ) qorzlen = #pkt.zones aorulen = #pkt.updates end local encStr if ( pkt.flags.raw ) then encStr = bin.pack(">SSS4", pkt.id, pkt.flags.raw, qorzlen, aorplen, aorulen, #pkt.additional) .. data .. additional else encStr = bin.pack(">SBS4", pkt.id, encFlags, qorzlen, aorplen, aorulen, #pkt.additional) .. data .. additional end return encStr end --- -- Decodes a domain in a DNS packet. Handles "compressed" data too. -- @param data Complete DNS packet. -- @param pos Starting position in packet. -- @return Position after decoding. -- @return Decoded domain, or <code>nil</code> on error. function decStr(data, pos) local function dec(data, pos, limit) local partlen local parts = {} local part -- Avoid infinite recursion on malformed compressed messages. limit = limit or 10 if limit < 0 then return pos, nil end pos, partlen = bin.unpack(">C", data, pos) while (partlen ~= 0) do if (partlen < 64) then pos, part = bin.unpack("A" .. partlen, data, pos) if part == nil then return pos end table.insert(parts, part) pos, partlen = bin.unpack(">C", data, pos) else pos, partlen = bin.unpack(">S", data, pos - 1) local _, part = dec(data, partlen - 0xC000 + 1, limit - 1) if part == nil then return pos end table.insert(parts, part) partlen = 0 end end return pos, table.concat(parts, ".") end return dec(data, pos) end --- -- Decodes questions in a DNS packet. -- @param data Complete DNS packet. -- @param count Value of question counter in header. -- @param pos Starting position in packet. -- @return Position after decoding. -- @return Table of decoded questions. local function decodeQuestions(data, count, pos) local q = {} for i = 1, count do local currQ = {} pos, currQ.dname = decStr(data, pos) pos, currQ.dtype, currQ.class = bin.unpack(">SS", data, pos) table.insert(q, currQ) end return pos, q end --- -- Table of functions to decode resource records local decoder = {} -- Decodes IP of A record, puts it in <code>entry.ip</code>. -- @param entry RR in packet. decoder[types.A] = function(entry) local ip = {} local _ _, ip[1], ip[2], ip[3], ip[4] = bin.unpack(">C4", entry.data) entry.ip = table.concat(ip, ".") end -- Decodes IP of AAAA record, puts it in <code>entry.ipv6</code>. -- @param entry RR in packet. decoder[types.AAAA] = function(entry) local ip = {} local pos = 1 local num for i = 1, 8 do pos, num = bin.unpack(">S", entry.data, pos) table.insert(ip, string.format('%x', num)) end entry.ipv6 = table.concat(ip, ":") end -- Decodes SSH fingerprint record, puts it in <code>entry.SSHFP</code> as -- defined in RFC 4255. -- -- <code>entry.SSHFP</code> has the fields <code>algorithm</code>, -- <code>fptype</code>, and <code>fingerprint</code>. -- @param entry RR in packet. decoder[types.SSHFP] = function(entry) local _ entry.SSHFP = {} _, entry.SSHFP.algorithm, entry.SSHFP.fptype, entry.SSHFP.fingerprint = bin.unpack(">C2H" .. (#entry.data - 2), entry.data) end -- Decodes SOA record, puts it in <code>entry.SOA</code>. -- -- <code>entry.SOA</code> has the fields <code>mname</code>, <code>rname</code>, -- <code>serial</code>, <code>refresh</code>, <code>retry</code>, -- <code>expire</code>, and <code>minimum</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.SOA] = function(entry, data, pos) local np = pos - #entry.data entry.SOA = {} np, entry.SOA.mname = decStr(data, np) np, entry.SOA.rname = decStr(data, np) np, entry.SOA.serial, entry.SOA.refresh, entry.SOA.retry, entry.SOA.expire, entry.SOA.minimum = bin.unpack(">I5", data, np) end -- An iterator that returns the positions of nonzero bits in the given binary -- string. local function bit_iter(bits) return coroutine.wrap(function() for i = 1, #bits do local n = string.byte(bits, i) local j = 0 local mask = 0x80 while mask > 0 do if bit.band(n, mask) ~= 0 then coroutine.yield((i - 1) * 8 + j) end j = j + 1 mask = bit.rshift(mask, 1) end end end) end -- Decodes NSEC records, puts result in <code>entry.NSEC</code>. See RFC 4034, -- section 4. -- -- <code>entry.NSEC</code> has the fields <code>dname</code>, -- <code>next_dname</code>, and <code>types</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.NSEC] = function (entry, data, pos) local np = pos - #entry.data entry.NSEC = {} entry.NSEC.dname = entry.dname np, entry.NSEC.next_dname = decStr(data, np) while np < pos do local block_num, type_bitmap np, block_num, type_bitmap = bin.unpack(">Cp", data, np) entry.NSEC.types = {} for i in bit_iter(type_bitmap) do entry.NSEC.types[(block_num - 1) * 256 + i] = true end end end -- Decodes NSEC3 records, puts result in <code>entry.NSEC3</code>. See RFC 5155. -- -- <code>entry.NSEC3</code> has the fields <code>dname</code>, -- <code>hash.alg</code>, and <code>hash.base32</code>. -- <code>hash.bin</code>, and <code>hash.hex</code>. -- <code>salt.bin</code>, and <code>salt.hex</code>. -- <code>iterations</code>, and <code>types</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.NSEC3] = function (entry, data, pos) local np = pos - #entry.data local _ local flags entry.NSEC3 = {} entry.NSEC3.dname = entry.dname entry.NSEC3.salt, entry.NSEC3.hash = {}, {} np, entry.NSEC3.hash.alg,flags,entry.NSEC3.iterations = bin.unpack(">CBS", data, np) -- do we even need to decode these do we care about opt out? -- entry.NSEC3.flags = decodeFlagsNSEC3(flags) np, entry.NSEC3.salt.bin = bin.unpack(">p", data, np) _, entry.NSEC3.salt.hex = bin.unpack("H" .. #entry.NSEC3.salt.bin, entry.NSEC3.salt.bin) np, entry.NSEC3.hash.bin = bin.unpack(">p" , data, np) _, entry.NSEC3.hash.hex = bin.unpack(">H" .. #entry.NSEC3.hash.bin , entry.NSEC3.hash.bin) entry.NSEC3.hash.base32 = base32.enc(entry.NSEC3.hash.bin, true) np, entry.NSEC3.WinBlockNo, entry.NSEC3.bmplength = bin.unpack(">CC", data, np) np, entry.NSEC3.bin = bin.unpack(">B".. entry.NSEC3.bmplength, data, np) entry.NSEC3.types = {} if entry.NSEC3.bin == nil then entry.NSEC3.bin = "" end for i=1, string.len(entry.NSEC3.bin) do local bit = string.sub(entry.NSEC3.bin,i,i) if bit == "1" then table.insert(entry.NSEC3.types, (entry.NSEC3.WinBlockNo*256+i-1)) end end end -- Decodes records that consist only of one domain, for example CNAME, NS, PTR. -- Puts result in <code>entry.domain</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. local function decDomain(entry, data, pos) local np = pos - #entry.data local _ _, entry.domain = decStr(data, np) end -- Decodes CNAME records. -- Puts result in <code>entry.domain</code>. -- @name decoder[types.CNAME] -- @class function -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.CNAME] = decDomain -- Decodes NS records. -- Puts result in <code>entry.domain</code>. -- @name decoder[types.NS] -- @class function -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.NS] = decDomain -- Decodes PTR records. -- Puts result in <code>entry.domain</code>. -- @name decoder[types.PTR] -- @class function -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.PTR] = decDomain -- Decodes TXT records. -- Puts result in <code>entry.domain</code>. -- @name decoder[types.TXT] -- @class function -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.TXT] = function (entry, data, pos) local len = entry.data:len() local np = pos - #entry.data local txt_len local txt if len > 0 then entry.TXT = {} entry.TXT.text = {} end while len > 0 do np, txt_len = bin.unpack("C", data, np) np, txt = bin.unpack("A" .. txt_len, data, np ) len = len - txt_len - 1 table.insert( entry.TXT.text, txt ) end end --- -- Decodes OPT record, puts it in <code>entry.OPT</code>. -- -- <code>entry.OPT</code> has the fields <code>mname</code>, <code>rname</code>, -- <code>serial</code>, <code>refresh</code>, <code>retry</code>, -- <code>expire</code>, and <code>minimum</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.OPT] = function(entry, data, pos) local np = pos - #entry.data - 6 local opt = { bufsize = entry.class } np, opt.rcode, opt.version, opt.zflags, opt.rdlen = bin.unpack(">CCSS", data, np) np, opt.data = bin.unpack("A" .. opt.rdlen, data, np) entry.OPT = opt end -- Decodes MX record, puts it in <code>entry.MX</code>. -- -- <code>entry.MX</code> has the fields <code>pref</code> and -- <code>server</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.MX] = function(entry, data, pos) local np = pos - #entry.data + 2 local _ entry.MX = {} _, entry.MX.pref = bin.unpack(">S", entry.data) _, entry.MX.server = decStr(data, np) end -- Decodes SRV record, puts it in <code>entry.SRV</code>. -- -- <code>entry.SRV</code> has the fields <code>prio</code>, -- <code>weight</code>, <code>port</code> and -- <code>target</code>. -- @param entry RR in packet. -- @param data Complete encoded DNS packet. -- @param pos Position in packet after RR. decoder[types.SRV] = function(entry, data, pos) local np = pos - #entry.data local _ entry.SRV = {} np, entry.SRV.prio, entry.SRV.weight, entry.SRV.port = bin.unpack(">S>S>S", data, np) np, entry.SRV.target = decStr(data, np) end -- Decodes returned resource records (answer, authority, or additional part). -- @param data Complete encoded DNS packet. -- @param count Value of according counter in header. -- @param pos Starting position in packet. -- @return Table of RRs. local function decodeRR(data, count, pos) local ans = {} for i = 1, count do local currRR = {} pos, currRR.dname = decStr(data, pos) pos, currRR.dtype, currRR.class, currRR.ttl = bin.unpack(">SSI", data, pos) local reslen pos, reslen = bin.unpack(">S", data, pos) pos, currRR.data = bin.unpack("A" .. reslen, data, pos) -- try to be smart: decode per type if decoder[currRR.dtype] then decoder[currRR.dtype](currRR, data, pos) end table.insert(ans, currRR) end return pos, ans end --- -- Splits a string up into a table of single characters. -- @param str String to be split up. -- @return Table of characters. local function str2tbl(str) local tbl = {} for i = 1, #str do table.insert(tbl, string.sub(str, i, i)) end return tbl end --- -- Decodes DNS flags. -- @param flgStr Flags as a binary digit string. -- @return Table representing flags. local function decodeFlags(flgStr) local flags = {} local flgTbl = str2tbl(flgStr) if flgTbl[1] == '1' then flags.QR = true end if flgTbl[2] == '1' then flags.OC1 = true end if flgTbl[3] == '1' then flags.OC2 = true end if flgTbl[4] == '1' then flags.OC3 = true end if flgTbl[5] == '1' then flags.OC4 = true end if flgTbl[6] == '1' then flags.AA = true end if flgTbl[7] == '1' then flags.TC = true end if flgTbl[8] == '1' then flags.RD = true end if flgTbl[9] == '1' then flags.RA = true end if flgTbl[13] == '1' then flags.RC1 = true end if flgTbl[14] == '1' then flags.RC2 = true end if flgTbl[15] == '1' then flags.RC3 = true end if flgTbl[16] == '1' then flags.RC4 = true end return flags end --- -- Decodes a DNS packet. -- @param data Encoded DNS packet. -- @return Table representing DNS packet. function decode(data) local pos local pkt = {} local encFlags local cnt = {} pos, pkt.id, encFlags, cnt.q, cnt.a, cnt.auth, cnt.add = bin.unpack(">SB2S4", data) -- for now, don't decode the flags pkt.flags = decodeFlags(encFlags) -- -- check whether this is an update response or not -- a quick fix to allow decoding of non updates and not break for updates -- the flags are enough for the current code to determine whether an update was successful or not -- local strflags=encodeFlags(pkt.flags) if ( strflags:sub(1,4) == "1010" ) then return pkt else pos, pkt.questions = decodeQuestions(data, cnt.q, pos) pos, pkt.answers = decodeRR(data, cnt.a, pos) pos, pkt.auth = decodeRR(data, cnt.auth, pos) pos, pkt.add = decodeRR(data, cnt.add, pos) end return pkt end --- -- Creates a new table representing a DNS packet. -- @return Table representing a DNS packet. function newPacket() local pkt = {} pkt.id = 1 pkt.flags = {} pkt.flags.RD = true pkt.questions = {} pkt.zones = {} pkt.updates = {} pkt.answers = {} pkt.auth = {} pkt.additional = {} return pkt end --- -- Adds a question to a DNS packet table. -- @param pkt Table representing DNS packet. -- @param dname Domain name to be asked. -- @param dtype RR to be asked. function addQuestion(pkt, dname, dtype, class) if type(pkt) ~= "table" then return nil end if type(pkt.questions) ~= "table" then return nil end local class = class or CLASS.IN local q = {} q.dname = dname q.dtype = dtype q.class = class table.insert(pkt.questions, q) return pkt end get_default_timeout = function() local timeout = {[0] = 10000, 7000, 5000, 4000, 4000, 4000} return timeout[nmap.timing_level()] or 4000 end --- -- Adds a zone to a DNS packet table -- @param pkt Table representing DNS packet. -- @param dname Domain name to be asked. function addZone(pkt, dname) if ( type(pkt) ~= "table" ) or (type(pkt.updates) ~= "table") then return nil end table.insert(pkt.zones, { dname=dname, dtype=types.SOA, class=CLASS.IN }) return pkt end --- -- Encodes the Z bitfield of an OPT record. -- @param flags Flag table, each entry representing a flag (only DO flag implmented). -- @return Binary digit string representing flags. local function encodeOPT_Z(flags) if type(flags) == "string" then return flags end if type(flags) ~= "table" then return nil end local bits = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} for n, k in pairs({[1] = "DO"}) do if flags[k] then bits[n] = 1 end end return table.concat(bits) end --- -- Adds an client-subnet payload to the OPT packet -- -- implementing http://tools.ietf.org/html/draft-vandergaast-edns-client-subnet-00 -- @param pkt Table representing DNS packet. -- @param Z Table of Z flags. Only DO is supported. -- @param client_subnet table containing the following fields -- <code>family</code> - 1 IPv4, 2 - IPv6 -- <code>mask</code> - byte containing the length of the subnet mask -- <code>address</code> - string containing the IP address function addClientSubnet(pkt,Z,subnet) local udp_payload_size = 4096 local code = 20730 -- temporary option-code http://comments.gmane.org/gmane.ietf.dnsext/19776 local scope_mask = 0 -- In requests, it MUST be set to 0 see draft local data = bin.pack(">SCCA",subnet.family or 1,subnet.mask,scope_mask,ipOps.ip_to_str(subnet.address)) local opt = bin.pack(">SS",code, #data) .. data addOPT(pkt,Z,opt) end --- -- Adds an NSID payload to the OPT packet -- @param pkt Table representing DNS packet. -- @param Z Table of Z flags. Only DO is supported. function addNSID (pkt,Z) local udp_payload_size = 4096 local opt = bin.pack(">SS",3, 0) -- nsid data addOPT(pkt,Z,opt) end --- -- Adds an OPT RR to a DNS packet's additional section. -- -- Only the table of Z flags is supported (i.e., not RDATA). See RFC 2671 -- section 4.3. -- @param pkt Table representing DNS packet. -- @param Z Table of Z flags. Only DO is supported. function addOPT(pkt, Z, opt) local rdata = opt or "" if type(pkt) ~= "table" then return nil end if type(pkt.additional) ~= "table" then return nil end local _, Z_int = bin.unpack(">S", bin.pack("B", encodeOPT_Z(Z))) local opt = { type = types.OPT, class = 4096, -- Actually the sender UDP payload size. ttl = 0 * (0x01000000) + 0 * (0x00010000) + Z_int, rdlen = #rdata, rdata = rdata, } table.insert(pkt.additional, opt) return pkt end --- -- Adds a update to a DNS packet table -- @param pkt Table representing DNS packet. -- @param dname Domain name to be asked. -- @param dtype to be updated -- @param ttl the time-to-live of the record -- @param data type specific data function addUpdate(pkt, dname, dtype, ttl, data, class) if ( type(pkt) ~= "table" ) or (type(pkt.updates) ~= "table") then return nil end table.insert(pkt.updates, { dname=dname, dtype=dtype, class=class, ttl=ttl, data=(data or "") } ) return pkt end --- Adds a record to the Zone -- @param dname containing the hostname to add -- @param options A table containing any of the following fields: -- * <code>dtype</code>: Desired DNS record type (default: <code>"A"</code>). -- * <code>host</code>: DNS server to be queried (default: DNS servers known to Nmap). -- * <code>timeout</code>: The time to wait for a response -- * <code>sendCount</code>: The number of send attempts to perform -- * <code>zone</code>: If not supplied deduced from hostname -- * <code>data</code>: Table or string containing update data (depending on record type): -- A - String containing the IP address -- CNAME - String containing the FQDN -- MX - Table containing <code>pref</code>, <code>mx</code> -- SRV - Table containing <code>prio</code>, <code>weight</code>, <code>port</code>, <code>target</code> -- -- @return status true on success false on failure -- @return msg containing the error message -- -- Examples -- -- Adding different types of records to a server -- * update( "www.cqure.net", { host=host, port=port, dtype="A", data="10.10.10.10" } ) -- * update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="www.cqure.net" } ) -- * update( "cqure.net", { host=host, port=port, dtype="MX", data={ pref=10, mx="mail.cqure.net"} }) -- * update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data={ prio=0, weight=100, port=389, target="ldap.cqure.net" } } ) -- -- Removing the above records by setting an empty data and a ttl of zero -- * update( "www.cqure.net", { host=host, port=port, dtype="A", data="", ttl=0 } ) -- * update( "alias.cqure.net", { host=host, port=port, dtype="CNAME", data="", ttl=0 } ) -- * update( "cqure.net", { host=host, port=port, dtype="MX", data="", ttl=0 } ) -- * update( "_ldap._tcp.cqure.net", { host=host, port=port, dtype="SRV", data="", ttl=0 } ) -- function update(dname, options) local options = options or {} local pkt = newPacket() local flags = pkt.flags local host, port = options.host, options.port local timeout = ( type(options.timeout) == "number" ) and options.timeout or get_default_timeout() local sendcount = options.sendCount or 2 local dtype = ( type(options.dtype) == "string" ) and types[options.dtype] or types.A local updata = options.data local ttl = options.ttl or 86400 local zone = options.zone or dname:match("^.-%.(.+)$") local class = CLASS.IN assert(host, "dns.update needs a valid host in options") assert(port, "dns.update needs a valid port in options") if ( options.zone ) then dname = dname .. "." .. options.zone end if ( not(zone) and not( dname:match("^.-%..+") ) ) then return false, "hostname needs to be supplied as FQDN" end flags.RD = false flags.OC1, flags.OC2, flags.OC3, flags.OC4 = false, true, false, true -- If ttl is zero and updata is string and zero length or nil, assume delete record if ( ttl == 0 and ( ( type(updata) == "string" and #updata == 0 ) or not(updata) ) ) then class = CLASS.ANY updata = "" if ( types.MX == dtype and not(options.zone) ) then zone=dname end if ( types.SRV == dtype and not(options.zone) ) then zone=dname:match("^_.-%._.-%.(.+)$") end -- if not, let's try to update the zone else if ( dtype == types.A ) then updata = updata and bin.pack(">I", ipOps.todword(updata)) or "" elseif( dtype == types.CNAME ) then updata = encodeFQDN(updata) elseif( dtype == types.MX ) then assert( not( type(updata) ~= "table" ), "dns.update expected options.data to be a table") if ( not(options.zone) ) then zone = dname end local data = bin.pack(">S", updata.pref) data = data .. encodeFQDN(updata.mx) updata = data elseif ( dtype == types.SRV ) then assert( not( type(updata) ~= "table" ), "dns.update expected options.data to be a table") local data = bin.pack(">SSS", updata.prio, updata.weight, updata.port ) data = data .. encodeFQDN(updata.target) updata = data zone = options.zone or dname:match("^_.-%._.-%.(.+)$") else return false, "Unsupported record type" end end pkt = addZone(pkt, zone) pkt = addUpdate(pkt, dname, dtype, ttl, updata, class) local data = encode(pkt) local status, response = sendPackets(data, host, port, timeout, sendcount, false) if ( status ) then local decoded = decode(response[1].data) local flags=encodeFlags(decoded.flags) if (flags:sub(-4) == "0000") then return true end end return false end if not unittest.testing() then return _ENV end -- Self test test_suite = unittest.TestSuite:new() test_suite:add_test(unittest.equal(encodeFQDN("test.me.com"), "\x04test\x02me\x03com\0"), "encodeFQDN") return _ENV;
mit
geanux/darkstar
scripts/globals/mobskills/Tebbad_Wing_Air.lua
25
1091
--------------------------------------------- -- Tebbad Wing -- -- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Tiamat, Smok and Ildebrann --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() ~= 1) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_PLAGUE; MobStatusEffectMove(mob, target, typeEffect, 10, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
kaen/Zero-K
LuaUI/Widgets/gui_chili_display_keys.lua
8
8743
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Display Keys", desc = "Displays the current key combination.", author = "GoogleFrog", date = "12 August 2015", license = "GNU GPL, v2 or later", layer = -10000, enabled = false } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- include("keysym.h.lua") local keyData, mouseData -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Options options_path = 'Settings/HUD Panels/Extras/Display Keys' options_order = { 'keyReleaseTimeout', 'mouseReleaseTimeout', } options = { keyReleaseTimeout = { name = "Key Release Timeout", type = "number", value = 0.6, min = 0, max = 5, step = 0.025, }, mouseReleaseTimeout = { name = "Mouse Release Timeout", type = "number", value = 0.3, min = 0, max = 5, step = 0.025, }, } local panelColor = {1,1,1,0.7} local highlightColor = {1,0.8, 0.1, 0.9} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Window Creation local function InitializeDisplayLabelControl(name) local data = {} local screenWidth, screenHeight = Spring.GetWindowGeometry() local window = Chili.Window:New{ parent = screen0, backgroundColor = {0, 0, 0, 0}, color = {0, 0, 0, 0}, dockable = true, name = name, padding = {0,0,0,0}, x = 0, y = 740, clientWidth = 380, clientHeight = 64, draggable = false, resizable = false, tweakDraggable = true, tweakResizable = true, minimizable = false, OnMouseDown = ShowOptions, } local mainPanel = Chili.Panel:New{ backgroundColor = {1,1,1,0.7}, color = {1,1,1, 0.7}, parent = window, padding = {0,0,0,0}, y = 0, x = 0, right = 0, bottom = 0, dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local displayLabel = Chili.Label:New{ parent = mainPanel, x = 15, y = 10, right = 10, bottom = 12, caption = "", valign = "center", align = "center", autosize = false, font = { size = 36, outline = true, outlineWidth = 2, outlineWeight = 2, }, } local function UpdateWindow(val) displayLabel:SetCaption(val) end local function Dispose() window:Dispose() end local data = { UpdateWindow = UpdateWindow, Dispose = Dispose, } return data end local function InitializeMouseButtonControl(name) local window = Chili.Window:New{ parent = screen0, backgroundColor = {0, 0, 0, 0}, color = {0, 0, 0, 0}, dockable = true, name = name, padding = {0,0,0,0}, x = 60, y = 676, clientWidth = 260, clientHeight = 64, draggable = false, resizable = false, tweakDraggable = true, tweakResizable = true, minimizable = false, OnMouseDown = ShowOptions, } local leftPanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = 0, right = "62%", bottom = 0, dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local middlePanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = "38%", right = "38%", bottom = 0, dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local rightPanel = Chili.Panel:New{ backgroundColor = panelColor, color = panelColor, parent = window, padding = {0,0,0,0}, y = 0, x = "62%", right = 0, bottom = 0, dockable = false; draggable = false, resizable = false, OnMouseDown = ShowOptions, } local function UpdateWindow(val) if val == 1 then leftPanel.backgroundColor = highlightColor leftPanel.color = highlightColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor elseif val == 2 then leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = highlightColor middlePanel.color = highlightColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor elseif val == 3 then leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = highlightColor rightPanel.color = highlightColor else leftPanel.backgroundColor = panelColor leftPanel.color = panelColor middlePanel.backgroundColor = panelColor middlePanel.color = panelColor rightPanel.backgroundColor = panelColor rightPanel.color = panelColor end leftPanel:Invalidate() middlePanel:Invalidate() rightPanel:Invalidate() window:Invalidate() end local function Dispose() window:Dispose() end local data = { UpdateWindow = UpdateWindow, Dispose = Dispose, } return data end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- General Functions local function DoDelayedUpdate(data, dt) if not data then return end if not data.updateTime then return end data.updateTime = data.updateTime - dt if data.updateTime > 0 then return end data.UpdateWindow(data.updateData) data.updateTime = false end function widget:Update(dt) if mouseData.pressed then local x, y, lmb, mmb, rmb = Spring.GetMouseState() if not (lmb or mmb or rmb) then mouseData.pressed = false mouseData.updateData = false mouseData.updateTime = options.mouseReleaseTimeout.value end end DoDelayedUpdate(keyData, dt) DoDelayedUpdate(mouseData, dt) end function widget:Shutdown() if keyData then keyData.Dispose() end if mouseData then mouseData.Dispose() end end function widget:Initialize() Chili = WG.Chili screen0 = Chili.Screen0 if (not Chili) then widgetHandler:RemoveWidget() return end mouseData = InitializeMouseButtonControl("Mouse Display", 280) keyData = InitializeDisplayLabelControl("Key Display", 380) end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Keys local function IsMod(key) return key == 32 or key >= 128 end local onlyMods = false local function Conc(str, add, val) if val then if onlyMods then return (str or "") .. (str and " + " or "") .. add else return (str or "") .. add .. " + " end else return str end end function widget:KeyPress(key, modifier, isRepeat) if not keyData then return end onlyMods = IsMod(key) and not keyData.pressed local keyText = Conc(false, "Space", modifier.meta) keyText = Conc(keyText, "Ctrl", modifier.ctrl) keyText = Conc(keyText, "Alt", modifier.alt) keyText = Conc(keyText, "Shift", modifier.shift) if not onlyMods then if not keyData.pressed then keyData.pressedString = string.upper(tostring(string.char(key))) end keyData.pressed = true keyText = (keyText or "") .. keyData.pressedString end keyData.UpdateWindow(keyText or "") keyData.updateData = keyText or "" keyData.updateTime = false end function widget:KeyRelease(key, modifier, isRepeat) if not keyData then return end if not IsMod(key) then keyData.pressed = false end onlyMods = not keyData.pressed local keyText = Conc(false, "Space", modifier.meta) keyText = Conc(keyText, "Ctrl", modifier.ctrl) keyText = Conc(keyText, "Alt", modifier.alt) keyText = Conc(keyText, "Shift", modifier.shift) if not onlyMods then keyText = (keyText or "") .. keyData.pressedString end keyData.updateData = keyText or "" keyData.updateTime = options.keyReleaseTimeout.value end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Mouse function widget:MousePress(x, y, button) if not mouseData then return end mouseData.pressed = true mouseData.UpdateWindow(button) mouseData.updateTime = false end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
geanux/darkstar
scripts/zones/Al_Zahbi/npcs/Falzuuk.lua
29
2711
----------------------------------- -- Area: Al Zahbi -- NPC: Falzuuk -- Type: Imperial Gate Guard -- @pos -60.486 0.999 105.397 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/besieged"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local merc_rank = getMercenaryRank(player); if (merc_rank == 0) then player:startEvent(0x00D9,npc); else maps = getMapBitmask(player); if (getAstralCandescence() == 1) then maps = maps + 0x80000000; end x,y,z,w = getImperialDefenseStats(); player:startEvent(0x00D8,player:getCurrency("imperial_standing"),maps,merc_rank,0,x,y,z,w); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8 and option >= 1 and option <= 2049) then itemid = getISPItem(option); player:updateEvent(0,0,0,canEquip(player,itemid)); end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00D8) then if (option == 0 or option == 16 or option == 32 or option == 48) then -- player chose sanction. if (option ~= 0) then player:delCurrency("imperial_standing", 100); end player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); local duration = getSanctionDuration(player); local subPower = 0; -- getImperialDefenseStats() player:addStatusEffect(EFFECT_SANCTION,option / 16,0,duration,subPower); -- effect size 1 = regen, 2 = refresh, 3 = food. player:messageSpecial(SANCTION); elseif (option % 256 == 17) then -- player bought one of the maps id = 1862 + (option - 17) / 256 player:addKeyItem(id); player:messageSpecial(KEYITEM_OBTAINED,id); player:delCurrency("imperial_standing", 1000); elseif (option <= 2049) then -- player bought item item, price = getISPItem(option) if (player:getFreeSlotsCount() > 0) then player:delCurrency("imperial_standing", price); player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); end end end end;
gpl-3.0
shayan-soft/virus
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
geanux/darkstar
scripts/globals/effects/prowess_killer.lua
34
2312
----------------------------------- -- -- EFFECT_PROWESS : "Killer" effects bonus -- ----------------------------------- ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VERMIN_KILLER, effect:getPower()); target:addMod(MOD_BIRD_KILLER, effect:getPower()); target:addMod(MOD_AMORPH_KILLER, effect:getPower()); target:addMod(MOD_LIZARD_KILLER, effect:getPower()); target:addMod(MOD_AQUAN_KILLER, effect:getPower()); target:addMod(MOD_PLANTOID_KILLER, effect:getPower()); target:addMod(MOD_BEAST_KILLER, effect:getPower()); target:addMod(MOD_UNDEAD_KILLER, effect:getPower()); target:addMod(MOD_ARCANA_KILLER, effect:getPower()); target:addMod(MOD_DRAGON_KILLER, effect:getPower()); target:addMod(MOD_DEMON_KILLER, effect:getPower()); target:addMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:addMod(MOD_HUMANOID_KILLER, effect:getPower()); target:addMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:addMod(MOD_LUMINION_KILLER, effect:getPower()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VERMIN_KILLER, effect:getPower()); target:delMod(MOD_BIRD_KILLER, effect:getPower()); target:delMod(MOD_AMORPH_KILLER, effect:getPower()); target:delMod(MOD_LIZARD_KILLER, effect:getPower()); target:delMod(MOD_AQUAN_KILLER, effect:getPower()); target:delMod(MOD_PLANTOID_KILLER, effect:getPower()); target:delMod(MOD_BEAST_KILLER, effect:getPower()); target:delMod(MOD_UNDEAD_KILLER, effect:getPower()); target:delMod(MOD_ARCANA_KILLER, effect:getPower()); target:delMod(MOD_DRAGON_KILLER, effect:getPower()); target:delMod(MOD_DEMON_KILLER, effect:getPower()); target:delMod(MOD_EMPTY_KILLER, effect:getPower()); -- target:delMod(MOD_HUMANOID_KILLER, effect:getPower()); target:delMod(MOD_LUMORIAN_KILLER, effect:getPower()); target:delMod(MOD_LUMINION_KILLER, effect:getPower()); end;
gpl-3.0
mullikine/vlc
share/lua/sd/jamendo.lua
58
6732
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> Rémi Duraffort <ivoire at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function descriptor() return { title="Jamendo Selections" } end function main() add_top_tracks( "ratingweek_desc", "rock", 100 ) add_top_tracks( "ratingweek_desc", "pop", 100 ) add_top_tracks( "ratingweek_desc", "jazz", 100 ) add_top_tracks( "ratingweek_desc", "dance", 100 ) add_top_tracks( "ratingweek_desc", "hipop+rap", 100 ) add_top_tracks( "ratingweek_desc", "world+reggae", 100 ) add_top_tracks( "ratingweek_desc", "lounge+ambient", 100 ) add_top_tracks( "ratingweek_desc", nil, 100 ) add_top_albums( "ratingweek_desc", nil, 20 ) add_radio_from_id( "9", 20 ) add_radio_from_id( "8", 20 ) add_radio_from_id( "6", 20 ) add_radio_from_id( "5", 20 ) add_radio_from_id( "7", 20 ) add_radio_from_id( "4", 20 ) end function add_top_albums( album_order, tag, max_results ) local url = "http://api.jamendo.com/get2/id+name+artist_name+album_image/album/xml/?imagesize=500&order=" .. album_order .. "&n=" .. max_results if tag ~= nil then url = url .. "&tag_idstr=" .. tag end local tree = simplexml.parse_url( url ) local node_name = "Top " .. max_results if album_order == "rating_desc" then node_name = node_name .. " most popular albums" elseif album_order == "ratingmonth_desc" then node_name = node_name .. " most popular albums this month" elseif album_order == "ratingweek_desc" then node_name = node_name .. " most popular albums this week" elseif album_order == "releasedate_desc" then node_name = node_name .. " latest released albums" elseif album_order == "downloaded_desc" then node_name = node_name .. " most downloaded albums" elseif album_order == "listened_desc" then node_name = node_name .. " most listened to albums" elseif album_order == "starred_desc" then node_name = node_name .. " most starred albums" elseif album_order == "playlisted_desc" then node_name = node_name .. " most playlisted albums" elseif album_order == "needreviews_desc" then node_name = node_name .. " albums requiring review" end if tag ~= nil then node_name = tag .. " - " .. node_name end local node = vlc.sd.add_node( {title=node_name} ) for _, album in ipairs( tree.children ) do simplexml.add_name_maps( album ) local album_node = node:add_subitem( { path = 'http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+album_genre+album_dates+album_image/track/xml/track_album+album_artist/?album_id=' .. album.children_map["id"][1].children[1], title = album.children_map["artist_name"][1].children[1] .. ' - ' .. album.children_map["name"][1].children[1], arturl = album.children_map["album_image"][1].children[1] }) end end function add_top_tracks( track_order, tag, max_results ) local url = "http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+genre+album_image+album_dates/track/xml/track_album+album_artist/?imagesize=500&order=" .. track_order .. "&n=" .. max_results if tag ~= nil then url = url .. "&tag_minweight=0.35&tag_idstr=" .. tag end local tree = simplexml.parse_url( url ) local node_name = "Top " .. max_results if track_order == "rating_desc" then node_name = node_name .. " most popular tracks" elseif track_order == "ratingmonth_desc" then node_name = node_name .. " most popular tracks this month" elseif track_order == "ratingweek_desc" then node_name = node_name .. " most popular tracks this week" elseif track_order == "releasedate_desc" then node_name = node_name .. " latest released tracks" elseif track_order == "downloaded_desc" then node_name = node_name .. " most downloaded tracks" elseif track_order == "listened_desc" then node_name = node_name .. " most listened to tracks" elseif track_order == "starred_desc" then node_name = node_name .. " most starred tracks" elseif track_order == "playlisted_desc" then node_name = node_name .. " most playlisted tracks" elseif track_order == "needreviews_desc" then node_name = node_name .. " tracks requiring review" end if tag ~= nil then node_name = string.upper(tag) .. " - " .. node_name end local node = vlc.sd.add_node( {title=node_name} ) for _, track in ipairs( tree.children ) do simplexml.add_name_maps( track ) node:add_subitem( {path="http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1], title=track.children_map["artist_name"][1].children[1].." - "..track.children_map["name"][1].children[1], artist=track.children_map["artist_name"][1].children[1], album=track.children_map["album_name"][1].children[1], genre=track.children_map["genre"][1].children[1], date=track.children_map["album_dates"][1].children_map["year"][1].children[1], arturl=track.children_map["album_image"][1].children[1], duration=track.children_map["duration"][1].children[1]} ) end end function add_radio_from_id( id, max_results ) local radio_name if id == "9" then radio_name="Rock" elseif id == "8" then radio_name="Pop / Songwriting" elseif id == "6" then radio_name="Jazz" elseif id == "5" then radio_name="Hip-Hop" elseif id == "7" then radio_name="Lounge" elseif id == "4" then radio_name="Dance / Electro" end vlc.sd.add_item( {path="http://api.jamendo.com/get2/id+name+artist_name+album_name+duration+album_genre+album_image+album_dates/track/xml/radio_track_inradioplaylist+track_album+album_artist/?imagesize=500&order=random_desc&radio_id=" .. id .. "&n=" .. max_results, title=radio_name} ) end
gpl-2.0
serl/vlc
share/lua/sd/jamendo.lua
58
6732
--[[ $Id$ Copyright © 2010 VideoLAN and AUTHORS Authors: Fabio Ritrovato <sephiroth87 at videolan dot org> Rémi Duraffort <ivoire at videolan dot org> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA. --]] require "simplexml" function descriptor() return { title="Jamendo Selections" } end function main() add_top_tracks( "ratingweek_desc", "rock", 100 ) add_top_tracks( "ratingweek_desc", "pop", 100 ) add_top_tracks( "ratingweek_desc", "jazz", 100 ) add_top_tracks( "ratingweek_desc", "dance", 100 ) add_top_tracks( "ratingweek_desc", "hipop+rap", 100 ) add_top_tracks( "ratingweek_desc", "world+reggae", 100 ) add_top_tracks( "ratingweek_desc", "lounge+ambient", 100 ) add_top_tracks( "ratingweek_desc", nil, 100 ) add_top_albums( "ratingweek_desc", nil, 20 ) add_radio_from_id( "9", 20 ) add_radio_from_id( "8", 20 ) add_radio_from_id( "6", 20 ) add_radio_from_id( "5", 20 ) add_radio_from_id( "7", 20 ) add_radio_from_id( "4", 20 ) end function add_top_albums( album_order, tag, max_results ) local url = "http://api.jamendo.com/get2/id+name+artist_name+album_image/album/xml/?imagesize=500&order=" .. album_order .. "&n=" .. max_results if tag ~= nil then url = url .. "&tag_idstr=" .. tag end local tree = simplexml.parse_url( url ) local node_name = "Top " .. max_results if album_order == "rating_desc" then node_name = node_name .. " most popular albums" elseif album_order == "ratingmonth_desc" then node_name = node_name .. " most popular albums this month" elseif album_order == "ratingweek_desc" then node_name = node_name .. " most popular albums this week" elseif album_order == "releasedate_desc" then node_name = node_name .. " latest released albums" elseif album_order == "downloaded_desc" then node_name = node_name .. " most downloaded albums" elseif album_order == "listened_desc" then node_name = node_name .. " most listened to albums" elseif album_order == "starred_desc" then node_name = node_name .. " most starred albums" elseif album_order == "playlisted_desc" then node_name = node_name .. " most playlisted albums" elseif album_order == "needreviews_desc" then node_name = node_name .. " albums requiring review" end if tag ~= nil then node_name = tag .. " - " .. node_name end local node = vlc.sd.add_node( {title=node_name} ) for _, album in ipairs( tree.children ) do simplexml.add_name_maps( album ) local album_node = node:add_subitem( { path = 'http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+album_genre+album_dates+album_image/track/xml/track_album+album_artist/?album_id=' .. album.children_map["id"][1].children[1], title = album.children_map["artist_name"][1].children[1] .. ' - ' .. album.children_map["name"][1].children[1], arturl = album.children_map["album_image"][1].children[1] }) end end function add_top_tracks( track_order, tag, max_results ) local url = "http://api.jamendo.com/get2/id+name+duration+artist_name+album_name+genre+album_image+album_dates/track/xml/track_album+album_artist/?imagesize=500&order=" .. track_order .. "&n=" .. max_results if tag ~= nil then url = url .. "&tag_minweight=0.35&tag_idstr=" .. tag end local tree = simplexml.parse_url( url ) local node_name = "Top " .. max_results if track_order == "rating_desc" then node_name = node_name .. " most popular tracks" elseif track_order == "ratingmonth_desc" then node_name = node_name .. " most popular tracks this month" elseif track_order == "ratingweek_desc" then node_name = node_name .. " most popular tracks this week" elseif track_order == "releasedate_desc" then node_name = node_name .. " latest released tracks" elseif track_order == "downloaded_desc" then node_name = node_name .. " most downloaded tracks" elseif track_order == "listened_desc" then node_name = node_name .. " most listened to tracks" elseif track_order == "starred_desc" then node_name = node_name .. " most starred tracks" elseif track_order == "playlisted_desc" then node_name = node_name .. " most playlisted tracks" elseif track_order == "needreviews_desc" then node_name = node_name .. " tracks requiring review" end if tag ~= nil then node_name = string.upper(tag) .. " - " .. node_name end local node = vlc.sd.add_node( {title=node_name} ) for _, track in ipairs( tree.children ) do simplexml.add_name_maps( track ) node:add_subitem( {path="http://api.jamendo.com/get2/stream/track/redirect/?id=" .. track.children_map["id"][1].children[1], title=track.children_map["artist_name"][1].children[1].." - "..track.children_map["name"][1].children[1], artist=track.children_map["artist_name"][1].children[1], album=track.children_map["album_name"][1].children[1], genre=track.children_map["genre"][1].children[1], date=track.children_map["album_dates"][1].children_map["year"][1].children[1], arturl=track.children_map["album_image"][1].children[1], duration=track.children_map["duration"][1].children[1]} ) end end function add_radio_from_id( id, max_results ) local radio_name if id == "9" then radio_name="Rock" elseif id == "8" then radio_name="Pop / Songwriting" elseif id == "6" then radio_name="Jazz" elseif id == "5" then radio_name="Hip-Hop" elseif id == "7" then radio_name="Lounge" elseif id == "4" then radio_name="Dance / Electro" end vlc.sd.add_item( {path="http://api.jamendo.com/get2/id+name+artist_name+album_name+duration+album_genre+album_image+album_dates/track/xml/radio_track_inradioplaylist+track_album+album_artist/?imagesize=500&order=random_desc&radio_id=" .. id .. "&n=" .. max_results, title=radio_name} ) end
gpl-2.0
sami2448/a
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
sepehrpk/bot1
plugins/btc.lua
289
1375
-- See https://bitcoinaverage.com/api local function getBTCX(amount,currency) local base_url = 'https://api.bitcoinaverage.com/ticker/global/' -- Do request on bitcoinaverage, the final / is critical! local res,code = https.request(base_url..currency.."/") if code ~= 200 then return nil end local data = json:decode(res) -- Easy, it's right there text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid -- If we have a number as second parameter, calculate the bitcoin amount if amount~=nil then btc = tonumber(amount) / tonumber(data.ask) text = text.."\n "..currency .." "..amount.." = BTC "..btc end return text end local function run(msg, matches) local cur = 'EUR' local amt = nil -- Get the global match out of the way if matches[1] == "!btc" then return getBTCX(amt,cur) end if matches[2] ~= nil then -- There is a second match amt = matches[2] cur = string.upper(matches[1]) else -- Just a EUR or USD param cur = string.upper(matches[1]) end return getBTCX(amt,cur) end return { description = "Bitcoin global average market value (in EUR or USD)", usage = "!btc [EUR|USD] [amount]", patterns = { "^!btc$", "^!btc ([Ee][Uu][Rr])$", "^!btc ([Uu][Ss][Dd])$", "^!btc (EUR) (%d+[%d%.]*)$", "^!btc (USD) (%d+[%d%.]*)$" }, run = run }
gpl-2.0
geanux/darkstar
scripts/zones/Port_Bastok/npcs/_6k9.lua
34
1073
----------------------------------- -- Area: Port Bastok -- NPC: Door: Arrivals Entrance -- @pos -80 1 -26 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x008C); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
blackops97/SAJJAD.iq
plugins/ar-info.lua
1
10383
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJAD HUSSIEN ▀▄ ▄▀ ▀▄ ▄▀ BY SAJJADHUSSIEN (@sajjad_iq98) ▀▄ ▄▀ ▀▄ ▄ JUST WRITED BY SAJJAD HUSSIEN ▀▄ ▄▀ ▀▄ ▄▀ I NFO USER : معلوماتي ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] do local Arian = 206839802 --put your id here(BOT OWNER ID) local function setrank(msg, name, value) -- setrank function local hash = nil if msg.to.type == 'chat' then hash = 'rank:'..msg.to.id..':variables' end if hash then redis:hset(hash, name, value) return send_msg('chat#id'..msg.to.id, 'set Rank for ('..name..') To : '..value, ok_cb, true) end end local function res_user_callback(extra, success, result) -- /info <username> function if success == 1 then if result.username then Username = '@'..result.username else Username = '----' end local text = '🔸 الاسم: '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'🔸 المعرف : '..Username..'\n' ..'🆔ايدي : '..result.id..'\n\n' ..'🔸اسم المجموعه 👥: '..msg.to.title..'\n' ..'ايدي 🆔 المجموعه 👥: '..msg.to.id..'\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(Arian) then text = text..'رتبتك 🔸: Executive Admin \n\n' elseif is_sudo(result.id) then text = text..'🔸 رتبتك: المطور مالتي 😻🙊\n\n' elseif is_owner(result.id, extra.chat2) then text = text..'🔸 رتبتك: مدير المجموعه 😘😃\n\n' elseif is_momod(result.id, extra.chat2) then text = text..'🔸 رتبتك: ادمن 😍\n\n' else text = text..'🔸 رتبتك: مجرد عضو 😒💔\n\n' end else text = text..'🔸 رتبتك'..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'🔸عدد الرسائل المرسله 📨: '..user_info_msgs..'\n\n' text = text..'🔧 #المطور: sajjadhussien\n📱#حساب المطور: @sajjad_iq98' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, ' Username not found.', ok_cb, false) end end local function action_by_id(extra, success, result) -- /info <ID> function if success == 1 then if result.username then Username = '@'..result.username else Username = '----' end local text = '🔸 الاسم: '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'🔸 المعرف : '..Username..'\n' ..'🆔ايدي : '..result.id..'\n\n' ..'🔸اسم المجموعه 👥: '..msg.to.title..'\n' ..'ايدي 🆔 المجموعه 👥: '..msg.to.id..'\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(Arian) then text = text..'رتبتك 🔸: Executive Admin \n\n' elseif is_sudo(result.id) then text = text..'🔸 رتبتك: المطور مالتي 😻🙊\n\n' elseif is_owner(result.id, extra.chat2) then text = text..'🔸 رتبتك: مدير المجموعه 😘😃\n\n' elseif is_momod(result.id, extra.chat2) then text = text..'🔸 رتبتك: ادمن 😍\n\n' else text = text..'🔸 رتبتك: مجرد عضو 😒💔\n\n' end else text = text..'🔸 رتبتك'..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'🔸عدد الرسائل المرسله 📨: '..user_info_msgs..'\n\n' text = text..'🔧 #المطور: sajjadhussien\n📱#حساب المطور: @sajjad_iq98' send_msg(extra.receiver, text, ok_cb, true) else send_msg(extra.receiver, 'id not found.\nuse : /info @username', ok_cb, false) end end local function action_by_reply(extra, success, result)-- (reply) /info function if result.from.username then Username = '@'..result.from.username else Username = '----' end local text = '🔸 الاسم: '..(result.first_name or '')..' '..(result.last_name or '')..'\n' ..'🔸 المعرف : '..Username..'\n' ..'🆔ايدي : '..result.id..'\n\n' ..'🔸اسم المجموعه 👥: '..msg.to.title..'\n' ..'ايدي 🆔 المجموعه 👥: '..msg.to.id..'\n' local hash = 'rank:'..extra.chat2..':variables' local value = redis:hget(hash, result.id) if not value then if result.id == tonumber(Arian) then text = text..'رتبتك 🔸: Executive Admin \n\n' elseif is_sudo(result.id) then text = text..'🔸 رتبتك: المطور مالتي 😻🙊\n\n' elseif is_owner(result.id, extra.chat2) then text = text..'🔸 رتبتك: مدير المجموعه 😘😃\n\n' elseif is_momod(result.id, extra.chat2) then text = text..'🔸 رتبتك: ادمن 😍\n\n' else text = text..'🔸 رتبتك: مجرد عضو 😒💔\n\n' end else text = text..'🔸 رتبتك'..value..'\n\n' end local uhash = 'user:'..result.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..result.id..':'..extra.chat2 user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'🔸عدد الرسائل المرسله 📨: '..user_info_msgs..'\n\n' text = text..'🔧 #المطور: sajjadhussien\n📱#حساب المطور: @sajjad_iq98' send_msg(extra.receiver, text, ok_cb, true) end local function action_by_reply2(extra, success, result) local value = extra.value setrank(result, result.from.id, value) end local function run(msg, matches) if matches[1]:lower() == 'setrank' then local hash = 'usecommands:'..msg.from.id..':'..msg.to.id redis:incr(hash) if not is_sudo(msg) then return "😠 لآَ تـمسـلتَ أَلمطـور فـقطَ يفَـعل هأَذأَ ✔️👍" end local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then local value = string.sub(matches[2], 1, 1000) msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value}) else local name = string.sub(matches[2], 1, 50) local value = string.sub(matches[3], 1, 1000) local text = setrank(msg, name, value) return text end end if matches[1]:lower() == 'معلوماتي' and not matches[2] then local receiver = get_receiver(msg) local Reply = msg.reply_id if msg.reply_id then msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply}) else if msg.from.username then Username = '@'..msg.from.username else Username = '----' end local text = '🔸 الاسم الاول: '..(msg.from.first_name or '----')..'\n' local text = text..'🔸 الاسم الاخيير : '..(msg.from.last_name or '----')..'\n' local text = text..'🔸 المعرف: '..Username..'\n' local text = text..'📱 رقم هاتفك: '..(msg.from.phone or 'لايوجد')..'\n' local text = text..'🆔 ايدي: '..msg.from.id..'\n' local text = text..'🔸 اسم المجموعه 👥 : '..msg.to.title..'\n' local text = text..'ايدي 🆔 المجموعه 👥 : '..msg.to.id..'\n' local hash = 'rank:'..msg.to.id..':variables' if hash then local value = redis:hget(hash, msg.from.id) if not value then if msg.from.id == tonumber(Arian) then text = text..'🔸 رتبتك: Executive Admin \n\n' elseif is_sudo(msg) then text = text..' 🔸رتبتك : المطور مالتي 😻🙊\n\n' elseif is_owner(msg) then text = text..' 🔸رتبتك : مدير المجموعه 🌺😍\n\n' elseif is_momod(msg) then text = text..'🔸 رتبتك : ادمن ☺️\n\n' else text = text..'🔸 رتبتك : مجرد عضو 😒💔\n\n' end else text = text..' 🔸رتبتك : '..value..'\n' end end local uhash = 'user:'..msg.from.id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id user_info_msgs = tonumber(redis:get(um_hash) or 0) text = text..'📨عدد الرسائل المرسله : '..user_info_msgs..'\n\n' if msg.to.type == 'chat' then text = text..'🔸 اسم المجموعه : '..msg.to.title..'\n' text = text..'🆔 ايدي المجموعه : '..msg.to.id end text = text..'🔧 #الـمطـور : SAJAD_iq\n🔧 #حساب المطور : @sajjad_iq98' return send_msg(receiver, text, ok_cb, true) end end if matches[1]:lower() == 'معلوماتي' and matches[2] then local user = matches[2] local chat2 = msg.to.id local receiver = get_receiver(msg) if string.match(user, '^%d+$') then user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2}) elseif string.match(user, '^@.+$') then username = string.gsub(user, '@', '') msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2}) end end end return { description = 'Know your information or the info of a chat members.', usage = { '!info: Return your info and the chat info if you are in one.', '(Reply)!info: Return info of replied user if used by reply.', '!info <id>: Return the info\'s of the <id>.', '!info @<user_name>: Return the member @<user_name> information from the current chat.', '!setrank <userid> <rank>: change members rank.', '(Reply)!setrank <rank>: change members rank.', }, patterns = { "^([Ii][Nn][Ff][Oo])$", "^([Ii][Nn][Ff][Oo]) (.*)$", "^(معلوماتي)$", "^(معلوماتي)(.*)$", "^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$", "^([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$" }, run = run } end
gpl-2.0
kaen/Zero-K
scripts/striderhub.lua
20
1377
include "constants.lua" include "nanoaim.h.lua" --pieces local body = piece "body" local aim = piece "aim" local emitnano = piece "emitnano" --local vars local smokePiece = { piece "aim", piece "body" } local nanoPieces = { piece "aim" } local nanoTurnSpeedHori = 0.5 * math.pi local nanoTurnSpeedVert = 0.3 * math.pi function script.Create() StartThread(SmokeUnit, smokePiece) StartThread(UpdateNanoDirectionThread, nanoPieces, 500, nanoTurnSpeedHori, nanoTurnSpeedVert) Spring.SetUnitNanoPieces(unitID, {emitnano}) end function script.StartBuilding() UpdateNanoDirection(nanoPieces, nanoTurnSpeedHori, nanoTurnSpeedVert) Spring.SetUnitCOBValue(unitID, COB.INBUILDSTANCE, 1); end function script.StopBuilding() Spring.SetUnitCOBValue(unitID, COB.INBUILDSTANCE, 0); end function script.QueryNanoPiece() --// send to LUPS GG.LUPS.QueryNanoPiece(unitID,unitDefID,Spring.GetUnitTeam(unitID),emitnano) return emitnano end function script.Killed(recentDamage, maxHealth) local severity = recentDamage / maxHealth if severity < 0.25 then --return 1 elseif severity < 0.50 then Explode (aim, SFX.FALL) --return 1 elseif severity < 0.75 then Explode (aim, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) --return 2 else Explode (body, SFX.SHATTER) Explode (aim, SFX.FALL + SFX.SMOKE + SFX.FIRE + SFX.EXPLODE_ON_HIT) --return 2 end end
gpl-2.0
geanux/darkstar
scripts/globals/items/pipin_hot_popoto.lua
35
1291
----------------------------------------- -- ID: 4282 -- Item: pipin_hot_popoto -- Food Effect: 60Min, All Races ----------------------------------------- -- HP 25 -- Vitality 3 -- HP recovered 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,4282); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 25); target:addMod(MOD_VIT, 3); target:addMod(MOD_HPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 25); target:delMod(MOD_VIT, 3); target:delMod(MOD_HPHEAL, 1); end;
gpl-3.0
girishramnani/Algorithm-Implementations
Depth_Limited_Search/Lua/Yonaba/dls.lua
26
3110
-- Generic Depth-Limited search algorithm implementation -- See : http://en.wikipedia.org/wiki/Depth-limited_search -- Notes : this is a generic implementation of Depth-Limited search algorithm. -- It is devised to be used on any type of graph (point-graph, tile-graph, -- or whatever. It expects to be initialized with a handler, which acts as -- an interface between the search algorithm and the search space. -- The DLS class expects a handler to be initialized. Roughly said, the handler -- is an interface between your search space and the generic search algorithm. -- This ensures flexibility, so that the generic algorithm can be adapted to -- search on any kind of space. -- The passed-in handler should implement those functions. -- handler.getNode(...) -> returns a Node (instance of node.lua) -- handler.getNeighbors(n) -> returns an array of all nodes that can be reached -- via node n (also called successors of node n) -- The actual implementation uses recursion to look up for the path. -- Between consecutive path requests, the user must call the :resetForNextSearch() -- method to clear all nodes data created during a previous search. -- The generic Node class provided (see node.lua) should also be implemented -- through the handler. Basically, it should describe how nodes are labelled -- and tested for equality for a custom search space. -- The following functions should be implemented: -- function Node:initialize(...) -> creates a Node with custom attributes -- function Node:isEqualTo(n) -> returns if self is equal to node n -- function Node:toString() -> returns a unique string representation of -- the node, for debug purposes -- See custom handlers for reference (*_hander.lua). -- Dependencies local class = require 'utils.class' -- Builds and returns the path to the goal node local function backtrace(node) local path = {} repeat table.insert(path, 1, node) node = node.parent until not node return path end -- Initializes Depth-Limited search with a custom handler local DLS = class() function DLS:initialize(handler) self.handler = handler end -- Clears all nodes for a next search -- Must be called in-between consecutive searches function DLS:resetForNextSearch() local nodes = self.handler.getAllNodes() for _, node in ipairs(nodes) do node.visited, node.parent = nil, nil end end -- Returns the path between start and goal locations -- start : a Node representing the start location -- goal : a Node representing the target location -- depth : the maximum depth of search -- returns : an array of nodes function DLS:findPath(start, goal, depth) if start == goal then return backtrace(start) end if depth == 0 then return end start.visited = true local neighbors = self.handler.getNeighbors(start) for _, neighbor in ipairs(neighbors) do if not neighbor.visited then neighbor.parent = start local foundGoal = self:findPath(neighbor, goal, depth - 1) if foundGoal then return foundGoal end end end end return DLS
mit
PhearNet/scanner
bin/nmap-openshift/nselib/tftp.lua
4
9608
--- Library implementing a minimal TFTP server -- -- Currently only write-operations are supported so that script can trigger -- TFTP transfers and receive the files and return them as result. -- -- The library contains the following classes -- * <code>Packet</code> -- ** The <code>Packet</code> classes contain one class for each TFTP operation. -- * <code>File</code> -- ** The <code>File</code> class holds a received file including the name and contents -- * <code>ConnHandler</code> -- ** The <code>ConnHandler</code> class handles and processes incoming connections. -- -- The following code snippet starts the TFTP server and waits for the file incoming.txt -- to be uploaded for 10 seconds: -- <code> -- tftp.start() -- local status, f = tftp.waitFile("incoming.txt", 10) -- if ( status ) then return f:getContent() end -- </code> -- -- @author Patrik Karlsson <patrik@cqure.net> -- @copyright Same as Nmap--See https://nmap.org/book/man-legal.html -- -- version 0.2 -- -- 2011-01-22 - re-wrote library to use coroutines instead of new_thread code. local bin = require "bin" local coroutine = require "coroutine" local nmap = require "nmap" local os = require "os" local stdnse = require "stdnse" local table = require "table" _ENV = stdnse.module("tftp", stdnse.seeall) threads, infiles, running = {}, {}, {} state = "STOPPED" srvthread = {} -- All opcodes supported by TFTP OpCode = { RRQ = 1, WRQ = 2, DATA = 3, ACK = 4, ERROR = 5, } --- A minimal packet implementation -- -- The current code only implements the ACK and ERROR packets -- As the server is write-only the other packet types are not needed Packet = { -- Implements the ACK packet ACK = { new = function( self, block ) local o = {} setmetatable(o, self) self.__index = self o.block = block return o end, __tostring = function( self ) return bin.pack(">SS", OpCode.ACK, self.block) end, }, -- Implements the error packet ERROR = { new = function( self, code, msg ) local o = {} setmetatable(o, self) self.__index = self o.msg = msg o.code = code return o end, __tostring = function( self ) return bin.pack(">SSz", OpCode.ERROR, self.code, self.msg) end, } } --- The File class holds files received by the TFTP server File = { --- Creates a new file object -- -- @param filename string containing the filename -- @param content string containing the file content -- @return o new class instance new = function(self, filename, content, sender) local o = {} setmetatable(o, self) self.__index = self o.name = filename o.content = content o.sender = sender return o end, getContent = function(self) return self.content end, setContent = function(self, content) self.content = content end, getName = function(self) return self.name end, setName = function(self, name) self.name = name end, setSender = function(self, sender) self.sender = sender end, getSender = function(self) return self.sender end, } -- The thread dispatcher is called by the start function once local function dispatcher() local last = os.time() local f_condvar = nmap.condvar(infiles) local s_condvar = nmap.condvar(state) while(true) do -- check if other scripts are active local counter = 0 for t in pairs(running) do counter = counter + 1 end if ( counter == 0 ) then state = "STOPPING" s_condvar "broadcast" end if #threads == 0 then break end for i, thread in ipairs(threads) do local status, res = coroutine.resume(thread) if ( not(res) ) then -- thread finished its task? table.remove(threads, i) break end end -- Make sure to process waitFile atleast every 2 seconds -- in case no files have arrived if ( os.time() - last >= 2 ) then last = os.time() f_condvar "broadcast" end end state = "STOPPED" s_condvar "broadcast" stdnse.debug1("Exiting _dispatcher") end -- Processes a new incoming file transfer -- Currently only uploads are supported -- -- @param host containing the hostname or ip of the initiating host -- @param port containing the port of the initiating host -- @param data string containing the initial data passed to the server local function processConnection( host, port, data ) local pos, op = bin.unpack(">S", data) local socket = nmap.new_socket("udp") socket:set_timeout(1000) local status, err = socket:connect(host, port) if ( not(status) ) then return status, err end socket:set_timeout(10) -- If we get anything else than a write request, abort the connection if ( OpCode.WRQ ~= op ) then stdnse.debug1("Unsupported opcode") socket:send( tostring(Packet.ERROR:new(0, "TFTP server has write-only support"))) end local pos, filename, enctype = bin.unpack("zz", data, pos) status, err = socket:send( tostring( Packet.ACK:new(0) ) ) local blocks = {} local lastread = os.time() while( true ) do local status, pdata = socket:receive() if ( not(status) ) then -- if we're here and haven't successfully read a packet for 5 seconds, abort if ( os.time() - lastread > 5 ) then coroutine.yield(false) else coroutine.yield(true) end else -- record last time we had a successful read lastread = os.time() pos, op = bin.unpack(">S", pdata) if ( OpCode.DATA ~= op ) then stdnse.debug1("Expected a data packet, terminating TFTP transfer") end local block, data pos, block, data = bin.unpack(">SA" .. #pdata - 4, pdata, pos ) blocks[block] = data -- First block was not 1 if ( #blocks == 0 ) then socket:send( tostring(Packet.ERROR:new(0, "Did not receive block 1"))) break end -- for every fifth block check that we've received the preceding four if ( ( #blocks % 5 ) == 0 ) then for b = #blocks - 4, #blocks do if ( not(blocks[b]) ) then socket:send( tostring(Packet.ERROR:new(0, "Did not receive block " .. b))) end end end -- Ack the data block status, err = socket:send( tostring(Packet.ACK:new(block)) ) if ( ( #blocks % 20 ) == 0 ) then -- yield every 5th iteration so other threads may work coroutine.yield(true) end -- If the data length was less than 512, this was our last block if ( #data < 512 ) then socket:close() break end end end local filecontent = {} -- Make sure we received all the blocks needed to proceed for i=1, #blocks do if ( not(blocks[i]) ) then return false, ("Block #%d was missing in transfer") end filecontent[#filecontent+1] = blocks[i] end stdnse.debug1("Finished receiving file \"%s\"", filename) -- Add anew file to the global infiles table table.insert( infiles, File:new(filename, table.concat(filecontent), host) ) local condvar = nmap.condvar(infiles) condvar "broadcast" end -- Waits for a connection from a client local function waitForConnection() local srvsock = nmap.new_socket("udp") local status = srvsock:bind(nil, 69) assert(status, "Failed to bind to TFTP server port") srvsock:set_timeout(0) while( state == "RUNNING" ) do local status, data = srvsock:receive() if ( not(status) ) then coroutine.yield(true) else local status, _, _, rhost, rport = srvsock:get_info() local x = coroutine.create( function() processConnection(rhost, rport, data) end ) table.insert( threads, x ) coroutine.yield(true) end end end --- Starts the TFTP server and creates a new thread handing over to the dispatcher function start() local disp = nil local mutex = nmap.mutex("srvsocket") -- register a running script running[coroutine.running()] = true mutex "lock" if ( state == "STOPPED" ) then srvthread = coroutine.running() table.insert( threads, coroutine.create( waitForConnection ) ) stdnse.new_thread( dispatcher ) state = "RUNNING" end mutex "done" end local function waitLast() -- The thread that started the server needs to wait here until the rest -- of the scripts finish running. We know we are done once the state -- shifts to STOPPED and we get a signal from the condvar in the -- dispatcher local s_condvar = nmap.condvar(state) while( srvthread == coroutine.running() and state ~= "STOPPED" ) do s_condvar "wait" end end --- Waits for a file with a specific filename for at least the number of -- seconds specified by the timeout parameter. -- -- If this function is called from the thread that's running the server it will -- wait until all the other threads have finished executing before returning. -- -- @param filename string containing the name of the file to receive -- @param timeout number containing the minimum number of seconds to wait -- for the file to be received -- @return status true on success false on failure -- @return File instance on success, nil on failure function waitFile( filename, timeout ) local condvar = nmap.condvar(infiles) local t = os.time() while(os.time() - t < timeout) do for _, f in ipairs(infiles) do if (f:getName() == filename) then running[coroutine.running()] = nil waitLast() return true, f end end condvar "wait" end -- de-register a running script running[coroutine.running()] = nil waitLast() return false end return _ENV;
mit
geanux/darkstar
scripts/globals/items/dish_of_spaghetti_nero_di_seppia.lua
35
1800
----------------------------------------- -- ID: 5193 -- Item: dish_of_spaghetti_nero_di_seppia -- Food Effect: 30Min, All Races ----------------------------------------- -- HP % 17 (cap 130) -- Dexterity 3 -- Vitality 2 -- Agility -1 -- Mind -2 -- Charisma -1 -- Double Attack 1 -- Store TP 6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5193); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 17); target:addMod(MOD_FOOD_HP_CAP, 130); target:addMod(MOD_DEX, 3); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, -1); target:addMod(MOD_MND, -2); target:addMod(MOD_CHR, -1); target:addMod(MOD_DOUBLE_ATTACK, 1); target:addMod(MOD_STORETP, 6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 17); target:delMod(MOD_FOOD_HP_CAP, 130); target:delMod(MOD_DEX, 3); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, -1); target:delMod(MOD_MND, -2); target:delMod(MOD_CHR, -1); target:delMod(MOD_DOUBLE_ATTACK, 1); target:delMod(MOD_STORETP, 6); end;
gpl-3.0
evilexecutable/ResourceKeeper
install/Lua/lib/luarocks/rocks/luasocket/3.0rc1-2/etc/forward.lua
43
2066
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if #arg < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
gpl-2.0
geanux/darkstar
scripts/globals/items/colored_egg.lua
35
1274
----------------------------------------- -- ID: 4487 -- Item: colored_egg -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Attack 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4487); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_ATT, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_ATT, 3); end;
gpl-3.0
geanux/darkstar
scripts/globals/abilities/drain_samba.lua
18
1464
----------------------------------- -- Ability: Drain Samba -- Inflicts the next target you strike with Drain daze, allowing all those engaged in battle with it to drain its HP. -- Obtained: Dancer Level 5 -- TP Required: 10% -- Recast Time: 1:00 -- Duration: 2:00 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FAN_DANCE)) then return MSGBASIC_UNABLE_TO_USE_JA2, 0; elseif (player:hasStatusEffect(EFFECT_TRANCE)) then return 0,0; elseif (player:getTP() < 10) then return MSGBASIC_NOT_ENOUGH_TP,0; else return 0,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Only remove TP if the player doesn't have Trance. if not player:hasStatusEffect(EFFECT_TRANCE) then player:delTP(10); end; local duration = 120 + player:getMod(MOD_SAMBA_DURATION); duration = duration * (100 + player:getMod(MOD_SAMBA_PDURATION))/100; player:delStatusEffect(EFFECT_HASTE_SAMBA); player:delStatusEffect(EFFECT_ASPIR_SAMBA); player:addStatusEffect(EFFECT_DRAIN_SAMBA,1,0,duration); end;
gpl-3.0
geanux/darkstar
scripts/zones/Lufaise_Meadows/TextIDs.lua
7
1194
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6383; -- Obtained: <item>. GIL_OBTAINED = 6384; -- Obtained <number> gil. KEYITEM_OBTAINED = 6386; -- Obtained key item: <keyitem>. NOTHING_OUT_OF_THE_ORDINARY = 6397; -- There is nothing out of the ordinary here. FISHING_MESSAGE_OFFSET = 7542; -- You can't fish here. -- Conquest CONQUEST = 7208; -- You've earned conquest points! -- Logging LOGGING_IS_POSSIBLE_HERE = 7714; -- Logging is possible here if you have -- Other Texts SURVEY_THE_SURROUNDINGS = 7721; -- You survey the surroundings but see nothing out of the ordinary. MURDEROUS_PRESENCE = 7722; -- Wait, you sense a murderous presence...! YOU_CAN_SEE_FOR_MALMS = 7723; -- You can see for malms in every direction. SPINE_CHILLING_PRESENCE = 7725; -- You sense a spine-chilling presence! KI_STOLEN = 7666; -- The ?Possible Special Code: 01??Possible Special Code: 05?3??BAD CHAR: 80??BAD CHAR: 80? has been stolen! -- conquest Base CONQUEST_BASE = 7040; -- Tallying conquest results...
gpl-3.0
tonylauCN/tutorials
openresty/debugger/lualibs/coxpcall/coxpcall.lua
4
2272
------------------------------------------------------------------------------- -- Coroutine safe xpcall and pcall versions -- -- Encapsulates the protected calls with a coroutine based loop, so errors can -- be dealed without the usual Lua 5.x pcall/xpcall issues with coroutines -- yielding inside the call to pcall or xpcall. -- -- Authors: Roberto Ierusalimschy and Andre Carregal -- Contributors: Thomas Harning Jr., Ignacio Burgueño, Fabio Mascarenhas -- -- Copyright 2005 - Kepler Project (www.keplerproject.org) -- -- $Id: coxpcall.lua,v 1.13 2008/05/19 19:20:02 mascarenhas Exp $ ------------------------------------------------------------------------------- -- Lua 5.2 makes this module a no-op if _VERSION == "Lua 5.2" then copcall = pcall coxpcall = xpcall return { pcall = pcall, xpcall = xpcall } end ------------------------------------------------------------------------------- -- Implements xpcall with coroutines ------------------------------------------------------------------------------- local performResume, handleReturnValue local oldpcall, oldxpcall = pcall, xpcall local pack = table.pack or function(...) return {n = select("#", ...), ...} end local unpack = table.unpack or unpack function handleReturnValue(err, co, status, ...) if not status then return false, err(debug.traceback(co, (...)), ...) end if coroutine.status(co) == 'suspended' then return performResume(err, co, coroutine.yield(...)) else return true, ... end end function performResume(err, co, ...) return handleReturnValue(err, co, coroutine.resume(co, ...)) end function coxpcall(f, err, ...) local res, co = oldpcall(coroutine.create, f) if not res then local params = pack(...) local newf = function() return f(unpack(params, 1, params.n)) end co = coroutine.create(newf) end return performResume(err, co, ...) end ------------------------------------------------------------------------------- -- Implements pcall with coroutines ------------------------------------------------------------------------------- local function id(trace, ...) return ... end function copcall(f, ...) return coxpcall(f, id, ...) end return { pcall = copcall, xpcall = coxpcall }
apache-2.0
tonylauCN/tutorials
lua/debugger/lualibs/coxpcall/coxpcall.lua
4
2272
------------------------------------------------------------------------------- -- Coroutine safe xpcall and pcall versions -- -- Encapsulates the protected calls with a coroutine based loop, so errors can -- be dealed without the usual Lua 5.x pcall/xpcall issues with coroutines -- yielding inside the call to pcall or xpcall. -- -- Authors: Roberto Ierusalimschy and Andre Carregal -- Contributors: Thomas Harning Jr., Ignacio Burgueño, Fabio Mascarenhas -- -- Copyright 2005 - Kepler Project (www.keplerproject.org) -- -- $Id: coxpcall.lua,v 1.13 2008/05/19 19:20:02 mascarenhas Exp $ ------------------------------------------------------------------------------- -- Lua 5.2 makes this module a no-op if _VERSION == "Lua 5.2" then copcall = pcall coxpcall = xpcall return { pcall = pcall, xpcall = xpcall } end ------------------------------------------------------------------------------- -- Implements xpcall with coroutines ------------------------------------------------------------------------------- local performResume, handleReturnValue local oldpcall, oldxpcall = pcall, xpcall local pack = table.pack or function(...) return {n = select("#", ...), ...} end local unpack = table.unpack or unpack function handleReturnValue(err, co, status, ...) if not status then return false, err(debug.traceback(co, (...)), ...) end if coroutine.status(co) == 'suspended' then return performResume(err, co, coroutine.yield(...)) else return true, ... end end function performResume(err, co, ...) return handleReturnValue(err, co, coroutine.resume(co, ...)) end function coxpcall(f, err, ...) local res, co = oldpcall(coroutine.create, f) if not res then local params = pack(...) local newf = function() return f(unpack(params, 1, params.n)) end co = coroutine.create(newf) end return performResume(err, co, ...) end ------------------------------------------------------------------------------- -- Implements pcall with coroutines ------------------------------------------------------------------------------- local function id(trace, ...) return ... end function copcall(f, ...) return coxpcall(f, id, ...) end return { pcall = copcall, xpcall = coxpcall }
apache-2.0
kaen/Zero-K
lups/ParticleClasses/UnitCloaker.lua
9
8552
-- $Id: UnitCloaker.lua 3871 2009-01-28 00:09:23Z jk $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local UnitCloaker = {} UnitCloaker.__index = UnitCloaker local warpShader local tex local cameraUniform,lightUniform local isS3oUniform, lifeUniform ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitCloaker.GetInfo() return { name = "UnitCloaker", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 16, --// extreme simply z-ordering :x --// gfx requirement fbo = true, shader = true, rtt = false, ctt = true, intel = 0, } end UnitCloaker.Default = { layer = 16, worldspace = true, inverse = false, life = math.huge, unit = -1, unitDefID = -1, repeatEffect = false, dieGameFrame = math.huge } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local loadedS3oTexture = -1 function UnitCloaker:BeginDraw() gl.Culling(GL.FRONT) gl.Culling(true) gl.DepthMask(true) gl.UseShader(warpShader) local x,y,z = Spring.GetCameraPosition() gl.Uniform(cameraUniform,x,y,z) x,y,z = gl.GetSun( "pos" ) gl.Light(0,GL.POSITION,x,y,z) gl.Uniform(lightUniform,x,y,z) x,y,z = gl.GetSun( "ambient" ,"unit") gl.Light(0,GL.AMBIENT,x,y,z) x,y,z = gl.GetSun( "diffuse" ,"unit") gl.Light(0,GL.DIFFUSE,x,y,z) --gl.Texture(1,'bitmaps/cdet.bmp') --gl.Texture(1,'bitmaps/clouddetail.bmp') --gl.Texture(1,'bitmaps/GPL/Lups/perlin_noise.jpg') gl.Texture(2,'bitmaps/GPL/Lups/mynoise2.png') gl.Texture(3,'$specular') gl.Texture(4,'$reflection') gl.MatrixMode(GL.PROJECTION) gl.PushMatrix() gl.MultMatrix("camera") gl.MatrixMode(GL.MODELVIEW) gl.PushMatrix() gl.LoadIdentity() end function UnitCloaker:EndDraw() gl.MatrixMode(GL.PROJECTION) gl.PopMatrix() gl.MatrixMode(GL.MODELVIEW) gl.PopMatrix() gl.Culling(GL.BACK) gl.Culling(false) gl.DepthMask(true) gl.UseShader(0) gl.Texture(0,false) gl.Texture(1,false) gl.Texture(2,false) gl.Texture(3,false) gl.Texture(4,false) gl.Color(1,1,1,1) loadedS3oTexture = -1 end function UnitCloaker:Draw() local udid = 0 if (self.isS3o) then udid = self.unitDefID end if (udid~=loadedS3oTexture) then gl.Texture(0, "%" .. udid .. ":0") gl.Texture(1, "%" .. udid .. ":1") loadedS3oTexture = udid end if (self.inverse) then gl.Uniform( lifeUniform, 1-(thisGameFrame-self.firstGameFrame)/self.life ) else gl.Uniform( lifeUniform, (thisGameFrame-self.firstGameFrame)/self.life ) end gl.Color(Spring.GetTeamColor(self.team)) if (self.isS3o) then gl.Culling(GL.BACK) gl.Unit(self.unit,true,-1) gl.Culling(GL.FRONT) else gl.Unit(self.unit,true,-1) end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitCloaker.Initialize() warpShader = gl.CreateShader({ vertex = [[ uniform vec3 cameraPos; uniform vec3 lightPos; uniform float life; varying float opac; varying vec4 texCoord; varying vec3 normal; varying vec3 viewdir; //const vec4 ObjectPlaneS = vec4(0.002, 0.002, 0.0, 0.3); //const vec4 ObjectPlaneT = vec4(0.0, 0.002, 0.002, 0.3); const vec4 ObjectPlaneS = vec4(0.005, 0.005, 0.000, 0.0); const vec4 ObjectPlaneT = vec4(0.000, 0.005, 0.005, 0.0); void main(void) { texCoord.st = gl_MultiTexCoord0.st; texCoord.p = dot( gl_Vertex, ObjectPlaneS ); texCoord.q = dot( gl_Vertex, ObjectPlaneT );// + life*0.25; normal = gl_NormalMatrix * gl_Normal; viewdir = (gl_ModelViewMatrix * gl_Vertex).xyz - cameraPos; gl_FrontColor = gl_Color; float a = max( dot(normal, lightPos), 0.0); gl_FrontSecondaryColor.rgb = a * gl_LightSource[0].diffuse.rgb + gl_LightSource[0].ambient.rgb; opac = dot(normalize(normal), normalize(viewdir)); opac = 1.0 - abs(opac); opac = pow(opac, 5.0); gl_Position = ftransform(); } ]], fragment = [[ uniform sampler2D texture1; uniform sampler2D texture2; uniform sampler2D noiseMap; uniform samplerCube specularMap; uniform samplerCube reflectMap; uniform float life; varying float opac; varying vec4 texCoord; varying vec3 normal; varying vec3 viewdir; void main(void) { vec4 noise = texture2D(noiseMap, texCoord.pq); //if (noise.r < life) { // discard; //} gl_FragColor = texture2D(texture1, texCoord.st); gl_FragColor.rgb = mix(gl_FragColor.rgb, gl_Color.rgb, gl_FragColor.a); vec4 extraColor = texture2D(texture2, texCoord.st); vec3 reflectDir = reflect(viewdir, normalize(normal)); vec3 spec = textureCube(specularMap, reflectDir).rgb * 4.0 * extraColor.g; vec3 refl = textureCube(reflectMap, reflectDir).rgb; refl = mix(gl_SecondaryColor.rgb, refl, extraColor.g); refl += extraColor.r; gl_FragColor.rgb = gl_FragColor.rgb * refl + spec; gl_FragColor.a = extraColor.a; if (life*1.4>noise.r) { float d = life*1.4-noise.r; gl_FragColor.a *= smoothstep(0.4,0.0,d); } gl_FragColor.rgb += vec3(life*0.25); } ]], uniform = { isS3o = false, }, uniformInt = { texture1 = 0, texture2 = 1, noiseMap = 2, specularMap = 3, reflectMap = 4, }, uniformFloat = { life = 1, } }) if (warpShader == nil) then print(PRIO_MAJOR,"LUPS->UnitCloaker: critical shader error: "..gl.GetShaderLog()) return false end cameraUniform = gl.GetUniformLocation(warpShader, 'cameraPos') lightUniform = gl.GetUniformLocation(warpShader, 'lightPos') lifeUniform = gl.GetUniformLocation(warpShader, 'life') end function UnitCloaker.Finalize() if (gl.DeleteShader) then gl.DeleteShader(warpShader) end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- -- used if repeatEffect=true; function UnitCloaker:ReInitialize() self.dieGameFrame = self.dieGameFrame + self.life end function UnitCloaker:CreateParticle() local name = UnitDefs[self.unitDefID].model.name self.isS3o = ((name:lower():find("s3o") or name:lower():find("obj")) and true) self.firstGameFrame = thisGameFrame self.dieGameFrame = self.firstGameFrame + self.life end function UnitCloaker:Visible() if self.allyTeam == LocalAllyTeamID then return Spring.IsUnitVisible(self.unit) end local _, specFullView = Spring.GetSpectatingState() local losState = Spring.GetUnitLosState(self.unit, LocalAllyTeamID) or {} return specFullView or (losState and losState.los) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitCloaker.Create(Options) SetUnitLuaDraw(Options.unit,true) local newObject = MergeTable(Options, UnitCloaker.Default) setmetatable(newObject,UnitCloaker) -- make handle lookup newObject:CreateParticle() return newObject end function UnitCloaker:Destroy() SetUnitLuaDraw(self.unit,false) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return UnitCloaker
gpl-2.0
PhearNet/scanner
bin/nmap-openshift/nselib/tls.lua
4
53890
--- -- A library providing functions for doing TLS/SSL communications -- -- These functions will build strings and process buffers. Socket communication -- is left to the script to implement. -- -- @author "Daniel Miller <bonsaiviking@gmail.com>" local stdnse = require "stdnse" local bin = require "bin" local math = require "math" local os = require "os" local table = require "table" _ENV = stdnse.module("tls", stdnse.seeall) -- Most of the values in the tables below are from: -- http://www.iana.org/assignments/tls-parameters/ PROTOCOLS = { ["SSLv3"] = 0x0300, ["TLSv1.0"] = 0x0301, ["TLSv1.1"] = 0x0302, ["TLSv1.2"] = 0x0303 } HIGHEST_PROTOCOL = "TLSv1.2" -- -- TLS Record Types -- TLS_RECORD_HEADER_LENGTH = 5 TLS_CONTENTTYPE_REGISTRY = { ["change_cipher_spec"] = 20, ["alert"] = 21, ["handshake"] = 22, ["application_data"] = 23, ["heartbeat"] = 24 } -- -- TLS Alert Levels -- TLS_ALERT_LEVELS = { ["warning"] = 1, ["fatal"] = 2, } -- -- TLS Alert Record Types -- TLS_ALERT_REGISTRY = { ["close_notify"] = 0, ["unexpected_message"] = 10, ["bad_record_mac"] = 20, ["decryption_failed"] = 21, ["record_overflow"] = 22, ["decompression_failure"] = 30, ["handshake_failure"] = 40, ["no_certificate"] = 41, ["bad_certificate"] = 42, ["unsupported_certificate"] = 43, ["certificate_revoked"] = 44, ["certificate_expired"] = 45, ["certificate_unknown"] = 46, ["illegal_parameter"] = 47, ["unknown_ca"] = 48, ["access_denied"] = 49, ["decode_error"] = 50, ["decrypt_error"] = 51, ["export_restriction"] = 60, ["protocol_version"] = 70, ["insufficient_security"] = 71, ["internal_error"] = 80, ["inappropriate_fallback"] = 86, ["user_canceled"] = 90, ["no_renegotiation"] = 100, ["unsupported_extension"] = 110, ["certificate_unobtainable"] = 111, ["unrecognized_name"] = 112, ["bad_certificate_status_response"] = 113, ["bad_certificate_hash_value"] = 114, ["unknown_psk_identity"] = 115 } -- -- TLS Handshake Record Types -- TLS_HANDSHAKETYPE_REGISTRY = { ["hello_request"] = 0, ["client_hello"] = 1, ["server_hello"] = 2, ["hello_verify_request"] = 3, ["NewSessionTicket"] = 4, ["certificate"] = 11, ["server_key_exchange"] = 12, ["certificate_request"] = 13, ["server_hello_done"] = 14, ["certificate_verify"] = 15, ["client_key_exchange"] = 16, ["finished"] = 20, ["certificate_url"] = 21, ["certificate_status"] = 22, ["supplemental_data"] = 23, ["next_protocol"] = 67, } -- -- Compression Algorithms -- http://www.iana.org/assignments/comp-meth-ids -- COMPRESSORS = { ["NULL"] = 0, ["DEFLATE"] = 1, ["LZS"] = 64 } --- -- RFC 4492 section 5.1.1 "Supported Elliptic Curves Extension". ELLIPTIC_CURVES = { sect163k1 = 1, sect163r1 = 2, sect163r2 = 3, sect193r1 = 4, sect193r2 = 5, sect233k1 = 6, sect233r1 = 7, sect239k1 = 8, sect283k1 = 9, sect283r1 = 10, sect409k1 = 11, sect409r1 = 12, sect571k1 = 13, sect571r1 = 14, secp160k1 = 15, secp160r1 = 16, secp160r2 = 17, secp192k1 = 18, secp192r1 = 19, secp224k1 = 20, secp224r1 = 21, secp256k1 = 22, secp256r1 = 23, secp384r1 = 24, secp521r1 = 25, arbitrary_explicit_prime_curves = 0xFF01, arbitrary_explicit_char2_curves = 0xFF02, } --- -- RFC 4492 section 5.1.2 "Supported Point Formats Extension". EC_POINT_FORMATS = { uncompressed = 0, ansiX962_compressed_prime = 1, ansiX962_compressed_char2 = 2, } --- -- RFC 5246 section 7.4.1.4.1. Signature Algorithms HashAlgorithms = { none = 0, md5 = 1, sha1 = 2, sha224 = 3, sha256 = 4, sha384 = 5, sha512 = 6, } SignatureAlgorithms = { anonymous = 0, rsa = 1, dsa = 2, ecdsa = 3, } --- -- Extensions -- RFC 6066, draft-agl-tls-nextprotoneg-03 -- https://www.iana.org/assignments/tls-extensiontype-values/tls-extensiontype-values.xhtml -- EXTENSIONS = { ["server_name"] = 0, ["max_fragment_length"] = 1, ["client_certificate_url"] = 2, ["trusted_ca_keys"] = 3, ["truncated_hmac"] = 4, ["status_request"] = 5, ["user_mapping"] = 6, ["client_authz"] = 7, ["server_authz"] = 8, ["cert_type"] = 9, ["elliptic_curves"] = 10, ["ec_point_formats"] = 11, ["srp"] = 12, ["signature_algorithms"] = 13, ["use_srtp"] = 14, ["heartbeat"] = 15, ["application_layer_protocol_negotiation"] = 16, ["status_request_v2"] = 17, ["signed_certificate_timestamp"] = 18, ["client_certificate_type"] = 19, ["server_certificate_type"] = 20, ["padding"] = 21, -- Temporary, expires 2015-03-12 ["SessionTicket TLS"] = 35, ["next_protocol_negotiation"] = 13172, ["renegotiation_info"] = 65281, } --- -- Builds data for each extension -- Defaults to tostring (i.e. pass in the packed data you want directly) EXTENSION_HELPERS = { ["server_name"] = function (server_name) -- Only supports host_name type (0), as per RFC -- Support for other types could be added later return bin.pack(">P", bin.pack(">CP", 0, server_name)) end, ["max_fragment_length"] = tostring, ["client_certificate_url"] = tostring, ["trusted_ca_keys"] = tostring, ["truncated_hmac"] = tostring, ["status_request"] = tostring, ["elliptic_curves"] = function (elliptic_curves) local list = {} for _, name in ipairs(elliptic_curves) do list[#list+1] = bin.pack(">S", ELLIPTIC_CURVES[name]) end return bin.pack(">P", table.concat(list)) end, ["ec_point_formats"] = function (ec_point_formats) local list = {} for _, format in ipairs(ec_point_formats) do list[#list+1] = bin.pack(">C", EC_POINT_FORMATS[format]) end return bin.pack(">p", table.concat(list)) end, ["signature_algorithms"] = function(signature_algorithms) local list = {} for _, pair in ipairs(signature_algorithms) do list[#list+1] = bin.pack(">CC", HashAlgorithms[pair[1]] or pair[1], SignatureAlgorithms[pair[2]] or pair[2] ) end return bin.pack(">P", table.concat(list)) end, ["next_protocol_negotiation"] = tostring, } -- -- Encryption Algorithms -- CIPHERS = { ["TLS_NULL_WITH_NULL_NULL"] = 0x0000, ["TLS_RSA_WITH_NULL_MD5"] = 0x0001, ["TLS_RSA_WITH_NULL_SHA"] = 0x0002, ["TLS_RSA_EXPORT_WITH_RC4_40_MD5"] = 0x0003, ["TLS_RSA_WITH_RC4_128_MD5"] = 0x0004, ["TLS_RSA_WITH_RC4_128_SHA"] = 0x0005, ["TLS_RSA_EXPORT_WITH_RC2_CBC_40_MD5"] = 0x0006, ["TLS_RSA_WITH_IDEA_CBC_SHA"] = 0x0007, ["TLS_RSA_EXPORT_WITH_DES40_CBC_SHA"] = 0x0008, ["TLS_RSA_WITH_DES_CBC_SHA"] = 0x0009, ["TLS_RSA_WITH_3DES_EDE_CBC_SHA"] = 0x000A, ["TLS_DH_DSS_EXPORT_WITH_DES40_CBC_SHA"] = 0x000B, ["TLS_DH_DSS_WITH_DES_CBC_SHA"] = 0x000C, ["TLS_DH_DSS_WITH_3DES_EDE_CBC_SHA"] = 0x000D, ["TLS_DH_RSA_EXPORT_WITH_DES40_CBC_SHA"] = 0x000E, ["TLS_DH_RSA_WITH_DES_CBC_SHA"] = 0x000F, ["TLS_DH_RSA_WITH_3DES_EDE_CBC_SHA"] = 0x0010, ["TLS_DHE_DSS_EXPORT_WITH_DES40_CBC_SHA"] = 0x0011, ["TLS_DHE_DSS_WITH_DES_CBC_SHA"] = 0x0012, ["TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA"] = 0x0013, ["TLS_DHE_RSA_EXPORT_WITH_DES40_CBC_SHA"] = 0x0014, ["TLS_DHE_RSA_WITH_DES_CBC_SHA"] = 0x0015, ["TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA"] = 0x0016, ["TLS_DH_anon_EXPORT_WITH_RC4_40_MD5"] = 0x0017, ["TLS_DH_anon_WITH_RC4_128_MD5"] = 0x0018, ["TLS_DH_anon_EXPORT_WITH_DES40_CBC_SHA"] = 0x0019, ["TLS_DH_anon_WITH_DES_CBC_SHA"] = 0x001A, ["TLS_DH_anon_WITH_3DES_EDE_CBC_SHA"] = 0x001B, ["SSL_FORTEZZA_KEA_WITH_NULL_SHA"] = 0x001C, ["SSL_FORTEZZA_KEA_WITH_FORTEZZA_CBC_SHA"] = 0x001D, ["TLS_KRB5_WITH_DES_CBC_SHA-or-SSL_FORTEZZA_KEA_WITH_RC4_128_SHA"] = 0x001E, --TLS vs SSLv3 ["TLS_KRB5_WITH_3DES_EDE_CBC_SHA"] = 0x001F, ["TLS_KRB5_WITH_RC4_128_SHA"] = 0x0020, ["TLS_KRB5_WITH_IDEA_CBC_SHA"] = 0x0021, ["TLS_KRB5_WITH_DES_CBC_MD5"] = 0x0022, ["TLS_KRB5_WITH_3DES_EDE_CBC_MD5"] = 0x0023, ["TLS_KRB5_WITH_RC4_128_MD5"] = 0x0024, ["TLS_KRB5_WITH_IDEA_CBC_MD5"] = 0x0025, ["TLS_KRB5_EXPORT_WITH_DES_CBC_40_SHA"] = 0x0026, ["TLS_KRB5_EXPORT_WITH_RC2_CBC_40_SHA"] = 0x0027, ["TLS_KRB5_EXPORT_WITH_RC4_40_SHA"] = 0x0028, ["TLS_KRB5_EXPORT_WITH_DES_CBC_40_MD5"] = 0x0029, ["TLS_KRB5_EXPORT_WITH_RC2_CBC_40_MD5"] = 0x002A, ["TLS_KRB5_EXPORT_WITH_RC4_40_MD5"] = 0x002B, ["TLS_PSK_WITH_NULL_SHA"] = 0x002C, ["TLS_DHE_PSK_WITH_NULL_SHA"] = 0x002D, ["TLS_RSA_PSK_WITH_NULL_SHA"] = 0x002E, ["TLS_RSA_WITH_AES_128_CBC_SHA"] = 0x002F, ["TLS_DH_DSS_WITH_AES_128_CBC_SHA"] = 0x0030, ["TLS_DH_RSA_WITH_AES_128_CBC_SHA"] = 0x0031, ["TLS_DHE_DSS_WITH_AES_128_CBC_SHA"] = 0x0032, ["TLS_DHE_RSA_WITH_AES_128_CBC_SHA"] = 0x0033, ["TLS_DH_anon_WITH_AES_128_CBC_SHA"] = 0x0034, ["TLS_RSA_WITH_AES_256_CBC_SHA"] = 0x0035, ["TLS_DH_DSS_WITH_AES_256_CBC_SHA"] = 0x0036, ["TLS_DH_RSA_WITH_AES_256_CBC_SHA"] = 0x0037, ["TLS_DHE_DSS_WITH_AES_256_CBC_SHA"] = 0x0038, ["TLS_DHE_RSA_WITH_AES_256_CBC_SHA"] = 0x0039, ["TLS_DH_anon_WITH_AES_256_CBC_SHA"] = 0x003A, ["TLS_RSA_WITH_NULL_SHA256"] = 0x003B, ["TLS_RSA_WITH_AES_128_CBC_SHA256"] = 0x003C, ["TLS_RSA_WITH_AES_256_CBC_SHA256"] = 0x003D, ["TLS_DH_DSS_WITH_AES_128_CBC_SHA256"] = 0x003E, ["TLS_DH_RSA_WITH_AES_128_CBC_SHA256"] = 0x003F, ["TLS_DHE_DSS_WITH_AES_128_CBC_SHA256"] = 0x0040, ["TLS_RSA_WITH_CAMELLIA_128_CBC_SHA"] = 0x0041, ["TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA"] = 0x0042, ["TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA"] = 0x0043, ["TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA"] = 0x0044, ["TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA"] = 0x0045, ["TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA"] = 0x0046, ["TLS_ECDH_ECDSA_WITH_NULL_SHA-draft"] = 0x0047, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECDSA_WITH_RC4_128_SHA-draft"] = 0x0048, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECDSA_WITH_DES_CBC_SHA-draft"] = 0x0049, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA-draft"] = 0x004A, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA-draft"] = 0x004B, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA-draft"] = 0x004C, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECNRA_WITH_DES_CBC_SHA-draft"] = 0x004D, --draft-ietf-tls-ecc-00 ["TLS_ECDH_ECNRA_WITH_3DES_EDE_CBC_SHA-draft"] = 0x004E, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECDSA_NULL_SHA-draft"] = 0x004F, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECDSA_WITH_RC4_128_SHA-draft"] = 0x0050, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECDSA_WITH_DES_CBC_SHA-draft"] = 0x0051, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECDSA_WITH_3DES_EDE_CBC_SHA-draft"] = 0x0052, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECNRA_NULL_SHA-draft"] = 0x0053, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECNRA_WITH_RC4_128_SHA-draft"] = 0x0054, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECNRA_WITH_DES_CBC_SHA-draft"] = 0x0055, --draft-ietf-tls-ecc-00 ["TLS_ECMQV_ECNRA_WITH_3DES_EDE_CBC_SHA-draft"] = 0x0056, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_NULL_WITH_SHA-draft"] = 0x0057, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_WITH_RC4_128_SHA-draft"] = 0x0058, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_WITH_DES_CBC_SHA-draft"] = 0x0059, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA-draft"] = 0x005A, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_EXPORT_WITH_DES40_CBC_SHA-draft"] = 0x005B, --draft-ietf-tls-ecc-00 ["TLS_ECDH_anon_EXPORT_WITH_RC4_40_SHA-draft"] = 0x005C, --draft-ietf-tls-ecc-00 ["TLS_RSA_EXPORT1024_WITH_RC4_56_MD5"] = 0x0060, ["TLS_RSA_EXPORT1024_WITH_RC2_CBC_56_MD5"] = 0x0061, ["TLS_RSA_EXPORT1024_WITH_DES_CBC_SHA"] = 0x0062, ["TLS_DHE_DSS_EXPORT1024_WITH_DES_CBC_SHA"] = 0x0063, ["TLS_RSA_EXPORT1024_WITH_RC4_56_SHA"] = 0x0064, ["TLS_DHE_DSS_EXPORT1024_WITH_RC4_56_SHA"] = 0x0065, ["TLS_DHE_DSS_WITH_RC4_128_SHA"] = 0x0066, ["TLS_DHE_RSA_WITH_AES_128_CBC_SHA256"] = 0x0067, ["TLS_DH_DSS_WITH_AES_256_CBC_SHA256"] = 0x0068, ["TLS_DH_RSA_WITH_AES_256_CBC_SHA256"] = 0x0069, ["TLS_DHE_DSS_WITH_AES_256_CBC_SHA256"] = 0x006A, ["TLS_DHE_RSA_WITH_AES_256_CBC_SHA256"] = 0x006B, ["TLS_DH_anon_WITH_AES_128_CBC_SHA256"] = 0x006C, ["TLS_DH_anon_WITH_AES_256_CBC_SHA256"] = 0x006D, ["TLS_DHE_DSS_WITH_3DES_EDE_CBC_RMD-draft"] = 0x0072, --draft-ietf-tls-openpgp-keys-05 ["TLS_DHE_DSS_WITH_AES_128_CBC_RMD-draft"] = 0x0073, --draft-ietf-tls-openpgp-keys-05 ["TLS_DHE_DSS_WITH_AES_256_CBC_RMD-draft"] = 0x0074, --draft-ietf-tls-openpgp-keys-05 ["TLS_DHE_RSA_WITH_3DES_EDE_CBC_RMD-draft"] = 0x0077, --draft-ietf-tls-openpgp-keys-05 ["TLS_DHE_RSA_WITH_AES_128_CBC_RMD-draft"] = 0x0078, --draft-ietf-tls-openpgp-keys-05 ["TLS_DHE_RSA_WITH_AES_256_CBC_RMD-draft"] = 0x0079, --draft-ietf-tls-openpgp-keys-05 ["TLS_RSA_WITH_3DES_EDE_CBC_RMD-draft"] = 0x007C, --draft-ietf-tls-openpgp-keys-05 ["TLS_RSA_WITH_AES_128_CBC_RMD-draft"] = 0x007D, --draft-ietf-tls-openpgp-keys-05 ["TLS_RSA_WITH_AES_256_CBC_RMD-draft"] = 0x007E, --draft-ietf-tls-openpgp-keys-05 ["TLS_GOSTR341094_WITH_28147_CNT_IMIT-draft"] = 0x0080, --draft-chudov-cryptopro-cptls-04 ["TLS_GOSTR341001_WITH_28147_CNT_IMIT-draft"] = 0x0081, --draft-chudov-cryptopro-cptls-04 ["TLS_GOSTR341094_WITH_NULL_GOSTR3411-draft"] = 0x0082, --draft-chudov-cryptopro-cptls-04 ["TLS_GOSTR341001_WITH_NULL_GOSTR3411-draft"] = 0x0083, --draft-chudov-cryptopro-cptls-04 ["TLS_RSA_WITH_CAMELLIA_256_CBC_SHA"] = 0x0084, ["TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA"] = 0x0085, ["TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA"] = 0x0086, ["TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA"] = 0x0087, ["TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA"] = 0x0088, ["TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA"] = 0x0089, ["TLS_PSK_WITH_RC4_128_SHA"] = 0x008A, ["TLS_PSK_WITH_3DES_EDE_CBC_SHA"] = 0x008B, ["TLS_PSK_WITH_AES_128_CBC_SHA"] = 0x008C, ["TLS_PSK_WITH_AES_256_CBC_SHA"] = 0x008D, ["TLS_DHE_PSK_WITH_RC4_128_SHA"] = 0x008E, ["TLS_DHE_PSK_WITH_3DES_EDE_CBC_SHA"] = 0x008F, ["TLS_DHE_PSK_WITH_AES_128_CBC_SHA"] = 0x0090, ["TLS_DHE_PSK_WITH_AES_256_CBC_SHA"] = 0x0091, ["TLS_RSA_PSK_WITH_RC4_128_SHA"] = 0x0092, ["TLS_RSA_PSK_WITH_3DES_EDE_CBC_SHA"] = 0x0093, ["TLS_RSA_PSK_WITH_AES_128_CBC_SHA"] = 0x0094, ["TLS_RSA_PSK_WITH_AES_256_CBC_SHA"] = 0x0095, ["TLS_RSA_WITH_SEED_CBC_SHA"] = 0x0096, ["TLS_DH_DSS_WITH_SEED_CBC_SHA"] = 0x0097, ["TLS_DH_RSA_WITH_SEED_CBC_SHA"] = 0x0098, ["TLS_DHE_DSS_WITH_SEED_CBC_SHA"] = 0x0099, ["TLS_DHE_RSA_WITH_SEED_CBC_SHA"] = 0x009A, ["TLS_DH_anon_WITH_SEED_CBC_SHA"] = 0x009B, ["TLS_RSA_WITH_AES_128_GCM_SHA256"] = 0x009C, ["TLS_RSA_WITH_AES_256_GCM_SHA384"] = 0x009D, ["TLS_DHE_RSA_WITH_AES_128_GCM_SHA256"] = 0x009E, ["TLS_DHE_RSA_WITH_AES_256_GCM_SHA384"] = 0x009F, ["TLS_DH_RSA_WITH_AES_128_GCM_SHA256"] = 0x00A0, ["TLS_DH_RSA_WITH_AES_256_GCM_SHA384"] = 0x00A1, ["TLS_DHE_DSS_WITH_AES_128_GCM_SHA256"] = 0x00A2, ["TLS_DHE_DSS_WITH_AES_256_GCM_SHA384"] = 0x00A3, ["TLS_DH_DSS_WITH_AES_128_GCM_SHA256"] = 0x00A4, ["TLS_DH_DSS_WITH_AES_256_GCM_SHA384"] = 0x00A5, ["TLS_DH_anon_WITH_AES_128_GCM_SHA256"] = 0x00A6, ["TLS_DH_anon_WITH_AES_256_GCM_SHA384"] = 0x00A7, ["TLS_PSK_WITH_AES_128_GCM_SHA256"] = 0x00A8, ["TLS_PSK_WITH_AES_256_GCM_SHA384"] = 0x00A9, ["TLS_DHE_PSK_WITH_AES_128_GCM_SHA256"] = 0x00AA, ["TLS_DHE_PSK_WITH_AES_256_GCM_SHA384"] = 0x00AB, ["TLS_RSA_PSK_WITH_AES_128_GCM_SHA256"] = 0x00AC, ["TLS_RSA_PSK_WITH_AES_256_GCM_SHA384"] = 0x00AD, ["TLS_PSK_WITH_AES_128_CBC_SHA256"] = 0x00AE, ["TLS_PSK_WITH_AES_256_CBC_SHA384"] = 0x00AF, ["TLS_PSK_WITH_NULL_SHA256"] = 0x00B0, ["TLS_PSK_WITH_NULL_SHA384"] = 0x00B1, ["TLS_DHE_PSK_WITH_AES_128_CBC_SHA256"] = 0x00B2, ["TLS_DHE_PSK_WITH_AES_256_CBC_SHA384"] = 0x00B3, ["TLS_DHE_PSK_WITH_NULL_SHA256"] = 0x00B4, ["TLS_DHE_PSK_WITH_NULL_SHA384"] = 0x00B5, ["TLS_RSA_PSK_WITH_AES_128_CBC_SHA256"] = 0x00B6, ["TLS_RSA_PSK_WITH_AES_256_CBC_SHA384"] = 0x00B7, ["TLS_RSA_PSK_WITH_NULL_SHA256"] = 0x00B8, ["TLS_RSA_PSK_WITH_NULL_SHA384"] = 0x00B9, ["TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BA, ["TLS_DH_DSS_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BB, ["TLS_DH_RSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BC, ["TLS_DHE_DSS_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BD, ["TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BE, ["TLS_DH_anon_WITH_CAMELLIA_128_CBC_SHA256"] = 0x00BF, ["TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C0, ["TLS_DH_DSS_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C1, ["TLS_DH_RSA_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C2, ["TLS_DHE_DSS_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C3, ["TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C4, ["TLS_DH_anon_WITH_CAMELLIA_256_CBC_SHA256"] = 0x00C5, ["TLS_ECDH_ECDSA_WITH_NULL_SHA"] = 0xC001, ["TLS_ECDH_ECDSA_WITH_RC4_128_SHA"] = 0xC002, ["TLS_ECDH_ECDSA_WITH_3DES_EDE_CBC_SHA"] = 0xC003, ["TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA"] = 0xC004, ["TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA"] = 0xC005, ["TLS_ECDHE_ECDSA_WITH_NULL_SHA"] = 0xC006, ["TLS_ECDHE_ECDSA_WITH_RC4_128_SHA"] = 0xC007, ["TLS_ECDHE_ECDSA_WITH_3DES_EDE_CBC_SHA"] = 0xC008, ["TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA"] = 0xC009, ["TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA"] = 0xC00A, ["TLS_ECDH_RSA_WITH_NULL_SHA"] = 0xC00B, ["TLS_ECDH_RSA_WITH_RC4_128_SHA"] = 0xC00C, ["TLS_ECDH_RSA_WITH_3DES_EDE_CBC_SHA"] = 0xC00D, ["TLS_ECDH_RSA_WITH_AES_128_CBC_SHA"] = 0xC00E, ["TLS_ECDH_RSA_WITH_AES_256_CBC_SHA"] = 0xC00F, ["TLS_ECDHE_RSA_WITH_NULL_SHA"] = 0xC010, ["TLS_ECDHE_RSA_WITH_RC4_128_SHA"] = 0xC011, ["TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA"] = 0xC012, ["TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA"] = 0xC013, ["TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA"] = 0xC014, ["TLS_ECDH_anon_WITH_NULL_SHA"] = 0xC015, ["TLS_ECDH_anon_WITH_RC4_128_SHA"] = 0xC016, ["TLS_ECDH_anon_WITH_3DES_EDE_CBC_SHA"] = 0xC017, ["TLS_ECDH_anon_WITH_AES_128_CBC_SHA"] = 0xC018, ["TLS_ECDH_anon_WITH_AES_256_CBC_SHA"] = 0xC019, ["TLS_SRP_SHA_WITH_3DES_EDE_CBC_SHA"] = 0xC01A, ["TLS_SRP_SHA_RSA_WITH_3DES_EDE_CBC_SHA"] = 0xC01B, ["TLS_SRP_SHA_DSS_WITH_3DES_EDE_CBC_SHA"] = 0xC01C, ["TLS_SRP_SHA_WITH_AES_128_CBC_SHA"] = 0xC01D, ["TLS_SRP_SHA_RSA_WITH_AES_128_CBC_SHA"] = 0xC01E, ["TLS_SRP_SHA_DSS_WITH_AES_128_CBC_SHA"] = 0xC01F, ["TLS_SRP_SHA_WITH_AES_256_CBC_SHA"] = 0xC020, ["TLS_SRP_SHA_RSA_WITH_AES_256_CBC_SHA"] = 0xC021, ["TLS_SRP_SHA_DSS_WITH_AES_256_CBC_SHA"] = 0xC022, ["TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256"] = 0xC023, ["TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384"] = 0xC024, ["TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256"] = 0xC025, ["TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384"] = 0xC026, ["TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256"] = 0xC027, ["TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384"] = 0xC028, ["TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256"] = 0xC029, ["TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384"] = 0xC02A, ["TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256"] = 0xC02B, ["TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384"] = 0xC02C, ["TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256"] = 0xC02D, ["TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384"] = 0xC02E, ["TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256"] = 0xC02F, ["TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384"] = 0xC030, ["TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256"] = 0xC031, ["TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384"] = 0xC032, ["TLS_ECDHE_PSK_WITH_RC4_128_SHA"] = 0xC033, ["TLS_ECDHE_PSK_WITH_3DES_EDE_CBC_SHA"] = 0xC034, ["TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA"] = 0xC035, ["TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA"] = 0xC036, ["TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256"] = 0xC037, ["TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384"] = 0xC038, ["TLS_ECDHE_PSK_WITH_NULL_SHA"] = 0xC039, ["TLS_ECDHE_PSK_WITH_NULL_SHA256"] = 0xC03A, ["TLS_ECDHE_PSK_WITH_NULL_SHA384"] = 0xC03B, ["TLS_RSA_WITH_ARIA_128_CBC_SHA256"] = 0xC03C, ["TLS_RSA_WITH_ARIA_256_CBC_SHA384"] = 0xC03D, ["TLS_DH_DSS_WITH_ARIA_128_CBC_SHA256"] = 0xC03E, ["TLS_DH_DSS_WITH_ARIA_256_CBC_SHA384"] = 0xC03F, ["TLS_DH_RSA_WITH_ARIA_128_CBC_SHA256"] = 0xC040, ["TLS_DH_RSA_WITH_ARIA_256_CBC_SHA384"] = 0xC041, ["TLS_DHE_DSS_WITH_ARIA_128_CBC_SHA256"] = 0xC042, ["TLS_DHE_DSS_WITH_ARIA_256_CBC_SHA384"] = 0xC043, ["TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256"] = 0xC044, ["TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384"] = 0xC045, ["TLS_DH_anon_WITH_ARIA_128_CBC_SHA256"] = 0xC046, ["TLS_DH_anon_WITH_ARIA_256_CBC_SHA384"] = 0xC047, ["TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256"] = 0xC048, ["TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384"] = 0xC049, ["TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256"] = 0xC04A, ["TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384"] = 0xC04B, ["TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256"] = 0xC04C, ["TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384"] = 0xC04D, ["TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256"] = 0xC04E, ["TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384"] = 0xC04F, ["TLS_RSA_WITH_ARIA_128_GCM_SHA256"] = 0xC050, ["TLS_RSA_WITH_ARIA_256_GCM_SHA384"] = 0xC051, ["TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256"] = 0xC052, ["TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384"] = 0xC053, ["TLS_DH_RSA_WITH_ARIA_128_GCM_SHA256"] = 0xC054, ["TLS_DH_RSA_WITH_ARIA_256_GCM_SHA384"] = 0xC055, ["TLS_DHE_DSS_WITH_ARIA_128_GCM_SHA256"] = 0xC056, ["TLS_DHE_DSS_WITH_ARIA_256_GCM_SHA384"] = 0xC057, ["TLS_DH_DSS_WITH_ARIA_128_GCM_SHA256"] = 0xC058, ["TLS_DH_DSS_WITH_ARIA_256_GCM_SHA384"] = 0xC059, ["TLS_DH_anon_WITH_ARIA_128_GCM_SHA256"] = 0xC05A, ["TLS_DH_anon_WITH_ARIA_256_GCM_SHA384"] = 0xC05B, ["TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256"] = 0xC05C, ["TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384"] = 0xC05D, ["TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256"] = 0xC05E, ["TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384"] = 0xC05F, ["TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256"] = 0xC060, ["TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384"] = 0xC061, ["TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256"] = 0xC062, ["TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384"] = 0xC063, ["TLS_PSK_WITH_ARIA_128_CBC_SHA256"] = 0xC064, ["TLS_PSK_WITH_ARIA_256_CBC_SHA384"] = 0xC065, ["TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256"] = 0xC066, ["TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384"] = 0xC067, ["TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256"] = 0xC068, ["TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384"] = 0xC069, ["TLS_PSK_WITH_ARIA_128_GCM_SHA256"] = 0xC06A, ["TLS_PSK_WITH_ARIA_256_GCM_SHA384"] = 0xC06B, ["TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256"] = 0xC06C, ["TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384"] = 0xC06D, ["TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256"] = 0xC06E, ["TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384"] = 0xC06F, ["TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256"] = 0xC070, ["TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384"] = 0xC071, ["TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC072, ["TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC073, ["TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC074, ["TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC075, ["TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC076, ["TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC077, ["TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC078, ["TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC079, ["TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC07A, ["TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC07B, ["TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC07C, ["TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC07D, ["TLS_DH_RSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC07E, ["TLS_DH_RSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC07F, ["TLS_DHE_DSS_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC080, ["TLS_DHE_DSS_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC081, ["TLS_DH_DSS_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC082, ["TLS_DH_DSS_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC083, ["TLS_DH_anon_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC084, ["TLS_DH_anon_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC085, ["TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC086, ["TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC087, ["TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC088, ["TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC089, ["TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC08A, ["TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC08B, ["TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC08C, ["TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC08D, ["TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC08E, ["TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC08F, ["TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC090, ["TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC091, ["TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256"] = 0xC092, ["TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384"] = 0xC093, ["TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC094, ["TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC095, ["TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC096, ["TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC097, ["TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC098, ["TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC099, ["TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256"] = 0xC09A, ["TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384"] = 0xC09B, ["TLS_RSA_WITH_AES_128_CCM"] = 0xC09C, ["TLS_RSA_WITH_AES_256_CCM"] = 0xC09D, ["TLS_DHE_RSA_WITH_AES_128_CCM"] = 0xC09E, ["TLS_DHE_RSA_WITH_AES_256_CCM"] = 0xC09F, ["TLS_RSA_WITH_AES_128_CCM_8"] = 0xC0A0, ["TLS_RSA_WITH_AES_256_CCM_8"] = 0xC0A1, ["TLS_DHE_RSA_WITH_AES_128_CCM_8"] = 0xC0A2, ["TLS_DHE_RSA_WITH_AES_256_CCM_8"] = 0xC0A3, ["TLS_PSK_WITH_AES_128_CCM"] = 0xC0A4, ["TLS_PSK_WITH_AES_256_CCM"] = 0xC0A5, ["TLS_DHE_PSK_WITH_AES_128_CCM"] = 0xC0A6, ["TLS_DHE_PSK_WITH_AES_256_CCM"] = 0xC0A7, ["TLS_PSK_WITH_AES_128_CCM_8"] = 0xC0A8, ["TLS_PSK_WITH_AES_256_CCM_8"] = 0xC0A9, ["TLS_PSK_DHE_WITH_AES_128_CCM_8"] = 0xC0AA, ["TLS_PSK_DHE_WITH_AES_256_CCM_8"] = 0xC0AB, ["TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256"] = 0xCC13, ["TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256"] = 0xCC14, ["TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256"] = 0xCC15, ["SSL_RSA_FIPS_WITH_DES_CBC_SHA"] = 0xFEFE, ["SSL_RSA_FIPS_WITH_3DES_EDE_CBC_SHA"] = 0xFEFF, } DEFAULT_CIPHERS = { "TLS_RSA_WITH_AES_128_CBC_SHA", -- mandatory TLSv1.2 "TLS_RSA_WITH_3DES_EDE_CBC_SHA", -- mandatory TLSv1.1 "TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA", -- mandatory TLSv1.0 "TLS_DHE_RSA_WITH_AES_256_CBC_SHA", -- DHE with strong AES "TLS_RSA_WITH_RC4_128_MD5", -- Weak and old, but likely supported on old stuff } local function find_key(t, value) local k, v for k, v in pairs(t) do if v == value then return k end end return nil end -- Keep this local to enforce use of the cipher_info function local cipher_info_cache = { -- pre-populate the special cases that break the parser below ["TLS_ECDH_anon_NULL_WITH_SHA-draft"] = { kex = "ECDH", dh = true, ec = true, server_auth = "anon", cipher = "NULL", hash = "SHA", draft = true }, ["TLS_ECMQV_ECDSA_NULL_SHA-draft"] = { kex = "ECMQV", ec = true, server_auth = "ECDSA", cipher = "NULL", hash = "SHA", draft = true }, ["TLS_ECMQV_ECNRA_NULL_SHA-draft"] = { kex = "ECMQV", ec = true, server_auth = "ECNRA", cipher = "NULL", hash = "SHA", draft = true }, ["TLS_GOSTR341094_WITH_28147_CNT_IMIT-draft"] = { kex = "GOSTR341094", server_auth = "GOSTR341094", cipher = "GOST28147", hash = "IMIT_GOST28147", draft = true }, ["TLS_GOSTR341001_WITH_28147_CNT_IMIT-draft"] = { kex = "GOSTR341001", server_auth = "GOSTR341001", cipher = "GOST28147", hash = "IMIT_GOST28147", draft = true }, ["TLS_GOSTR341094_WITH_NULL_GOSTR3411-draft"] = { kex = "GOSTR341094", server_auth = "GOSTR341094", cipher = "NULL", hash = "HMAC_GOSTR3411", draft = true }, ["TLS_GOSTR341001_WITH_NULL_GOSTR3411-draft"] = { kex = "GOSTR341001", server_auth = "GOSTR341001", cipher = "NULL", hash = "HMAC_GOSTR3411", draft = true }, } -- A couple helpers for server_key_exchange parsing local function unpack_dhparams (blob, pos) local p, g, y pos, p, g, y = bin.unpack(">PPP", blob, pos) return pos, {p=p, g=g, y=y}, #p * 8 end local function unpack_ecdhparams (blob, pos) local eccurvetype pos, eccurvetype = bin.unpack("C", blob, pos) local ret = {} local strength if eccurvetype == 1 then local p, a, b, base, order, cofactor pos, p, a, b, base, order, cofactor = bin.unpack("pppppp", blob, pos) strength = math.log(order, 2) ret.curve_params = { ec_curve_type = "explicit_prime", prime_p=p, curve={a=a, b=b}, base=base, order=order, cofactor=cofactor } elseif eccurvetype == 2 then local p = {} local m, basis pos, m, basis = bin.unpack(">SC", blob, pos) if basis == 1 then -- ec_trinomial pos, p.k = bin.unpack("p", blob, pos) elseif basis == 2 then -- ec_pentanomial pos, p.k1, p.k2, p.k3 = bin.unpack("ppp", blob, pos) end local a, b, base, order, cofactor pos, a, b, base, order, cofactor = bin.unpack("ppppp", blob, pos) strength = math.log(order, 2) ret.curve_params = { ec_curve_type = "explicit_char2", m=m, basis=basis, field=p, curve={a=a, b=b}, base=base, order=order, cofactor=cofactor } elseif eccurvetype == 3 then local curve pos, curve = bin.unpack(">S", blob, pos) ret.curve_params = { ec_curve_type = "namedcurve", curve = find_key(ELLIPTIC_CURVES, curve) } local size = ret.curve_params.curve:match("(%d+)[rk]%d$") if size then strength = tonumber(size) end end pos, ret.public = bin.unpack("p", blob, pos) return pos, ret, strength end local function unpack_signed (blob, pos, protocol) if pos > #blob then -- not-signed return pos, nil end local hash_alg, sig_alg, sig -- TLSv1.2 changed to allow arbitrary hash and sig algorithms if protocol and PROTOCOLS[protocol] >= 0x0303 then pos, hash_alg, sig_alg, sig = bin.unpack("CC>P", blob, pos) else pos, sig = bin.unpack(">P", blob, pos) end return pos, {hash_algorithm=hash_alg, signature_algorithm=sig_alg, signature=sig} end --- Get the strength-equivalent RSA key size -- -- Based on NIST SP800-57 part 1 rev 3 -- @param ktype Key type ("dh", "ec", "rsa", "dsa") -- @param bits Size of key in bits -- @return Size in bits of RSA key with equivalent strength function rsa_equiv (ktype, bits) if ktype == "rsa" or ktype == "dsa" or ktype == "dh" then return bits elseif ktype == "ec" then if bits < 160 then return 512 -- Possibly down to 0, but details not published elseif bits < 224 then return 1024 elseif bits < 256 then return 2048 elseif bits < 384 then return 3072 elseif bits < 512 then return 7680 else -- 512+ return 15360 end end return nil end KEX_ALGORITHMS = {} -- RFC 5246 KEX_ALGORITHMS.NULL = { anon = true } KEX_ALGORITHMS.DH_anon = { anon = true, type = "dh", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.dhparams, ret.strength = unpack_dhparams(blob) return ret end } KEX_ALGORITHMS.DH_anon_EXPORT = { anon=true, export=true, type = "dh", server_key_exchange = KEX_ALGORITHMS.DH_anon.server_key_exchange } KEX_ALGORITHMS.ECDH_anon = { anon=true, type = "ec", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.ecdhparams, ret.strength = unpack_ecdhparams(blob) return ret end } KEX_ALGORITHMS.ECDH_anon_EXPORT = { anon=true, export=true, type = "ec", server_key_exchange = KEX_ALGORITHMS.ECDH_anon.server_key_exchange } KEX_ALGORITHMS.RSA = { pubkey="rsa", } -- http://www-archive.mozilla.org/projects/security/pki/nss/ssl/fips-ssl-ciphersuites.html KEX_ALGORITHMS.RSA_FIPS = KEX_ALGORITHMS.RSA KEX_ALGORITHMS.RSA_EXPORT = { export=true, pubkey="rsa", type = "rsa", server_key_exchange = function (blob, protocol) local pos local ret = {rsa={}} pos, ret.rsa.modulus, ret.rsa.exponent = bin.unpack(">PP", blob) pos, ret.signed = unpack_signed(blob, pos) ret.strength = #ret.rsa.modulus return ret end } KEX_ALGORITHMS.RSA_EXPORT1024 = KEX_ALGORITHMS.RSA_EXPORT KEX_ALGORITHMS.DHE_RSA={ pubkey="rsa", type = "dh", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.dhparams, ret.strength = unpack_dhparams(blob) pos, ret.signed = unpack_signed(blob, pos) return ret end } KEX_ALGORITHMS.DHE_RSA_EXPORT={ export=true, pubkey="rsa", type = "dh", server_key_exchange = KEX_ALGORITHMS.DHE_RSA.server_key_exchange } KEX_ALGORITHMS.DHE_DSS={ pubkey="dsa", type = "dh", server_key_exchange = KEX_ALGORITHMS.DHE_RSA.server_key_exchange } KEX_ALGORITHMS.DHE_DSS_EXPORT={ export=true, pubkey="dsa", type = "dh", server_key_exchange = KEX_ALGORITHMS.DHE_RSA.server_key_exchange } KEX_ALGORITHMS.DHE_DSS_EXPORT1024 = KEX_ALGORITHMS.DHE_DSS_EXPORT1024 KEX_ALGORITHMS.DH_DSS={ pubkey="dh", } KEX_ALGORITHMS.DH_DSS_EXPORT={ export=true, pubkey="dh", } KEX_ALGORITHMS.DH_RSA={ pubkey="dh", } KEX_ALGORITHMS.DH_RSA_EXPORT={ export=true, pubkey="dh", } KEX_ALGORITHMS.ECDHE_RSA={ pubkey="rsa", type = "ec", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.ecdhparams, ret.strength = unpack_ecdhparams(blob) pos, ret.signed = unpack_signed(blob, pos) return ret end } KEX_ALGORITHMS.ECDHE_ECDSA={ pubkey="ec", type = "ec", server_key_exchange = KEX_ALGORITHMS.ECDHE_RSA.server_key_exchange } KEX_ALGORITHMS.ECDH_ECDSA={ pubkey="ec", } KEX_ALGORITHMS.ECDH_RSA={ pubkey="ec", } -- draft-ietf-tls-ecc-00 KEX_ALGORITHMS.ECDH_ECNRA={ pubkey="ec", } KEX_ALGORITHMS.ECMQV_ECDSA={ pubkey="ec", type = "ecmqv", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.mqvparams = bin.unpack("p", blob) return ret end } KEX_ALGORITHMS.ECMQV_ECNRA={ pubkey="ec", } -- rfc4279 KEX_ALGORITHMS.PSK = { type = "psk", server_key_exchange = function (blob, protocol) local pos, hint = bin.unpack(">P", blob) return {psk_identity_hint=hint} end } KEX_ALGORITHMS.RSA_PSK = { pubkey="rsa", type = "psk", server_key_exchange = KEX_ALGORITHMS.PSK.server_key_exchange } KEX_ALGORITHMS.DHE_PSK = { type = "dh", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.psk_identity_hint = bin.unpack(">P", blob) pos, ret.dhparams, ret.strength = unpack_dhparams(blob, pos) return ret end } --nomenclature change KEX_ALGORITHMS.PSK_DHE = KEX_ALGORITHMS.DHE_PSK --rfc5489 KEX_ALGORITHMS.ECDHE_PSK={ type = "ec", server_key_exchange = function (blob, protocol) local pos local ret = {} pos, ret.psk_identity_hint = bin.unpack(">P", blob) pos, ret.ecdhparams, ret.strength = unpack_ecdhparams(blob, pos) return ret end } -- RFC 5054 KEX_ALGORITHMS.SRP_SHA = { type = "srp", server_key_exchange = function (blob, protocol) local pos local ret = {srp={}} pos, ret.srp.N, ret.srp.g, ret.srp.s, ret.srp.B = bin.unpack(">PPpP", blob) pos, ret.signed = unpack_signed(blob, pos) ret.strength = #ret.srp.N return ret end } KEX_ALGORITHMS.SRP_SHA_DSS = { pubkey="dsa", type = "srp", server_key_exchange = KEX_ALGORITHMS.SRP_SHA.server_key_exchange } KEX_ALGORITHMS.SRP_SHA_RSA = { pubkey="rsa", type = "srp", server_key_exchange = KEX_ALGORITHMS.SRP_SHA.server_key_exchange } -- RFC 6101 KEX_ALGORITHMS.FORTEZZA_KEA={} -- RFC 4491 KEX_ALGORITHMS.GOSTR341001={} KEX_ALGORITHMS.GOSTR341094={} -- RFC 2712 KEX_ALGORITHMS.KRB5={} KEX_ALGORITHMS.KRB5_EXPORT={ export=true, } --- Get info about a cipher suite -- -- Returned table has "kex", "cipher", "mode", "size", and -- "hash" keys, as well as boolean flag "draft". The "draft" -- flag is only supported for some suites that have different enumeration -- values in draft versus final RFC. -- @param c The cipher suite name, e.g. TLS_RSA_WITH_AES_128_GCM_SHA256 -- @return A table of info as described above. function cipher_info (c) local info = cipher_info_cache[c] if info then return info end info = {} local tokens = stdnse.strsplit("_", c) local i = 1 if tokens[i] ~= "TLS" and tokens[i] ~= "SSL" then stdnse.debug2("cipher_info: Not a TLS ciphersuite: %s", c) return nil end -- kex, cipher, size, mode, hash i = i + 1 while tokens[i] and tokens[i] ~= "WITH" do i = i + 1 end info.kex = table.concat(tokens, "_", 2, i-1) if tokens[i] and tokens[i] ~= "WITH" then stdnse.debug2("cipher_info: Can't parse (no WITH): %s", c) return nil end -- cipher i = i + 1 local t = tokens[i] info.cipher = t if t == "3DES" then i = i + 1 -- 3DES_EDE end -- key size if t == "3DES" then -- NIST SP 800-57 info.size = 112 elseif t == "CHACHA20" then info.size = 256 elseif t == "IDEA" then info.size = 128 elseif t == "SEED" then info.size = 128 elseif t == "FORTEZZA" then info.size = 80 elseif t == "DES" then info.size = 56 elseif t == "RC2" or t == "DES40" then info.size = 40 elseif t == "NULL" then info.size = 0 else i = i + 1 info.size = tonumber(tokens[i]) end -- stream ciphers don't have a mode if info.cipher == "RC4" then info.mode = "stream" elseif info.cipher == "CHACHA20" then i = i + 1 info.cipher = "CHACHA20-POLY1305" info.mode = "stream" elseif info.cipher ~= "NULL" then i = i + 1 info.mode = tokens[i] end -- export key size override if info.export and tonumber(tokens[i+1]) then i = i + 1 info.size = tonumber(tokens[i]) end -- hash if info.mode == "CCM" then info.hash = "SHA256" else i = i + 1 t = (tokens[i]):match("(.*)%-draft$") if t then info.draft = true else t = tokens[i] end info.hash = t end cipher_info_cache[c] = info return info end SCSVS = { ["TLS_EMPTY_RENEGOTIATION_INFO_SCSV"] = 0x00FF, -- rfc5746 ["TLS_FALLBACK_SCSV"] = 0x5600, -- draft-ietf-tls-downgrade-scsv-00 } -- Helper function to unpack a 3-byte integer value local function unpack_3byte (buffer, pos) local low, high pos, high, low = bin.unpack("C>S", buffer, pos) return pos, low + high * 0x10000 end --- -- Read a SSL/TLS record -- @param buffer The read buffer -- @param i The position in the buffer to start reading -- @param fragment Message fragment left over from previous record (nil if none) -- @return The current position in the buffer -- @return The record that was read, as a table function record_read(buffer, i, fragment) local b, h, len local add = 0 ------------ -- Header -- ------------ -- Ensure we have enough data for the header. if #buffer - i < TLS_RECORD_HEADER_LENGTH then return i, nil end -- Parse header. h = {} local j, typ, proto = bin.unpack(">CS", buffer, i) local name = find_key(TLS_CONTENTTYPE_REGISTRY, typ) if name == nil then stdnse.debug1("Unknown TLS ContentType: %d", typ) return j, nil end h["type"] = name name = find_key(PROTOCOLS, proto) if name == nil then stdnse.debug1("Unknown TLS Protocol: 0x%04x", proto) return j, nil end h["protocol"] = name j, h["length"] = bin.unpack(">S", buffer, j) -- Ensure we have enough data for the body. len = j + h["length"] - 1 if #buffer < len then return i, nil end -- Adjust buffer and length to account for message fragment left over -- from last record. if fragment then add = #fragment len = len + add buffer = buffer:sub(1, j - 1) .. fragment .. buffer:sub(j, -1) end -- Convert to human-readable form. ---------- -- Body -- ---------- h["body"] = {} while j <= len do -- RFC 2246, 6.2.1 "multiple client messages of the same ContentType may -- be coalesced into a single TLSPlaintext record" b = {} if h["type"] == "alert" then -- Parse body. j, b["level"] = bin.unpack("C", buffer, j) j, b["description"] = bin.unpack("C", buffer, j) -- Convert to human-readable form. b["level"] = find_key(TLS_ALERT_LEVELS, b["level"]) b["description"] = find_key(TLS_ALERT_REGISTRY, b["description"]) table.insert(h["body"], b) elseif h["type"] == "handshake" then -- Check for message fragmentation. if len - j < 3 then h.fragment = buffer:sub(j, len) return len + 1 - add, h end -- Parse body. j, b["type"] = bin.unpack("C", buffer, j) local msg_end j, msg_end = unpack_3byte(buffer, j) msg_end = msg_end + j -- Convert to human-readable form. b["type"] = find_key(TLS_HANDSHAKETYPE_REGISTRY, b["type"]) -- Check for message fragmentation. if msg_end > len + 1 then h.fragment = buffer:sub(j - 4, len) return len + 1 - add, h end if b["type"] == "server_hello" then -- Parse body. j, b["protocol"] = bin.unpack(">S", buffer, j) j, b["time"] = bin.unpack(">I", buffer, j) j, b["random"] = bin.unpack("A28", buffer, j) j, b["session_id_length"] = bin.unpack("C", buffer, j) j, b["session_id"] = bin.unpack("A" .. b["session_id_length"], buffer, j) j, b["cipher"] = bin.unpack(">S", buffer, j) j, b["compressor"] = bin.unpack("C", buffer, j) -- Optional extensions for TLS only if j < msg_end and h["protocol"] ~= "SSLv3" then local num_exts b["extensions"] = {} j, num_exts = bin.unpack(">S", buffer, j) for e = 0, num_exts do if j >= msg_end then break end local extcode, datalen j, extcode = bin.unpack(">S", buffer, j) extcode = find_key(EXTENSIONS, extcode) or extcode j, b["extensions"][extcode] = bin.unpack(">P", buffer, j) end end -- Convert to human-readable form. b["protocol"] = find_key(PROTOCOLS, b["protocol"]) b["cipher"] = find_key(CIPHERS, b["cipher"]) b["compressor"] = find_key(COMPRESSORS, b["compressor"]) elseif b["type"] == "certificate" then local cert_end j, cert_end = unpack_3byte(buffer, j) cert_end = cert_end + j if cert_end > msg_end then stdnse.debug2("server_certificate length > handshake body length!") end b["certificates"] = {} while j < cert_end do local cert_len, cert j, cert_len = unpack_3byte(buffer, j) j, cert = bin.unpack("A" .. cert_len, buffer, j) -- parse these with sslcert.parse_ssl_certificate table.insert(b["certificates"], cert) end else -- TODO: implement other handshake message types stdnse.debug2("Unknown handshake message type: %s", b["type"]) j, b["data"] = bin.unpack("A" .. msg_end - j, buffer, j) end table.insert(h["body"], b) elseif h["type"] == "heartbeat" then j, b["type"], b["payload_length"] = bin.unpack("C>S", buffer, j) j, b["payload"], b["padding"] = bin.unpack("PP", buffer, j) table.insert(h["body"], b) else stdnse.debug1("Unknown message type: %s", h["type"]) end end -- Ignore unparsed bytes. j = len + 1 return j - add, h end --- -- Build a SSL/TLS record -- @param type The type of record ("handshake", "change_cipher_spec", etc.) -- @param protocol The protocol and version ("SSLv3", "TLSv1.0", etc.) -- @param b The record body -- @return The SSL/TLS record as a string function record_write(type, protocol, b) return table.concat({ -- Set the header as a handshake. bin.pack("C", TLS_CONTENTTYPE_REGISTRY[type]), -- Set the protocol. bin.pack(">S", PROTOCOLS[protocol]), -- Set the length of the header body. bin.pack(">S", #b), b }) end -- Claim to support every hash and signature algorithm combination (TLSv1.2 only) -- local signature_algorithms_all do local sigalgs = {} for hash, _ in pairs(HashAlgorithms) do for sig, _ in pairs(SignatureAlgorithms) do -- RFC 5246 7.4.1.4.1. -- The "anonymous" value is meaningless in this context but used in -- Section 7.4.3. It MUST NOT appear in this extension. if sig ~= "anonymous" then sigalgs[#sigalgs+1] = {hash, sig} end end end signature_algorithms_all = EXTENSION_HELPERS["signature_algorithms"](sigalgs) end --- -- Build a client_hello message -- -- The options table has the following keys: -- * <code>"protocol"</code> - The TLS protocol version string -- * <code>"ciphers"</code> - a table containing the cipher suite names. Defaults to the NULL cipher -- * <code>"compressors"</code> - a table containing the compressor names. Default: NULL -- * <code>"extensions"</code> - a table containing the extension names. Default: no extensions -- @param t Table of options -- @return The client_hello record as a string function client_hello(t) local b, ciphers, compressor, compressors, h, len t = t or {} ---------- -- Body -- ---------- b = {} -- Set the protocol. local protocol = t["protocol"] or HIGHEST_PROTOCOL table.insert(b, bin.pack(">S", PROTOCOLS[protocol])) -- Set the random data. table.insert(b, bin.pack(">I", os.time())) -- Set the random data. table.insert(b, stdnse.generate_random_string(28)) -- Set the session ID. table.insert(b, '\0') -- Cipher suites. ciphers = {} -- Add specified ciphers. for _, cipher in pairs(t["ciphers"] or DEFAULT_CIPHERS) do if type(cipher) == "string" then cipher = CIPHERS[cipher] or SCSVS[cipher] end if type(cipher) == "number" and cipher >= 0 and cipher <= 0xffff then table.insert(ciphers, bin.pack(">S", cipher)) else stdnse.debug1("Unknown cipher in client_hello: %s", cipher) end end table.insert(b, bin.pack(">P", table.concat(ciphers))) -- Compression methods. compressors = {} if t["compressors"] ~= nil then -- Add specified compressors. for _, compressor in pairs(t["compressors"]) do if compressor ~= "NULL" then table.insert(compressors, bin.pack("C", COMPRESSORS[compressor])) end end end -- Always include NULL as last choice table.insert(compressors, bin.pack("C", COMPRESSORS["NULL"])) table.insert(b, bin.pack(">p", table.concat(compressors))) -- TLS extensions if PROTOCOLS[protocol] and protocol ~= "SSLv3" then local extensions = {} if t["extensions"] ~= nil then -- Do we need to add the signature_algorithms extension? local need_sigalg = (protocol == "TLSv1.2") -- Add specified extensions. for extension, data in pairs(t["extensions"]) do if type(extension) == "number" then table.insert(extensions, bin.pack(">S", extension)) else if extension == "signature_algorithms" then need_sigalg = false end table.insert(extensions, bin.pack(">S", EXTENSIONS[extension])) end table.insert(extensions, bin.pack(">P", data)) end if need_sigalg then table.insert(extensions, bin.pack(">S", EXTENSIONS["signature_algorithms"])) table.insert(extensions, bin.pack(">P", signature_algorithms_all)) end end -- Extensions are optional if #extensions ~= 0 then table.insert(b, bin.pack(">P", table.concat(extensions))) end end ------------ -- Header -- ------------ b = table.concat(b) h = {} -- Set type to ClientHello. table.insert(h, bin.pack("C", TLS_HANDSHAKETYPE_REGISTRY["client_hello"])) -- Set the length of the body. len = bin.pack(">I", #b) -- body length is 24 bits big-endian, so the 3 LSB of len table.insert(h, len:sub(2,4)) table.insert(h, b) -- Record layer version should be SSLv3 (lowest compatible record version) return record_write("handshake", "SSLv3", table.concat(h)) end local function read_atleast(s, n) local buf = {} local count = 0 while count < n do local status, data = s:receive_bytes(n - count) if not status then return status, data, table.concat(buf) end buf[#buf+1] = data count = count + #data end return true, table.concat(buf) end --- Get an entire record into a buffer -- -- Caller is responsible for closing the socket if necessary. -- @param sock The socket to read additional data from -- @param buffer The string buffer holding any previously-read data -- (default: "") -- @param i The position in the buffer where the record should start -- (default: 1) -- @return status Socket status -- @return Buffer containing at least 1 record if status is true -- @return Error text if there was an error function record_buffer(sock, buffer, i) buffer = buffer or "" i = i or 1 local count = #buffer:sub(i) local status, resp, rem if count < TLS_RECORD_HEADER_LENGTH then status, resp, rem = read_atleast(sock, TLS_RECORD_HEADER_LENGTH - count) if not status then return false, buffer .. rem, resp end buffer = buffer .. resp count = count + #resp end -- ContentType, ProtocolVersion, length local _, _, _, len = bin.unpack(">CSS", buffer, i) if count < TLS_RECORD_HEADER_LENGTH + len then status, resp = read_atleast(sock, TLS_RECORD_HEADER_LENGTH + len - count) if not status then return false, buffer, resp end buffer = buffer .. resp end return true, buffer end return _ENV;
mit
dani-sj/capitan01
plugins/banhammer.lua
106
11894
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^([Bb]anall) (.*)$", "^([Bb]anall)$", "^([Bb]anlist) (.*)$", "^([Bb]anlist)$", "^([Gg]banlist)$", "^([Bb]an) (.*)$", "^([Kk]ick)$", "^([Uu]nban) (.*)$", "^([Uu]nbanall) (.*)$", "^([Uu]nbanall)$", "^([Kk]ick) (.*)$", "^([Kk]ickme)$", "^([Bb]an)$", "^([Uu]nban)$", "^([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
geanux/darkstar
scripts/zones/Upper_Jeuno/npcs/Paya-Sabya.lua
17
1335
----------------------------------- -- Area: Upper Jeuno -- NPC: Paya-Sabya -- Involved in Mission: Magicite -- @zone 244 -- @pos 9 1 70 ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(SILVER_BELL) and player:hasKeyItem(YAGUDO_TORCH) == false and player:getVar("YagudoTorchCS") == 0) then player:startEvent(0x0050); else player:startEvent(0x004f); 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 == 0x0050) then player:setVar("YagudoTorchCS",1); end end;
gpl-3.0
geanux/darkstar
scripts/zones/Dynamis-Beaucedine/mobs/Adamantking_Effigy.lua
12
3434
----------------------------------- -- Area: Dynamis Beaucedine -- NPC: Adamantking Effigy -- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg ----------------------------------- package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Beaucedine/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local spawnList = beaucedineQuadavList; if (mob:getStatPoppedMobs() == false) then mob:setStatPoppedMobs(true); for nb = 1, table.getn(spawnList), 2 do if (mob:getID() == spawnList[nb]) then for nbi = 1, table.getn(spawnList[nb + 1]), 1 do if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end local mobNBR = spawnList[nb + 1][nbi]; if (mobNBR <= 20) then if (mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY) local DynaMob = getDynaMob(target,mobNBR,3); if (DynaMob ~= nil) then -- Spawn Mob SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob):setPos(X,Y,Z); GetMobByID(DynaMob):setSpawn(X,Y,Z); -- Spawn Pet for BST, DRG, and SMN if (mobNBR == 9 or mobNBR == 14 or mobNBR == 15) then SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob + 1):setPos(X,Y,Z); GetMobByID(DynaMob + 1):setSpawn(X,Y,Z); end end elseif (mobNBR > 20) then SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); local MJob = GetMobByID(mobNBR):getMainJob(); if (MJob == 9 or MJob == 14 or MJob == 15) then -- Spawn Pet for BST, DRG, and SMN SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(mobNBR + 1):setPos(X,Y,Z); GetMobByID(mobNBR + 1):setSpawn(X,Y,Z); end end end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) local mobID = mob:getID(); -- Time Bonus: 063 066 if (mobID == 17326892 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(15); mob:addInBattlefieldList(); elseif (mobID == 17326895 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(15); mob:addInBattlefieldList(); -- HP Bonus: 056 059 065 070 074 103 elseif (mobID == 17326885 or mobID == 17326888 or mobID == 17326894 or mobID == 17326899 or mobID == 17326903 or mobID == 17326932) then killer:restoreHP(2000); killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); -- MP Bonus: 057 061 067 072 076 elseif (mobID == 17326886 or mobID == 17326890 or mobID == 17326896 or mobID == 17326901 or mobID == 17326905) then killer:restoreMP(2000); killer:messageBasic(025,(killer:getMaxMP()-killer:getMP())); end end;
gpl-3.0
geanux/darkstar
scripts/globals/items/greedie.lua
18
1317
----------------------------------------- -- ID: 4500 -- Item: greedie -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 1 -- Mind -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4500); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_MND, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_MND, -3); end;
gpl-3.0
geanux/darkstar
scripts/globals/items/cream_puff.lua
35
1313
----------------------------------------- -- ID: 5718 -- Item: Cream Puff -- Food Effect: 30 mintutes, All Races ----------------------------------------- -- Intelligence +7 -- HP -10 -- Resist Slow ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5718); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_INT, 7); target:addMod(MOD_HP, -10); target:addMod(MOD_SLOWRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_INT, 7); target:delMod(MOD_HP, -10); target:delMod(MOD_SLOWRES, 5); end;
gpl-3.0
geanux/darkstar
scripts/zones/Castle_Oztroja/npcs/_m70.lua
19
1199
----------------------------------- -- Area: Castle Oztroja -- NPC: _m70 (Torch Stand) -- Involved in Mission: Magicite -- @pos -97.134 24.250 -105.979 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Castle_Oztroja/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(YAGUDO_TORCH)) then player:startEvent(0x000b); else player:messageSpecial(PROBABLY_WORKS_WITH_SOMETHING_ELSE); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
girishramnani/Algorithm-Implementations
Bresenham_Based_Supercover_Line/Lua/Yonaba/bresenham_based_supercover_test.lua
27
1151
-- Tests for bresenham.lua local supercover_line = require 'bresenham_based_supercover' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end -- Checks if t1 and t2 arrays are the same local function same(t1, t2) for k,v in ipairs(t1) do if t2[k].x ~= v.x or t2[k].y ~= v.y then return false end end return true end run('Testing Bresenham-based supercover line marching', function() local expected = { {x = 1, y = 1}, {x = 2, y = 1}, {x = 1, y = 2}, {x = 2, y = 2}, {x = 3, y = 2}, {x = 2, y = 3}, {x = 3, y = 3}, {x = 4, y = 3}, {x = 3, y = 4}, {x = 4, y = 4}, {x = 5, y = 4}, {x = 4, y = 5}, {x = 5, y = 5} } assert(same(supercover_line(1, 1, 5, 5), expected)) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
kaen/Zero-K
LuaRules/Gadgets/game_lagmonitor.lua
4
16109
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Lag Monitor", desc = "Gives away units of people who are lagging", author = "KingRaptor", date = "11/5/2012", --6/11/2013 license = "Public domain", layer = 0, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- --List of stuff in this gadget (to help us remember stuff for future debugging/improvement): --Main logic: --1) Periodic(CheckAFK & Ping) ---> mark player as AFK/Lagging ---> Check if player has Shared Command --> Check for Candidate with highest ELO -- > Loop(send unit away to candidate & remember unit Ownership). --2) Periodic(CheckAFK & Ping) ---> IF AFK/Lagger is no longer lagging --> Return all units & delete unit Ownership. --Other logics: --1) If Owner's builder (constructor) created a unit --> Owner inherit the ownership to that unit --2) If Taker finished an Owner's unit --> the unit belong to Taker --3) wait 3 strike (3 time AFK & Ping) before --> mark player as AFK/Lagging --Everything else: anti-bug, syntax, methods, ect local lineage = {} --keep track of unit ownership: Is populated when gadget give away units, and when units is created. Depopulated when units is destroyed, or is finished construction, or when gadget return units to owner. local afkTeams = {} local unitAlreadyFinished = {} local oldTeam = {} -- team which player was on last frame local oldAllyTeam = {} -- allyTeam which player was on last frame local factories = {} local transferredFactories = {} -- unitDef and health states of the unit that was being produced be the transferred factory local shareLevels = {} GG.Lagmonitor_activeTeams = {} local spAddTeamResource = Spring.AddTeamResource local spEcho = Spring.Echo local spGetGameSeconds = Spring.GetGameSeconds local spGetPlayerInfo = Spring.GetPlayerInfo local spGetTeamInfo = Spring.GetTeamInfo local spGetTeamList = Spring.GetTeamList local spGetTeamResources = Spring.GetTeamResources local spGetTeamRulesParam = Spring.GetTeamRulesParam local spGetTeamUnits = Spring.GetTeamUnits local spGetUnitAllyTeam = Spring.GetUnitAllyTeam local spGetUnitDefID = Spring.GetUnitDefID local spGetUnitTeam = Spring.GetUnitTeam local spGetPlayerList = Spring.GetPlayerList local spTransferUnit = Spring.TransferUnit local spUseTeamResource = Spring.UseTeamResource local spGetUnitIsBuilding = Spring.GetUnitIsBuilding local spGetUnitHealth = Spring.GetUnitHealth local spSetUnitHealth = Spring.SetUnitHealth local gameFrame = -1 local allyTeamList = Spring.GetAllyTeamList() for i=1,#allyTeamList do local allyTeamID = allyTeamList[i] local teamList = Spring.GetTeamList(allyTeamID) GG.Lagmonitor_activeTeams[allyTeamID] = {count = #teamList} for j=1,#teamList do local teamID = teamList[j] GG.Lagmonitor_activeTeams[allyTeamID][teamID] = true end end local LAG_THRESHOLD = 25000 local AFK_THRESHOLD = 30 -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function ProductionCancelled(data, factoryTeam) -- return invested metal if produced unit wasn't recreated local ud = UnitDefs[data.producedDefID] local returnedMetal = data.build * (ud and ud.metalCost or 0) spAddTeamResource(factoryTeam, "metal", returnedMetal) end function gadget:UnitDestroyed(unitID, unitDefID, unitTeam) if GG.wasMorphedTo and GG.wasMorphedTo[unitID] then --copy lineage for unit Morph local newUnitID = GG.wasMorphedTo[unitID] local originalTeamIDs = lineage[unitID] if originalTeamIDs ~= nil and #originalTeamIDs > 0 then -- lineage of the morphed unit will be the same as its pre-morph lineage[newUnitID] = {unpack(originalTeamIDs)} --NOTE!: this copy value to new table instead of copying table-reference (to avoid bug) end unitAlreadyFinished[newUnitID] = true --for reverse build -- what is reverse build? end lineage[unitID] = nil --to delete any units that do not need returning. unitAlreadyFinished[unitID] = nil if transferredFactories[unitID] then --the dying unit is the factory we transfered to other team but it haven't continued previous build queue yet. ProductionCancelled(transferredFactories[unitID], unitTeam) -- refund metal for partial build transferredFactories[unitID] = nil end factories[unitID] = nil end function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID) --lineage[unitID] = builderID and (lineage[builderID] or spGetUnitTeam(builderID)) or unitTeam if builderID ~= nil then local builderDefID = spGetUnitDefID(builderID) local ud = (builderDefID and UnitDefs[builderDefID]) if ud and (not ud.isFactory) then --(set ownership to original owner for all units except units from factory so that receipient player didn't lose his investment creating that unit) local originalTeamIDs = lineage[builderID] if originalTeamIDs ~= nil and #originalTeamIDs > 0 then -- lineage of the new unit will be the same as its builder lineage[unitID] = {unpack(originalTeamIDs)} --NOTE!: this copy value to new table instead of copying table-reference (to avoid bug) end elseif transferredFactories[builderID] then --this unit was created inside a recently transfered factory local data = transferredFactories[builderID] if (data.producedDefID == unitDefID) then --this factory has continued its previous build queue data.producedDefID = nil data.expirationFrame = nil spSetUnitHealth(unitID, data) --set health of current build to pre-transfer level else ProductionCancelled(data, unitTeam) -- different unitDef was created after factory transfer, refund end transferredFactories[builderID] = nil end end end function gadget:UnitFinished(unitID, unitDefID, unitTeam) --player who finished a unit will own that unit; its lineage will be deleted and the unit will never be returned to the lagging team. if unitDefID and UnitDefs[unitDefID] and UnitDefs[unitDefID].isFactory then factories[unitID] = {} else if lineage[unitID] and (not unitAlreadyFinished[unitID]) then --(relinguish ownership for all unit except factories so the returning player has something to do) lineage[unitID] = {} --relinguish the original ownership of the unit end end unitAlreadyFinished[unitID] = true --for reverse build end local pActivity = {} function gadget:RecvLuaMsg(msg, playerID) if msg:find("AFK",1,true) then pActivity[playerID] = tonumber(msg:sub(4)) end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local UPDATE_PERIOD = 50 -- gameframes, 1.67 second local function GetRecepient(allyTeam, laggers) local teams = spGetTeamList(allyTeam) local highestRank = 0 local candidatesForTake = {} local target -- look for active people to give units to, including AIs for i=1,#teams do local leader = select(2, spGetTeamInfo(teams[i])) local name, active, spectator, _, _, _, _, _, _, customKeys = spGetPlayerInfo(leader) if active and not spectator and not laggers[leader] and not spGetTeamRulesParam(teams[i], "WasKilled") then -- only consider giving to someone in position to take! candidatesForTake[#candidatesForTake+1] = {name = name, team = teams[i], rank = ((tonumber(customKeys.elo) or 0))} end end -- pick highest rank for i=1,#candidatesForTake do local player = candidatesForTake[i] if player.rank > highestRank then highestRank = player.rank target = player end end -- no rank info? pick at random if not target and #candidatesForTake > 0 then target = candidatesForTake[math.random(1,#candidatesForTake)] end return target end local function TransferUnitAndKeepProduction(unitID, newTeamID, given) if (factories[unitID]) then --is a factory local producedUnitID = spGetUnitIsBuilding(unitID) if (producedUnitID) then local producedDefID = spGetUnitDefID(producedUnitID) if (producedDefID) then local data = factories[unitID] data.producedDefID = producedDefID data.expirationFrame = gameFrame + 31 local health, _, paralyzeDamage, captureProgress, buildProgress = spGetUnitHealth(producedUnitID) -- following 4 members are compatible with params required by Spring.SetUnitHealth data.health = health data.paralyze = paralyzeDamage data.capture = captureProgress data.build = buildProgress transferredFactories[unitID] = data spSetUnitHealth(producedUnitID, { build = 0 }) -- reset buildProgress to 0 before transfer factory, so no resources are given to AFK team when cancelling current build queue end end end GG.allowTransfer = true spTransferUnit(unitID, newTeamID, given) GG.allowTransfer = false end function gadget:GameFrame(n) gameFrame = n; if n % 15 == 0 then -- check factories that haven't recreated the produced unit after transfer for factoryID, data in pairs(transferredFactories) do if (data.expirationFrame <= gameFrame) then ProductionCancelled(data, spGetUnitTeam(factoryID)) --refund metal to current team transferredFactories[factoryID] = nil end end end if n%UPDATE_PERIOD == 0 then --check every UPDATE_PERIOD-th frame local laggers = {} local specList = {} local players = spGetPlayerList() local recepientByAllyTeam = {} local gameSecond = spGetGameSeconds() --local afkPlayers = "" -- remember which player is AFK/Lagg. Information will be sent to 'gui_take_remind.lua' as string for i=1,#players do local playerID = players[i] local name,active,spec,team,allyTeam,ping = spGetPlayerInfo(playerID) local justResigned = false if oldTeam[playerID] then if spec then active = false spec = false team = oldTeam[playerID] allyTeam = oldAllyTeam[playerID] oldTeam[playerID] = nil oldAllyTeam[playerID] = nil justResigned = true end elseif team and not spec then oldTeam[playerID] = team oldAllyTeam[playerID] = allyTeam end local afk = gameSecond - (pActivity[playerID] or 0) --mouse activity local _,_,_,isAI,_,_ = spGetTeamInfo(team) if not (spec or isAI) then if (afkTeams[team] == true) then -- team was AFK if active and ping <= 2000 and afk < AFK_THRESHOLD then -- team no longer AFK, return his or her units spEcho("game_message: Player " .. name .. " is no longer lagging or AFK; returning all his or her units") for unitID, teamList in pairs(lineage) do --Return unit to the oldest inheritor (or to original owner if possible) local delete = false; for i=1,#teamList do local uteam = teamList[i]; if (uteam == team) then if allyTeam == spGetUnitAllyTeam(unitID) then TransferUnitAndKeepProduction(unitID, team, true) delete = true end end -- remove all teams after the previous owner (inclusive) if (delete) then lineage[unitID][i] = nil; end end end if (shareLevels[team]) then Spring.SetTeamShareLevel(team, "metal", shareLevels[team]) shareLevels[team] = nil end afkTeams[team] = nil GG.Lagmonitor_activeTeams[allyTeam].count = GG.Lagmonitor_activeTeams[allyTeam].count + 1 GG.Lagmonitor_activeTeams[allyTeam][team] = true end end if (not active or ping >= LAG_THRESHOLD or afk > AFK_THRESHOLD) then -- player afk: mark him, except AIs laggers[playerID] = {name = name, team = team, allyTeam = allyTeam, resigned = justResigned} end elseif (spec and not isAI) then specList[playerID] = true --record spectator list in non-AI team end end --afkPlayers = afkPlayers .. "#".. players[#players] --cap the string with the largest playerID information. ie: (string)1010219899#98 can be read like this-> (1=dummy) id:01 ally:02, (1=dummy) id:98 ally:99, (#=dummy) highestID:98 --SendToUnsynced("LagmonitorAFK",afkPlayers) --tell widget about AFK list (widget need to deserialize this string) for playerID, lagger in pairs(laggers) do -- FIRST! check if everyone else on the team is also lagging local team = lagger.team local allyTeam = lagger.allyTeam local playersInTeam = spGetPlayerList(team, true) --return only active player local discontinue = false for j=1,#playersInTeam do local playerID = playersInTeam[j] if not (laggers[playerID] or specList[playerID]) then --Note: we need the extra specList check because Spectators is sharing same teamID as team 0 discontinue = true -- someone on same team is not lagging & not spec, don't move units around! break end end -- no-one on team not lagging (the likely situation in absence of commshare), continue working if not discontinue then recepientByAllyTeam[allyTeam] = recepientByAllyTeam[allyTeam] or GetRecepient(allyTeam, laggers) -- okay, we have someone to give to, prep transfer if recepientByAllyTeam[allyTeam] then if (afkTeams[team] == nil) then -- if team was not an AFK-er (but now is an AFK-er) then process the following, but do nothing for the same AFK-er. --REASON for WHY THE ABOVE^ CHECK was ADDED: if someone sent units to this AFK-er then (typically) var:"laggers[playerID]" will be filled twice for the same player & normally unit will be sent (redirected back) to the non-AFK-er, but (unfortunately) equation:"GG.Lagmonitor_activeTeams[allyTeam].count = GG.Lagmonitor_activeTeams[allyTeam].count - 1" will can also run twice for the AFK-er ally and it will effect 'unit_mex_overdrive.lua'. GG.Lagmonitor_activeTeams[allyTeam].count = GG.Lagmonitor_activeTeams[allyTeam].count - 1 GG.Lagmonitor_activeTeams[allyTeam][team] = false end afkTeams[team] = true --mark team as AFK -- orly local mShareLevel = select(6, Spring.GetTeamResources(team, "metal")) if (mShareLevel > 0) then shareLevels[team] = mShareLevel end Spring.SetTeamShareLevel(team, "metal", 0) -- Energy share is not set because the storage needs to be full for full overdrive. -- Also energy income is mostly private and a large energy influx to the rest of the -- team is likely to be wasted or overdriven inefficently. local units = spGetTeamUnits(team) or {} if #units > 0 then -- transfer units when number of units in AFK team is > 0 -- Transfer Units GG.allowTransfer = true for j=1,#units do local unit = units[j] if allyTeam == spGetUnitAllyTeam(unit) then -- add this team to the lineage list, then send the unit away if lineage[unit] == nil then lineage[unit] = { team } else -- this unit belonged to someone else before me, add me to the end of the list lineage[unit][#lineage[unit]+1] = team end TransferUnitAndKeepProduction(unit, recepientByAllyTeam[allyTeam].team, true) end end GG.allowTransfer = false -- Send message if lagger.resigned then spEcho("game_message: " .. lagger.name .. " resigned, giving all units to ".. recepientByAllyTeam[allyTeam].name .. " (ally #".. allyTeam ..")") else spEcho("game_message: Giving all units of "..lagger.name .. " to " .. recepientByAllyTeam[allyTeam].name .. " due to lag/AFK (ally #".. allyTeam ..")") end end end -- if end -- if end -- for end -- if end function gadget:GameOver() gadgetHandler:RemoveGadget() --shutdown after game over, so that at end of a REPLAY Lagmonitor doesn't bounce unit among player end
gpl-2.0
bungle/lua-resty-nettle
lib/resty/nettle/streebog.lua
1
2045
local types = require "resty.nettle.types.common" local context = require "resty.nettle.types.streebog" local lib = require "resty.nettle.library" local ffi = require "ffi" local ffi_new = ffi.new local ffi_str = ffi.string local lower = string.lower local setmetatable = setmetatable local hashes = { streebog256 = { length = 32, context = context, buffer = types.uint8_t_32, init = lib.nettle_streebog256_init, update = lib.nettle_streebog512_update, digest = lib.nettle_streebog256_digest, }, streebog512 = { length = 64, context = context, buffer = types.uint8_t_64, init = lib.nettle_streebog512_init, update = lib.nettle_streebog512_update, digest = lib.nettle_streebog512_digest, }, } local streebog = {} streebog.__index = streebog function streebog:update(data, len) return self.hash.update(self.context, len or #data, data) end function streebog:digest() local hash = self.hash hash.digest(self.context, hash.length, hash.buffer) return ffi_str(hash.buffer, hash.length) end local function factory(hash) return setmetatable({ new = function() local ctx = ffi_new(hash.context) hash.init(ctx) return setmetatable({ context = ctx, hash = hash }, streebog) end }, { __call = function(_, data, len) local ctx = ffi_new(hash.context) hash.init(ctx) hash.update(ctx, len or #data, data) hash.digest(ctx, hash.length, hash.buffer) return ffi_str(hash.buffer, hash.length) end }) end return setmetatable({ streebog256 = factory(hashes.streebog256), streebog512 = factory(hashes.streebog512), }, { __call = function(_, algorithm, data, len) local hash = hashes[lower(algorithm)] if not hash then return nil, "the supported Streebog algorithms are Streebog256, and Streebog512" end local ctx = ffi_new(hash.context) hash.init(ctx) hash.update(ctx, len or #data, data) hash.digest(ctx, hash.length, hash.buffer) return ffi_str(hash.buffer, hash.length) end })
bsd-2-clause
Aarhus-BSS/Aarhus-Research-Rebuilt
lib/luaj-3.0.1/test/lua/vm.lua
7
10643
print( '-------- basic vm tests --------' ) print( '-- boolean tests' ) local function booleantests() t = true f = false n = nil s = "Hello" z = 0 one = 1 print(t) print(f) print(not t) print(not f) print(not n) print(not z) print(not s) print(not(not(t))) print(not(not(z))) print(not(not(n))) print(t and f) print(t or f) print(f and t) print(f or t) print(f or one) print(f or z) print(f or n) print(t and one) print(t and z) print(t and n) end print( 'booleantests result:', pcall( booleantests ) ) print( '------------- varargs' ) local function varargstest() function p(a,...) print("a",a) print("...",...) print("...,a",...,a) print("a,...",a,...) end function q(a,...) print("a,arg[1],arg[2],arg[3]",a,arg.n,arg[1],arg[2],arg[3]) end function r(a,...) print("a,arg[1],arg[2],arg[3]",a,arg.n,arg[1],arg[2],arg[3]) print("a",a) print("...",...) print("...,a",...,a) print("a,...",a,...) end function s(a) local arg = { '1', '2', '3' } print("a,arg[1],arg[2],arg[3]",a,arg[1],arg[2],arg[3]) print("a",a) end function t(a,...) local arg = { '1', '2', '3' } print("a,arg[1],arg[2],arg[3]",a,arg[1],arg[2],arg[3]) print("a",a) print("...",...) print("...,a",...,a) print("a,...",a,...) end function u(arg) print( 'arg', arg ) end function v(arg,...) print( 'arg', arg ) print("...",...) print("arg,...",arg,...) end arg = { "global-1", "global-2", "global-3" } function tryall(f,name) print( '---- function '..name..'()' ) print( '--'..name..'():' ) print( ' ->', pcall( f ) ) print( '--'..name..'("q"):' ) print( ' ->', pcall( f, "q" ) ) print( '--'..name..'("q","r"):' ) print( ' ->', pcall( f, "q", "r" ) ) print( '--'..name..'("q","r","s"):' ) print( ' ->', pcall( f, "q", "r", "s" ) ) end tryall(p,'p') tryall(q,'q') tryall(r,'r') tryall(s,'s') tryall(t,'t') tryall(u,'u') tryall(v,'v') end print( 'varargstest result:', pcall( varargstest ) ) -- The purpose of this test case is to demonstrate that -- basic metatable operations on non-table types work. -- i.e. that s.sub(s,...) could be used in place of string.sub(s,...) print( '---------- metatable tests' ) local function metatabletests() -- tostring replacement that assigns ids local ts,id,nid,types = tostring,{},0,{table='tbl',thread='thr',userdata='uda',['function']='func'} tostring = function(x) if not x or not types[type(x)] then return ts(x) end if not id[x] then nid=nid+1; id[x]=types[type(x)]..'.'..nid end return id[x] end local results = function(s,e,...) if s then return e,... end return false,type(e) end local pcall = function(...) return results( pcall(...) ) end local s = "hello" print(s:sub(2,4)) local t = {} function op(name,...) local a,b = pcall( setmetatable, t, ... ) print( name, t, getmetatable(t), a, b ) end op('set{} ',{}) op('set-nil',nil) op('set{} ',{}) op('set') op('set{} ',{}) op('set{} ',{}) op('set{}{}',{},{}) op('set-nil',nil) op('set{__}',{__metatable={}}) op('set{} ',{}) op('set-nil',nil) t = {} op('set{} ',{}) op('set-nil',nil) op('set{__}',{__metatable='abc'}) op('set{} ',{}) op('set-nil',nil) local i = 1234 local t = setmetatable( {}, { __mode="v", __index=function(t,k) local v = i i = i + 1 rawset(t,k,v) return v end, } ) local l = { 'a', 'b', 'a', 'b', 'c', 'a', 'b', 'c', 'd' } for i,key in ipairs(l) do print( 't.'..key, t[key] ) end end print( 'metatabletests result:', pcall( metatabletests ) ) -- test tables with more than 50 elements print( '------------ huge tables' ) local function hugetables() local t = { 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1, } print ("#t=",#t,'t[1,50,51,59]', t[1], t[50], t[51], t[59]) print (table.concat(t,',')) local t2= { 0,3,4,7,9,8,12,15,23,5, 10,13,14,17,19,18,112,115,123,15, 20,33,24,27,29,28,212,215,223,25, 40,43,44,47,49,48,412,415,423,45, 50,53,54,57,59,58,512,515,523,55, 60,63,64,67,69,68,612,615,623,65, 70,73,74,77,79,78,72,715,723,75, } print ("#t2=",#t2,'t[1,50,51,59]', t[1], t[50], t[51], t[59]) print (table.concat(t2,',')) local t = { [2000]='a', [2001]='b', [2002]='c', [2003]='d', [2004]='e', [2005]='f', [2006]='g', [2007]='h', [2008]='i', [2009]='j', [3000]='a', [3001]='b', [3002]='c', [3003]='d', [3004]='e', [3005]='f', [3006]='g', [3007]='h', [3008]='i', [3009]='j', [4000]='a', [4001]='b', [4002]='c', [4003]='d', [4004]='e', [4005]='f', [4006]='g', [4007]='h', [4008]='i', [4009]='j', [5000]='a', [5001]='b', [5002]='c', [5003]='d', [5004]='e', [5005]='f', [5006]='g', [5007]='h', [5008]='i', [5009]='j', [6000]='a', [6001]='b', [6002]='c', [6003]='d', [6004]='e', [6005]='f', [6006]='g', [6007]='h', [6008]='i', [6009]='j', [7000]='a', [7001]='b', [7002]='c', [7003]='d', [7004]='e', [7005]='f', [7006]='g', [7007]='h', [7008]='i', [7009]='j', [8000]='a', [8001]='b', [8002]='c', [8003]='d', [8004]='e', [8005]='f', [8006]='g', [8007]='h', [8008]='i', [8009]='j', } for i=2000,8000,1000 do for j=0,9,1 do print( 't['..tostring(i+j)..']', t[i+j] ) end end end print( 'hugetables result:', pcall( hugetables ) ) print( '--------- many locals' ) local function manylocals() -- test program with more than 50 non-sequential integer elements local t0000='a'; local t0001='b'; local t0002='c'; local t0003='d'; local t0004='e'; local t0005='f'; local t0006='g'; local t0007='h'; local t0008='i'; local t0009='j'; local t1000='a'; local t1001='b'; local t1002='c'; local t1003='d'; local t1004='e'; local t1005='f'; local t1006='g'; local t1007='h'; local t1008='i'; local t1009='j'; local t2000='a'; local t2001='b'; local t2002='c'; local t2003='d'; local t2004='e'; local t2005='f'; local t2006='g'; local t2007='h'; local t2008='i'; local t2009='j'; local t3000='a'; local t3001='b'; local t3002='c'; local t3003='d'; local t3004='e'; local t3005='f'; local t3006='g'; local t3007='h'; local t3008='i'; local t3009='j'; local t4000='a'; local t4001='b'; local t4002='c'; local t4003='d'; local t4004='e'; local t4005='f'; local t4006='g'; local t4007='h'; local t4008='i'; local t4009='j'; local t5000='a'; local t5001='b'; local t5002='c'; local t5003='d'; local t5004='e'; local t5005='f'; local t5006='g'; local t5007='h'; local t5008='i'; local t5009='j'; local t6000='a'; local t6001='b'; local t6002='c'; local t6003='d'; local t6004='e'; local t6005='f'; local t6006='g'; local t6007='h'; local t6008='i'; local t6009='j'; local t7000='a'; local t7001='b'; local t7002='c'; local t7003='d'; local t7004='e'; local t7005='f'; local t7006='g'; local t7007='h'; local t7008='i'; local t7009='j'; local t8000='a'; local t8001='b'; local t8002='c'; local t8003='d'; local t8004='e'; local t8005='f'; local t8006='g'; local t8007='h'; local t8008='i'; local t8009='j'; local t9000='a'; local t9001='b'; local t9002='c'; local t9003='d'; local t9004='e'; local t9005='f'; local t9006='g'; local t9007='h'; local t9008='i'; local t9009='j'; local t10000='a'; local t10001='b'; local t10002='c'; local t10003='d'; local t10004='e'; local t10005='f'; local t10006='g'; local t10007='h'; local t10008='i'; local t10009='j'; local t11000='a'; local t11001='b'; local t11002='c'; local t11003='d'; local t11004='e'; local t11005='f'; local t11006='g'; local t11007='h'; local t11008='i'; local t11009='j'; local t12000='a'; local t12001='b'; local t12002='c'; local t12003='d'; local t12004='e'; local t12005='f'; local t12006='g'; local t12007='h'; local t12008='i'; local t12009='j'; local t13000='a'; local t13001='b'; local t13002='c'; local t13003='d'; local t13004='e'; local t13005='f'; local t13006='g'; local t13007='h'; local t13008='i'; local t13009='j'; -- print the variables print(t0000,'a'); print(t0001,'b'); print(t0002,'c'); print(t0003,'d'); print(t0004,'e'); print(t0005,'f'); print(t0006,'g'); print(t0007,'h'); print(t0008,'i'); print(t0009,'j'); print(t1000,'a'); print(t1001,'b'); print(t1002,'c'); print(t1003,'d'); print(t1004,'e'); print(t1005,'f'); print(t1006,'g'); print(t1007,'h'); print(t1008,'i'); print(t1009,'j'); print(t2000,'a'); print(t2001,'b'); print(t2002,'c'); print(t2003,'d'); print(t2004,'e'); print(t2005,'f'); print(t2006,'g'); print(t2007,'h'); print(t2008,'i'); print(t2009,'j'); print(t3000,'a'); print(t3001,'b'); print(t3002,'c'); print(t3003,'d'); print(t3004,'e'); print(t3005,'f'); print(t3006,'g'); print(t3007,'h'); print(t3008,'i'); print(t3009,'j'); print(t4000,'a'); print(t4001,'b'); print(t4002,'c'); print(t4003,'d'); print(t4004,'e'); print(t4005,'f'); print(t4006,'g'); print(t4007,'h'); print(t4008,'i'); print(t4009,'j'); print(t5000,'a'); print(t5001,'b'); print(t5002,'c'); print(t5003,'d'); print(t5004,'e'); print(t5005,'f'); print(t5006,'g'); print(t5007,'h'); print(t5008,'i'); print(t5009,'j'); print(t6000,'a'); print(t6001,'b'); print(t6002,'c'); print(t6003,'d'); print(t6004,'e'); print(t6005,'f'); print(t6006,'g'); print(t6007,'h'); print(t6008,'i'); print(t6009,'j'); print(t7000,'a'); print(t7001,'b'); print(t7002,'c'); print(t7003,'d'); print(t7004,'e'); print(t7005,'f'); print(t7006,'g'); print(t7007,'h'); print(t7008,'i'); print(t7009,'j'); print(t8000,'a'); print(t8001,'b'); print(t8002,'c'); print(t8003,'d'); print(t8004,'e'); print(t8005,'f'); print(t8006,'g'); print(t8007,'h'); print(t8008,'i'); print(t8009,'j'); print(t9000,'a'); print(t9001,'b'); print(t9002,'c'); print(t9003,'d'); print(t9004,'e'); print(t9005,'f'); print(t9006,'g'); print(t9007,'h'); print(t9008,'i'); print(t9009,'j'); print(t10000,'a'); print(t10001,'b'); print(t10002,'c'); print(t10003,'d'); print(t10004,'e'); print(t10005,'f'); print(t10006,'g'); print(t10007,'h'); print(t10008,'i'); print(t10009,'j'); print(t11000,'a'); print(t11001,'b'); print(t11002,'c'); print(t11003,'d'); print(t11004,'e'); print(t11005,'f'); print(t11006,'g'); print(t11007,'h'); print(t11008,'i'); print(t11009,'j'); print(t12000,'a'); print(t12001,'b'); print(t12002,'c'); print(t12003,'d'); print(t12004,'e'); print(t12005,'f'); print(t12006,'g'); print(t12007,'h'); print(t12008,'i'); print(t12009,'j'); print(t13000,'a'); print(t13001,'b'); print(t13002,'c'); print(t13003,'d'); print(t13004,'e'); print(t13005,'f'); print(t13006,'g'); print(t13007,'h'); print(t13008,'i'); print(t13009,'j'); end print( 'manylocals result:', pcall( manylocals ) )
apache-2.0
geanux/darkstar
scripts/zones/Waughroon_Shrine/bcnms/on_my_way.lua
19
1883
----------------------------------- -- 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
geanux/darkstar
scripts/globals/items/bunch_of_wild_pamamas.lua
36
2224
----------------------------------------- -- ID: 4596 -- Item: Bunch of Wild Pamamas -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength -3 -- Intelligence 1 -- Additional Effect with Opo-Opo Crown -- HP 50 -- MP 50 -- CHR 14 -- Additional Effect with Kinkobo or -- Primate Staff -- DELAY -90 -- ACC 10 -- Additional Effect with Primate Staff +1 -- DELAY -80 -- ACC 12 ----------------------------------------- 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,PamamasEquip(target),0,1800,4596); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:addMod(MOD_HP, 50); target:addMod(MOD_MP, 50); target:addMod(MOD_AGI, -3); target:addMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:addMod(MOD_DELAY, -90); target:addMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:addMod(MOD_DELAY, -80); target:addMod(MOD_ACC, 12); end target:addMod(MOD_STR, -3); target:addMod(MOD_INT, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (power == 1 or power == 4 or power == 5) then target:delMod(MOD_HP, 50); target:delMod(MOD_MP, 50); target:delMod(MOD_AGI, -3); target:delMod(MOD_CHR, 14); end if (power == 2 or power == 4) then target:delMod(MOD_DELAY, -90); target:delMod(MOD_ACC, 10); end if (power == 3 or power == 5) then target:delMod(MOD_DELAY, -80); target:delMod(MOD_ACC, 12); end target:delMod(MOD_STR, -3); target:delMod(MOD_INT, 1); end;
gpl-3.0
tahashakiba/zz
plugins/media.lua
297
1590
do local function run(msg, matches) local receiver = get_receiver(msg) local url = matches[1] local ext = matches[2] local file = download_to_file(url) local cb_extra = {file_path=file} local mime_type = mimetype.get_content_type_no_sub(ext) if ext == 'gif' then print('send_file') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'text' then print('send_document') send_document(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'image' then print('send_photo') send_photo(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'audio' then print('send_audio') send_audio(receiver, file, rmtmp_cb, cb_extra) elseif mime_type == 'video' then print('send_video') send_video(receiver, file, rmtmp_cb, cb_extra) else print('send_file') send_file(receiver, file, rmtmp_cb, cb_extra) end end return { description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.", usage = "", patterns = { "(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$", "(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$" }, run = run } end
gpl-2.0
vvtam/vlc
share/lua/modules/dkjson.lua
95
25741
--[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.1* This module writes no global values, not even the module table. Import it using json = require ("dkjson") Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This is mainly useful for tables that can be empty. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.1"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the functions `quotestring` and `decode`. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable this option: --]==] local always_try_using_lpeg = true --[==[ In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. You can contact the author by sending an e-mail to 'kolf' at the e-mail provider 'gmx.de'. --------------------------------------------------------------------- *Copyright (C) 2010, 2011 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall = error, require, pcall local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local common = require ("common") local us_tostring = common.us_tostring if _VERSION == 'Lua 5.1' then local function noglobals (s,k,v) error ("global access: " .. k, 2) end setfenv (1, setmetatable ({}, { __index = noglobals, __newindex = noglobals })) end local _ENV = nil -- blocking globals in Lua 5.2 local json = { version = "dkjson 2.1" } pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = us_tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local metatype = valmeta and valmeta.__jsontype local isa, n if metatype == 'array' then isa = true n = value.n or #value elseif metatype == 'object' then isa = false else isa, n = isarray (value) end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 1 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end function json.decode (str, pos, nullval, objectmeta, arraymeta) objectmeta = objectmeta or {__jsontype = 'object'} arraymeta = arraymeta or {__jsontype = 'array'} return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local SpecialChars = (R"\0\31" + S"\"\\\127" + P"\194" * (R"\128\159" + P"\173") + P"\216" * R"\128\132" + P"\220\132" + P"\225\158" * S"\180\181" + P"\226\128" * (R"\140\143" + S"\168\175") + P"\226\129" * R"\160\175" + P"\239\187\191" + P"\229\191" + R"\176\191") / escapeutf8 local QuoteStr = g.Cs (g.Cc "\"" * (SpecialChars + 1)^0 * g.Cc "\"") quotestring = function (str) return pegmatch (QuoteStr, str) end json.quotestring = quotestring local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, objectmeta, arraymeta) local state = { objectmeta = objectmeta or {__jsontype = 'object'}, arraymeta = arraymeta or {__jsontype = 'array'} } local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
geanux/darkstar
scripts/globals/abilities/building_flourish.lua
28
2817
----------------------------------- -- Ability: Building Flourish -- Enhances potency of your next weapon skill. Requires at least one Finishing Move. -- Obtained: Dancer Level 50 -- Finishing Moves Used: 1-3 -- Recast Time: 00:10 -- Duration: 01:00 -- -- Using one Finishing Move boosts the Accuracy of your next weapon skill. -- Using two Finishing Moves boosts both the Accuracy and Attack of your next weapon skill. -- Using three Finishing Moves boosts the Accuracy, Attack and Critical Hit Rate of your next weapon skill. ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then return 0,0; elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then return 0,0; else return MSGBASIC_NO_FINISHINGMOVES,0; end; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_1); player:addStatusEffect(EFFECT_BUILDING_FLOURISH,1,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT)); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_2); player:addStatusEffect(EFFECT_BUILDING_FLOURISH,2,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT)); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_3); player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT)); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_4); player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200); player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT)); elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then player:delStatusEffect(EFFECT_FINISHING_MOVE_5); player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200); player:addStatusEffect(EFFECT_BUILDING_FLOURISH,3,0,60, 0, player:getMerit(MERIT_BUILDING_FLOURISH_EFFECT)); end; end;
gpl-3.0
geanux/darkstar
scripts/zones/Northern_San_dOria/npcs/Chapal-Afal_WW.lua
30
4774
----------------------------------- -- Area: Northern Sand Oria -- NPC: Chapal-Afal, W.W. -- @pos -55 -2 31 231 -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Northern_San_dOria/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border local size = table.getn(WindInv); local inventory = WindInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end player:updateEvent(2,CPVerify,inventory[Item + 2]); break end end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %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 >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end if (player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if (inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end end if (player:hasItem(inventory[Item + 2]) == false) then player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end break end end elseif (option >= 65541 and option <= 65565) then -- player chose supply quest. local region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end end;
gpl-3.0
jcjohnson/torch-rnn
LSTM.lua
13
8765
require 'torch' require 'nn' local layer, parent = torch.class('nn.LSTM', 'nn.Module') --[[ If we add up the sizes of all the tensors for output, gradInput, weights, gradWeights, and temporary buffers, we get that a SequenceLSTM stores this many scalar values: NTD + 6NTH + 8NH + 8H^2 + 8DH + 9H For N = 100, D = 512, T = 100, H = 1024 and with 4 bytes per number, this comes out to 305MB. Note that this class doesn't own input or gradOutput, so you'll see a bit higher memory usage in practice. --]] function layer:__init(input_dim, hidden_dim) parent.__init(self) local D, H = input_dim, hidden_dim self.input_dim, self.hidden_dim = D, H self.weight = torch.Tensor(D + H, 4 * H) self.gradWeight = torch.Tensor(D + H, 4 * H):zero() self.bias = torch.Tensor(4 * H) self.gradBias = torch.Tensor(4 * H):zero() self:reset() self.cell = torch.Tensor() -- This will be (N, T, H) self.gates = torch.Tensor() -- This will be (N, T, 4H) self.buffer1 = torch.Tensor() -- This will be (N, H) self.buffer2 = torch.Tensor() -- This will be (N, H) self.buffer3 = torch.Tensor() -- This will be (1, 4H) self.grad_a_buffer = torch.Tensor() -- This will be (N, 4H) self.h0 = torch.Tensor() self.c0 = torch.Tensor() self.remember_states = false self.grad_c0 = torch.Tensor() self.grad_h0 = torch.Tensor() self.grad_x = torch.Tensor() self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x} end function layer:reset(std) if not std then std = 1.0 / math.sqrt(self.hidden_dim + self.input_dim) end self.bias:zero() self.bias[{{self.hidden_dim + 1, 2 * self.hidden_dim}}]:fill(1) self.weight:normal(0, std) return self end function layer:resetStates() self.h0 = self.h0.new() self.c0 = self.c0.new() end local function check_dims(x, dims) assert(x:dim() == #dims) for i, d in ipairs(dims) do assert(x:size(i) == d) end end function layer:_unpack_input(input) local c0, h0, x = nil, nil, nil if torch.type(input) == 'table' and #input == 3 then c0, h0, x = unpack(input) elseif torch.type(input) == 'table' and #input == 2 then h0, x = unpack(input) elseif torch.isTensor(input) then x = input else assert(false, 'invalid input') end return c0, h0, x end function layer:_get_sizes(input, gradOutput) local c0, h0, x = self:_unpack_input(input) local N, T = x:size(1), x:size(2) local H, D = self.hidden_dim, self.input_dim check_dims(x, {N, T, D}) if h0 then check_dims(h0, {N, H}) end if c0 then check_dims(c0, {N, H}) end if gradOutput then check_dims(gradOutput, {N, T, H}) end return N, T, D, H end --[[ Input: - c0: Initial cell state, (N, H) - h0: Initial hidden state, (N, H) - x: Input sequence, (N, T, D) Output: - h: Sequence of hidden states, (N, T, H) --]] function layer:updateOutput(input) self.recompute_backward = true local c0, h0, x = self:_unpack_input(input) local N, T, D, H = self:_get_sizes(input) self._return_grad_c0 = (c0 ~= nil) self._return_grad_h0 = (h0 ~= nil) if not c0 then c0 = self.c0 if c0:nElement() == 0 or not self.remember_states then c0:resize(N, H):zero() elseif self.remember_states then local prev_N, prev_T = self.cell:size(1), self.cell:size(2) assert(prev_N == N, 'batch sizes must be constant to remember states') c0:copy(self.cell[{{}, prev_T}]) end end if not h0 then h0 = self.h0 if h0:nElement() == 0 or not self.remember_states then h0:resize(N, H):zero() elseif self.remember_states then local prev_N, prev_T = self.output:size(1), self.output:size(2) assert(prev_N == N, 'batch sizes must be the same to remember states') h0:copy(self.output[{{}, prev_T}]) end end local bias_expand = self.bias:view(1, 4 * H):expand(N, 4 * H) local Wx = self.weight[{{1, D}}] local Wh = self.weight[{{D + 1, D + H}}] local h, c = self.output, self.cell h:resize(N, T, H):zero() c:resize(N, T, H):zero() local prev_h, prev_c = h0, c0 self.gates:resize(N, T, 4 * H):zero() for t = 1, T do local cur_x = x[{{}, t}] local next_h = h[{{}, t}] local next_c = c[{{}, t}] local cur_gates = self.gates[{{}, t}] cur_gates:addmm(bias_expand, cur_x, Wx) cur_gates:addmm(prev_h, Wh) cur_gates[{{}, {1, 3 * H}}]:sigmoid() cur_gates[{{}, {3 * H + 1, 4 * H}}]:tanh() local i = cur_gates[{{}, {1, H}}] local f = cur_gates[{{}, {H + 1, 2 * H}}] local o = cur_gates[{{}, {2 * H + 1, 3 * H}}] local g = cur_gates[{{}, {3 * H + 1, 4 * H}}] next_h:cmul(i, g) next_c:cmul(f, prev_c):add(next_h) next_h:tanh(next_c):cmul(o) prev_h, prev_c = next_h, next_c end return self.output end function layer:backward(input, gradOutput, scale) self.recompute_backward = false scale = scale or 1.0 assert(scale == 1.0, 'must have scale=1') local c0, h0, x = self:_unpack_input(input) if not c0 then c0 = self.c0 end if not h0 then h0 = self.h0 end local grad_c0, grad_h0, grad_x = self.grad_c0, self.grad_h0, self.grad_x local h, c = self.output, self.cell local grad_h = gradOutput local N, T, D, H = self:_get_sizes(input, gradOutput) local Wx = self.weight[{{1, D}}] local Wh = self.weight[{{D + 1, D + H}}] local grad_Wx = self.gradWeight[{{1, D}}] local grad_Wh = self.gradWeight[{{D + 1, D + H}}] local grad_b = self.gradBias grad_h0:resizeAs(h0):zero() grad_c0:resizeAs(c0):zero() grad_x:resizeAs(x):zero() local grad_next_h = self.buffer1:resizeAs(h0):zero() local grad_next_c = self.buffer2:resizeAs(c0):zero() for t = T, 1, -1 do local next_h, next_c = h[{{}, t}], c[{{}, t}] local prev_h, prev_c = nil, nil if t == 1 then prev_h, prev_c = h0, c0 else prev_h, prev_c = h[{{}, t - 1}], c[{{}, t - 1}] end grad_next_h:add(grad_h[{{}, t}]) local i = self.gates[{{}, t, {1, H}}] local f = self.gates[{{}, t, {H + 1, 2 * H}}] local o = self.gates[{{}, t, {2 * H + 1, 3 * H}}] local g = self.gates[{{}, t, {3 * H + 1, 4 * H}}] local grad_a = self.grad_a_buffer:resize(N, 4 * H):zero() local grad_ai = grad_a[{{}, {1, H}}] local grad_af = grad_a[{{}, {H + 1, 2 * H}}] local grad_ao = grad_a[{{}, {2 * H + 1, 3 * H}}] local grad_ag = grad_a[{{}, {3 * H + 1, 4 * H}}] -- We will use grad_ai, grad_af, and grad_ao as temporary buffers -- to to compute grad_next_c. We will need tanh_next_c (stored in grad_ai) -- to compute grad_ao; the other values can be overwritten after we compute -- grad_next_c local tanh_next_c = grad_ai:tanh(next_c) local tanh_next_c2 = grad_af:cmul(tanh_next_c, tanh_next_c) local my_grad_next_c = grad_ao my_grad_next_c:fill(1):add(-1, tanh_next_c2):cmul(o):cmul(grad_next_h) grad_next_c:add(my_grad_next_c) -- We need tanh_next_c (currently in grad_ai) to compute grad_ao; after -- that we can overwrite it. grad_ao:fill(1):add(-1, o):cmul(o):cmul(tanh_next_c):cmul(grad_next_h) -- Use grad_ai as a temporary buffer for computing grad_ag local g2 = grad_ai:cmul(g, g) grad_ag:fill(1):add(-1, g2):cmul(i):cmul(grad_next_c) -- We don't need any temporary storage for these so do them last grad_ai:fill(1):add(-1, i):cmul(i):cmul(g):cmul(grad_next_c) grad_af:fill(1):add(-1, f):cmul(f):cmul(prev_c):cmul(grad_next_c) grad_x[{{}, t}]:mm(grad_a, Wx:t()) grad_Wx:addmm(scale, x[{{}, t}]:t(), grad_a) grad_Wh:addmm(scale, prev_h:t(), grad_a) local grad_a_sum = self.buffer3:resize(1, 4 * H):sum(grad_a, 1) grad_b:add(scale, grad_a_sum) grad_next_h:mm(grad_a, Wh:t()) grad_next_c:cmul(f) end grad_h0:copy(grad_next_h) grad_c0:copy(grad_next_c) if self._return_grad_c0 and self._return_grad_h0 then self.gradInput = {self.grad_c0, self.grad_h0, self.grad_x} elseif self._return_grad_h0 then self.gradInput = {self.grad_h0, self.grad_x} else self.gradInput = self.grad_x end return self.gradInput end function layer:clearState() self.cell:set() self.gates:set() self.buffer1:set() self.buffer2:set() self.buffer3:set() self.grad_a_buffer:set() self.grad_c0:set() self.grad_h0:set() self.grad_x:set() self.output:set() end function layer:updateGradInput(input, gradOutput) if self.recompute_backward then self:backward(input, gradOutput, 1.0) end return self.gradInput end function layer:accGradParameters(input, gradOutput, scale) if self.recompute_backward then self:backward(input, gradOutput, scale) end end function layer:__tostring__() local name = torch.type(self) local din, dout = self.input_dim, self.hidden_dim return string.format('%s(%d -> %d)', name, din, dout) end
mit
olszak94/forgottenserver
data/talkactions/scripts/buyhouse.lua
16
1163
function onSay(player, words, param) local housePrice = configManager.getNumber(configKeys.HOUSE_PRICE) if housePrice == -1 then return true end if not player:isPremium() then player:sendCancelMessage("You need a premium account.") return false end local position = player:getPosition() position:getNextPosition(player:getDirection()) local tile = Tile(position) local house = tile and tile:getHouse() if house == nil then player:sendCancelMessage("You have to be looking at the door of the house you would like to buy.") return false end if house:getOwnerGuid() > 0 then player:sendCancelMessage("This house already has an owner.") return false end if player:getHouse() then player:sendCancelMessage("You are already the owner of a house.") return false end local price = house:getTileCount() * housePrice if not player:removeMoney(price) then player:sendCancelMessage("You do not have enough money.") return false end house:setOwnerGuid(player:getGuid()) player:sendTextMessage(MESSAGE_INFO_DESCR, "You have successfully bought this house, be sure to have the money for the rent in the bank.") return false end
gpl-2.0
forward619/luci
applications/luci-app-pbx/luasrc/model/cbi/pbx-users.lua
146
5623
--[[ 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/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end modulename = "pbx-users" modulenamecalls = "pbx-calls" modulenameadvanced = "pbx-advanced" m = Map (modulename, translate("User Accounts"), translate("Here you must configure at least one SIP account, that you \ will use to register with this service. Use this account either in an Analog Telephony \ Adapter (ATA), or in a SIP software like CSipSimple, Linphone, or Sipdroid on your \ smartphone, or Ekiga, Linphone, or X-Lite on your computer. By default, all SIP accounts \ will ring simultaneously if a call is made to one of your VoIP provider accounts or GV \ numbers.")) -- Recreate the config, and restart services after changes are commited to the configuration. function m.on_after_commit(self) luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") end externhost = m.uci:get(modulenameadvanced, "advanced", "externhost") bindport = m.uci:get(modulenameadvanced, "advanced", "bindport") ipaddr = m.uci:get("network", "lan", "ipaddr") ----------------------------------------------------------------------------- s = m:section(NamedSection, "server", "user", translate("Server Setting")) s.anonymous = true if ipaddr == nil or ipaddr == "" then ipaddr = "(IP address not static)" end if bindport ~= nil then just_ipaddr = ipaddr ipaddr = ipaddr .. ":" .. bindport end s:option(DummyValue, "ipaddr", translate("Server Setting for Local SIP Devices"), translate("Enter this IP (or IP:port) in the Server/Registrar setting of SIP devices you will \ use ONLY locally and never from a remote location.")).default = ipaddr if externhost ~= nil then if bindport ~= nil then just_externhost = externhost externhost = externhost .. ":" .. bindport end s:option(DummyValue, "externhost", translate("Server Setting for Remote SIP Devices"), translate("Enter this hostname (or hostname:port) in the Server/Registrar setting of SIP \ devices you will use from a remote location (they will work locally too).") ).default = externhost end if bindport ~= nil then s:option(DummyValue, "bindport", translate("Port Setting for SIP Devices"), translatef("If setting Server/Registrar to %s or %s does not work for you, try setting \ it to %s or %s and entering this port number in a separate field that specifies the \ Server/Registrar port number. Beware that some devices have a confusing \ setting that sets the port where SIP requests originate from on the SIP \ device itself (the bind port). The port specified on this page is NOT this bind port \ but the port this service listens on.", ipaddr, externhost, just_ipaddr, just_externhost)).default = bindport end ----------------------------------------------------------------------------- s = m:section(TypedSection, "local_user", translate("SIP Device/Softphone Accounts")) s.anonymous = true s.addremove = true s:option(Value, "fullname", translate("Full Name"), translate("You can specify a real name to show up in the Caller ID here.")) du = s:option(Value, "defaultuser", translate("User Name"), translate("Use (four to five digit) numeric user name if you are connecting normal telephones \ with ATAs to this system (so they can dial user names).")) du.datatype = "uciname" pwd = s:option(Value, "secret", translate("Password"), translate("Your password disappears when saved for your protection. It will be changed \ only when you enter a value different from the saved one.")) pwd.password = true pwd.rmempty = false -- We skip reading off the saved value and return nothing. function pwd.cfgvalue(self, section) return "" end -- We check the entered value against the saved one, and only write if the entered value is -- something other than the empty string, and it differes from the saved value. function pwd.write(self, section, value) local orig_pwd = m:get(section, self.option) if value and #value > 0 and orig_pwd ~= value then Value.write(self, section, value) end end p = s:option(ListValue, "ring", translate("Receives Incoming Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" p = s:option(ListValue, "can_call", translate("Makes Outgoing Calls")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
geanux/darkstar
scripts/globals/items/serving_of_golden_royale.lua
36
1429
----------------------------------------- -- ID: 5558 -- Item: Serving of Golden Royale -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10 -- MP +10 -- Intelligence +2 -- HP Recoverd while healing 2 -- MP Recovered while healing 2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5558); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_MP, 10); target:addMod(MOD_INT, 2); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_MP, 10); target:delMod(MOD_INT, 2); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 2); end;
gpl-3.0
geanux/darkstar
scripts/zones/Ifrits_Cauldron/npcs/HomePoint#1.lua
19
1200
----------------------------------- -- Area: Ifrit's Cauldron -- NPC: HomePoint#1 -- @pos -63 50 81 205 ----------------------------------- package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Ifrits_Cauldron/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 95); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
dani-sj/capitan01
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
Shayan123456/shayanhallaji
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
mirkix/ardupilot
libraries/AP_Scripting/tests/math.lua
26
25303
-- $Id: math.lua,v 1.77 2016/06/23 15:17:20 roberto Exp roberto $ --[[ ***************************************************************************** * Copyright (C) 1994-2016 Lua.org, PUC-Rio. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ***************************************************************************** ]] -- This code is copied from https://github.com/lua/tests and slightly modified to work within ArduPilot gcs:send_text(6, "testing numbers and math lib") local minint = math.mininteger local maxint = math.maxinteger local intbits = math.floor(math.log(maxint, 2) + 0.5) + 1 assert((1 << intbits) == 0) assert(minint == 1 << (intbits - 1)) assert(maxint == minint - 1) -- number of bits in the mantissa of a floating-point number local floatbits = 24 do local p = 2.0^floatbits while p < p + 1.0 do p = p * 2.0 floatbits = floatbits + 1 end end local function isNaN (x) return (x ~= x) end assert(isNaN(0/0)) assert(not isNaN(1/0)) do local x = 2.0^floatbits assert(x > x - 1.0 and x == x + 1.0) gcs:send_text(6, string.format("%d-bit integers, %d-bit (mantissa) floats", intbits, floatbits)) end assert(math.type(0) == "integer" and math.type(0.0) == "float" and math.type("10") == nil) local function checkerror (msg, f, ...) local s, err = pcall(f, ...) assert(not s and string.find(err, msg)) end local msgf2i = "number.* has no integer representation" -- float equality function eq (a,b,limit) if not limit then if floatbits >= 50 then limit = 1E-11 else limit = 1E-5 end end -- a == b needed for +inf/-inf return a == b or math.abs(a-b) <= limit end -- equality with types function eqT (a,b) return a == b and math.type(a) == math.type(b) end -- basic float notation assert(0e12 == 0 and .0 == 0 and 0. == 0 and .2e2 == 20 and 2.E-1 == 0.2) do local a,b,c = "2", " 3e0 ", " 10 " assert(a+b == 5 and -b == -3 and b+"2" == 5 and "10"-c == 0) assert(type(a) == 'string' and type(b) == 'string' and type(c) == 'string') assert(a == "2" and b == " 3e0 " and c == " 10 " and -c == -" 10 ") assert(c%a == 0 and a^b == 08) a = 0 assert(a == -a and 0 == -0) end do local x = -1 local mz = 0/x -- minus zero t = {[0] = 10, 20, 30, 40, 50} assert(t[mz] == t[0] and t[-0] == t[0]) end do -- tests for 'modf' local a,b = math.modf(3.5) assert(a == 3.0 and b == 0.5) a,b = math.modf(-2.5) assert(a == -2.0 and b == -0.5) a,b = math.modf(-3e23) assert(a == -3e23 and b == 0.0) a,b = math.modf(3e35) assert(a == 3e35 and b == 0.0) a,b = math.modf(-1/0) -- -inf assert(a == -1/0 and b == 0.0) a,b = math.modf(1/0) -- inf assert(a == 1/0 and b == 0.0) a,b = math.modf(0/0) -- NaN assert(isNaN(a) and isNaN(b)) a,b = math.modf(3) -- integer argument assert(eqT(a, 3) and eqT(b, 0.0)) a,b = math.modf(minint) assert(eqT(a, minint) and eqT(b, 0.0)) end assert(math.huge > 10e30) assert(-math.huge < -10e30) -- integer arithmetic assert(minint < minint + 1) assert(maxint - 1 < maxint) assert(0 - minint == minint) assert(minint * minint == 0) assert(maxint * maxint * maxint == maxint) -- testing floor division and conversions for _, i in pairs{-16, -15, -3, -2, -1, 0, 1, 2, 3, 15} do for _, j in pairs{-16, -15, -3, -2, -1, 1, 2, 3, 15} do for _, ti in pairs{0, 0.0} do -- try 'i' as integer and as float for _, tj in pairs{0, 0.0} do -- try 'j' as integer and as float local x = i + ti local y = j + tj assert(i//j == math.floor(i/j)) end end end end assert(1//0.0 == 1/0) assert(-1 // 0.0 == -1/0) assert(eqT(3.5 // 1.5, 2.0)) assert(eqT(3.5 // -1.5, -3.0)) assert(maxint // maxint == 1) assert(maxint // 1 == maxint) assert((maxint - 1) // maxint == 0) assert(maxint // (maxint - 1) == 1) assert(minint // minint == 1) assert(minint // minint == 1) assert((minint + 1) // minint == 0) assert(minint // (minint + 1) == 1) assert(minint // 1 == minint) assert(minint // -1 == -minint) assert(minint // -2 == 2^(intbits - 2)) assert(maxint // -1 == -maxint) -- negative exponents do assert(2^-3 == 1 / 2^3) assert(eq((-3)^-3, 1 / (-3)^3)) for i = -3, 3 do -- variables avoid constant folding for j = -3, 3 do -- domain errors (0^(-n)) are not portable if not _port or i ~= 0 or j > 0 then assert(eq(i^j, 1 / i^(-j))) end end end end -- comparison between floats and integers (border cases) if floatbits < intbits then assert(2.0^floatbits == (1 << floatbits)) assert(2.0^floatbits - 1.0 == (1 << floatbits) - 1.0) assert(2.0^floatbits - 1.0 ~= (1 << floatbits)) -- float is rounded, int is not assert(2.0^floatbits + 1.0 ~= (1 << floatbits) + 1) else -- floats can express all integers with full accuracy assert(maxint == maxint + 0.0) assert(maxint - 1 == maxint - 1.0) assert(minint + 1 == minint + 1.0) assert(maxint ~= maxint - 1.0) end assert(maxint + 0.0 == 2.0^(intbits - 1) - 1.0) assert(minint + 0.0 == minint) assert(minint + 0.0 == -2.0^(intbits - 1)) -- order between floats and integers assert(1 < 1.1); assert(not (1 < 0.9)) assert(1 <= 1.1); assert(not (1 <= 0.9)) assert(-1 < -0.9); assert(not (-1 < -1.1)) assert(1 <= 1.1); assert(not (-1 <= -1.1)) assert(-1 < -0.9); assert(not (-1 < -1.1)) assert(-1 <= -0.9); assert(not (-1 <= -1.1)) assert(minint <= minint + 0.0) assert(minint + 0.0 <= minint) assert(not (minint < minint + 0.0)) assert(not (minint + 0.0 < minint)) assert(maxint < minint * -1.0) assert(maxint <= minint * -1.0) do local fmaxi1 = 2^(intbits - 1) assert(maxint < fmaxi1) assert(maxint <= fmaxi1) assert(not (fmaxi1 <= maxint)) assert(minint <= -2^(intbits - 1)) assert(-2^(intbits - 1) <= minint) end if floatbits < intbits then gcs:send_text(6, "testing order (floats can't represent all int)") local fmax = 2^floatbits local ifmax = fmax | 0 assert(fmax < ifmax + 1) assert(fmax - 1 < ifmax) assert(-(fmax - 1) > -ifmax) assert(not (fmax <= ifmax - 1)) assert(-fmax > -(ifmax + 1)) assert(not (-fmax >= -(ifmax - 1))) assert(fmax/2 - 0.5 < ifmax//2) assert(-(fmax/2 - 0.5) > -ifmax//2) assert(maxint < 2^intbits) assert(minint > -2^intbits) assert(maxint <= 2^intbits) assert(minint >= -2^intbits) else gcs:send_text(6, "testing order (floats can represent all ints)") assert(maxint < maxint + 1.0) assert(maxint < maxint + 0.5) assert(maxint - 1.0 < maxint) assert(maxint - 0.5 < maxint) assert(not (maxint + 0.0 < maxint)) assert(maxint + 0.0 <= maxint) assert(not (maxint < maxint + 0.0)) assert(maxint + 0.0 <= maxint) assert(maxint <= maxint + 0.0) assert(not (maxint + 1.0 <= maxint)) assert(not (maxint + 0.5 <= maxint)) assert(not (maxint <= maxint - 1.0)) assert(not (maxint <= maxint - 0.5)) assert(minint < minint + 1.0) assert(minint < minint + 0.5) assert(minint <= minint + 0.5) assert(minint - 1.0 < minint) assert(minint - 1.0 <= minint) assert(not (minint + 0.0 < minint)) assert(not (minint + 0.5 < minint)) assert(not (minint < minint + 0.0)) assert(minint + 0.0 <= minint) assert(minint <= minint + 0.0) assert(not (minint + 1.0 <= minint)) assert(not (minint + 0.5 <= minint)) assert(not (minint <= minint - 1.0)) end do local NaN = 0/0 assert(not (NaN < 0)) assert(not (NaN > minint)) assert(not (NaN <= -9)) assert(not (NaN <= maxint)) assert(not (NaN < maxint)) assert(not (minint <= NaN)) assert(not (minint < NaN)) end -- avoiding errors at compile time --local function checkcompt (msg, code) -- checkerror(msg, assert(load(code))) --end --checkcompt("divide by zero", "return 2 // 0") --checkcompt(msgf2i, "return 2.3 >> 0") --checkcompt(msgf2i, ("return 2.0^%d & 1"):format(intbits - 1)) --checkcompt("field 'huge'", "return math.huge << 1") --checkcompt(msgf2i, ("return 1 | 2.0^%d"):format(intbits - 1)) --checkcompt(msgf2i, "return 2.3 ~ '0.0'") -- testing overflow errors when converting from float to integer (runtime) local function f2i (x) return x | x end checkerror(msgf2i, f2i, math.huge) -- +inf checkerror(msgf2i, f2i, -math.huge) -- -inf checkerror(msgf2i, f2i, 0/0) -- NaN if floatbits < intbits then -- conversion tests when float cannot represent all integers assert(maxint + 1.0 == maxint + 0.0) assert(minint - 1.0 == minint + 0.0) checkerror(msgf2i, f2i, maxint + 0.0) assert(f2i(2.0^(intbits - 2)) == 1 << (intbits - 2)) assert(f2i(-2.0^(intbits - 2)) == -(1 << (intbits - 2))) assert((2.0^(floatbits - 1) + 1.0) // 1 == (1 << (floatbits - 1)) + 1) -- maximum integer representable as a float local mf = maxint - (1 << (floatbits - intbits)) + 1 assert(f2i(mf + 0.0) == mf) -- OK up to here mf = mf + 1 assert(f2i(mf + 0.0) ~= mf) -- no more representable else -- conversion tests when float can represent all integers assert(maxint + 1.0 > maxint) assert(minint - 1.0 < minint) assert(f2i(maxint + 0.0) == maxint) checkerror("no integer rep", f2i, maxint + 1.0) checkerror("no integer rep", f2i, minint - 1.0) end -- 'minint' should be representable as a float no matter the precision assert(f2i(minint + 0.0) == minint) -- testing numeric strings assert("2" + 1 == 3) assert("2 " + 1 == 3) assert(" -2 " + 1 == -1) assert(" -0xa " + 1 == -9) -- Literal integer Overflows (new behavior in 5.3.3) do -- no overflows assert(eqT(tonumber(tostring(maxint)), maxint)) assert(eqT(tonumber(tostring(minint)), minint)) -- add 1 to last digit as a string (it cannot be 9...) local function incd (n) local s = string.format("%d", n) s = string.gsub(s, "%d$", function (d) assert(d ~= '9') return string.char(string.byte(d) + 1) end) return s end -- 'tonumber' with overflow by 1 assert(eqT(tonumber(incd(maxint)), maxint + 1.0)) assert(eqT(tonumber(incd(minint)), minint - 1.0)) -- large numbers assert(eqT(tonumber("1"..string.rep("0", 30)), 1e30)) assert(eqT(tonumber("-1"..string.rep("0", 30)), -1e30)) -- hexa format still wraps around assert(eqT(tonumber("0x1"..string.rep("0", 30)), 0)) -- lexer in the limits --assert(minint == load("return " .. minint)()) --assert(eqT(maxint, load("return " .. maxint)())) assert(eqT(10000000000000000000000.0, 10000000000000000000000)) assert(eqT(-10000000000000000000000.0, -10000000000000000000000)) end -- testing 'tonumber' -- 'tonumber' with numbers assert(tonumber(3.4) == 3.4) assert(eqT(tonumber(3), 3)) assert(eqT(tonumber(maxint), maxint) and eqT(tonumber(minint), minint)) assert(tonumber(1/0) == 1/0) -- 'tonumber' with strings assert(tonumber("0") == 0) assert(tonumber("") == nil) assert(tonumber(" ") == nil) assert(tonumber("-") == nil) assert(tonumber(" -0x ") == nil) assert(tonumber{} == nil) assert(tonumber'+0.01' == 1/100 and tonumber'+.01' == 0.01 and tonumber'.01' == 0.01 and tonumber'-1.' == -1 and tonumber'+1.' == 1) assert(tonumber'+ 0.01' == nil and tonumber'+.e1' == nil and tonumber'1e' == nil and tonumber'1.0e+' == nil and tonumber'.' == nil) assert(tonumber('-012') == -010-2) assert(tonumber('-1.2e2') == - - -120) assert(tonumber("0xffffffffffff") == (1 << (4*12)) - 1) assert(tonumber("0x"..string.rep("f", (intbits//4))) == -1) assert(tonumber("-0x"..string.rep("f", (intbits//4))) == 1) -- testing 'tonumber' with base assert(tonumber(' 001010 ', 2) == 10) assert(tonumber(' 001010 ', 10) == 001010) assert(tonumber(' -1010 ', 2) == -10) assert(tonumber('10', 36) == 36) assert(tonumber(' -10 ', 36) == -36) assert(tonumber(' +1Z ', 36) == 36 + 35) assert(tonumber(' -1z ', 36) == -36 + -35) assert(tonumber('-fFfa', 16) == -(10+(16*(15+(16*(15+(16*15))))))) assert(tonumber(string.rep('1', (intbits - 2)), 2) + 1 == 2^(intbits - 2)) assert(tonumber('ffffFFFF', 16)+1 == (1 << 32)) assert(tonumber('0ffffFFFF', 16)+1 == (1 << 32)) assert(tonumber('-0ffffffFFFF', 16) - 1 == -(1 << 40)) for i = 2,36 do local i2 = i * i local i10 = i2 * i2 * i2 * i2 * i2 -- i^10 assert(tonumber('\t10000000000\t', i) == i10) end if not _soft then -- tests with very long numerals assert(tonumber("0x"..string.rep("f", 13)..".0") == 2.0^(4*13) - 1) assert(tonumber("0x"..string.rep("f", 150)..".0") == 2.0^(4*150) - 1) assert(tonumber("0x"..string.rep("f", 300)..".0") == 2.0^(4*300) - 1) assert(tonumber("0x"..string.rep("f", 500)..".0") == 2.0^(4*500) - 1) assert(tonumber('0x3.' .. string.rep('0', 1000)) == 3) assert(tonumber('0x' .. string.rep('0', 1000) .. 'a') == 10) assert(tonumber('0x0.' .. string.rep('0', 13).."1") == 2.0^(-4*14)) assert(tonumber('0x0.' .. string.rep('0', 150).."1") == 2.0^(-4*151)) assert(tonumber('0x0.' .. string.rep('0', 300).."1") == 2.0^(-4*301)) assert(tonumber('0x0.' .. string.rep('0', 500).."1") == 2.0^(-4*501)) assert(tonumber('0xe03' .. string.rep('0', 1000) .. 'p-4000') == 3587.0) assert(tonumber('0x.' .. string.rep('0', 1000) .. '74p4004') == 0x7.4) end -- testing 'tonumber' for invalid formats --[[ local function f (...) if select('#', ...) == 1 then return (...) else return "***" end end assert(f(tonumber('fFfa', 15)) == nil) assert(f(tonumber('099', 8)) == nil) assert(f(tonumber('1\0', 2)) == nil) assert(f(tonumber('', 8)) == nil) assert(f(tonumber(' ', 9)) == nil) assert(f(tonumber(' ', 9)) == nil) assert(f(tonumber('0xf', 10)) == nil) assert(f(tonumber('inf')) == nil) assert(f(tonumber(' INF ')) == nil) assert(f(tonumber('Nan')) == nil) assert(f(tonumber('nan')) == nil) assert(f(tonumber(' ')) == nil) assert(f(tonumber('')) == nil) assert(f(tonumber('1 a')) == nil) assert(f(tonumber('1 a', 2)) == nil) assert(f(tonumber('1\0')) == nil) assert(f(tonumber('1 \0')) == nil) assert(f(tonumber('1\0 ')) == nil) assert(f(tonumber('e1')) == nil) assert(f(tonumber('e 1')) == nil) assert(f(tonumber(' 3.4.5 ')) == nil) ]] -- testing 'tonumber' for invalid hexadecimal formats assert(tonumber('0x') == nil) assert(tonumber('x') == nil) assert(tonumber('x3') == nil) assert(tonumber('0x3.3.3') == nil) -- two decimal points assert(tonumber('00x2') == nil) assert(tonumber('0x 2') == nil) assert(tonumber('0 x2') == nil) assert(tonumber('23x') == nil) assert(tonumber('- 0xaa') == nil) assert(tonumber('-0xaaP ') == nil) -- no exponent assert(tonumber('0x0.51p') == nil) assert(tonumber('0x5p+-2') == nil) -- testing hexadecimal numerals assert(0x10 == 16 and 0xfff == 2^12 - 1 and 0XFB == 251) assert(0x0p12 == 0 and 0x.0p-3 == 0) assert(0xFFFFFFFF == (1 << 32) - 1) assert(tonumber('+0x2') == 2) assert(tonumber('-0xaA') == -170) assert(tonumber('-0xffFFFfff') == -(1 << 32) + 1) -- possible confusion with decimal exponent assert(0E+1 == 0 and 0xE+1 == 15 and 0xe-1 == 13) -- floating hexas assert(tonumber(' 0x2.5 ') == 0x25/16) assert(tonumber(' -0x2.5 ') == -0x25/16) assert(tonumber(' +0x0.51p+8 ') == 0x51) assert(0x.FfffFFFF == 1 - '0x.00000001') assert('0xA.a' + 0 == 10 + 10/16) assert(0xa.aP4 == 0XAA) assert(0x4P-2 == 1) assert(0x1.1 == '0x1.' + '+0x.1') assert(0Xabcdef.0 == 0x.ABCDEFp+24) assert(1.1 == 1.+.1) assert(100.0 == 1E2 and .01 == 1e-2) assert(1111111111 - 1111111110 == 1000.00e-03) assert(1.1 == '1.'+'.1') assert(tonumber'1111111111' - tonumber'1111111110' == tonumber" +0.001e+3 \n\t") assert(0.1e-30 > 0.9E-31 and 0.9E30 < 0.1e31) assert(0.123456 > 0.123455) assert(tonumber('+1.23E18') == 1.23*10.0^18) -- testing order operators assert(not(1<1) and (1<2) and not(2<1)) assert(not('a'<'a') and ('a'<'b') and not('b'<'a')) assert((1<=1) and (1<=2) and not(2<=1)) assert(('a'<='a') and ('a'<='b') and not('b'<='a')) assert(not(1>1) and not(1>2) and (2>1)) assert(not('a'>'a') and not('a'>'b') and ('b'>'a')) assert((1>=1) and not(1>=2) and (2>=1)) assert(('a'>='a') and not('a'>='b') and ('b'>='a')) assert(1.3 < 1.4 and 1.3 <= 1.4 and not (1.3 < 1.3) and 1.3 <= 1.3) -- testing mod operator assert(eqT(-4 % 3, 2)) assert(eqT(4 % -3, -2)) assert(eqT(-4.0 % 3, 2.0)) assert(eqT(4 % -3.0, -2.0)) assert(math.pi - math.pi % 1 == 3) assert(math.pi - math.pi % 0.001 == 3.141) assert(eqT(minint % minint, 0)) assert(eqT(maxint % maxint, 0)) assert((minint + 1) % minint == minint + 1) assert((maxint - 1) % maxint == maxint - 1) assert(minint % maxint == maxint - 1) assert(minint % -1 == 0) assert(minint % -2 == 0) assert(maxint % -2 == -1) -- testing unsigned comparisons assert(math.ult(3, 4)) assert(not math.ult(4, 4)) assert(math.ult(-2, -1)) assert(math.ult(2, -1)) assert(not math.ult(-2, -2)) assert(math.ult(maxint, minint)) assert(not math.ult(minint, maxint)) assert(eq(math.sin(-9.8)^2 + math.cos(-9.8)^2, 1)) assert(eq(math.tan(math.pi/4), 1)) assert(eq(math.sin(math.pi/2), 1) and eq(math.cos(math.pi/2), 0)) assert(eq(math.atan(1), math.pi/4) and eq(math.acos(0), math.pi/2) and eq(math.asin(1), math.pi/2)) assert(eq(math.deg(math.pi/2), 90) and eq(math.rad(90), math.pi/2)) assert(math.abs(-10.43) == 10.43) assert(eqT(math.abs(minint), minint)) assert(eqT(math.abs(maxint), maxint)) assert(eqT(math.abs(-maxint), maxint)) assert(eq(math.atan(1,0), math.pi/2)) assert(math.fmod(10,3) == 1) assert(eq(math.sqrt(10)^2, 10)) assert(eq(math.log(2, 10), math.log(2)/math.log(10))) assert(eq(math.log(2, 2), 1)) assert(eq(math.log(9, 3), 2)) assert(eq(math.exp(0), 1)) assert(eq(math.sin(10), math.sin(10%(2*math.pi)))) assert(tonumber(' 1.3e-2 ') == 1.3e-2) assert(tonumber(' -1.00000000000001 ') == -1.00000000000001) -- testing constant limits -- 2^23 = 8388608 assert(8388609 + -8388609 == 0) assert(8388608 + -8388608 == 0) assert(8388607 + -8388607 == 0) do -- testing floor & ceil assert(eqT(math.floor(3.4), 3)) assert(eqT(math.ceil(3.4), 4)) assert(eqT(math.floor(-3.4), -4)) assert(eqT(math.ceil(-3.4), -3)) assert(eqT(math.floor(maxint), maxint)) assert(eqT(math.ceil(maxint), maxint)) assert(eqT(math.floor(minint), minint)) assert(eqT(math.floor(minint + 0.0), minint)) assert(eqT(math.ceil(minint), minint)) assert(eqT(math.ceil(minint + 0.0), minint)) assert(math.floor(1e50) == 1e50) assert(math.ceil(1e50) == 1e50) assert(math.floor(-1e50) == -1e50) assert(math.ceil(-1e50) == -1e50) for _, p in pairs{31,32,63,64} do assert(math.floor(2^p) == 2^p) assert(math.floor(2^p + 0.5) == 2^p) assert(math.ceil(2^p) == 2^p) assert(math.ceil(2^p - 0.5) == 2^p) end checkerror("number expected", math.floor, {}) checkerror("number expected", math.ceil, print) assert(eqT(math.tointeger(minint), minint)) assert(eqT(math.tointeger(minint .. ""), minint)) assert(eqT(math.tointeger(maxint), maxint)) assert(eqT(math.tointeger(maxint .. ""), maxint)) assert(eqT(math.tointeger(minint + 0.0), minint)) assert(math.tointeger(0.0 - minint) == nil) assert(math.tointeger(math.pi) == nil) assert(math.tointeger(-math.pi) == nil) assert(math.floor(math.huge) == math.huge) assert(math.ceil(math.huge) == math.huge) assert(math.tointeger(math.huge) == nil) assert(math.floor(-math.huge) == -math.huge) assert(math.ceil(-math.huge) == -math.huge) assert(math.tointeger(-math.huge) == nil) assert(math.tointeger("34.0") == 34) assert(math.tointeger("34.3") == nil) assert(math.tointeger({}) == nil) assert(math.tointeger(0/0) == nil) -- NaN end -- testing fmod for integers for i = -6, 6 do for j = -6, 6 do if j ~= 0 then local mi = math.fmod(i, j) local mf = math.fmod(i + 0.0, j) assert(mi == mf) assert(math.type(mi) == 'integer' and math.type(mf) == 'float') if (i >= 0 and j >= 0) or (i <= 0 and j <= 0) or mi == 0 then assert(eqT(mi, i % j)) end end end end assert(eqT(math.fmod(minint, minint), 0)) assert(eqT(math.fmod(maxint, maxint), 0)) assert(eqT(math.fmod(minint + 1, minint), minint + 1)) assert(eqT(math.fmod(maxint - 1, maxint), maxint - 1)) checkerror("zero", math.fmod, 3, 0) do -- testing max/min checkerror("value expected", math.max) checkerror("value expected", math.min) assert(eqT(math.max(3), 3)) assert(eqT(math.max(3, 5, 9, 1), 9)) assert(math.max(maxint, 10e60) == 10e60) assert(eqT(math.max(minint, minint + 1), minint + 1)) assert(eqT(math.min(3), 3)) assert(eqT(math.min(3, 5, 9, 1), 1)) assert(math.min(3.2, 5.9, -9.2, 1.1) == -9.2) assert(math.min(1.9, 1.7, 1.72) == 1.7) assert(math.min(-10e60, minint) == -10e60) assert(eqT(math.min(maxint, maxint - 1), maxint - 1)) assert(eqT(math.min(maxint - 2, maxint, maxint - 1), maxint - 2)) end -- testing implicit convertions local a,b = '10', '20' assert(a*b == 200 and a+b == 30 and a-b == -10 and a/b == 0.5 and -b == -20) assert(a == '10' and b == '20') do gcs:send_text(6, "testing -0 and NaN") local mz, z = -0.0, 0.0 assert(mz == z) assert(1/mz < 0 and 0 < 1/z) local a = {[mz] = 1} assert(a[z] == 1 and a[mz] == 1) a[z] = 2 assert(a[z] == 2 and a[mz] == 2) local inf = math.huge * 2 + 1 mz, z = -1/inf, 1/inf assert(mz == z) assert(1/mz < 0 and 0 < 1/z) local NaN = inf - inf assert(NaN ~= NaN) assert(not (NaN < NaN)) assert(not (NaN <= NaN)) assert(not (NaN > NaN)) assert(not (NaN >= NaN)) assert(not (0 < NaN) and not (NaN < 0)) local NaN1 = 0/0 assert(NaN ~= NaN1 and not (NaN <= NaN1) and not (NaN1 <= NaN)) local a = {} assert(not pcall(rawset, a, NaN, 1)) assert(a[NaN] == nil) a[1] = 1 assert(not pcall(rawset, a, NaN, 1)) assert(a[NaN] == nil) -- strings with same binary representation as 0.0 (might create problems -- for constant manipulation in the pre-compiler) local a1, a2, a3, a4, a5 = 0, 0, "\0\0\0\0\0\0\0\0", 0, "\0\0\0\0\0\0\0\0" assert(a1 == a2 and a2 == a4 and a1 ~= a3) assert(a3 == a5) end gcs:send_text(6, "testing 'math.random'") math.randomseed(0) do -- test random for floats local max = -math.huge local min = math.huge for i = 0, 20000 do local t = math.random() assert(0 <= t and t < 1) max = math.max(max, t) min = math.min(min, t) if eq(max, 1, 0.001) and eq(min, 0, 0.001) then goto ok end end -- loop ended without satisfing condition assert(false) ::ok:: end do local function aux (p, lim) -- test random for small intervals local x1, x2 if #p == 1 then x1 = 1; x2 = p[1] else x1 = p[1]; x2 = p[2] end local mark = {}; local count = 0 -- to check that all values appeared for i = 0, lim or 2000 do local t = math.random(table.unpack(p)) assert(x1 <= t and t <= x2) if not mark[t] then -- new value mark[t] = true count = count + 1 end if count == x2 - x1 + 1 then -- all values appeared; OK goto ok end end -- loop ended without satisfing condition assert(false) ::ok:: end aux({-10,0}) aux({6}) aux({-10, 10}) aux({minint, minint}) aux({maxint, maxint}) aux({minint, minint + 9}) aux({maxint - 3, maxint}) end do local function aux(p1, p2) -- test random for large intervals local max = minint local min = maxint local n = 200 local mark = {}; local count = 0 -- to count how many different values for _ = 1, n do local t = math.random(p1, p2) max = math.max(max, t) min = math.min(min, t) if not mark[t] then -- new value mark[t] = true count = count + 1 end end -- at least 80% of values are different assert(count >= n * 0.8) -- min and max not too far from formal min and max local diff = (p2 - p1) // 8 assert(min < p1 + diff and max > p2 - diff) end aux(0, maxint) aux(1, maxint) aux(minint, -1) aux(minint // 2, maxint // 2) end for i=1,100 do assert(math.random(maxint) > 0) assert(math.random(minint, -1) < 0) end assert(not pcall(math.random, 1, 2, 3)) -- too many arguments -- empty interval assert(not pcall(math.random, minint + 1, minint)) assert(not pcall(math.random, maxint, maxint - 1)) assert(not pcall(math.random, maxint, minint)) -- interval too large assert(not pcall(math.random, minint, 0)) assert(not pcall(math.random, -1, maxint)) assert(not pcall(math.random, minint // 2, maxint // 2 + 1)) function update() gcs:send_text(6, 'Math tests passed') return update, 1000 end return update()
gpl-3.0
mohammadrezatitan/parsol
libs/serpent.lua
656
7877
local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License local c, d = "Paul Kulchenko", "Lua serializer and pretty printer" local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'} local badtype = {thread = true, userdata = true, cdata = true} local keyword, globals, G = {}, {}, (_G or _ENV) for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false', 'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat', 'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end for k,v in pairs(G) do globals[v] = k end -- build func to name mapping for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end local function s(t, opts) local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge) local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge) local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0 local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)", -- tostring(val) is needed because __tostring may return a non-string value function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s) or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026 or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r'] local n = name == nil and '' or name local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n] local safe = plain and n or '['..safestr(n)..']' return (path or '')..(plain and path and '.' or '')..safe, safe end local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'} local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end table.sort(k, function(a,b) -- sort numeric keys first: k[key] is not nil for numerical keys return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum)) < (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end local function val2str(t, name, indent, insref, path, plainindex, level) local ttype, level, mt = type(t), (level or 0), getmetatable(t) local spath, sname = safename(path, name) local tag = plainindex and ((type(name) == "number") and '' or name..space..'='..space) or (name ~= nil and sname..space..'='..space or '') if seen[t] then -- already seen this element sref[#sref+1] = spath..space..'='..space..seen[t] return tag..'nil'..comment('ref', level) end if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself seen[t] = insref or spath if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end ttype = type(t) end -- new value falls through to be serialized if ttype == "table" then if level >= maxl then return tag..'{}'..comment('max', level) end seen[t] = insref or spath if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty local maxn, o, out = math.min(#t, maxnum or #t), {}, {} for key = 1, maxn do o[key] = key end if not maxnum or #o < maxnum then local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end if maxnum and #o > maxnum then o[maxnum+1] = nil end if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output) for n, key in ipairs(o) do local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing or opts.keyallow and not opts.keyallow[key] or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types or sparse and value == nil then -- skipping nils; do nothing elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then if not seen[key] and not globals[key] then sref[#sref+1] = 'placeholder' local sname = safename(iname, gensym(key)) -- iname is table for local variables sref[#sref] = val2str(key,sname,indent,sname,iname,true) end sref[#sref+1] = 'placeholder' local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']' sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path)) else out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1) end end local prefix = string.rep(indent or '', level) local head = indent and '{\n'..prefix..indent or '{' local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space)) local tail = indent and "\n"..prefix..'}' or '}' return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level) elseif badtype[ttype] then seen[t] = insref or spath return tag..globerr(t, level) elseif ttype == 'function' then seen[t] = insref or spath local ok, res = pcall(string.dump, t) local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or "((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level)) return tag..(func or globerr(t, level)) else return tag..safestr(t) end -- handle all other types end local sepr = indent and "\n" or ";"..space local body = val2str(t, name, indent) -- this call also populates sref local tail = #sref>1 and table.concat(sref, sepr)..sepr or '' local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or '' return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end" end local function deserialize(data, opts) local env = (opts and opts.safe == false) and G or setmetatable({}, { __index = function(t,k) return t end, __call = function(t,...) error("cannot call functions") end }) local f, res = (loadstring or load)('return '..data, nil, nil, env) if not f then f, res = (loadstring or load)(data, nil, nil, env) end if not f then return f, res end if setfenv then setfenv(f, env) end return pcall(f) end local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s, load = deserialize, dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end, line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end, block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Qulun_Dome/npcs/Magicite.lua
19
1569
----------------------------------- -- Area: Qulun Dome -- NPC: Magicite -- Involved in Mission: Magicite -- @pos 11 25 -81 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:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_AURASTONE) == false) then if (player:getVar("MissionStatus") < 4) then player:startEvent(0x0000,1); -- play Lion part of the CS (this is first magicite) else player:startEvent(0x0000); -- don't play Lion part of the CS end else player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY); 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 == 0x0000) then player:setVar("MissionStatus",4); player:addKeyItem(MAGICITE_AURASTONE); player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_AURASTONE); end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Jugner_Forest/npcs/Cavernous_Maw.lua
29
1495
----------------------------------- -- Area: Jugner Forest -- NPC: Cavernous Maw -- @pos -118 -8 -518 104 -- Teleports Players to Jugner Forest [S] ----------------------------------- package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/Jugner_Forest/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) and hasMawActivated(player,3)) then player:startEvent(0x0389); else player:messageSpecial(NOTHING_HAPPENS); 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 == 0x0389 and option == 1) then toMaw(player,13); end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/globals/chocobo_digging.lua
46
7397
-- chocobo_digging.lua require("scripts/globals/status"); require("scripts/globals/utils"); require("scripts/globals/settings"); ----------------------------------- -- DIG REQUIREMENTS ----------------------------------- DIGREQ_NONE = 0; DIGREQ_BURROW = 1; DIGREQ_BORE = 2; DIGREQ_MODIFIER = 4; DIGREQ_NIGHT = 8; local DIGABILITY_BURROW = 1; local DIGABILITY_BORE = 2; local function canDig(player) local DigCount = player:getVar('[DIG]DigCount'); local LastDigTime = player:getLocalVar('[DIG]LastDigTime'); local ZoneItemsDug = GetServerVariable('[DIG]ZONE'..player:getZoneID()..'_ITEMS'); local ZoneInTime = player:getLocalVar('[DIG]ZoneInTime'); local CurrentTime = os.time(os.date('!*t')); local SkillRank = player:getSkillRank(SKILL_DIG); -- base delay -5 for each rank local DigDelay = 16 - (SkillRank * 5); local AreaDigDelay = 60 - (SkillRank * 5); -- neither player nor zone have reached their dig limit if ((DigCount < 100 and ZoneItemsDug < 20) or DIG_FATIGUE == 0 ) then -- pesky delays if ((ZoneInTime <= AreaDigDelay + CurrentTime) and (LastDigTime + DigDelay <= CurrentTime)) then return true; end end return false; end; local function calculateSkillUp(player) -- 59 cause we're gonna use SKILL_DIG for burrow/bore local SkillRank = player:getSkillRank(SKILL_DIG); local MaxSkill = (SkillRank + 1) * 100; local RealSkill = player:getSkillLevel(SKILL_DIG); local SkillIncrement = 1; -- this probably needs correcting local SkillUpChance = math.random(0, 100); -- make sure our skill isn't capped if (RealSkill < MaxSkill) then -- can we skill up? if (SkillUpChance <= 15) then if ((SkillIncrement + RealSkill) > MaxSkill) then SkillIncrement = MaxSkill - RealSkill; end -- skill up! player:setSkillLevel(SKILL_DIG, RealSkill + SkillIncrement); -- gotta update the skill rank and push packet for i = 0, 10, 1 do if (SkillRank == i and RealSkill >= ((SkillRank * 100) + 100)) then player:setSkillRank(SKILL_DIG, SkillRank + 1); end end if ((RealSkill / 10) < ((RealSkill + SkillIncrement) / 10)) then -- todo: get this working correctly (apparently the lua binding updates RealSkills and WorkingSkills) player:setSkillLevel(SKILL_DIG, player:getSkillLevel(SKILL_DIG) + 0x20); end end end end; function updatePlayerDigCount(player, increment) local CurrentTime = os.time(os.date('!*t')); if (increment == 0) then player:setVar('[DIG]DigCount', 0); else local DigCount = player:getVar('[DIG]DigCount'); player:setVar('[DIG]DigCount', DigCount + increment); end player:setLocalVar('[DIG]LastDigTime', CurrentTime); end; function updateZoneDigCount(zone, increment) local ZoneDigCount = GetServerVariable('[DIG]ZONE'..zone..'_ITEMS'); -- 0 means we wanna wipe (probably only gonna happen onGameDay or something) if (increment == 0) then SetServerVariable('[DIG]ZONE'..zone..'ITEMS', 0); else SetServerVariable('[DIG]ZONE'..zone..'ITEMS', ZoneDigCount + increment); end end; function chocoboDig(player, itemMap, precheck, messageArray) -- make sure the player can dig before going any further -- (and also cause i need a return before core can go any further with this) if (precheck) then return canDig(player); else local DigCount = player:getVar('[DIG]DigCount'); local Chance = math.random(0, 100); if (Chance <= 15) then player:messageText(player, messageArray[2]); calculateSkillUp(player); else -- recalculate chance to compare with item abundance Chance = math.random(0, 100); -- select a random item local RandomItem = itemMap[math.random(1, #itemMap)]; local RItemAbundance = RandomItem[2]; local ItemID = 0; local weather = player:getWeather(); local moon = VanadielMoonPhase(); local day = VanadielDayElement(); -- item and DIG_ABUNDANCE_BONUS 3 digits, dont wanna get left out Chance = Chance * 100; -- We need to check for moon phase, too. 45-60% results in a much lower dig chance than the rest of the phases if (moon >= 45 and moon <=60) then Chance = Chance * .5; end if (Chance < (RItemAbundance + DIG_ABUNDANCE_BONUS)) then local RItemID = RandomItem[1]; local RItemReq = RandomItem[3]; -- rank 1 is burrow, rank 2 is bore (see DIGABILITY at the top of the file) local DigAbility = player:getSkillRank(SKILL_DIG); local Mod = player:getMod(MOD_EGGHELM); if ((RItemReq == DIGREQ_NONE) or (RItemReq == DIGREQ_BURROW and DigAbility == DIGABILITY_BURROW) or (RItemReq == DIGREQ_BORE and DigAbility == DIGABILITY_BORE) or (RItemReq == DIGREQ_MODIFIER and Mod == 1) or (RItemReq == DIGREQ_NIGHT and VanadielTOTD() == TIME_NIGHT)) then ItemID = RItemID; else ItemID = 0; end -- Let's see if the item should be obtained in this zone with this weather local crystalMap = { 0, -- fire crystal 8, -- fire cluster 5, -- water crystal 13, -- water cluster 3, -- earth crystal 11, -- earth cluster 2, -- wind crystal 10, -- wind cluster 1, -- ice crystal 9, -- ice cluster 4, -- lightning crystal 12, -- lightning cluster 6, -- light crystal 14, -- light cluster 7, -- dark crystal 15, -- dark cluster }; if (weather >= 4 and ItemID == 4096) then ItemID = ItemID + crystalMap[weather-3]; end local oreMap = { 0, -- fire ore 3, -- earth ore 5, -- water ore 2, -- wind ore 1, -- ice ore 4, -- lightning ore 6, -- light ore 7, -- dark ore }; -- If the item is an elemental ore, we need to check if the requirements are met if (ItemID == 1255 and weather > 1 and (moon >= 10 and moon <= 40) and SkillRank >= 7) then ItemID = ItemID + oreMap[day+1]; end -- make sure we have a valid item if (ItemID ~= 0) then -- make sure we have enough room for the item if (player:addItem(ItemID)) then player:messageSpecial(ITEM_OBTAINED, ItemID); else player:messageSpecial(DIG_THROW_AWAY, ItemID); end else -- beat the dig chance, but not the item chance player:messageText(player, messageArray[2], false); end end calculateSkillUp(player); updatePlayerDigCount(player, 1); end return true; end end;
gpl-3.0
Sonicrich05/FFXI-Server
scripts/zones/Port_Bastok/npcs/Silver_Owl.lua
34
1328
----------------------------------- -- Area: Port Bastok -- NPC: Silver Owl -- Type: Tenshodo Merchant -- @pos -99.155 4.649 23.292 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then if (player:sendGuild(60420, 1, 23, 4)) then player:showText(npc,TENSHODO_SHOP_OPEN_DIALOG); end else player:startEvent(0x0096,1) 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
Sonicrich05/FFXI-Server
scripts/globals/icanheararainbow.lua
29
7834
-- Functions below used in quest: I Can Hear a Rainbow require( "scripts/globals/status"); require( "scripts/globals/quests"); require( "scripts/globals/weather"); colorsAvailable = { 102, 103, 104, 105, 106, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 123, 124, 125}; -- Zone IDs -- Data below from http://wiki.ffxiclopedia.org/wiki/I_Can_Hear_a_Rainbow - Feb. 02, 2013 colorsAvailable[100] = { false, true, false, false, false, false, false}; -- West Ronfaure colorsAvailable[101] = { false, true, false, false, false, false, false}; -- East Ronfaure colorsAvailable[102] = { false, false, false, true, true, false, false}; -- La Theine Plateau colorsAvailable[103] = { true, false, true, false, false, false, false}; -- Valkurm Dunes colorsAvailable[104] = { false, false, false, false, true, false, true }; -- Jugner Forest colorsAvailable[105] = { false, false, true, false, false, true, false}; -- Batallia Downs colorsAvailable[106] = { false, true, false, false, false, false, false}; -- North Gustaberg colorsAvailable[107] = { false, true, false, false, false, false, false}; -- South Gustaberg colorsAvailable[108] = { false, false, true, false, false, false, true }; -- Konschtat Highlands colorsAvailable[109] = { false, false, false, false, true, false, true }; -- Pashhow Marshlands colorsAvailable[110] = { true, false, false, false, true, false, false}; -- Rolanberry Fields colorsAvailable[111] = { false, false, false, false, false, true, false}; -- Beaucedine Glacier colorsAvailable[112] = { false, false, false, false, false, true, false}; -- Xarcabard colorsAvailable[113] = { true, false, false, true, false, false, false}; -- Cape Teriggan colorsAvailable[114] = { true, true, true, false, false, false, false}; -- Eastern Altepa Desert colorsAvailable[115] = { false, true, false, false, false, false, false}; -- West Sarutabaruta colorsAvailable[116] = { false, true, false, false, false, false, false}; -- East Sarutabaruta colorsAvailable[117] = { false, false, true, true, false, false, false}; -- Tahrongi Canyon colorsAvailable[118] = { false, true, false, true, true, false, false}; -- Buburimu Peninsula colorsAvailable[119] = { true, false, true, false, false, false, false}; -- Meriphataud Mountains colorsAvailable[120] = { false, false, true, false, false, false, true }; -- Sauromugue Champaign colorsAvailable[121] = { false, false, false, false, true, false, true }; -- The Sanctuary of Zi'Tah colorsAvailable[123] = { true, false, false, false, true, false, false}; -- Yuhtunga Jungle colorsAvailable[124] = { true, true, false, false, true, false, false}; -- Yhoator Jungle colorsAvailable[125] = { true, false, true, false, false, false, false}; -- Western Altepa Desert -- The Event IDs to trigger the light cutscene for the following 3 zones is currently unknown. -- They are included only because they are listed at http://wiki.ffxiclopedia.org/wiki/I_Can_Hear_a_Rainbow -- colorsAvailable[128] = { false, false, false, true, false, false, false}; -- Valley of Sorrows -- colorsAvailable[136] = { false, false, false, false, false, true, false}; -- Beaucedine Glacier (S) -- colorsAvailable[205] = { true, false, false, false, false, false, false}; -- Ifrit's Cauldron ----------------------------------- -- triggerLightCutscene ----------------------------------- function triggerLightCutscene( player) local cutsceneTriggered = false; local RED = 1; local ORANGE = 2; local YELLOW = 3; local GREEN = 4; local BLUE = 5; local INDIGO = 6; local VIOLET = 7; local zone = player:getZoneID(); local weather = player:getWeather(); if (player:hasItem( 1125, 0)) then -- Player has Carbuncle's Ruby? if (player:getQuestStatus( WINDURST, I_CAN_HEAR_A_RAINBOW) == QUEST_ACCEPTED) then if (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),0) == false and (weather == WEATHER_HOT_SPELL or weather == WEATHER_HEAT_WAVE)) then if (colorsAvailable[zone][RED]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",0,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),1) == false and (weather == WEATHER_NONE or weather == WEATHER_SUNSHINE)) then if (colorsAvailable[zone][ORANGE]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",1,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),2) == false and (weather == WEATHER_DUST_STORM or weather == WEATHER_SAND_STORM)) then if (colorsAvailable[zone][YELLOW]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",2,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),3) == false and (weather == WEATHER_WIND or weather == WEATHER_GALES)) then if (colorsAvailable[zone][GREEN]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",3,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),4) == false and (weather == WEATHER_RAIN or weather == WEATHER_SQUALL)) then if (colorsAvailable[zone][BLUE]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",4,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),5) == false and (weather == WEATHER_SNOW or weather == WEATHER_BLIZZARDS)) then if (colorsAvailable[zone][INDIGO]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",5,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end elseif (player:getMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),6) == false and (weather == WEATHER_THUNDER or weather == WEATHER_THUNDERSTORMS)) then if (colorsAvailable[zone][VIOLET]) then cutsceneTriggered = true; player:setMaskBit(player:getVar("I_CAN_HEAR_A_RAINBOW"),"I_CAN_HEAR_A_RAINBOW",6,true); player:setVar( "I_CAN_HEAR_A_RAINBOW_Weather", weather); end end if (cutsceneTriggered) then fixChocoboBug(player); end end end return cutsceneTriggered; end; ----------------------------------- -- lightCutsceneUpdate ----------------------------------- function lightCutsceneUpdate( player) local weather = player:getVar( "I_CAN_HEAR_A_RAINBOW_Weather"); if (weather == WEATHER_SUNSHINE) then -- In some zones the light cutscene does not handle WEATHER_SUNSHINE properly weather = WEATHER_NONE; end if (player:getVar( "I_CAN_HEAR_A_RAINBOW") < 127) then player:updateEvent( 0, 0, weather); else player:updateEvent( 0, 0, weather, 6); end end; ----------------------------------- -- lightCutsceneFinish ----------------------------------- function lightCutsceneFinish( player) fixChocoboBug(player); player:setVar("I_CAN_HEAR_A_RAINBOW_Weather", 0); end; ----------------------------------- -- fixChocoboBug ----------------------------------- function fixChocoboBug( player) if (player:hasStatusEffect(EFFECT_CHOCOBO)) then if (player:getAnimation() == 5) then player:setAnimation( 0); elseif (player:getAnimation() == 0) then player:setAnimation( 5); end end end;
gpl-3.0
ynohtna92/SlideNinjaSlide
game/dota_addons/slideninjaslide/scripts/vscripts/abilities.lua
1
33968
--[[ Abilities ]] --[[ Leap of Faith ]] --[[Stop loop sound Author: chrislotix Date: 6.1.2015.]] function LeapOfFaithStopSound ( keys ) local sound_name = "Hero_Chen.TeleportLoop" local target = keys.target StopSoundEvent(sound_name, target) if target.lofdummy ~= nil then -- StopEffect(target, "particles/units/heroes/hero_chen/chen_teleport.vpcf") StopEffect(target.lofdummy, "particles/units/heroes/hero_chen/chen_teleport_bits.vpcf") -- StopEffect(target, "particles/units/heroes/hero_chen/chen_teleport_cast.vpcf") -- StopEffect(target, "particles/units/heroes/hero_chen/chen_teleport_cast_sparks.vpcf") StopEffect(target.lofdummy, "particles/units/heroes/hero_chen/chen_teleport_rings.vpcf") target.lofdummy:ForceKill( true ) target.lofdummy = nil end end --[[ Author: Ractidous Date: 29.01.2015. Hide caster's model. ]] function HideHero( keys ) keys.caster:AddNoDraw() end --[[ Author: Ractidous Date: 29.01.2015. Show caster's model. ]] function ShowHero ( keys ) keys.caster:RemoveNoDraw() end --[[Author: Noya Date: 09.08.2015. Hides all dem hats ]] function HideWearables( event ) local hero = event.caster local ability = event.ability hero.hiddenWearables = {} -- Keep every wearable handle in a table to show them later local model = hero:FirstMoveChild() while model ~= nil do if model:GetClassname() == "dota_item_wearable" then model:AddEffects(EF_NODRAW) -- Set model hidden table.insert(hero.hiddenWearables, model) end model = model:NextMovePeer() end end function ShowWearables( event ) local hero = event.caster for i,v in pairs(hero.hiddenWearables) do v:RemoveEffects(EF_NODRAW) end end function RemoveSkateAnimation( unit ) unit:RemoveModifierByName(unit.skateAnimation) end --[[Author: A_Dizzle Date: 23.02.2015 Moves the Hero forward a random distance ]] function LeapOfFaith ( keys ) local caster = keys.caster local target = keys.target local min = keys.min local max = keys.max local connect = target:GetAbsOrigin() local direction = target:GetForwardVector() local distance = math.random(min, max) print(distance) local point = (direction * distance) + connect print(point) local lastValid = connect local endPoint = point local midpoints = math.ceil((connect - endPoint):Length() / 32) local navConnect = false local index = 1 while not navConnect and index < midpoints do lastPoint = connect connect = connect + (endPoint - connect):Normalized() * 32 * index navConnect = not GridNav:IsTraversable(connect) or GridNav:IsBlocked(connect) index = index + 1 end if not navConnect then lastPoint = connect connect = endPoint navConnect = not GridNav:IsTraversable(connect) or GridNav:IsBlocked(connect) if not navConnect then lastPoint = endPoint end end target:Stop() FindClearSpaceForUnit(target, lastPoint, false) local dummy = CreateUnitByName( "npc_dummy_unit", target:GetAbsOrigin(), false, caster, caster, caster:GetTeamNumber() ) target.lofdummy = dummy --ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_teleport.vpcf", PATTACH_ABSORIGIN_FOLLOW, target) ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_teleport_bits.vpcf", PATTACH_ABSORIGIN_FOLLOW, dummy) -- ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_teleport_cast.vpcf", PATTACH_ABSORIGIN_FOLLOW, target) -- ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_teleport_cast_sparks.vpcf", PATTACH_ABSORIGIN_FOLLOW, target) ParticleManager:CreateParticle("particles/units/heroes/hero_chen/chen_teleport_rings.vpcf", PATTACH_ABSORIGIN_FOLLOW, dummy) end function SpongeBobTokyoDrift( keys ) local caster = keys.caster local duration = keys.duration local time = 0 local particles_active = {} print("Tokyo Drift") Timers:CreateTimer(0.1, function() local fxIndex = ParticleManager:CreateParticle("particles/units/heroes/hero_beastmaster/beastmaster_primal_target_flash.vpcf", PATTACH_ABSORIGIN_FOLLOW, caster) ParticleManager:SetParticleControlEnt( fxIndex, 2, caster, PATTACH_ABSORIGIN_FOLLOW, "attach_hitloc", caster:GetAbsOrigin(), true ) table.insert(particles_active, fxIndex) if time < duration and caster:IsAlive() then time = time + 0.1 return 0.1 else for _,v in ipairs(particles_active) do ParticleManager:DestroyParticle(v, false) end return nil end end) end --[[ FORKED from SpellLibrary Original Author: Pizzalol Date: 05.01.2015. 'Leap' ]] function SpongeBobLeapOfFaith( keys ) local caster = keys.caster local duration = keys.duration local mid = duration / 2 local height = 250 local jump = height/(mid/0.03) local time_elapsed = 0 print(caster:GetAbsOrigin().z) caster:OnAction(function(box, unit) --PrintTable(box) local pos = unit:GetAbsOrigin() local x = pos.x local y = pos.y local middle = box.middle local xblock = true local value = 0 local normal = Vector(1,0,0) if x > middle.x then if y > middle.y then -- up,right local relx = (pos.x - middle.x) / box.xScale local rely = (pos.y - middle.y) / box.yScale if relx > rely then --right normal = Vector(1,0,0) value = box.xMax xblock = true else --up normal = Vector(0,1,0) value = box.yMax xblock = false end elseif y <= middle.y then -- down,right local relx = (pos.x - middle.x) / box.xScale local rely = (middle.y - pos.y) / box.yScale if relx > rely then --right normal = Vector(1,0,0) value = box.xMax xblock = true else --down normal = Vector(0,-1,0) value = box.yMin xblock = false end end elseif x <= middle.x then if y > middle.y then -- up,left local relx = (middle.x - pos.x) / box.xScale local rely = (pos.y - middle.y) / box.yScale if relx > rely then --left normal = Vector(-1,0,0) value = box.xMin xblock = true else --up normal = Vector(0,1,0) value = box.yMax xblock = false end elseif y <= middle.y then -- down,left local relx = (middle.x - pos.x) / box.xScale local rely = (middle.y - pos.y) / box.yScale if relx > rely then --left normal = Vector(-1,0,0) value = box.xMin xblock = true else --down normal = Vector(0,-1,0) value = box.yMin xblock = false end end end Physics:BlockInAABox(unit, xblock, value, buffer, findClearSpace) if IsPhysicsUnit(unit) then --print('turn hero', unit:GetAbsOrigin()) local reflection = (-2 * unit:GetForwardVector():Dot(normal) * normal) + unit:GetForwardVector() --unit:SetForwardVector(reflection) unit:MoveToPosition((200 * reflection) + unit:GetAbsOrigin()) end end) Timers:CreateTimer(0, function() local ground_position = GetGroundPosition(caster:GetAbsOrigin() , caster) time_elapsed = time_elapsed + 0.03 if time_elapsed < mid then caster:SetAbsOrigin(caster:GetAbsOrigin() + Vector(0,0,jump)) -- Up else caster:SetAbsOrigin(caster:GetAbsOrigin() - Vector(0,0,jump)) -- Down end --print(caster:GetAbsOrigin().z, ground_position.z) if caster:GetAbsOrigin().z - ground_position.z <= 0 then caster:OnAction( nil ) return nil end return 0.03 end) end function BubbleBeam( keys ) print("BubbleBeam") -- init ability local caster = keys.caster local ability = keys.ability local radius = keys.radius local bubbleSpeed = keys.bubble_speed if ( caster.slide ) then bubbleSpeed = bubbleSpeed + (caster:GetIdealSpeed()*0.5) end print(bubbleSpeed, radius) local duration = keys.duration local casterOrigin = caster:GetAbsOrigin() local targetDirection = caster:GetForwardVector() local projVelocity = targetDirection * bubbleSpeed local startTime = GameRules:GetGameTime() local endTime = startTime + duration -- Create linear projectile local projID = ProjectileManager:CreateLinearProjectile( { Ability = ability, EffectName = keys.proj_particle, vSpawnOrigin = casterOrigin, fDistance = 1000, fStartRadius = radius, fEndRadius = radius, Source = caster, bHasFrontalCone = false, bReplaceExisting = false, iUnitTargetTeam = DOTA_UNIT_TARGET_TEAM_ENEMY, iUnitTargetFlags = DOTA_UNIT_TARGET_FLAG_NONE, iUnitTargetType = DOTA_UNIT_TARGET_BASIC, fExpireTime = endTime, bDeleteOnHit = true, vVelocity = projVelocity, bProvidesVision = false, iVisionRadius = 1000, iVisionTeamNumber = caster:GetTeamNumber() } ) end function BubbleBeamOnHit( keys ) print("BubbleBeamOnHit") local target = keys.target local duration = keys.duration local mid = duration/2 local height = 200 local jump = height/(mid/0.03) local time_elapsed = 0 Timers:CreateTimer(0, function() local ground_position = GetGroundPosition(target:GetAbsOrigin() , target) time_elapsed = time_elapsed + 0.03 if time_elapsed < mid then target:SetAbsOrigin(target:GetAbsOrigin() + Vector(0,0,jump)) -- Up else target:SetAbsOrigin(target:GetAbsOrigin() - Vector(0,0,jump)) -- Down end --print(caster:GetAbsOrigin().z, ground_position.z) if target:GetAbsOrigin().z - ground_position.z <= 0 then return nil end return 0.03 end) end function BubbleBeamStop( keys ) print("BubbleBeamStop") end function Gaynish( keys ) GameMode:FleeWolf( keys.caster:GetAbsOrigin(), keys.target) end function DickClap( keys ) local ability = keys.ability local radius = ability:GetLevelSpecialValueFor("radius", ability:GetLevel() - 1) local target_team = DOTA_UNIT_TARGET_TEAM_ENEMY local target_type = DOTA_UNIT_TARGET_ALL local target_flag = DOTA_UNIT_TARGET_FLAG_INVULNERABLE local units = FindUnitsInRadius(keys.caster:GetTeamNumber(), keys.caster:GetAbsOrigin(), nil, radius, target_team, target_type, target_flag, FIND_CLOSEST, false) if #units > 0 then for _,v in ipairs(units) do GameMode:FleeWolf( keys.caster:GetAbsOrigin(), v) end end end function BladeFuryFlee( keys ) local caster = keys.caster local target = keys.target GameMode:FleeWolf( caster:GetAbsOrigin(), target ) end function BladeFuryStop( keys ) local caster = keys.caster caster:StopSound("Hero_Juggernaut.BladeFuryStart") end function DoomStopSound( keys ) print('DoomSoundStop') local unit = keys.unit StopSoundEvent("Hero_DoomBringer.Doom", unit) end function CycloneStopSound( keys ) local unit = keys.target StopSoundEvent("Brewmaster_Storm.Cyclone", unit) end function CycloneUnitStart( keys ) local target = keys.target local target_origin = target:GetAbsOrigin() local position = Vector(target_origin.x, target_origin.y, target_origin.z) local ability = keys.ability local duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel() - 1) target.cyclone_forward_vector = target:GetForwardVector() local total_degrees = 20 local ground_position = GetGroundPosition(position, target) local cyclone_initial_height = 250 + ground_position.z local cyclone_min_height = 200 + ground_position.z local cyclone_max_height = 350 + ground_position.z local tornado_start = GameRules:GetGameTime() -- Height per time calculation local time_to_reach_initial_height = duration / 10 --1/10th of the total cyclone duration will be spent ascending and descending to and from the initial height. local initial_ascent_height_per_frame = ((cyclone_initial_height - position.z) / time_to_reach_initial_height) * .03 --This is the height to add every frame when the unit is first cycloned, and applies until the caster reaches their max height. local up_down_cycle_height_per_frame = initial_ascent_height_per_frame / 3 --This is the height to add or remove every frame while the caster is in up/down cycle mode. if up_down_cycle_height_per_frame > 7.5 then --Cap this value so the unit doesn't jerk up and down for short-duration cyclones. up_down_cycle_height_per_frame = 7.5 end local final_descent_height_per_frame = nil --This is calculated when the unit begins descending. -- Time to go down local time_to_stop_fly = duration - time_to_reach_initial_height -- Loop up and down local going_up = true -- Loop every frame for the duration Timers:CreateTimer(function() local time_in_air = GameRules:GetGameTime() - tornado_start --Rotate as close to 20 degrees per .03 seconds (666.666 degrees per second) as possible, but such that the target lands facing their initial direction. if target.cyclone_degrees_to_spin == nil and duration ~= nil then local ideal_degrees_per_second = 666.666 local ideal_full_spins = (ideal_degrees_per_second / 360) * duration ideal_full_spins = math.floor(ideal_full_spins + .5) --Round the number of spins to aim for to the closest integer. local degrees_per_second_ending_in_same_forward_vector = (360 * ideal_full_spins) / duration target.cyclone_degrees_to_spin = degrees_per_second_ending_in_same_forward_vector * .03 end target:SetForwardVector(RotatePosition(Vector(0,0,0), QAngle(0, target.cyclone_degrees_to_spin, 0), target:GetForwardVector())) -- First send the target to the cyclone's initial height. if position.z < cyclone_initial_height and time_in_air <= time_to_reach_initial_height then --print("+",initial_ascent_height_per_frame,position.z) position.z = position.z + initial_ascent_height_per_frame target:SetAbsOrigin(position) return 0.03 -- Go down until the target reaches the ground. elseif time_in_air > time_to_stop_fly and time_in_air <= duration then --Since the unit may be anywhere between the cyclone's min and max height values when they start descending to the ground, --the descending height per frame must be calculated when that begins, so the unit will end up right on the ground when the duration is supposed to end. if final_descent_height_per_frame == nil then local descent_initial_height_above_ground = position.z - ground_position.z --print("ground position: " .. GetGroundPosition(position, target).z) --print("position.z : " .. position.z) final_descent_height_per_frame = (descent_initial_height_above_ground / time_to_reach_initial_height) * .03 end --print("-",final_descent_height_per_frame,position.z) position.z = position.z - final_descent_height_per_frame target:SetAbsOrigin(position) return 0.03 -- Do Up and down cycles elseif time_in_air <= duration then -- Up if position.z < cyclone_max_height and going_up then --print("going up") position.z = position.z + up_down_cycle_height_per_frame target:SetAbsOrigin(position) return 0.03 -- Down elseif position.z >= cyclone_min_height then going_up = false --print("going down") position.z = position.z - up_down_cycle_height_per_frame target:SetAbsOrigin(position) return 0.03 -- Go up again else --print("going up again") going_up = true return 0.03 end -- End else --print(GetGroundPosition(target:GetAbsOrigin(), target)) --print("End TornadoHeight") end end) end --[[Author: Pizzalol Date: 03.04.2015. Pulls the targets to the center]] function Vacuum( keys ) local caster = keys.caster local target = keys.target local target_location = target:GetAbsOrigin() local ability = keys.ability local ability_level = ability:GetLevel() - 1 -- Ability variables local duration = ability:GetLevelSpecialValueFor("duration", ability_level) local radius = ability:GetLevelSpecialValueFor("radius", ability_level) local vacuum_modifier = keys.vacuum_modifier local remaining_duration = duration - (GameRules:GetGameTime() - target.vacuum_start_time) -- Targeting variables local target_teams = ability:GetAbilityTargetTeam() local target_types = ability:GetAbilityTargetType() local target_flags = ability:GetAbilityTargetFlags() local units = FindUnitsInRadius(caster:GetTeamNumber(), target_location, nil, radius, target_teams, target_types, target_flags, FIND_CLOSEST, false) -- Calculate the position of each found unit for _,unit in ipairs(units) do local unit_location = unit:GetAbsOrigin() local vector_distance = target_location - unit_location local distance = (vector_distance):Length2D() local direction = (vector_distance):Normalized() -- Check if its a new vacuum cast -- Set the new pull speed if it is if unit.vacuum_caster ~= target then unit.vacuum_caster = target -- The standard speed value is for 1 second durations so we have to calculate the difference -- with 1/duration unit.vacuum_caster.pull_speed = distance * 1/0.6 * 1/30 end -- Apply the stun and no collision modifier then set the new location if not unit:HasModifier(vacuum_modifier) then ability:ApplyDataDrivenModifier(caster, unit, vacuum_modifier, {duration = remaining_duration}) end if distance > 10 then unit:SetAbsOrigin(unit_location + direction * unit.vacuum_caster.pull_speed) end end end --[[Author: Pizzalol Date: 03.04.2015. Track the starting vacuum time]] function VacuumStart( keys ) local target = keys.target target.vacuum_start_time = GameRules:GetGameTime() end function BehindStart( keys ) local ability = keys.ability local target = keys.target local caster = keys.caster local initial_position = caster:GetAbsOrigin() local initial_fv = caster:GetForwardVector() local target_position = keys.target:GetAbsOrigin() local target_fv = keys.target:GetForwardVector() local target_bv = target_fv * -1 local behind_position = target_position + target_bv * 100 local duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel() - 1) RemoveSkateAnimation( caster ) local fxIndex = ParticleManager:CreateParticle("particles/units/heroes/hero_riki/riki_blink_strike.vpcf", PATTACH_CUSTOMORIGIN, caster) ParticleManager:SetParticleControl(fxIndex, 0, initial_position) ParticleManager:SetParticleControl(fxIndex, 1, behind_position) FindClearSpaceForUnit(caster, behind_position, true) caster:SetForwardVector(target_fv) Timers:CreateTimer(duration, function() local fxIndex2 = ParticleManager:CreateParticle("particles/units/heroes/hero_riki/riki_blink_strike.vpcf", PATTACH_CUSTOMORIGIN, caster) ParticleManager:SetParticleControl(fxIndex2, 0, behind_position) ParticleManager:SetParticleControl(fxIndex2, 1, initial_position) FindClearSpaceForUnit(caster, initial_position, true) caster:SetForwardVector(initial_fv) end) end function BehindAttack( keys ) local caster = keys.caster caster:StartGesture(ACT_DOTA_OVERRIDE_ABILITY_2) Timers:CreateTimer(0.30, function() caster:EmitSound("Hero_LoneDruid.TrueForm.Attack") end) end function TrueFormStart( event ) local caster = event.caster local model = event.model local ability = event.ability -- Saves the original model if caster.caster_model == nil then caster.caster_model = caster:GetModelName() end -- Sets the new model caster:SetOriginalModel(model) end -- Reverts back to the original model function TrueFormEnd( event ) local caster = event.caster local ability = event.ability caster:SetModel(caster.caster_model) caster:SetOriginalModel(caster.caster_model) end function SillynessTriggered( hero, unit ) local ability = hero:FindAbilityByName("rgr_sillyness") local damage = ability:GetLevelSpecialValueFor("damage", ability:GetLevel() - 1) local damage_taken = ability:GetLevelSpecialValueFor("damage_taken", ability:GetLevel() - 1) if hero:GetHealth() > damage_taken then local damageTable = { victim = hero, attacker = unit, damage = damage_taken, damage_type = DAMAGE_TYPE_PURE, } ApplyDamage(damageTable) local damageTable2 = { victim = unit, attacker = hero, damage = damage, damage_type = DAMAGE_TYPE_PHYSICAL, } ApplyDamage(damageTable2) hero:StartGesture(ACT_DOTA_ATTACK) ability:ApplyDataDrivenModifier(hero, unit, "modifier_rgr_sillyness_target", {}) return true else return false end end function Devour( keys ) local caster = keys.caster local fv = caster:GetForwardVector() local devour_point = caster:GetAbsOrigin() + fv * 100 local radius = 100 local units = FindUnitsInRadius(caster:GetTeamNumber(), devour_point, nil, radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_BASIC, DOTA_UNIT_TARGET_FLAG_INVULNERABLE, FIND_CLOSEST, false) RemoveSkateAnimation( caster ) caster:StartGesture(ACT_DOTA_CAST_ABILITY_1) if #units > 0 then for _,unit in pairs(units) do local target = unit -- Closest if target:IsAlive() then PrintTable(target) local devourParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_doom_bringer/doom_bringer_devour.vpcf", PATTACH_POINT_FOLLOW, caster) ParticleManager:SetParticleControlEnt(devourParticle, 0, target, PATTACH_POINT_FOLLOW, "attach_origin", target:GetAbsOrigin(), true) ParticleManager:SetParticleControlEnt(devourParticle, 1, caster, PATTACH_POINT_FOLLOW, "attach_origin", caster:GetAbsOrigin(), true) keys.ability:ApplyDataDrivenModifier(caster, caster, "modifier_devour_eaten", {}) keys.ability:ApplyDataDrivenModifier(caster, target, "modifier_devour_eaten_target", {}) keys.ability.devourUnit = target return end end end end function DevourUnit( keys ) keys.target:AddNoDraw() end function DevourUnitEnd( keys ) local unit = keys.ability.devourUnit local caster = keys.caster if unit then keys.ability.devourUnit:RemoveNoDraw() keys.ability.devourUnit:RemoveModifierByName("modifier_devour_eaten_target") FindClearSpaceForUnit(unit, caster:GetAbsOrigin(), true) unit:Stop() end end -- Store Hawk target to give to hawk unit when it spawns function HawkStoreTarget( keys ) local target = keys.target local caster = keys.caster caster.hawkTarget = target end function HawkTargetCheck( keys ) local target = keys.target if target:IsIdle() and not target.hawkTarget:IsAlive() then target:ForceKill(false) end end function HawkAttack( keys ) local target = keys.target local caster = keys.caster if caster.hawkTarget and caster.hawkTarget:IsAlive() then target.hawkTarget = caster.hawkTarget Timers:CreateTimer(0.10, function() target:MoveToTargetToAttack(caster.hawkTarget) end) else target:ForceKill(false) end end function HawkAttackFlee( keys ) local unit = keys.attacker local target = keys.target GameMode:FleeWolf( unit:GetAbsOrigin(), target ) end function HawkTargetKilled( keys ) local unit = keys.attacker unit:ForceKill(false) end function QuilbeastSuicideDamage( keys ) local caster = keys.caster local target = keys.target local ability = GameMode.vPlayerIDToHero[caster:GetPlayerOwnerID()]:FindAbilityByName("rgr_summon_quilbeast") local dmg = ability:GetLevelSpecialValueFor("damage", ability:GetLevel() - 1) local damageTable = { victim = target, attacker = caster, damage = dmg, damage_type = DAMAGE_TYPE_PHYSICAL, } ApplyDamage(damageTable) end function QuilbeastSuicide( keys ) local caster = keys.caster caster:ForceKill(false) end function AttackClosestTarget( keys ) local target = keys.target local ability = target:GetAbilityByIndex(0) local unit = GetClosestTargetInRadius( target, 2000 ) if unit then Timers:CreateTimer(0.1, function() print("move to target") target:CastAbilityOnTarget( unit, ability, target:GetPlayerOwnerID()) end) end end -- ShortestPathableTarget function GetClosestTargetInRadius( unit, radius ) local target_team = DOTA_UNIT_TARGET_TEAM_ENEMY local target_type = DOTA_UNIT_TARGET_ALL local target_flag = DOTA_UNIT_TARGET_FLAG_INVULNERABLE local units = FindUnitsInRadius(unit:GetTeamNumber(), unit:GetAbsOrigin(), nil, radius, target_team, target_type, target_flag, FIND_CLOSEST, false) local shortest = nil local target = nil if #units > 0 then for _,v in ipairs(units) do local s = GridNav:FindPathLength( unit:GetAbsOrigin(), v:GetAbsOrigin() ) if shortest == nil or s < shortest then target = v shortest = s end end end return target end function GetFrontPoint( keys ) local caster = keys.caster local fv = caster:GetForwardVector() local origin = caster:GetAbsOrigin() local distance = 200 local front_point = origin + fv * distance local result = {} table.insert(result, front_point) return result end function SetUnitsMoveForward( keys ) local caster = keys.caster local target = keys.target local fv = caster:GetForwardVector() target:SetForwardVector(fv) end function CycloneUnitEnd( keys ) local target = keys.target if target.cyclone_forward_vector ~= nil then target:SetForwardVector(target.cyclone_forward_vector) end target.cyclone_degrees_to_spin = nil end function EvasionStart( keys ) print('EvasionStart') local ability = keys.ability local hero = keys.target local time_to_enabled = ability:GetLevelSpecialValueFor("evasion", ability:GetLevel() - 1) if hero.evasionTimer ~= nil then Timers:RemoveTimer(hero.evasionTimer) end hero.evasionTimer = Timers:CreateTimer(time_to_enabled, function() print('EvasionRenewed') ability:ApplyDataDrivenModifier(hero, hero, keys.modifier, {}) end) end -- Triggering Intensifies function EvasionTriggered( hero, unit ) hero:RemoveModifierByName("modifier_evasion_evade") local evasionParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_templar_assassin/templar_assassin_refract_hit.vpcf", PATTACH_POINT_FOLLOW, hero) ParticleManager:SetParticleControlEnt(evasionParticle, 0, hero, PATTACH_POINT_FOLLOW, "attach_origin", hero:GetAbsOrigin(), true) ParticleManager:SetParticleControlEnt(evasionParticle, 2, hero, PATTACH_POINT_FOLLOW, "attach_origin", hero:GetAbsOrigin(), true) ParticleManager:SetParticleControlForward(evasionParticle, 1, (hero:GetAbsOrigin()-unit:GetAbsOrigin()):Normalized() ) end -- This function is called when the unit hits a creep with the chemical rage modifier function ChemicalRageOnHit( hero ) if (hero:GetStrength()*0.01*hero:GetHealthPercent()) > RandomFloat(0,20) then hero:SetHealth(hero:GetHealth()-RandomFloat(0.01, hero:GetHealth() - 1)) return true else return false end end --[[Author: Pizzalol Date: 18.01.2015. Checks if the target is an illusion, if true then it kills it otherwise the target model gets swapped into a frog]] function voodoo_start( keys ) local target = keys.target local model = keys.model if target:IsIllusion() then target:ForceKill(true) else if target.target_model == nil then target.target_model = target:GetModelName() end target:SetOriginalModel(model) end end --[[Author: Pizzalol Date: 18.01.2015. Reverts the target model back to what it was]] function voodoo_end( keys ) local target = keys.target -- Checking for errors if target.target_model ~= nil then target:SetModel(target.target_model) target:SetOriginalModel(target.target_model) end end --[[ Author: kritth Date: 10.01.2015 Marks seen only to ally ]] function ghostship_mark_allies( caster, ability, target ) local allHeroes = HeroList:GetAllHeroes() local delay = ability:GetLevelSpecialValueFor( "tooltip_delay", ability:GetLevel() - 1 ) local particleName = "particles/units/heroes/hero_kunkka/kunkka_ghostship_marker.vpcf" for k, v in pairs( allHeroes ) do if v:GetPlayerID() and v:GetTeam() == caster:GetTeam() then local fxIndex = ParticleManager:CreateParticleForPlayer( particleName, PATTACH_ABSORIGIN, v, PlayerResource:GetPlayer( v:GetPlayerID() ) ) ParticleManager:SetParticleControl( fxIndex, 0, target ) EmitSoundOnClient( "Ability.pre.Torrent", PlayerResource:GetPlayer( v:GetPlayerID() ) ) -- Destroy particle after delay Timers:CreateTimer( delay, function() ParticleManager:DestroyParticle( fxIndex, false ) return nil end ) end end end --[[ Author: kritth Date: 10.01.2015 Start traversing the ship ]] function ghostship_start_traverse( keys ) -- Variables local caster = keys.caster local ability = keys.ability local casterPoint = caster:GetAbsOrigin() local targetPoint = keys.target_points[1] local spawnDistance = ability:GetLevelSpecialValueFor( "ghostship_distance", ability:GetLevel() - 1 ) local projectileSpeed = ability:GetLevelSpecialValueFor( "ghostship_speed", ability:GetLevel() - 1 ) local radius = ability:GetLevelSpecialValueFor( "ghostship_width", ability:GetLevel() - 1 ) local stunDelay = ability:GetLevelSpecialValueFor( "tooltip_delay", ability:GetLevel() - 1 ) local stunDuration = ability:GetLevelSpecialValueFor( "stun_duration", ability:GetLevel() - 1 ) local damage = ability:GetAbilityDamage() local damageType = ability:GetAbilityDamageType() local targetBuffTeam = DOTA_UNIT_TARGET_TEAM_FRIENDLY local targetImpactTeam = DOTA_UNIT_TARGET_TEAM_ENEMY local targetType = DOTA_UNIT_TARGET_ALL local targetFlag = DOTA_UNIT_TARGET_FLAG_NONE -- Get necessary vectors local forwardVec = targetPoint - casterPoint forwardVec = forwardVec:Normalized() local backwardVec = casterPoint - targetPoint backwardVec = backwardVec:Normalized() local spawnPoint = casterPoint + ( spawnDistance * backwardVec ) local impactPoint = casterPoint + ( spawnDistance * forwardVec ) local velocityVec = Vector( forwardVec.x, forwardVec.y, 0 ) -- Show visual effect ghostship_mark_allies( caster, ability, impactPoint ) -- Spawn projectiles local projectileTable = { Ability = ability, EffectName = "particles/units/heroes/hero_kunkka/kunkka_ghost_ship.vpcf", vSpawnOrigin = spawnPoint, fDistance = spawnDistance * 2, fStartRadius = radius, fEndRadius = radius, fExpireTime = GameRules:GetGameTime() + 5, Source = caster, bHasFrontalCone = false, bReplaceExisting = false, bProvidesVision = false, iUnitTargetTeam = targetImpactTeam, iUnitTargetType = targetType, vVelocity = velocityVec * projectileSpeed } ProjectileManager:CreateLinearProjectile( projectileTable ) -- Create timer for crashing Timers:CreateTimer( stunDelay, function() local units = FindUnitsInRadius( caster:GetTeamNumber(), impactPoint, caster, radius, targetImpactTeam, targetType, targetFlag, FIND_ANY_ORDER, false ) -- Fire sound event local dummy = CreateUnitByName( "npc_dummy_unit", impactPoint, false, caster, caster, caster:GetTeamNumber() ) StartSoundEvent( "Ability.Ghostship.crash", dummy ) dummy:ForceKill( true ) -- Stun and damage enemies for k, v in pairs( units ) do if not v:IsMagicImmune() then local damageTable = { victim = v, attacker = caster, damage = damage, damage_type = damageType } ApplyDamage( damageTable ) end v:AddNewModifier( caster, nil, "modifier_stunned", { duration = stunDuration } ) end return nil -- Delete timer end) end --[[Author: A_Dizzle Date: 19.11.2015 Moves the Hero forward a random distance ]] function LeapOfGayness( keys ) local target = keys.target local ability = keys.ability local min = ability:GetLevelSpecialValueFor("min_blink_range", ability:GetLevel() - 1) local max = ability:GetLevelSpecialValueFor("blink_range", ability:GetLevel() - 1) local duration = ability:GetLevelSpecialValueFor("duration", ability:GetLevel() - 1) local mid = duration / 2 local height = 250 local jump = height/(mid/0.03) local time_elapsed = 0 local connect = target:GetAbsOrigin() local direction = target:GetForwardVector() local distance = math.random(min, max) print(mid, jump, distance) local forward = distance/(duration/0.03) local moved = 0 local point = (direction * distance) + connect local targetParticle = ParticleManager:CreateParticle("particles/units/heroes/hero_gyrocopter/gyro_guided_missile_target.vpcf", PATTACH_CUSTOMORIGIN, target) ParticleManager:SetParticleControl(targetParticle, 0, point) Timers:CreateTimer(duration, function() StopEffect(target, "particles/units/heroes/hero_gyrocopter/gyro_guided_missile_target.vpcf") end) Timers:CreateTimer(0, function() local ground_position = GetGroundPosition(target:GetAbsOrigin() , target) time_elapsed = time_elapsed + 0.03 local nextPoint = target:GetAbsOrigin() + (direction * 55) if not GridNav:IsTraversable(nextPoint) or GridNav:IsBlocked(nextPoint) then local testPoint1 = target:GetAbsOrigin() + Vector(0,32,0) -- UP local testPoint2 = target:GetAbsOrigin() + Vector(32,0,0) -- Right local testPoint3 = target:GetAbsOrigin() + Vector(0,-32,0) -- Down local testPoint4 = target:GetAbsOrigin() + Vector(-32,0,0) -- Left local newDirection = direction if not GridNav:IsTraversable(testPoint1) or GridNav:IsBlocked(testPoint1) then newDirection = reflection(Vector(0,-1,0), direction) end if not GridNav:IsTraversable(testPoint2) or GridNav:IsBlocked(testPoint2) then newDirection = reflection(Vector(-1,0,0), direction) end if not GridNav:IsTraversable(testPoint3) or GridNav:IsBlocked(testPoint3) then newDirection = reflection(Vector(0,1,0), direction) end if not GridNav:IsTraversable(testPoint4) or GridNav:IsBlocked(testPoint4) then newDirection = reflection(Vector(1,0,0), direction) end if newDirection ~= direction then direction = newDirection print(moved) local newPoint = target:GetAbsOrigin() + newDirection * (distance-moved) newPoint.z = ground_position.z ParticleManager:SetParticleControl(targetParticle, 0, newPoint) end end if time_elapsed < mid then target:SetAbsOrigin(target:GetAbsOrigin() + Vector(0,0,jump) + direction*forward) -- Up else target:SetAbsOrigin(target:GetAbsOrigin() - Vector(0,0,jump) + direction*forward) -- Down end moved = moved + forward if target:GetAbsOrigin().z - ground_position.z <= 0 then return nil end return 0.03 end) target:Stop() end function reflection( normal, ray ) local reflection = ray - 2*ray:Dot(normal)*normal print(reflection) return reflection end function debug_teleport( keys ) print(keys.target_points[1]) FindClearSpaceForUnit(keys.caster, keys.target_points[1], true) end
mit
Sonicrich05/FFXI-Server
scripts/zones/Lower_Jeuno/npcs/Zauko.lua
17
5107
----------------------------------- -- Area: Lower Jeuno -- NPC: Zauko -- Involved in Quests: Save the Clock Tower, Community Service -- @zone 245 -- @pos -3 0 11 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; package.loaded["scripts/globals/settings"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) ----- Save The Clock Tower Quest ----- if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then a = player:getVar("saveTheClockTowerNPCz2"); -- NPC Zone2 if (a == 0 or (a ~= 256 and a ~= 288 and a ~= 320 and a ~= 384 and a ~= 768 and a ~= 352 and a ~= 896 and a ~= 416 and a ~= 832 and a ~= 448 and a ~= 800 and a ~= 480 and a ~= 864 and a ~= 928 and a ~= 960 and a ~= 992)) then player:startEvent(0x0032,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local hour = VanadielHour(); local cService = player:getVar("cService"); questServerVar = GetServerVariable("[JEUNO]CommService"); ----- Community Service Quest ----- -- The reason for all the Default Dialogue "else"s is because of all the different checks needed and to keep default dialogue -- If they're not there then the player will keep triggering the Quest Complete (Repeat) Cutscene -- Please leave them here unless you can find a way to fix this but the quest as it should do. -- Quest Start -- if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_AVAILABLE and player:getFameLevel(JEUNO) >=1) then if (hour >= 18 and hour < 21) then if (questServerVar == 0) then player:startEvent(0x0074,questServerVar+1); -- Quest Start Dialogue (NOTE: The Cutscene says somebody else is working on it but it still adds the quest) else player:startEvent(0x0074,questServerVar); end else player:startEvent(0x0076); -- Default Dialogue end -- Task Failed -- elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then if (cService >= 1 and cService < 12 == true) then -- If the quest is accepted but all lamps are NOT lit if (hour >= 18 and hour < 23) then player:startEvent(0x0077); -- Task Failed Dialogue else player:startEvent(0x0076); end -- Quest Complete -- else player:startEvent(0x0075); -- Quest Complete Dialogue end -- Repeat Quest -- elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 18) then if (hour >= 18 and hour < 21) then player:startEvent(0x0074,1) -- Quest Start (Repeat) else player:startEvent(0x0076); -- Default Dialogue end -- Repeat Quest Task Failed -- elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then if (cService >= 14 and cService < 24 == true) then if (hour >= 18 and hour < 23) then -- If Quest Repeat is accepted but lamps are not lit player:startEvent(0x0077); -- Task Failed Dialogue end elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 0) then player:startEvent(0x0076); -- Repeat Quest Complete -- else player:startEvent(0x0071); -- Quest Complete (Repeat) end else player:startEvent(0x0076); 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); -- ClockTower Quest -- if (csid == 0x0032) then player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1); player:setVar("saveTheClockTowerNPCz2",player:getVar("saveTheClockTowerNPCz2") + 256); ---- Community Service Quest ---- elseif (csid == 0x0074 and option == 0) then -- Quest Start if (questServerVar == 0) then player:addQuest(JEUNO,COMMUNITY_SERVICE); SetServerVariable("[JEUNO]CommService",1); end elseif (csid == 0x0075) then -- Quest Finish player:completeQuest(JEUNO,COMMUNITY_SERVICE); player:addFame(JEUNO,JEUNO_FAME*30); player:setVar("cService",13) player:addTitle(TORCHBEARER); elseif (csid == 0x0071) then -- Quest Finish (Repeat) player:addKeyItem(LAMP_LIGHTERS_MEMBERSHIP_CARD); -- Lamp Lighter's Membership Card player:messageSpecial(KEYITEM_OBTAINED,LAMP_LIGHTERS_MEMBERSHIP_CARD); player:addFame(JEUNO, JEUNO_FAME*15); player:setVar("cService",0); end end;
gpl-3.0
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/abilities/light_arts.lua
2
1315
----------------------------------- -- Ability: Light Arts ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- OnUseAbility ----------------------------------- function OnAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_LIGHT_ARTS) or player:hasStatusEffect(EFFECT_ADDENDUM_WHITE) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; function OnUseAbility(player, target, ability) player:delStatusEffect(EFFECT_DARK_ARTS); player:delStatusEffect(EFFECT_ADDENDUM_BLACK); player:delStatusEffect(EFFECT_PARSIMONY); player:delStatusEffect(EFFECT_ALACRITY); player:delStatusEffect(EFFECT_MANIFESTATION); player:delStatusEffect(EFFECT_EBULLIENCE); player:delStatusEffect(EFFECT_FOCALIZATION); player:delStatusEffect(EFFECT_EQUANIMITY); player:delStatusEffect(EFFECT_IMMANENCE); local skillbonus = player:getMod(MOD_LIGHT_ARTS_SKILL); local effectbonus = player:getMod(MOD_LIGHT_ARTS_EFFECT); local regenbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10); end player:addStatusEffect(EFFECT_LIGHT_ARTS,effectbonus,0,7200,0,regenbonus); return EFFECT_LIGHT_ARTS; end;
gpl-3.0
kyroskoh/kong
spec/plugins/logging_spec.lua
2
6605
local IO = require "kong.tools.io" local utils = require "kong.tools.utils" local cjson = require "cjson" local stringy = require "stringy" local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local STUB_GET_URL = spec_helper.STUB_GET_URL local TCP_PORT = spec_helper.find_port() local UDP_PORT = spec_helper.find_port({TCP_PORT}) local HTTP_PORT = spec_helper.find_port({TCP_PORT, UDP_PORT}) local HTTP_DELAY_PORT = spec_helper.find_port({TCP_PORT, UDP_PORT, HTTP_PORT}) local FILE_LOG_PATH = os.tmpname() local function create_mock_bin() local res, status = http_client.post("http://mockbin.org/bin/create", '{ "status": 200, "statusText": "OK", "httpVersion": "HTTP/1.1", "headers": [], "cookies": [], "content": { "mimeType" : "application/json" }, "redirectURL": "", "headersSize": 0, "bodySize": 0 }', { ["content-type"] = "application/json" }) assert.are.equal(201, status) return res:sub(2, res:len() - 1) end local mock_bin = create_mock_bin() describe("Logging Plugins", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { { name = "tests tcp logging", request_host = "tcp_logging.com", upstream_url = "http://mockbin.com" }, { name = "tests tcp logging2", request_host = "tcp_logging2.com", upstream_url = "http://localhost:"..HTTP_DELAY_PORT }, { name = "tests udp logging", request_host = "udp_logging.com", upstream_url = "http://mockbin.com" }, { name = "tests http logging", request_host = "http_logging.com", upstream_url = "http://mockbin.com" }, { name = "tests https logging", request_host = "https_logging.com", upstream_url = "http://mockbin.com" }, { name = "tests file logging", request_host = "file_logging.com", upstream_url = "http://mockbin.com" } }, plugin = { { name = "tcp-log", config = { host = "127.0.0.1", port = TCP_PORT }, __api = 1 }, { name = "tcp-log", config = { host = "127.0.0.1", port = TCP_PORT }, __api = 2 }, { name = "udp-log", config = { host = "127.0.0.1", port = UDP_PORT }, __api = 3 }, { name = "http-log", config = { http_endpoint = "http://localhost:"..HTTP_PORT.."/" }, __api = 4 }, { name = "http-log", config = { http_endpoint = "https://mockbin.org/bin/"..mock_bin }, __api = 5 }, { name = "file-log", config = { path = FILE_LOG_PATH }, __api = 6 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) it("should log to TCP", function() local thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "tcp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log proper latencies", function() local http_thread = spec_helper.start_http_server(HTTP_DELAY_PORT) -- Starting the mock TCP server local tcp_thread = spec_helper.start_tcp_server(TCP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(spec_helper.PROXY_URL.."/delay", nil, { host = "tcp_logging2.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = tcp_thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.truthy(log_message.latencies.proxy < 3000) assert.truthy(log_message.latencies.request >= log_message.latencies.kong + log_message.latencies.proxy) http_thread:join() end) it("should log to UDP", function() local thread = spec_helper.start_udp_server(UDP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "udp_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright local log_message = cjson.decode(res) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTP", function() local thread = spec_helper.start_http_server(HTTP_PORT) -- Starting the mock TCP server -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "http_logging.com" }) assert.are.equal(200, status) -- Getting back the TCP server input local ok, res = thread:join() assert.truthy(ok) assert.truthy(res) -- Making sure it's alright assert.are.same("POST / HTTP/1.1", res[1]) local log_message = cjson.decode(res[7]) assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to HTTPs", function() -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "https_logging.com" }) assert.are.equal(200, status) local total_time = 0 local res, status, body repeat assert.truthy(total_time <= 10) -- Fail after 10 seconds res, status = http_client.get("http://mockbin.org/bin/"..mock_bin.."/log", nil, { accept = "application/json" }) assert.are.equal(200, status) body = cjson.decode(res) local wait = 1 os.execute("sleep "..tostring(wait)) total_time = total_time + wait until(#body.log.entries > 0) assert.are.equal(1, #body.log.entries) local log_message = cjson.decode(body.log.entries[1].request.postData.text) -- Making sure it's alright assert.are.same("127.0.0.1", log_message.client_ip) end) it("should log to file", function() local uuid = utils.random_string() -- Making the request local _, status = http_client.get(STUB_GET_URL, nil, { host = "file_logging.com", file_log_uuid = uuid } ) assert.are.equal(200, status) while not (IO.file_exists(FILE_LOG_PATH)) do -- Wait for the file to be created end while not (IO.file_size(FILE_LOG_PATH) > 0) do -- Wait for the log to be appended end local file_log = IO.read_file(FILE_LOG_PATH) local log_message = cjson.decode(stringy.strip(file_log)) assert.are.same("127.0.0.1", log_message.client_ip) assert.are.same(uuid, log_message.request.headers.file_log_uuid) os.remove(FILE_LOG_PATH) end) end)
apache-2.0
Sonicrich05/FFXI-Server
scripts/globals/items/senroh_skewer.lua
36
1404
----------------------------------------- -- ID: 5982 -- Item: Senroh Skewer -- Food Effect: 30 Mins, All Races ----------------------------------------- -- Dexterity 2 -- Vitality 3 -- Mind -1 -- Defense % 25 Cap 150 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5982); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_VIT, 3); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 150); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_VIT, 3); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 150); end;
gpl-3.0
FelixPe/nodemcu-firmware
lua_modules/gossip/gossip.lua
6
7585
-- Gossip protocol implementation -- https://github.com/alexandruantochi/ local gossip = {}; local constants = {}; local utils = {}; local network = {}; local state = {}; -- Utils utils.contains = function(list, element) for k in pairs(list) do if list[k] == element then return true; end end return false; end utils.debug = function(message) if gossip.config.debug then if gossip.config.debugOutput then gossip.config.debugOutput(message); else print(message); end end end utils.getNetworkState = function() return sjson.encode(gossip.networkState); end utils.isNodeDataValid = function(nodeData) return (nodeData and nodeData.revision and nodeData.heartbeat and nodeData.state) ~= nil; end utils.compare = function(first, second) if first > second then return -1; end if first < second then return 1; end return 0; end utils.compareNodeData = function(first, second) local firstDataValid = utils.isNodeDataValid(first); local secondDataValid = utils.isNodeDataValid(second); if firstDataValid and secondDataValid then for index in ipairs(constants.comparisonFields) do local comparisonField = constants.comparisonFields[index]; local comparisonResult = utils.compare(first[comparisonField], second[comparisonField]); if comparisonResult ~= 0 then return comparisonResult; end end elseif firstDataValid then return -1; elseif secondDataValid then return 1; end return 0; end -- computes data1 - data2 based on node compare function utils.getMinus = function(data1, data2) local diff = {}; for ip, nodeData1 in pairs(data1) do if utils.compareNodeData(nodeData1, data2[ip]) == -1 then diff[ip] = nodeData1; end end return diff; end utils.setConfig = function(userConfig) for k, v in pairs(userConfig) do if gossip.config[k] ~= nil and type(gossip.config[k]) == type(v) then gossip.config[k] = v; end end end -- State state.setRev = function() local revision = 0; if file.exists(constants.revFileName) then revision = file.getcontents(constants.revFileName) + 1; end file.putcontents(constants.revFileName, revision); utils.debug('Revision set to ' .. revision); return revision; end state.setRevFileValue = function(revNumber) if revNumber then file.putcontents(constants.revFileName, revNumber); utils.debug('Revision overriden to ' .. revNumber); else utils.debug('Please provide a revision number.'); end end state.start = function() if gossip.started then utils.debug('Gossip already started.'); return; end gossip.ip = wifi.sta.getip(); if not gossip.ip then utils.debug('Node not connected to network. Gossip will not start.'); return; end gossip.networkState[gossip.ip] = {}; local localState = gossip.networkState[gossip.ip]; localState.revision = state.setRev(); localState.heartbeat = tmr.time(); localState.state = constants.nodeState.UP; gossip.inboundSocket = net.createUDPSocket(); gossip.inboundSocket:listen(gossip.config.comPort); gossip.inboundSocket:on('receive', network.receiveData); gossip.started = true; gossip.timer = tmr.create(); gossip.timer:register(gossip.config.roundInterval, tmr.ALARM_AUTO, network.sendSyn); gossip.timer:start(); utils.debug('Gossip started.'); end state.tickNodeState = function(ip) if gossip.networkState[ip] then local nodeState = gossip.networkState[ip].state; if nodeState < constants.nodeState.REMOVE then nodeState = nodeState + constants.nodeState.TICK; gossip.networkState[ip].state = nodeState; end end end -- Network network.pushGossip = function(data, ip) gossip.networkState[gossip.ip].data = data; network.sendSyn(nil, ip); end network.updateNetworkState = function(updateData) if gossip.updateCallback then gossip.updateCallback(updateData); end for ip, data in pairs(updateData) do if not utils.contains(gossip.config.seedList, ip) then table.insert(gossip.config.seedList, ip); end gossip.networkState[ip] = data; end end -- luacheck: push no unused network.sendSyn = function(t, ip) local destination = ip or network.pickRandomNode(); gossip.networkState[gossip.ip].heartbeat = tmr.time(); if destination then network.sendData(destination, gossip.networkState, constants.updateType.SYN); state.tickNodeState(destination); end end -- luacheck: pop network.pickRandomNode = function() if #gossip.config.seedList > 0 then local randomListPick = node.random(1, #gossip.config.seedList); utils.debug('Randomly picked: ' .. gossip.config.seedList[randomListPick]); return gossip.config.seedList[randomListPick]; end utils.debug( 'Seedlist is empty. Please provide one or wait for node to be contacted.'); return nil; end network.sendData = function(ip, data, sendType) local outboundSocket = net.createUDPSocket(); data.type = sendType; local dataToSend = sjson.encode(data); data.type = nil; outboundSocket:send(gossip.config.comPort, ip, dataToSend); outboundSocket:close(); end network.receiveSyn = function(ip, synData) utils.debug('Received SYN from ' .. ip); local update = utils.getMinus(synData, gossip.networkState); local diff = utils.getMinus(gossip.networkState, synData); network.updateNetworkState(update); network.sendAck(ip, diff); end network.receiveAck = function(ip, ackData) utils.debug('Received ACK from ' .. ip); local update = utils.getMinus(ackData, gossip.networkState); network.updateNetworkState(update); end network.sendAck = function(ip, diff) local diffIps = ''; for k in pairs(diff) do diffIps = diffIps .. ' ' .. k; end utils.debug('Sending ACK to ' .. ip .. ' with ' .. diffIps .. ' updates.'); network.sendData(ip, diff, constants.updateType.ACK); end -- luacheck: push no unused network.receiveData = function(socket, data, port, ip) if gossip.networkState[ip] then gossip.networkState[ip].state = constants.nodeState.UP; end local messageDecoded, updateData = pcall(sjson.decode, data); if not messageDecoded then utils.debug('Invalid JSON received from ' .. ip); return; end local updateType = updateData.type; updateData.type = nil; if updateType == constants.updateType.SYN then network.receiveSyn(ip, updateData); elseif updateType == constants.updateType.ACK then network.receiveAck(ip, updateData); else utils.debug('Invalid data comming from ip ' .. ip .. '. No valid type specified.'); end end -- luacheck: pop -- Constants constants.nodeState = {TICK = 1, UP = 0, SUSPECT = 2, DOWN = 3, REMOVE = 4}; constants.defaultConfig = { seedList = {}, roundInterval = 15000, comPort = 5000, debug = false }; constants.comparisonFields = {'revision', 'heartbeat', 'state'}; constants.updateType = {ACK = 'ACK', SYN = 'SYN'} constants.revFileName = 'gossip/rev.dat'; -- Return gossip = { started = false, config = constants.defaultConfig, setConfig = utils.setConfig, start = state.start, setRevFileValue = state.setRevFileValue, networkState = {}, getNetworkState = utils.getNetworkState, pushGossip = network.pushGossip }; -- return if (... == 'test') then return { _gossip = gossip, _constants = constants, _utils = utils, _network = network, _state = state }; elseif net and file and tmr and wifi then return gossip; else error('Gossip requires these modules to work: net, file, tmr, wifi'); end
mit
RavenX8/osIROSE-new
scripts/mobs/ai/hunter_clown.lua
2
1950
registerNpc(186, { walk_speed = 170, run_speed = 700, scale = 110, r_weapon = 1042, l_weapon = 0, level = 50, hp = 23, attack = 228, hit = 144, def = 131, res = 70, avoid = 83, attack_spd = 85, is_magic_damage = 0, ai_type = 29, give_exp = 39, drop_type = 195, drop_money = 25, drop_item = 55, union_number = 55, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 2100, npc_type = 6, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); registerNpc(189, { walk_speed = 170, run_speed = 700, scale = 125, r_weapon = 1042, l_weapon = 0, level = 59, hp = 36, attack = 271, hit = 171, def = 158, res = 82, avoid = 97, attack_spd = 100, is_magic_damage = 0, ai_type = 264, give_exp = 44, drop_type = 195, drop_money = 25, drop_item = 38, union_number = 38, need_summon_count = 0, sell_tab0 = 0, sell_tab1 = 0, sell_tab2 = 0, sell_tab3 = 0, can_target = 0, attack_range = 2100, npc_type = 6, hit_material_type = 1, face_icon = 0, summon_mob_type = 0, quest_type = 0, height = 0 }); function OnInit(entity) return true end function OnCreate(entity) return true end function OnDelete(entity) return true end function OnDead(entity) end function OnDamaged(entity) end
apache-2.0
premake/premake-core
tests/base/test_tree.lua
16
4592
-- -- tests/base/test_tree.lua -- Automated test suite source code tree handling. -- Copyright (c) 2009-2012 Jason Perkins and the Premake project -- local p = premake local suite = test.declare("base_tree") local tree = p.tree -- -- Setup/teardown -- local tr function suite.setup() tr = tree.new() end local function prepare() tree.traverse(tr, { onnode = function(node, depth) _p(depth + 2, node.name) end }) end -- -- Tests for tree.new() -- function suite.NewReturnsObject() test.isnotnil(tr) end -- -- Tests for tree.add() -- function suite.CanAddAtRoot() tree.add(tr, "Root") prepare() test.capture [[ Root ]] end function suite.CanAddAtChild() tree.add(tr, "Root/Child") prepare() test.capture [[ Root Child ]] end function suite.CanAddAtGrandchild() tree.add(tr, "Root/Child/Grandchild") prepare() test.capture [[ Root Child Grandchild ]] end -- -- Tests for tree.getlocalpath() -- function suite.GetLocalPath_ReturnsPath_OnNoParentPath() local c = tree.add(tr, "Root/Child") c.parent.path = nil test.isequal("Root/Child", tree.getlocalpath(c)) end function suite.GetLocalPath_ReturnsName_OnParentPathSet() local c = tree.add(tr, "Root/Child") test.isequal("Child", tree.getlocalpath(c)) end -- -- Tests for tree.remove() -- function suite.Remove_RemovesNodes() local n1 = tree.add(tr, "1") local n2 = tree.add(tr, "2") local n3 = tree.add(tr, "3") tree.remove(n2) local r = "" for _, n in ipairs(tr.children) do r = r .. n.name end test.isequal("13", r) end function suite.Remove_WorksInTraversal() tree.add(tr, "Root/1") tree.add(tr, "Root/2") tree.add(tr, "Root/3") local r = "" tree.traverse(tr, { onleaf = function(node) r = r .. node.name tree.remove(node) end }) test.isequal("123", r) test.isequal(0, #tr.children[1]) end -- -- Tests for tree.sort() -- function suite.Sort_SortsAllLevels() tree.add(tr, "B/3") tree.add(tr, "B/1") tree.add(tr, "A/2") tree.add(tr, "A/1") tree.add(tr, "B/2") tree.sort(tr) prepare() test.capture [[ A 1 2 B 1 2 3 ]] end -- -- If the root of the tree contains multiple items, it should not -- be removed by trimroot() -- function suite.trimroot_onItemsAtRoot() tree.add(tr, "A/1") tree.add(tr, "B/1") tree.trimroot(tr) prepare() test.capture [[ A 1 B 1 ]] end -- -- Should trim to first level with multiple items. -- function suite.trimroot_onItemsInFirstNode() tree.add(tr, "A/1") tree.add(tr, "A/2") tree.trimroot(tr) prepare() test.capture [[ 1 2 ]] end -- -- If the tree contains only a single node, don't trim it. -- function suite.trimroot_onSingleNode() tree.add(tr, "A") tree.trimroot(tr) prepare() test.capture [[ A ]] end -- -- If the tree contains only a single node, don't trim it. -- function suite.trimroot_onSingleLeafNode() tree.add(tr, "A/1") tree.trimroot(tr) prepare() test.capture [[ 1 ]] end -- -- A ".." folder containing a single subfolder should never appear -- at the top of the source tree. -- function suite.trimroot_removesDotDot_onTopLevelSiblings() tree.add(tr, "../../tests/test_hello.c") tree.add(tr, "../src/test.c") tree.trimroot(tr) prepare() test.capture [[ tests test_hello.c src test.c ]] end function suite.trimroot_removesDotDot_onTopLevel() tree.add(tr, "../tests/test_hello.c") tree.add(tr, "src/test.c") tree.trimroot(tr) prepare() test.capture [[ tests test_hello.c src test.c ]] end function suite.trimroot_removesDotDot_onMultipleNestings() tree.add(tr, "../../../tests/test_hello.c") tree.add(tr, "../src/test.c") tree.trimroot(tr) prepare() test.capture [[ tests test_hello.c src test.c ]] end -- -- When nodes are trimmed, the paths on the remaining nodes should -- be updated to reflect the new hierarchy. -- function suite.trimroot_updatesPaths_onNodesRemoved() tree.add(tr, "A/1") tree.add(tr, "A/2") tree.trimroot(tr) test.isequal("1", tr.children[1].path) end function suite.trimroot_updatesPaths_onDotDotRemoved() tree.add(tr, "../../../tests/test_hello.c") tree.add(tr, "../src/test.c") tree.trimroot(tr) test.isequal("tests", tr.children[1].path) end -- -- Nodes with the key "trim" set to false should be removed. -- function suite.trimroot_respectsTrimFlag() local n = tree.add(tr, "A") tree.add(tr, "A/1") n.trim = false tree.trimroot(tr) prepare() test.capture [[ A 1 ]] end
bsd-3-clause
kidaa/ffxinfinity
FFXI Server-Development/Build Files/scripts/globals/items/bowl_of_jack-o-soup.lua
3
1449
----------------------------------------- -- ID: 4522 -- Item: Bowl of Jack-o'-Soup -- Food Effect: 240Min, All Races ----------------------------------------- -- Health % 2 -- Agility 3 -- Vitality -1 -- Health Regen While Healing 5 -- Ranged ACC % 8 -- Ranged ACC Cap 25 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4522); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPP, 2); target:addMod(MOD_AGI, 3); target:addMod(MOD_VIT, -1); target:addMod(MOD_HPHEAL, 5); target:addMod(MOD_FOOD_RACCP, 8); target:addMod(MOD_FOOD_RACC_CAP, 25); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPP, 2); target:delMod(MOD_AGI, 3); target:delMod(MOD_VIT, -1); target:delMod(MOD_HPHEAL, 5); target:delMod(MOD_FOOD_RACCP, 8); target:delMod(MOD_FOOD_RACC_CAP, 25); end;
gpl-3.0
jow-/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/nat_traffic.lua
79
1251
local function scrape() -- documetation about nf_conntrack: -- https://www.frozentux.net/iptables-tutorial/chunkyhtml/x1309.html nat_metric = metric("node_nat_traffic", "gauge" ) for e in io.lines("/proc/net/nf_conntrack") do -- output(string.format("%s\n",e )) local fields = space_split(e) local src, dest, bytes; bytes = 0; for _, field in ipairs(fields) do if src == nil and string.match(field, '^src') then src = string.match(field,"src=([^ ]+)"); elseif dest == nil and string.match(field, '^dst') then dest = string.match(field,"dst=([^ ]+)"); elseif string.match(field, '^bytes') then local b = string.match(field, "bytes=([^ ]+)"); bytes = bytes + b; -- output(string.format("\t%d %s",ii,field )); end end -- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) .- bytes=([^ ]+)"); -- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) sport=[^ ]+ dport=[^ ]+ packets=[^ ]+ bytes=([^ ]+)") local labels = { src = src, dest = dest } -- output(string.format("src=|%s| dest=|%s| bytes=|%s|", src, dest, bytes )) nat_metric(labels, bytes ) end end return { scrape = scrape }
gpl-2.0
Sonicrich05/FFXI-Server
scripts/globals/mobskills/Randgrith.lua
19
1028
--------------------------------------------- -- Randgrith -- -- Description: Lowers target's evasion. -- Type: Physical -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if (mob:getTP() == 300) then duration = 60; elseif (mob:getTP() >= 200) then duration = 40; end MobStatusEffectMove(mob, target, EFFECT_EVASION_DOWN, 30, 0, duration); MobBuffMove(mob, EFFECT_ACCURACY_BOOST, 10, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0