repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
Scavenge/darkstar
scripts/zones/Norg/npcs/Shivivi.lua
14
3175
----------------------------------- -- Area: Norg -- NPC: Shivivi -- Starts Quest: Secret of the Damp Scroll -- @zone 252 -- @pos 68.729 -6.281 -6.432 ----------------------------------- package.loaded["scripts/zones/Norg/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Norg/TextIDs"); require("scripts/globals/pathfind"); local path = { 59.698738, -6.282220, -0.842413, 60.732185, -6.282220, -1.238357, 61.612240, -6.282220, -1.784821, 62.487907, -6.282220, -2.353283, 72.850945, -6.282220, -9.126195, 73.853767, -6.282220, -9.553433, 74.856308, -6.282220, -9.683896, 73.738983, -6.282220, -9.515277, 72.831741, -6.282220, -9.069685, 71.878197, -6.282220, -8.482308, 70.934311, -6.282220, -7.872030, 59.120659, -6.282220, -0.152556, 58.260170, -6.282220, 0.364192, 57.274529, -6.282220, 0.870113, 56.267262, -6.282220, 1.278537, 55.206066, -6.282220, 1.567320, 54.107983, -6.282220, 1.825333, 52.989727, -6.282220, 2.044612, 51.915558, -6.282220, 2.155138, 50.790054, -6.282220, 2.229803, 48.477810, -6.282220, 2.361498, 52.035912, -6.282220, 2.157254, 53.062607, -6.282220, 2.020960, 54.161610, -6.282220, 1.805452, 55.267555, -6.282220, 1.563984, 56.350552, -6.282220, 1.252867, 57.370754, -6.282220, 0.821186, 58.355640, -6.282220, 0.306034, 59.294991, -6.282220, -0.273827, 60.222008, -6.282220, -0.873351, 72.913628, -6.282220, -9.164549, 73.919716, -6.282220, -9.571738, 75.007599, -6.282220, -9.696978, 73.930611, -6.282220, -9.597872, 72.944572, -6.282220, -9.142765, 72.017265, -6.282220, -8.573789, 71.103760, -6.282220, -7.982807, 59.055004, -6.282220, -0.111382, 58.112335, -6.282220, 0.439206 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) DampScroll = player:getQuestStatus(OUTLANDS,SECRET_OF_THE_DAMP_SCROLL); mLvl = player:getMainLvl(); if (DampScroll == QUEST_AVAILABLE and player:getFameLevel(NORG) >= 3 and mLvl >= 10 and player:hasItem(1210) == true) then player:startEvent(0x001f,1210); -- Start the quest elseif (DampScroll == QUEST_ACCEPTED) then player:startEvent(0x0020); -- Reminder Dialogue else player:startEvent(0x0055); end npc:wait(0); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x001f) then player:addQuest(OUTLANDS,SECRET_OF_THE_DAMP_SCROLL); end npc:wait(0); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/spells/bluemagic/cocoon.lua
28
1337
----------------------------------------- -- Spell: Cocoon -- Enhances defense -- Spell cost: 10 MP -- Monster Type: Vermin -- Spell Type: Magical (Earth) -- Blue Magic Points: 1 -- Stat Bonus: VIT+3 -- Level: 8 -- Casting Time: 1.75 seconds -- Recast Time: 60 seconds -- Duration: 90 seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_DEFENSE_BOOST; local power = 50; -- Percentage, not amount. local duration = 90; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:addStatusEffect(typeEffect,power,0,duration) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
ghoghnousteam/ghoghnous
plugins/yoda.lua
642
1199
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(text) local api = "https://yoda.p.mashape.com/yoda?" text = string.gsub(text, " ", "+") local parameters = "sentence="..(text or "") local url = api..parameters local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) return body end local function run(msg, matches) return request(matches[1]) end return { description = "Listen to Yoda and learn from his words!", usage = "!yoda You will learn how to speak like me someday.", patterns = { "^![y|Y]oda (.*)$" }, run = run }
gpl-2.0
roboplus12/roboplus
plugins/yoda.lua
642
1199
local ltn12 = require "ltn12" local https = require "ssl.https" -- Edit data/mashape.lua with your Mashape API key -- http://docs.mashape.com/api-keys local mashape = load_from_file('data/mashape.lua', { api_key = '' }) local function request(text) local api = "https://yoda.p.mashape.com/yoda?" text = string.gsub(text, " ", "+") local parameters = "sentence="..(text or "") local url = api..parameters local api_key = mashape.api_key if api_key:isempty() then return 'Configure your Mashape API Key' end local headers = { ["X-Mashape-Key"] = api_key, ["Accept"] = "text/plain" } local respbody = {} local body, code = https.request{ url = url, method = "GET", headers = headers, sink = ltn12.sink.table(respbody), protocol = "tlsv1" } if code ~= 200 then return code end local body = table.concat(respbody) return body end local function run(msg, matches) return request(matches[1]) end return { description = "Listen to Yoda and learn from his words!", usage = "!yoda You will learn how to speak like me someday.", patterns = { "^![y|Y]oda (.*)$" }, run = run }
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/unit_morph.lua
2
41395
-- $Id: unit_morph.lua 4651 2009-05-23 17:04:46Z carrepairer $ -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- file: unit_morph.lua -- brief: Adds unit morphing command -- author: Dave Rodgers (improved by jK, Licho and aegis) -- -- Copyright (C) 2007. -- Licensed under the terms of the GNU GPL, v2 or later. -- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "UnitMorph", desc = "Adds unit morphing", author = "trepan (improved by jK, Licho, aegis, CarRepairer, Aquanim)", date = "Jan, 2008", license = "GNU GPL, v2 or later", layer = -1, --must start after unit_priority.lua gadget to use GG.AddMiscPriority() enabled = true } end include("LuaRules/Configs/customcmds.h.lua") local emptyTable = {} -- for speedups -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Interface with other gadgets: -- -- -- During Initialize() this morph gadget creates a global table, GG.MorphInfo, from which you can read: -- -- GG.MorphInfo[unitDefId] -- nil if for units that can't morph, otherwise a table, of key=destinationUnitDefId, value=morphCmdId -- -- GG.MorphInfo["MAX_MORPH"] -- the number of morph handled -- -- GG.MorphInfo["CMD_MORPH_BASE_ID"] -- The CMD ID of the generic morph command -- GG.MorphInfo["CMD_MORPH_BASE_ID"]+1 -- The CMD ID of the first specific morph command -- GG.MorphInfo["CMD_MORPH_BASE_ID"]+GG.MorphInfo["MAX_MORPH"] -- The CMD ID of the last specific morph command -- -- GG.MorphInfo["CMD_MORPH_STOP_BASE_ID"] -- The CMD ID of the generic morph stop command -- GG.MorphInfo["CMD_MORPH_STOP_BASE_ID"]+1 -- The CMD ID of the first specific morph stop command -- GG.MorphInfo["CMD_MORPH_STOP_BASE_ID"]+GG.MorphInfo["MAX_MORPH"] -- The CMD ID of the last specific morph stop command -- -- Thus other gadgets can know which morphing commands are available -- Then they can simply issue: -- Spring.GiveOrderToUnit(u,genericMorphCmdID,{},{}) -- or Spring.GiveOrderToUnit(u,genericMorphCmdID,{targetUnitDefId},{}) -- or Spring.GiveOrderToUnit(u,specificMorphCmdID,{},{}) -- -- where: -- genericMorphCmdID is the same unique value, no matter what is the source unit or target unit -- specificMorphCmdID is a different value for each source<->target morphing pair -- --[[ Sample codes that could be used in other gadgets: -- Morph unit u Spring.GiveOrderToUnit(u,31210,{},{}) -- Morph unit u into a supertank: local otherDefId=UnitDefNames["supertank"].id Spring.GiveOrderToUnit(u,31210,{otherDefId},{}) -- In place of writing 31210 you could use a morphCmdID that you'd read with: local morphCmdID=(GG.MorphInfo or {})["CMD_MORPH_BASE_ID"] if not morphCmdID then Spring.Echo("Error! Can't find Morph Cmd ID!"") return end -- Print all the morphing possibilities: for src,morph in pairs(GG.MorphInfo) do if type(src) == "number" then local txt=UnitDefs[src].name.." may morph into " for dst,cmd in pairs(morph) do txt=txt..UnitDefs[src].name.." with CMD "..cmd end Spring.Echo(txt) end end ]]-- local MAX_MORPH = 0 -- Set in morph defs -------------------------------------------------------------------------------- -- COMMON -------------------------------------------------------------------------------- local function isFactory(UnitDefID) return UnitDefs[UnitDefID].isFactory or false end local function isFinished(UnitID) local _,_,_,_,buildProgress = Spring.GetUnitHealth(UnitID) return (buildProgress == nil) or (buildProgress >= 1) end local function HeadingToFacing(heading) return math.floor((heading + 8192) / 16384) % 4 end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if (gadgetHandler:IsSyncedCode()) then -------------------------------------------------------------------------------- -- SYNCED -------------------------------------------------------------------------------- include("LuaRules/colors.h.lua") local spGetUnitPosition = Spring.GetUnitPosition -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local stopPenalty = 0.667 local freeMorph = false local PRIVATE = {private = true} -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local morphDefs = {} --// make it global in Initialize() local extraUnitMorphDefs = {} -- stores mainly planetwars morphs local hostName = nil -- planetwars hostname local PWUnits = {} -- planetwars units local morphUnits = {} --// make it global in Initialize() local reqDefIDs = {} --// all possible unitDefID's, which are used as a requirement for a morph local morphToStart = {} -- morphes to start next frame GG.wasMorphedTo = {} -- when a unit finishes morphing, a mapping of old unitID to new unitID is recorded here prior to old unit destruction local morphCmdDesc = { -- id = CMD_MORPH, -- added by the calling function because there is now more than one option type = CMDTYPE.ICON, name = 'Morph', cursor = 'Morph', -- add with LuaUI? action = 'morph', } local stopUpgradeCmdDesc = { id = CMD_UPGRADE_STOP, type = CMDTYPE.ICON, name = "", action = 'upgradecommstop', cursor = 'Morph', tooltip = 'Stop commander upgrade.', } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function GetMorphToolTip(unitID, unitDefID, teamID, morphDef) local ud = UnitDefs[morphDef.into] local tt = '' if (morphDef.text ~= nil) then tt = tt .. WhiteStr .. morphDef.text .. '\n' else tt = tt .. 'Morph into a ' .. ud.humanName .. '\n' end tt = tt .. GreenStr .. 'time: ' .. morphDef.time .. '\n' tt = tt .. CyanStr .. 'metal: ' .. morphDef.metal .. '\n' tt = tt .. YellowStr .. 'energy: ' .. morphDef.energy .. '\n' return tt end local function AddMorphCmdDesc(unitID, unitDefID, teamID, morphDef, teamTech) if GG.Unlocks and not GG.Unlocks.GetIsUnitUnlocked(teamID, unitDefID) then return end morphCmdDesc.tooltip = GetMorphToolTip(unitID, unitDefID, teamID, morphDef) GG.AddMiscPriorityUnit(unitID) if morphDef.texture then morphCmdDesc.texture = "LuaRules/Images/Morph/".. morphDef.texture morphCmdDesc.name = '' else morphCmdDesc.texture = "#" .. morphDef.into --//only works with a patched layout.lua or the TweakedLayout widget! end morphCmdDesc.id = morphDef.cmd local cmdDescID = Spring.FindUnitCmdDesc(unitID, morphDef.cmd) if (cmdDescID) then Spring.EditUnitCmdDesc(unitID, cmdDescID, morphCmdDesc) else Spring.InsertUnitCmdDesc(unitID, morphCmdDesc) end morphCmdDesc.tooltip = nil morphCmdDesc.texture = nil morphCmdDesc.text = nil end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function ReAssignAssists(newUnit,oldUnit) local ally = Spring.GetUnitAllyTeam(newUnit) local alliedTeams = Spring.GetTeamList(ally) for n = 1, #alliedTeams do local teamID = alliedTeams[n] local alliedUnits = Spring.GetTeamUnits(teamID) for i = 1, #alliedUnits do local unitID = alliedUnits[i] local cmds = Spring.GetCommandQueue(unitID, -1) for j=1, #cmds do local cmd = cmds[j] local params = cmd.params if (cmd.id == CMD.GUARD or cmd.id == CMD_ORBIT or (cmd.id == CMD.REPAIR and #params == 1 --[[not area repair]])) and (params[1] == oldUnit) then params[1] = newUnit local opts = (cmd.options.meta and 4 or 0) + (cmd.options.ctrl and 64 or 0) + (cmd.options.alt and 128 or 0) Spring.GiveOrderToUnit(unitID,CMD.INSERT,{cmd.tag, cmd.id, opts, params[1], params[2], params[3]},{}) Spring.GiveOrderToUnit(unitID,CMD.REMOVE,{cmd.tag},{}) end end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function GetMorphRate(unitID) return (1-(Spring.GetUnitRulesParam(unitID,"slowState") or 0)) end local function StartMorph(unitID, unitDefID, teamID, morphDef) -- do not allow morph for unfinsihed units if not isFinished(unitID) then return true end -- do not allow morph for units being transported which are not combat morphs if Spring.GetUnitTransporter(unitID) and not morphDef.combatMorph then return true end Spring.SetUnitRulesParam(unitID, "morphing", 1) if not morphDef.combatMorph then Spring.SetUnitRulesParam(unitID, "morphDisable", 1) GG.UpdateUnitAttributes(unitID) local env = Spring.UnitScript.GetScriptEnv(unitID) if env and env.script.StopMoving then Spring.UnitScript.CallAsUnit(unitID,env.script.StopMoving, hx, hy, hz) end end morphUnits[unitID] = { def = morphDef, progress = 0.0, increment = morphDef.increment, morphID = morphID, teamID = teamID, combatMorph = morphDef.combatMorph, morphRate = 0.0, } if morphDef.cmd then local cmdDescID = Spring.FindUnitCmdDesc(unitID, morphDef.cmd) if (cmdDescID) then Spring.EditUnitCmdDesc(unitID, cmdDescID, {id = morphDef.stopCmd, name = RedStr .. "Stop"}) end elseif morphDef.stopCmd == CMD_UPGRADE_STOP then Spring.InsertUnitCmdDesc(unitID, stopUpgradeCmdDesc) end SendToUnsynced("unit_morph_start", unitID, unitDefID, morphDef.cmd) local newMorphRate = GetMorphRate(unitID) GG.StartMiscPriorityResourcing(unitID, (newMorphRate*morphDef.metal/morphDef.time), nil, 2) --is using unit_priority.lua gadget to handle morph priority. Note: use metal per second as buildspeed (like regular constructor), modified for slow morphUnits[unitID].morphRate = newMorphRate end function gadget:UnitTaken(unitID, unitDefID, oldTeamID, newTeamID) local morphData = morphUnits[unitID] if not morphData then return end GG.StopMiscPriorityResourcing(unitID, 2) morphData.teamID = newTeamID GG.StartMiscPriorityResourcing(unitID, (morphData.def.metal / morphData.def.time), false, 2) end local function StopMorph(unitID, morphData) GG.StopMiscPriorityResourcing(unitID, 2) --is using unit_priority.lua gadget to handle morph priority. morphUnits[unitID] = nil if not morphData.combatMorph then Spring.SetUnitRulesParam(unitID, "morphDisable", 0) GG.UpdateUnitAttributes(unitID) end Spring.SetUnitRulesParam(unitID, "morphing", 0) local scale = morphData.progress * stopPenalty local unitDefID = Spring.GetUnitDefID(unitID) Spring.SetUnitResourcing(unitID,"e", UnitDefs[unitDefID].energyMake) Spring.GiveOrderToUnit(unitID, CMD.ONOFF, { 1 }, { "alt" }) local usedMetal = morphData.def.metal * scale Spring.AddUnitResource(unitID, 'metal', usedMetal) --local usedEnergy = morphData.def.energy * scale --Spring.AddUnitResource(unitID, 'energy', usedEnergy) SendToUnsynced("unit_morph_stop", unitID) if morphData.def.cmd then local cmdDescID = Spring.FindUnitCmdDesc(unitID, morphData.def.stopCmd) if (cmdDescID) then Spring.EditUnitCmdDesc(unitID, cmdDescID, {id = morphData.def.cmd, name = morphCmdDesc.name}) end elseif morphData.def.stopCmd == CMD_UPGRADE_STOP then local cmdDescID = Spring.FindUnitCmdDesc(unitID, CMD_UPGRADE_STOP) if cmdDescID then Spring.RemoveUnitCmdDesc(unitID, cmdDescID) end end end local function CreateMorphedToUnit(defName, x, y, z, face, unitTeam, isBeingBuilt, upgradeDef) if upgradeDef and GG.Upgrades_CreateUpgradedUnit then return GG.Upgrades_CreateUpgradedUnit(defName, x, y, z, face, unitTeam, isBeingBuilt, upgradeDef) else return Spring.CreateUnit(defName, x, y, z, face, unitTeam, isBeingBuilt) end end local function FinishMorph(unitID, morphData) local udDst = UnitDefs[morphData.def.into] local unitDefID = Spring.GetUnitDefID(unitID) local ud = UnitDefs[unitDefID] local defName = udDst.name local unitTeam = morphData.teamID -- copy dominatrix stuff local originTeam, originAllyTeam, controllerID, controllerAllyTeam = GG.Capture.GetMastermind(unitID) -- you see, Anarchid's exploit is fixed this way if (originTeam ~= nil) and (Spring.ValidUnitID(controllerID)) then unitTeam = Spring.GetUnitTeam(controllerID) end local px, py, pz = spGetUnitPosition(unitID) local h = Spring.GetUnitHeading(unitID) Spring.SetUnitBlocking(unitID, false) morphUnits[unitID] = nil --// copy health local oldHealth,oldMaxHealth,paralyzeDamage,captureProgress,buildProgress = Spring.GetUnitHealth(unitID) local isBeingBuilt = false if buildProgress < 1 then isBeingBuilt = true end local newUnit if udDst.isBuilding or udDst.isFactory then local x = math.floor(px/16)*16 local y = py local z = math.floor(pz/16)*16 local face = HeadingToFacing(h) local xsize = udDst.xsize local zsize =(udDst.zsize or udDst.ysize) if ((face == 1) or(face == 3)) then xsize, zsize = zsize, xsize end if xsize/4 ~= math.floor(xsize/4) then x = x+8 end if zsize/4 ~= math.floor(zsize/4) then z = z+8 end Spring.SetTeamRulesParam(unitTeam, "morphUnitCreating", 1, PRIVATE) newUnit = CreateMorphedToUnit(defName, x, y, z, face, unitTeam, isBeingBuilt, morphData.def.upgradeDef) Spring.SetTeamRulesParam(unitTeam, "morphUnitCreating", 0, PRIVATE) if not newUnit then StopMorph(unitID, morphData) return end Spring.SetUnitPosition(newUnit, x, y, z) else Spring.SetTeamRulesParam(unitTeam, "morphUnitCreating", 1, PRIVATE) newUnit = CreateMorphedToUnit(defName, px, py, pz, HeadingToFacing(h), unitTeam, isBeingBuilt, morphData.def.upgradeDef) Spring.SetTeamRulesParam(unitTeam, "morphUnitCreating", 0, PRIVATE) if not newUnit then StopMorph(unitID, morphData) return end Spring.SetUnitRotation(newUnit, 0, -h * math.pi / 32768, 0) Spring.SetUnitPosition(newUnit, px, py, pz) end if (extraUnitMorphDefs[unitID] ~= nil) then -- nothing here for now end if (hostName ~= nil) and PWUnits[unitID] then -- send planetwars deployment message PWUnit = PWUnits[unitID] PWUnit.currentDef = udDst local data = PWUnit.owner..","..defName..","..math.floor(px)..","..math.floor(pz)..",".."S" -- todo determine and apply smart orientation of the structure Spring.SendCommands("w "..hostName.." pwmorph:"..data) extraUnitMorphDefs[unitID] = nil --GG.PlanetWars.units[unitID] = nil --GG.PlanetWars.units[newUnit] = PWUnit SendToUnsynced('PWCreate', unitTeam, newUnit) elseif (not morphData.def.facing) then -- set rotation only if unit is not planetwars and facing is not true --Spring.Echo(morphData.def.facing) Spring.SetUnitRotation(newUnit, 0, -h * math.pi / 32768, 0) end --// copy lineage --local lineage = Spring.GetUnitLineage(unitID) --// copy facplop local facplop = Spring.GetUnitRulesParam(unitID, "facplop") --//copy command queue local cmds = Spring.GetCommandQueue(unitID, -1) local states = Spring.GetUnitStates(unitID) states.retreat = Spring.GetUnitRulesParam(unitID, "retreatState") or 0 states.buildPrio = Spring.GetUnitRulesParam(unitID, "buildpriority") or 1 states.miscPrio = Spring.GetUnitRulesParam(unitID, "miscpriority") or 1 --// copy cloak state local wantCloakState = Spring.GetUnitRulesParam(unitID, "wantcloak") --// copy shield power local shieldNum = Spring.GetUnitRulesParam(unitID, "comm_shield_num") or -1 local oldShieldState, oldShieldCharge = Spring.GetUnitShieldState(unitID, shieldNum) --//copy experience local newXp = Spring.GetUnitExperience(unitID) local oldBuildTime = Spring.Utilities.GetUnitCost(unitID, unitDefID) --//copy unit speed local velX,velY,velZ = Spring.GetUnitVelocity(unitID) --remember speed Spring.SetUnitRulesParam(newUnit, "jumpReload", Spring.GetUnitRulesParam(unitID, "jumpReload") or 1) --// FIXME: - re-attach to current transport? --// update selection SendToUnsynced("unit_morph_finished", unitID, newUnit) GG.wasMorphedTo[unitID] = newUnit Spring.SetUnitRulesParam(unitID, "wasMorphedTo", newUnit) Spring.SetUnitBlocking(newUnit, true) -- copy disarmed local paradisdmg, pdtime = GG.getUnitParalysisExternal(unitID) if (paradisdmg ~= nil) then GG.setUnitParalysisExternal(newUnit, paradisdmg, pdtime) end -- copy dominatrix lineage if (originTeam ~= nil) then GG.Capture.SetMastermind(newUnit, originTeam, originAllyTeam, controllerID, controllerAllyTeam) end Spring.DestroyUnit(unitID, false, true) -- selfd = false, reclaim = true --//transfer unit speed local gy = Spring.GetGroundHeight(px, pz) if py>gy+1 then --unit is off-ground Spring.AddUnitImpulse(newUnit,0,1,0) --dummy impulse (applying impulse>1 stop engine from forcing new unit to stick on map surface, unstick!) Spring.AddUnitImpulse(newUnit,0,-1,0) --negate dummy impulse end Spring.AddUnitImpulse(newUnit,velX,velY,velZ) --restore speed -- script.StartMoving is not called if a unit is created and then given velocity via impulse. local speed = math.sqrt(velX^2 + velY^2 + velZ^2) if speed > 0.6 then local env = Spring.UnitScript.GetScriptEnv(newUnit) if env and env.script.StartMoving then Spring.UnitScript.CallAsUnit(newUnit,env.script.StartMoving) end end --// transfer facplop if facplop and (facplop == 1) then Spring.SetUnitRulesParam(newUnit, "facplop", 1, {inlos = true}) end --// transfer health -- old health is declared far above local _,newMaxHealth = Spring.GetUnitHealth(newUnit) local newHealth = (oldHealth / oldMaxHealth) * newMaxHealth if newHealth <= 1 then newHealth = 1 end local newPara = 0 newPara = paralyzeDamage*newMaxHealth/oldMaxHealth local slowDamage = Spring.GetUnitRulesParam(unitID,"slowState") if slowDamage then GG.addSlowDamage(newUnit, slowDamage*newMaxHealth) end Spring.SetUnitHealth(newUnit, {health = newHealth, build = buildProgress, paralyze = newPara}) --//transfer experience newXp = newXp * (oldBuildTime / Spring.Utilities.GetUnitCost(unitID, morphData.def.into)) Spring.SetUnitExperience(newUnit, newXp) --// transfer shield power if oldShieldState then Spring.SetUnitShieldState(newUnit, shieldNum, oldShieldCharge) end --//transfer some state Spring.GiveOrderArrayToUnitArray({ newUnit }, { {CMD.FIRE_STATE, { states.firestate }, emptyTable }, {CMD.MOVE_STATE, { states.movestate }, emptyTable }, {CMD.REPEAT, { states["repeat"] and 1 or 0 }, emptyTable }, {CMD_WANT_CLOAK, { wantCloakState or 0 }, emptyTable }, {CMD.ONOFF, { 1 }, emptyTable}, {CMD.TRAJECTORY, { states.trajectory and 1 or 0 }, emptyTable }, {CMD_PRIORITY, { states.buildPrio }, emptyTable }, {CMD_RETREAT, { states.retreat }, states.retreat == 0 and {"right"} or emptyTable }, {CMD_MISC_PRIORITY, { states.miscPrio }, emptyTable }, }) --//reassign assist commands to new unit ReAssignAssists(newUnit,unitID) --//transfer command queue for i = 1, #cmds do local cmd = cmds[i] if i == 1 and cmd.id < 0 then -- repair case for construction local units = Spring.GetUnitsInRectangle(cmd.params[1]-32, cmd.params[3]-32, cmd.params[1]+32, cmd.params[3]+32) local allyTeam = Spring.GetUnitAllyTeam(unitID) local notFound = true for j = 1, #units do local areaUnitID = units[j] if allyTeam == Spring.GetUnitAllyTeam(areaUnitID) and Spring.GetUnitDefID(areaUnitID) == -cmd.id then Spring.GiveOrderToUnit(newUnit, CMD.REPAIR, {areaUnitID}, cmd.options.coded) notFound = false break end end if notFound then Spring.GiveOrderToUnit(newUnit, cmd.id, cmd.params, cmd.options.coded) end else Spring.GiveOrderToUnit(newUnit, cmd.id, cmd.params, cmd.options.coded) end end end local function UpdateMorph(unitID, morphData) local transportID = Spring.GetUnitTransporter(unitID) local transportUnitDefID = 0 if transportID then if not morphData.combatMorph then StopMorph(unitID, morphUnits[unitID]) morphUnits[unitID] = nil return true end transportUnitDefID = Spring.GetUnitDefID(transportID) if not UnitDefs[transportUnitDefID].isFirePlatform then return true end end -- if EMPd or disarmed do not morph if (Spring.GetUnitRulesParam(unitID, "disarmed") == 1) or (Spring.GetUnitIsStunned(unitID)) then return true end if (morphData.progress < 1.0) then local newMorphRate = GetMorphRate(unitID) if (morphData.morphRate ~= newMorphRate) then --GG.StopMiscPriorityResourcing(unitID, 2) not necessary GG.StartMiscPriorityResourcing(unitID, (newMorphRate*morphData.def.metal/morphData.def.time), nil, 2) --is using unit_priority.lua gadget to handle morph priority. Modifies resource drain if slowness has changed. morphData.morphRate = newMorphRate end local allow = GG.AllowMiscPriorityBuildStep(unitID, morphData.teamID) --use unit_priority.lua gadget to handle morph priority. local resourceUse = { m = (morphData.def.resTable.m * morphData.morphRate), e = (morphData.def.resTable.e * morphData.morphRate), } if freeMorph then morphData.progress = 1 elseif allow and (Spring.UseUnitResource(unitID, resourceUse)) then morphData.progress = morphData.progress + morphData.increment*morphData.morphRate end end if (morphData.progress >= 1.0 and Spring.GetUnitRulesParam(unitID, "is_jumping") ~= 1 and not transportID) then FinishMorph(unitID, morphData) return false -- remove from the list, all done end return true end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function SetFreeMorph(newFree) freeMorph = newFree end function gadget:Initialize() --// get the morphDefs morphDefs, MAX_MORPH = include("LuaRules/Configs/morph_defs.lua") if (not morphDefs) then gadgetHandler:RemoveGadget() return end GG.SetFreeMorph = SetFreeMorph --// make it global for unsynced access via SYNCED _G.morphUnits = morphUnits _G.morphDefs = morphDefs _G.extraUnitMorphDefs = extraUnitMorphDefs --// Register CmdIDs for number = 0, MAX_MORPH - 1 do gadgetHandler:RegisterCMDID(CMD_MORPH + number) gadgetHandler:RegisterCMDID(CMD_MORPH_STOP + number) end gadgetHandler:RegisterCMDID(CMD_UPGRADE_STOP) --// check existing ReqUnits+TechLevel local allUnits = Spring.GetAllUnits() for i = 1, #allUnits do local unitID = allUnits[i] local unitDefID = Spring.GetUnitDefID(unitID) local teamID = Spring.GetUnitTeam(unitID) if reqDefIDs[unitDefID] and isFinished(unitID) then local teamReq = teamReqUnits[teamID] teamReq[unitDefID] = (teamReq[unitDefID] or 0) + 1 end end --// add the Morph Menu Button to existing units for i = 1, #allUnits do local unitID = allUnits[i] local teamID = Spring.GetUnitTeam(unitID) local unitDefID = Spring.GetUnitDefID(unitID) local morphDefSet = morphDefs[unitDefID] if (morphDefSet) then for _,morphDef in pairs(morphDefSet) do if (morphDef) then local cmdDescID = Spring.FindUnitCmdDesc(unitID, morphDef.cmd) if (not cmdDescID) then AddMorphCmdDesc(unitID, unitDefID, teamID, morphDef) end end end elseif UnitDefs[unitDefID].customParams.dynamic_comm then GG.AddMiscPriorityUnit(unitID) end end end function gadget:Shutdown() local allUnits = Spring.GetAllUnits() for i = 1, #allUnits do local unitID = allUnits[i] local morphData = morphUnits[unitID] if morphData then StopMorph(unitID, morphData) end for number = 0, MAX_MORPH - 1 do local cmdDescID = Spring.FindUnitCmdDesc(unitID, CMD_MORPH + number) if cmdDescID then Spring.RemoveUnitCmdDesc(unitID, cmdDescID) end end end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:UnitCreated(unitID, unitDefID, teamID) GG.wasMorphedTo[unitID] = nil local morphDefSet = morphDefs[unitDefID] if (morphDefSet) then for _,morphDef in pairs(morphDefSet) do if (morphDef) then AddMorphCmdDesc(unitID, unitDefID, teamID, morphDef) end end elseif UnitDefs[unitDefID].customParams.dynamic_comm then GG.AddMiscPriorityUnit(unitID) end end function gadget:UnitDestroyed(unitID, unitDefID, teamID) if (morphUnits[unitID]) then StopMorph(unitID, morphUnits[unitID]) morphUnits[unitID] = nil end end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GameFrame(n) -- start pending morphs for unitid, data in pairs(morphToStart) do StartMorph(unitid, unpack(data)) end morphToStart = {} for unitID, morphData in pairs(morphUnits) do if (not UpdateMorph(unitID, morphData)) then morphUnits[unitID] = nil end end end local function processMorph(unitID, unitDefID, teamID, cmdID, cmdParams) local morphDef = nil if cmdID == CMD_MORPH then if type(GG.MorphInfo[unitDefID]) ~= "table" then --Spring.Echo('Morph gadget: CommandFallback generic morph on non morphable unit') return true end if cmdParams[1] then --Spring.Echo('Morph gadget: CommandFallback generic morph with target provided') morphDef=(morphDefs[unitDefID] or {})[GG.MorphInfo[unitDefID][cmdParams[1]]] else --Spring.Echo('Morph gadget: CommandFallback generic morph, default target') for _, md in pairs(morphDefs[unitDefID]) do morphDef = md break end end else --Spring.Echo('Morph gadget: CommandFallback specific morph') morphDef = (morphDefs[unitDefID] or {})[cmdID] or extraUnitMorphDefs[unitID] end if (not morphDef) then return true end if morphDef then local morphData = morphUnits[unitID] local health, maxHealth, paralyzeDamage, captureProgress, buildProgress = Spring.GetUnitHealth(unitID) if (not morphData) and buildProgress == 1 then -- dont start directly to break recursion --StartMorph(unitID, unitDefID, teamID, morphDef) morphToStart[unitID] = {unitDefID, teamID, morphDef} return true end end return false end local function processUpgrade(unitID, unitDefID, teamID, cmdID, cmdParams) if morphUnits[unitID] then -- Unit is already upgrading. return false end if not GG.Upgrades_GetValidAndMorphAttributes then return false end local health, maxHealth, paralyzeDamage, captureProgress, buildProgress = Spring.GetUnitHealth(unitID) if buildProgress < 1 then return true end local valid, targetUnitDefID, morphDef = GG.Upgrades_GetValidAndMorphAttributes(unitID, cmdParams) if not valid then return false end morphToStart[unitID] = {targetUnitDefID, teamID, morphDef} end function gadget:AllowCommand_GetWantedCommand() return true -- morph command is dynamic so incoperating it is difficult end function gadget:AllowCommand_GetWantedUnitDefID() boolDef = {} for udid,_ in pairs(morphDefs) do boolDef[udid] = true end for udid = 1, #UnitDefs do local ud = UnitDefs[udid] if ud and ud.customParams and ud.customParams.level then -- commander detection boolDef[udid] = true end end return boolDef end function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if cmdID == CMD_MORPH_UPGRADE_INTERNAL then return processUpgrade(unitID, unitDefID, teamID, cmdID, cmdParams) end local morphData = morphUnits[unitID] if (morphData) then if (cmdID == morphData.def.stopCmd) or (cmdID == CMD.STOP and not morphData.def.combatMorph) or (cmdID == CMD_MORPH_STOP) then StopMorph(unitID, morphData) morphUnits[unitID] = nil return false elseif cmdID == CMD.SELFD then StopMorph(unitID, morphData) morphUnits[unitID] = nil end elseif (cmdID >= CMD_MORPH and cmdID <= CMD_MORPH+MAX_MORPH) then local morphDef = nil if cmdID == CMD_MORPH then if type(GG.MorphInfo[unitDefID]) ~= "table" then --Spring.Echo('Morph gadget: AllowCommand generic morph on non morphable unit') return false elseif #cmdParams == 0 then --Spring.Echo('Morph gadget: AllowCommand generic morph, default target') --return true for _, md in pairs(morphDefs[unitDefID]) do morphDef = md break end elseif GG.MorphInfo[unitDefID][cmdParams[1]] then --Spring.Echo('Morph gadget: AllowCommand generic morph, target valid') --return true morphDef = (morphDefs[unitDefID] or {})[GG.MorphInfo[unitDefID][cmdParams[1]]] else --Spring.Echo('Morph gadget: AllowCommand generic morph, invalid target') return false end --Spring.Echo('Morph gadget: AllowCommand morph cannot be here!') elseif (cmdID > CMD_MORPH and cmdID <= CMD_MORPH+MAX_MORPH) then --Spring.Echo('Morph gadget: AllowCommand specific morph') morphDef = (morphDefs[unitDefID] or {})[cmdID] or extraUnitMorphDefs[unitID] end if morphDef then if (isFactory(unitDefID)) then --// the factory cai is broken and doesn't call CommandFallback(), --// so we have to start the morph here -- dont start directly to break recursion --StartMorph(unitID, unitDefID, teamID, morphDef) morphToStart[unitID] = {unitDefID, teamID, morphDef} return false else --// morph allowed if morphDef.combatMorph then -- process now, no shift queue for combat morph to preserve command queue processMorph(unitID, unitDefID, teamID, cmdID, cmdParams) return false else return true end end end return false end return true end function gadget:CommandFallback(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions) if cmdID == CMD_MORPH_UPGRADE_INTERNAL then return true, processUpgrade(unitID, unitDefID, teamID, cmdID, cmdParams) end if (cmdID < CMD_MORPH or cmdID > CMD_MORPH+MAX_MORPH) then return false --// command was not used end return true, processMorph(unitID, unitDefID, teamID, cmdID, cmdParams) -- command was used, process decides if to remove end -------------------------------------------------------------------------------- -- END SYNCED -------------------------------------------------------------------------------- else -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- -- -- speed-ups -- local gameFrame local SYNCED = SYNCED local CallAsTeam = CallAsTeam local spairs = spairs local snext = snext local spGetUnitPosition = Spring.GetUnitPosition local GetUnitTeam = Spring.GetUnitTeam local GetUnitHeading = Spring.GetUnitHeading local GetGameFrame = Spring.GetGameFrame local GetSpectatingState = Spring.GetSpectatingState local AddWorldIcon = Spring.AddWorldIcon local AddWorldText = Spring.AddWorldText local IsUnitVisible = Spring.IsUnitVisible local GetLocalTeamID = Spring.GetLocalTeamID local spAreTeamsAllied = Spring.AreTeamsAllied local glBillboard = gl.Billboard local glColor = gl.Color local glPushMatrix = gl.PushMatrix local glTranslate = gl.Translate local glRotate = gl.Rotate local glUnitShape = gl.UnitShape local glPopMatrix = gl.PopMatrix local glText = gl.Text local glCulling = gl.Culling local glPushAttrib = gl.PushAttrib local glPopAttrib = gl.PopAttrib local glPolygonOffset = gl.PolygonOffset local glBlending = gl.Blending local glDepthTest = gl.DepthTest local glUnit = gl.Unit local GL_LEQUAL = GL.LEQUAL local GL_ONE = GL.ONE local GL_SRC_ALPHA = GL.SRC_ALPHA local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA local GL_COLOR_BUFFER_BIT = GL.COLOR_BUFFER_BIT local headingToDegree = (360 / 65535) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local useLuaUI = false local oldFrame = 0 --//used to save bandwidth between unsynced->LuaUI local drawProgress = true --//a widget can do this job too (see healthbars) -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- --//synced -> unsynced actions local function SelectSwap(cmd, oldID, newID) local selUnits = Spring.GetSelectedUnits() for i = 1, #selUnits do local unitID = selUnits[i] if (unitID == oldID) then selUnits[i] = newID Spring.SelectUnitArray(selUnits) break end end if (Script.LuaUI('MorphFinished')) then if useLuaUI then local readTeam, spec, specFullView = nil,GetSpectatingState() if specFullView then readTeam = Script.ALL_ACCESS_TEAM else readTeam = GetLocalTeamID() end CallAsTeam({['read'] = readTeam }, function() if (IsUnitVisible(oldID)) then Script.LuaUI.MorphFinished(oldID,newID) end end ) end end return true end local function StartMorph(cmd, unitID, unitDefID, morphID) if (Script.LuaUI('MorphStart')) then if useLuaUI then local readTeam, spec, specFullView = nil, GetSpectatingState() if specFullView then readTeam = Script.ALL_ACCESS_TEAM else readTeam = GetLocalTeamID() end CallAsTeam({['read'] = readTeam }, function() if (unitID)and(IsUnitVisible(unitID)) then Script.LuaUI.MorphStart(unitID, (SYNCED.morphDefs[unitDefID] or {})[morphID] or SYNCED.extraUnitMorphDefs[unitID]) end end ) end end return true end local function StopMorph(cmd, unitID) if (Script.LuaUI('MorphStop')) then if useLuaUI then local readTeam, spec, specFullView = nil, GetSpectatingState() if specFullView then readTeam = Script.ALL_ACCESS_TEAM else readTeam = GetLocalTeamID() end CallAsTeam({['read'] = readTeam }, function() if (unitID)and(IsUnitVisible(unitID)) then Script.LuaUI.MorphStop(unitID) end end ) end end return true end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:Initialize() gadgetHandler:AddSyncAction("unit_morph_finished", SelectSwap) gadgetHandler:AddSyncAction("unit_morph_start", StartMorph) gadgetHandler:AddSyncAction("unit_morph_stop", StopMorph) end function gadget:Shutdown() gadgetHandler:RemoveSyncAction("unit_morph_finished") gadgetHandler:RemoveSyncAction("unit_morph_start") gadgetHandler:RemoveSyncAction("unit_morph_stop") end function gadget:Update() local frame = GetGameFrame() if frame > oldFrame then oldFrame = frame local morphUnitsSynced = SYNCED.morphUnits if snext(morphUnitsSynced) then local useLuaUI_ = Script.LuaUI('MorphUpdate') if useLuaUI_ ~= useLuaUI then --//Update Callins on change drawProgress = not Script.LuaUI('MorphDrawProgress') useLuaUI = useLuaUI_ end if useLuaUI then local morphTable = {} local readTeam, spec, specFullView = nil,GetSpectatingState() if specFullView then readTeam = Script.ALL_ACCESS_TEAM else readTeam = GetLocalTeamID() end CallAsTeam({ ['read'] = readTeam }, function() for unitID, morphData in spairs(morphUnitsSynced) do if (unitID and morphData)and(IsUnitVisible(unitID)) then morphTable[unitID] = {progress = morphData.progress, into = morphData.def.into, combatMorph = morphData.combatMorph} end end end ) Script.LuaUI.MorphUpdate(morphTable) end end end end local teamColors = {} local function SetTeamColor(teamID,a) local color = teamColors[teamID] if color then color[4] = a glColor(color) return end local r, g, b = Spring.GetTeamColor(teamID) if (r and g and b) then color = { r, g, b } teamColors[teamID] = color glColor(color) return end end --//patchs an annoying popup the first time you morph a unittype(+team) local alreadyInit = {} local function InitializeUnitShape(unitDefID,unitTeam) local iTeam = alreadyInit[unitTeam] if iTeam and iTeam[unitDefID] then return end glPushMatrix() gl.ColorMask(false) glUnitShape(unitDefID, unitTeam) gl.ColorMask(true) glPopMatrix() if (alreadyInit[unitTeam] == nil) then alreadyInit[unitTeam] = {} end alreadyInit[unitTeam][unitDefID] = true end local function DrawMorphUnit(unitID, morphData, localTeamID) local h = GetUnitHeading(unitID) if (h == nil) then return --// bonus, heading is only available when the unit is in LOS end local px,py,pz = spGetUnitPosition(unitID) if (px == nil) then return end local unitTeam = morphData.teamID InitializeUnitShape(morphData.def.into,unitTeam) --BUGFIX local frac = ((gameFrame + unitID) % 30) / 30 local alpha = 2.0 * math.abs(0.5 - frac) local angle if morphData.def.facing then angle = -HeadingToFacing(h) * 90 + 180 else angle = h * headingToDegree end SetTeamColor(unitTeam,alpha) glPushMatrix() glTranslate(px, py, pz) glRotate(angle, 0, 1, 0) glUnitShape(morphData.def.into, unitTeam) glPopMatrix() --// cheesy progress indicator if (drawProgress) and (localTeamID) and ((spAreTeamsAllied(unitTeam,localTeamID)) or (localTeamID == Script.ALL_ACCESS_TEAM)) then glPushMatrix() glPushAttrib(GL_COLOR_BUFFER_BIT) glTranslate(px, py+14, pz) glBillboard() local progStr = string.format("%.1f%%", 100 * morphData.progress) gl.Text(progStr, 0, -20, 9, "oc") glPopAttrib() glPopMatrix() end end local phase = 0 local function DrawCombatMorphUnit(unitID, morphData, localTeamID) local c1 = math.sin(phase)*.2 + .2 local c2 = math.sin(phase+ math.pi)*.2 + .2 local mult = 2 glBlending(GL_ONE, GL_ONE) glDepthTest(GL_LEQUAL) --glLighting(true) glPolygonOffset(-10, -10) glCulling(GL.BACK) glColor(c1*mult,0,c2*mult,1) glUnit(unitID, true) glColor(1,1,1,1) --glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) --glPolygonOffset(false) --glCulling(false) --glDepthTest(false) end local function DrawWorldFunc() local morphUnits = SYNCED.morphUnits if (not snext(morphUnits)) then return --//no morphs to draw end gameFrame = GetGameFrame() glBlending(GL_SRC_ALPHA, GL_ONE) glDepthTest(GL_LEQUAL) local spec, specFullView = GetSpectatingState() local readTeam if (specFullView) then readTeam = Script.ALL_ACCESS_TEAM else readTeam = GetLocalTeamID() end CallAsTeam({['read'] = readTeam}, function() for unitID, morphData in spairs(morphUnits) do if (unitID and morphData)and(IsUnitVisible(unitID)) then if morphData.combatMorph then DrawCombatMorphUnit(unitID, morphData,readTeam) else DrawMorphUnit(unitID, morphData,readTeam) end end end end ) glDepthTest(false) glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) phase = phase + .06 end function gadget:DrawWorld() DrawWorldFunc() end function gadget:DrawWorldRefraction() DrawWorldFunc() end local function split(msg,sep) local s=sep or '|' local t={} for e in string.gmatch(msg..s,'([^%'..s..']+)%'..s) do t[#t+1] = e end return t end -- Exemple of AI messages: -- "aiShortName|morph|762" -- morph the unit of unitId 762 -- "aiShortName|morph|861|12" -- morph the unit of unitId 861 into an unit of unitDefId 12 -- -- Does not work because apparently Spring.GiveOrderToUnit from unsynced gadgets are ignored. -- function gadget:AICallIn(data) if type(data) == "string" then local message = split(data) if message[1] == "Shard" or true then-- Because other AI shall be allowed to send such morph command without having to pretend to be Shard if message[2] == "morph" and message[3] then local unitID = tonumber(message[3]) if unitID and Spring.ValidUnitID(unitID) then if message[4] then local destDefId=tonumber(message[4]) --Spring.Echo("Morph AICallIn: Morphing Unit["..unitID.."] into "..UnitDefs[destDefId].name) Spring.GiveOrderToUnit(unitID,CMD_MORPH,{destDefId},{}) else --Spring.Echo("Morph AICallIn: Morphing Unit["..unitID.."] to auto") Spring.GiveOrderToUnit(unitID,CMD_MORPH,{},{}) end else Spring.Echo("Not a valid unitID in AICallIn morph request: \""..data.."\"") end end end end end -- Just something to test the above AICallIn --function gadget:KeyPress(key) -- if key == 32 then--space key -- gadget:AICallIn("asn|morph|762") -- end --end -------------------------------------------------------------------------------- -- UNSYNCED -------------------------------------------------------------------------------- end -------------------------------------------------------------------------------- -- COMMON --------------------------------------------------------------------------------
gpl-2.0
Scavenge/darkstar
scripts/commands/changesjob.lua
17
1078
--------------------------------------------------------------------------------------------------- -- func: changesjob -- desc: Changes the players current subjob. --------------------------------------------------------------------------------------------------- require("scripts/globals/status"); cmdprops = { permission = 1, parameters = "si" }; function onTrigger(player, jobId, level) jobId = tonumber(jobId) or JOBS[string.upper(jobId)]; if (jobId == nil) then player:PrintToPlayer("You must enter a job ID or short-name."); return; end if (jobId <= 0 or jobId >= MAX_JOB_TYPE) then player:PrintToPlayer(string.format("Invalid job '%s' given. Use short-name or id. e.g. WAR", jobId)); return; end -- Change the players subjob.. player:changesJob(jobId); -- Attempt to set the players subjob level.. if (level ~= nil and level > 0 and level <= 99) then player:setsLevel(level); else player:PrintToPlayer("Invalid level given. Level must be between 1 and 99!"); end end
gpl-3.0
angking0802wu/UniLua
Assets/StreamingAssets/LuaRoot/test/vararg.lua
9
2659
print('testing vararg') _G.arg = nil function f(a, ...) local arg = {n = select('#', ...), ...} for i=1,arg.n do assert(a[i]==arg[i]) end return arg.n end function c12 (...) assert(arg == nil) local x = {...}; x.n = #x local res = (x.n==2 and x[1] == 1 and x[2] == 2) if res then res = 55 end return res, 2 end function vararg (...) return {n = select('#', ...), ...} end local call = function (f, args) return f(table.unpack(args, 1, args.n)) end assert(f() == 0) assert(f({1,2,3}, 1, 2, 3) == 3) assert(f({"alo", nil, 45, f, nil}, "alo", nil, 45, f, nil) == 5) assert(c12(1,2)==55) a,b = assert(call(c12, {1,2})) assert(a == 55 and b == 2) a = call(c12, {1,2;n=2}) assert(a == 55 and b == 2) a = call(c12, {1,2;n=1}) assert(not a) assert(c12(1,2,3) == false) local a = vararg(call(next, {_G,nil;n=2})) local b,c = next(_G) assert(a[1] == b and a[2] == c and a.n == 2) a = vararg(call(call, {c12, {1,2}})) assert(a.n == 2 and a[1] == 55 and a[2] == 2) a = call(print, {'+'}) assert(a == nil) local t = {1, 10} function t:f (...) local arg = {...}; return self[...]+#arg end assert(t:f(1,4) == 3 and t:f(2) == 11) print('+') lim = 20 local i, a = 1, {} while i <= lim do a[i] = i+0.3; i=i+1 end function f(a, b, c, d, ...) local more = {...} assert(a == 1.3 and more[1] == 5.3 and more[lim-4] == lim+0.3 and not more[lim-3]) end function g(a,b,c) assert(a == 1.3 and b == 2.3 and c == 3.3) end call(f, a) call(g, a) a = {} i = 1 while i <= lim do a[i] = i; i=i+1 end assert(call(math.max, a) == lim) print("+") -- new-style varargs function oneless (a, ...) return ... end function f (n, a, ...) local b assert(arg == nil) if n == 0 then local b, c, d = ... return a, b, c, d, oneless(oneless(oneless(...))) else n, b, a = n-1, ..., a assert(b == ...) return f(n, a, ...) end end a,b,c,d,e = assert(f(10,5,4,3,2,1)) assert(a==5 and b==4 and c==3 and d==2 and e==1) a,b,c,d,e = f(4) assert(a==nil and b==nil and c==nil and d==nil and e==nil) -- varargs for main chunks f = load[[ return {...} ]] x = f(2,3) assert(x[1] == 2 and x[2] == 3 and x[3] == nil) f = load[[ local x = {...} for i=1,select('#', ...) do assert(x[i] == select(i, ...)) end assert(x[select('#', ...)+1] == nil) return true ]] assert(f("a", "b", nil, {}, assert)) assert(f()) a = {select(3, table.unpack{10,20,30,40})} assert(#a == 2 and a[1] == 30 and a[2] == 40) a = {select(1)} assert(next(a) == nil) a = {select(-1, 3, 5, 7)} assert(a[1] == 7 and a[2] == nil) a = {select(-2, 3, 5, 7)} assert(a[1] == 5 and a[2] == 7 and a[3] == nil) pcall(select, 10000) pcall(select, -10000) print('OK')
mit
Scavenge/darkstar
scripts/zones/Arrapago_Reef/npcs/qm4.lua
30
1327
----------------------------------- -- Area: Arrapago Reef -- NPC: ??? (Spawn Nuhn(ZNM T3)) -- @pos -451 -7 389 54 ----------------------------------- package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Arrapago_Reef/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 16998874; if (trade:hasItemQty(2596,1) and trade:getItemCount() == 1) then -- Trade Rose Scampi if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end 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
Scavenge/darkstar
scripts/zones/Castle_Oztroja/npcs/_m70.lua
14
1251
----------------------------------- -- 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
Scavenge/darkstar
scripts/zones/Windurst_Woods/npcs/Spare_Three.lua
17
1507
----------------------------------- -- Area: Windurst Woods -- NPC: Spare Three -- Working 100% -- Involved in quest: A Greeting Cardian ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) AGreetingCardian = player:getQuestStatus(WINDURST,A_GREETING_CARDIAN); local AGCcs = player:getVar("AGreetingCardian_Event"); if (AGreetingCardian == QUEST_ACCEPTED and AGCcs == 2) then player:startEvent(0x0127); -- A Greeting Cardian step two else player:startEvent(0x118); -- standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0127) then player:setVar("AGreetingCardian_Event",3); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/spells/absorb-int.lua
9
1360
-------------------------------------- -- Spell: Absorb-INT -- Steals an enemy's intelligence. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) if (target:hasStatusEffect(EFFECT_INT_DOWN) or caster:hasStatusEffect(EFFECT_INT_BOOST)) then spell:setMsg(75); -- no effect else local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistance(caster,spell,target,dINT,37,0); if (resist <= 0.125) then spell:setMsg(85); else spell:setMsg(333); caster:addStatusEffect(EFFECT_INT_BOOST,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_DISPELABLE); -- caster gains INT target:addStatusEffect(EFFECT_INT_DOWN,ABSORB_SPELL_AMOUNT*resist*((100+(caster:getMod(MOD_AUGMENTS_ABSORB)))/100), ABSORB_SPELL_TICK, ABSORB_SPELL_AMOUNT*ABSORB_SPELL_TICK,FLAG_ERASABLE); -- target loses INT end end return EFFECT_INT_DOWN; end;
gpl-3.0
ania1234/EarMod
scripts/brains/earbrain.lua
1
2636
require "behaviours/follow" require "behaviours/wander" require "behaviours/faceentity" require "behaviours/panic" require "behaviours/chattynode" require "behaviours/doaction" require "behaviours/keepcircle" require "behaviours/chaseandattack" require "behaviours/runaway" local MIN_FOLLOW_DIST = 0 local MAX_FOLLOW_DIST = 9 local TARGET_FOLLOW_DIST = 6 local MAX_WANDER_DIST = 3 local START_RUN_DIST = 3 local STOP_RUN_DIST = 5 local MAX_CHASE_TIME = 10 local MAX_CHASE_DIST = 30 local RUN_AWAY_DIST = 5 local STOP_RUN_AWAY_DIST = 8 local function GetFaceTargetFn(inst) return inst.components.follower.leader end local function KeepFaceTargetFn(inst, target) return inst.components.follower.leader == target end local EarBrain = Class(Brain, function(self, inst) Brain._ctor(self, inst) end) function EarBrain:OnStart() local clock = GetClock() local day = WhileNode( function() return clock and not clock:IsNight() end, "IsDay", PriorityNode{ Follow(self.inst, function() return self.inst.components.follower.leader end, MIN_FOLLOW_DIST, TARGET_FOLLOW_DIST, MAX_FOLLOW_DIST), --ChattyNode(self.inst, STRINGS.EAR_TALK_NIGHT_CONVERSATION, Keepcircle(self.inst)), ChattyNode(self.inst, STRINGS.EAR_TALK_CASUAL_CONVERSATION, Wander(self.inst, function() return self.inst.components.knownlocations:GetLocation("home") end, MAX_WANDER_DIST)), }, 0.5) local night = WhileNode( function() return clock and clock:IsNight() end, "IsNight", PriorityNode{ Follow(self.inst, function() return self.inst.components.follower.leader end, MIN_FOLLOW_DIST, TARGET_FOLLOW_DIST, MAX_FOLLOW_DIST), ChattyNode(self.inst, STRINGS.EAR_TALK_NIGHT_CONVERSATION, Keepcircle(self.inst)), }, 1) local root = PriorityNode({ ChattyNode(self.inst, STRINGS.PIG_TALK_FIGHT, WhileNode( function() return self.inst.components.combat.target == nil or not self.inst.components.combat:InCooldown() end, "AttackMomentarily", ChaseAndAttack(self.inst, MAX_CHASE_TIME, MAX_CHASE_DIST) )), ChattyNode(self.inst, STRINGS.PIG_TALK_FIGHT, WhileNode( function() return self.inst.components.combat.target and self.inst.components.combat:InCooldown() end, "Dodge", RunAway(self.inst, function() return self.inst.components.combat.target end, RUN_AWAY_DIST, STOP_RUN_AWAY_DIST) )), RunAway(self.inst, function(guy) return guy:HasTag("pig") and guy.components.combat and guy.components.combat.target == self.inst end, RUN_AWAY_DIST, STOP_RUN_AWAY_DIST ), day, night }, .5) self.bt = BT(self.inst, root) end return EarBrain
gpl-3.0
Scavenge/darkstar
scripts/zones/North_Gustaberg_[S]/npcs/Cavernous_Maw.lua
29
1418
----------------------------------- -- Area: North Gustaberg [S] -- NPC: Cavernous Maw -- @pos 466 0 479 88 -- Teleports Players to North Gustaberg ----------------------------------- package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/North_Gustaberg_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (hasMawActivated(player,7) == false) then player:startEvent(0x0064); else player:startEvent(0x0065); 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:",csid); -- printf("RESULT:",option); if (option == 1) then if (csid == 0x0064) then player:addNationTeleport(MAW,128); end toMaw(player,12); end end;
gpl-3.0
taxler/radish
lua/parse/char/utf8/set/init.lua
1
1028
local lib = {} local aliases = { C = 'Other'; Cc = 'Other.Control'; Cf = 'Other.Format'; Cs = 'Other.Surrogate'; Co = 'Other.Private_Use'; L = 'Letter'; Ll = 'Letter.Lowercase'; Lu = 'Letter.Uppercase'; Lt = 'Letter.Titlecase'; Lo = 'Letter.Other'; Lm = 'Letter.Modifier'; M = 'Mark'; Mc = 'Mark.Spacing_Combining'; Me = 'Mark.Enclosing'; Mn = 'Mark.Nonspacing'; N = 'Number'; Nd = 'Number.Decimal_Digit'; Nl = 'Number.Letter'; No = 'Number.Other'; P = 'Punctuation'; Pc = 'Punctuation.Connector'; Pd = 'Punctuation.Dash'; Pe = 'Punctuation.Close'; Pf = 'Punctuation.Final_Quote'; Pi = 'Punctuation.Initial_Quote'; Po = 'Punctuation.Other'; Ps = 'Punctuation.Open'; S = 'Symbol'; Sc = 'Symbol.Currency'; Sk = 'Symbol.Modifier'; Sm = 'Symbol.Math'; So = 'Symbol.Other'; Z = 'Separator'; Zl = 'Separator.Line'; Zp = 'Separator.Paragraph'; Zs = 'Separator.Space'; } function lib.get(v) return require('parse.char.utf8.set.' .. (aliases[v] or v)) end return lib
mit
Scavenge/darkstar
scripts/globals/effects/bust.lua
35
1737
----------------------------------- -- -- -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (effect:getSubType() == MOD_DMG) then target:addMod(MOD_DMG, effect:getPower()); else if (effect:getSubType() == MOD_ACC) then target:addMod(MOD_RACC, -effect:getPower()); elseif (effect:getSubType() == MOD_ATTP) then target:addMod(MOD_RATTP, -effect:getPower()); elseif (effect:getSubType() == MOD_PET_MACC) then target:addMod(MOD_PET_MATT, -effect:getPower()); end target:addMod(effect:getSubType(), -effect:getPower()); end --print("added "..effect:getPower().." of mod "..effect:getSubType()); end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) if (effect:getSubType() == MOD_DMG) then target:delMod(MOD_DMG, effect:getPower()); else if (effect:getSubType() == MOD_ACC) then target:delMod(MOD_RACC, -effect:getPower()); elseif (effect:getSubType() == MOD_ATTP) then target:delMod(MOD_RATTP, -effect:getPower()); elseif (effect:getSubType() == MOD_PET_MACC) then target:delMod(MOD_PET_MATT, -effect:getPower()); end target:delMod(effect:getSubType(), -effect:getPower()); end --print("removed "..effect:getPower().." of mod "..effect:getSubType()); end;
gpl-3.0
PicoleDeLimao/Ninpou2
game/dota_addons/ninpou2/scripts/vscripts/items/bijuu_chakra_armor.lua
1
1386
--[[ Author: PicoleDeLimao Date: 04.09.2016 Implement Bijuu Chakra Armor Shield ]] function InitializeShield(event) local caster = event.caster local ability = event.ability caster.bijuuChakraShieldHealth = ability:GetLevelSpecialValueFor("shield_amount", ability:GetLevel() - 1) local particle = ParticleManager:CreateParticle("particles/econ/items/bloodseeker/bloodseeker_eztzhok_weapon/bloodseeker_bloodbath_eztzhok.vpcf", PATTACH_ABSORIGIN, caster) ParticleManager:SetParticleControl(particle, 1, caster:GetAbsOrigin() + Vector(500, 500, 500)) caster:EmitSound("Hero_Windrunner.Pick") end function BlockDamage(event) local caster = event.caster local ability = event.ability local damage = event.Damage local damageBlock = nil if damage <= caster.bijuuChakraShieldHealth then caster.bijuuChakraShieldHealth = caster.bijuuChakraShieldHealth - damage caster:SetHealth(caster.oldHealth) damageBlock = damage else caster:SetHealth(caster.oldHealth - damage + caster.bijuuChakraShieldHealth) caster:RemoveModifierByName("modifier_item_bijuu_chakra_armor_buff") damageBlock = caster.bijuuChakraShieldHealth end SendOverheadEventMessage(caster:GetPlayerOwner(), OVERHEAD_ALERT_BLOCK, caster, damageBlock, nil) end -- Keeps track of the caster health function CasterHealth(event) local caster = event.caster caster.oldHealth = caster:GetHealth() end
apache-2.0
Scavenge/darkstar
scripts/globals/abilities/pets/attachments/tension_spring_ii.lua
27
1092
----------------------------------- -- Attachment: Tension Spring II ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onUseAbility ----------------------------------- function onEquip(pet) pet:addMod(MOD_ATTP, 6) pet:addMod(MOD_RATTP, 6) end function onUnequip(pet) pet:delMod(MOD_ATTP, 6) pet:addMod(MOD_RATTP, 6) end function onManeuverGain(pet,maneuvers) if (maneuvers == 1) then pet:addMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) elseif (maneuvers == 2) then pet:addMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) elseif (maneuvers == 3) then pet:addMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) end end function onManeuverLose(pet,maneuvers) if (maneuvers == 1) then pet:delMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) elseif (maneuvers == 2) then pet:delMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) elseif (maneuvers == 3) then pet:delMod(MOD_ATTP, 3); pet:addMod(MOD_RATTP, 3) end end
gpl-3.0
Scavenge/darkstar
scripts/globals/items/tavnazian_salad.lua
12
1683
----------------------------------------- -- ID: 4279 -- Item: tavnazian_salad -- Food Effect: 180Min, All Races ----------------------------------------- -- Health 20 -- Magic 20 -- Dexterity 4 -- Agility 4 -- Vitality 6 -- Charisma 4 -- Defense % 25 -- Defense 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,10800,4279); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_VIT, 6); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 150); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_VIT, 6); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 150); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Northern_San_dOria/npcs/Amarefice.lua
53
1893
----------------------------------- -- Area: Northern San d'Oria -- NPC: Amarefice -- Type: Woodworking Synthesis Image Support -- @pos -181.506 10.15 259.905 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,9); local SkillCap = getCraftSkillCap(player,SKILL_WOODWORKING); local SkillLevel = player:getSkillLevel(SKILL_WOODWORKING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == false) then player:startEvent(0x0270,SkillCap,SkillLevel,1,207,player:getGil(),0,4095,0); else player:startEvent(0x0270,SkillCap,SkillLevel,1,207,player:getGil(),7127,4095,0); end else player:startEvent(0x0270,SkillCap,SkillLevel,1,201,player:getGil(),0,0,0); -- Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0270 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,1,1); player:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,1,0,120); end end;
gpl-3.0
yrpen/lua-scripts
pets_system/talkactions/pet_heal.lua
1
1738
-- <talkaction words="!petheal" script="pet_heal.lua" /> function onSay(player, words, param, channel) local petUid = player:getPetUid() if petUid == PETS.CONSTANS.STATUS_DOESNT_EXIST then player:petSystemMessage("You don't have a pet!") elseif petUid == PETS.CONSTANS.STATUS_DEAD then player:petSystemMessage("Your pet is dead!") elseif petUid == PETS.CONSTANS.STATUS_OK then local lostHealth = player:getPetLostHealth() local soulNeded = PETS.CONFIG.healSoulBase + lostHealth * PETS.CONFIG.healSoulCost if lostHealth == 0 then player:petSystemMessage("Your pet doesn't need healing!") elseif player:getSoul() >= soulNeded then player:addSoul(-soulNeded) player:setPetLostHealth(0) player:petSystemMessage("You healed your pet ".. lostHealth .. " health, it cost you " .. soulNeded .." soul points.") else player:petSystemMessage("You need ".. soulNeded .." soul points!") end elseif petUid >= 0 then local pet = Creature(petUid) local lostHealth = pet:getMaxHealth() - pet:getHealth() local soulNeded = PETS.CONFIG.healSoulBase + lostHealth * PETS.CONFIG.healSoulCost if lostHealth == 0 then player:petSystemMessage("Your pet doesn't need healing!") elseif player:getSoul() >= soulNeded then player:addSoul(-soulNeded) pet:addHealth(lostHealth) player:petSystemMessage("You healed your pet ".. lostHealth .. " health, it cost " .. soulNeded .." soul points!") else player:petSystemMessage("You need ".. soulNeded .." soul points!") end end return true end
mit
Scavenge/darkstar
scripts/zones/Bastok_Mines/npcs/Gerbaum.lua
17
2291
----------------------------------- -- Area: Bastok Mines -- NPC: Gerbaum -- Starts & Finishes Repeatable Quest: Minesweeper (100%) ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); ZeruhnSoot = trade:hasItemQty(560,3); if (ZeruhnSoot == true and count == 3) then MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER); if (MineSweep >= 1) then player:tradeComplete(); player:startEvent(0x006d); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER); if (MineSweep == 0) then player:startEvent(0x006c); else rand = math.random(1,2); if (rand == 1) then player:startEvent(0x0016); else player:startEvent(0x0017); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER); if (csid == 0x006c) then if (MineSweep == 0) then player:addQuest(BASTOK,MINESWEEPER); end elseif (csid == 0x006d) then if (MineSweep == 1) then player:completeQuest(BASTOK,MINESWEEPER); player:addFame(BASTOK,75); player:addTitle(ZERUHN_SWEEPER); else player:addFame(BASTOK,8); end player:addGil(GIL_RATE*150); player:messageSpecial(GIL_OBTAINED,GIL_RATE*150); end end;
gpl-3.0
1yvT0s/luvit
tests/test-tls-peer-certificate.lua
5
2171
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ]]-- require('tap')(function (test) local fixture = require('./fixture-tls') local tls = require('tls') local options = { key = fixture.loadFile('agent.key'), cert = fixture.loadFile('alice.crt'), rejectUnauthorized=false } local verified = false test("tls peer certificate", function() local server server = tls.createServer(options, function(cleartext,err) assert(not err,err) cleartext:write('world') cleartext:destroy() end) server:listen(fixture.commonPort, function() local socket socket = tls.connect({host = '127.0.0.1', port = fixture.commonPort}) socket:on('connect',function() socket:write('Hello') socket:on('data',function(chunk,err) p(chunk,err) local peercert = assert(socket:getPeerCertificate()) peercert = peercert:parse() assert(tostring(peercert.subject) == '/CN=alice/subjectAltName=uniformResourceIdentifier:http://localhost:8000/alice.foaf#me') verified = true socket:destroy() server:close() end) socket:on('end',function() print('END') end) socket:on('error',function(err) --print('ERROR',err) local peercert = assert(socket:getPeerCertificate()) peercert = peercert:parse() assert(tostring(peercert.subject) == '/CN=alice/subjectAltName=uniformResourceIdentifier:http://localhost:8000/alice.foaf#me') verified = true socket:destroy() server:close() end) end) end) end) end)
apache-2.0
BlockMen/minetest_next
mods/tnt/init.lua
1
10693
tnt = {} -- Default to enabled in singleplayer and disabled in multiplayer local singleplayer = minetest.is_singleplayer() local setting = minetest.setting_getbool("enable_tnt") if (not singleplayer and setting ~= true) or (singleplayer and setting == false) then return end -- loss probabilities array (one in X will be lost) local loss_prob = {} loss_prob["default:cobble"] = 3 loss_prob["default:dirt"] = 4 local radius = tonumber(minetest.setting_get("tnt_radius") or 3) -- Fill a list with data for content IDs, after all nodes are registered local cid_data = {} minetest.after(0, function() for name, def in pairs(minetest.registered_nodes) do cid_data[minetest.get_content_id(name)] = { name = name, drops = def.drops, flammable = def.groups.flammable, on_blast = def.on_blast, } end end) local function rand_pos(center, pos, radius) local def local reg_nodes = minetest.registered_nodes local i = 0 repeat -- Give up and use the center if this takes too long if i > 4 then pos.x, pos.z = center.x, center.z break end pos.x = center.x + math.random(-radius, radius) pos.z = center.z + math.random(-radius, radius) def = reg_nodes[minetest.get_node(pos).name] i = i + 1 until def and not def.walkable end local function eject_drops(drops, pos, radius) local drop_pos = vector.new(pos) for _, item in pairs(drops) do local count = item:get_count() local max = item:get_stack_max() if count > max then item:set_count(max) end while count > 0 do if count < max then item:set_count(count) end rand_pos(pos, drop_pos, radius) local obj = minetest.add_item(drop_pos, item) if obj then obj:get_luaentity().collect = true obj:setacceleration({x = 0, y = -10, z = 0}) obj:setvelocity({x = math.random(-3, 3), y = 10, z = math.random(-3, 3)}) end count = count - max end end end local function add_drop(drops, item) item = ItemStack(item) local name = item:get_name() if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then return end local drop = drops[name] if drop == nil then drops[name] = item else drop:set_count(drop:get_count() + item:get_count()) end end local fire_node = {name = "fire:basic_flame"} local function destroy(drops, pos, cid, disable_drops) if minetest.is_protected(pos, "") then return end local def = cid_data[cid] if def and def.on_blast then def.on_blast(vector.new(pos), 1) return end if def and def.flammable then minetest.set_node(pos, fire_node) else minetest.remove_node(pos) if disable_drops then return end if def then local node_drops = minetest.get_node_drops(def.name, "") for _, item in ipairs(node_drops) do add_drop(drops, item) end end end end local function calc_velocity(pos1, pos2, old_vel, power) local vel = vector.direction(pos1, pos2) vel = vector.normalize(vel) vel = vector.multiply(vel, power) -- Divide by distance local dist = vector.distance(pos1, pos2) dist = math.max(dist, 1) vel = vector.divide(vel, dist) -- Add old velocity vel = vector.add(vel, old_vel) return vel end local function entity_physics(pos, radius) -- Make the damage radius larger than the destruction radius local objs = minetest.get_objects_inside_radius(pos, radius) for _, obj in pairs(objs) do local obj_pos = obj:getpos() local obj_vel = obj:getvelocity() local dist = math.max(1, vector.distance(pos, obj_pos)) if obj_vel ~= nil then obj:setvelocity(calc_velocity(pos, obj_pos, obj_vel, radius * 10)) end local damage = (4 / dist) * radius obj:set_hp(obj:get_hp() - damage) end end local function add_effects(pos, radius) minetest.add_particlespawner({ amount = 128, time = 1, minpos = vector.subtract(pos, radius / 2), maxpos = vector.add(pos, radius / 2), minvel = {x = -20, y = -20, z = -20}, maxvel = {x = 20, y = 20, z = 20}, minacc = vector.new(), maxacc = vector.new(), minexptime = 1, maxexptime = 3, minsize = 8, maxsize = 16, texture = "tnt_smoke.png", }) end function tnt.burn(pos) local name = minetest.get_node(pos).name local group = minetest.get_item_group(name,"tnt") if group > 0 then minetest.sound_play("tnt_ignite", {pos = pos}) minetest.set_node(pos, {name = name .. "_burning"}) minetest.get_node_timer(pos):start(1) elseif name == "tnt:gunpowder" then minetest.sound_play("tnt_gunpowder_burning", {pos = pos, max_hear_distance = 8, gain = 2}) minetest.set_node(pos, {name = "tnt:gunpowder_burning"}) minetest.get_node_timer(pos):start(1) end end function tnt.explode(pos, radius, disable_drops) local pos = vector.round(pos) local vm = VoxelManip() local pr = PseudoRandom(os.time()) local p1 = vector.subtract(pos, radius) local p2 = vector.add(pos, radius) local minp, maxp = vm:read_from_map(p1, p2) local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp}) local data = vm:get_data() local drops = {} local p = {} local c_air = minetest.get_content_id("air") for z = -radius, radius do for y = -radius, radius do local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z) for x = -radius, radius do if (x * x) + (y * y) + (z * z) <= (radius * radius) + pr:next(-radius, radius) then local cid = data[vi] p.x = pos.x + x p.y = pos.y + y p.z = pos.z + z if cid ~= c_air then destroy(drops, p, cid, disable_drops) end end vi = vi + 1 end end end return drops end function tnt.boom(pos, radius, damage_radius, disable_drops) minetest.sound_play("tnt_explode", {pos = pos, gain = 1.5, max_hear_distance = 80}) minetest.set_node(pos, {name = "tnt:boom"}) minetest.get_node_timer(pos):start(0.5) local drops = tnt.explode(pos, radius, disable_drops) entity_physics(pos, damage_radius) if not disable_drops then eject_drops(drops, pos, radius) end add_effects(pos, radius) end minetest.register_node("tnt:boom", { drawtype = "plantlike", tiles = {"tnt_boom.png"}, light_source = default.LIGHT_MAX, walkable = false, drop = "", groups = {dig_immediate = 3}, on_timer = function(pos, elapsed) minetest.remove_node(pos) end, -- unaffected by explosions on_blast = function() end, }) minetest.register_node("tnt:gunpowder", { description = "Gun Powder", drawtype = "raillike", paramtype = "light", is_ground_content = false, sunlight_propagates = true, walkable = false, tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"}, inventory_image = "tnt_gunpowder_inventory.png", wield_image = "tnt_gunpowder_inventory.png", selection_box = { type = "fixed", fixed = {-1/2, -1/2, -1/2, 1/2, -1/2 + 1/16, 1/2}, }, groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")}, sounds = default.node_sound_leaves_defaults(), on_punch = function(pos, node, puncher) if puncher:get_wielded_item():get_name() == "default:torch" then tnt.burn(pos) end end, on_blast = function(pos, intensity) tnt.burn(pos) end, }) minetest.register_node("tnt:gunpowder_burning", { drawtype = "raillike", paramtype = "light", sunlight_propagates = true, walkable = false, light_source = 5, tiles = { { name = "tnt_gunpowder_burning_straight_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1} }, { name = "tnt_gunpowder_burning_curved_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1} }, { name = "tnt_gunpowder_burning_t_junction_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1} }, { name = "tnt_gunpowder_burning_crossing_animated.png", animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1} } }, selection_box = { type = "fixed", fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2}, }, drop = "", groups = {dig_immediate = 2, attached_node = 1, connect_to_raillike = minetest.raillike_group("gunpowder")}, sounds = default.node_sound_leaves_defaults(), on_timer = function(pos, elapsed) for dx = -1, 1 do for dz = -1, 1 do for dy = -1, 1 do if not (dx == 0 and dz == 0) then tnt.burn({x = pos.x + dx, y = pos.y + dy, z = pos.z + dz}) end end end end minetest.remove_node(pos) end, -- unaffected by explosions on_blast = function() end, }) minetest.register_abm({ nodenames = {"group:tnt", "tnt:gunpowder"}, neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"}, interval = 1, chance = 1, action = tnt.burn, }) function tnt.register_tnt(name, def) if not def or not name then return false end if not def.tiles then def.tiles = {} end local tnt_top = def.tiles.top or "tnt_top.png" local tnt_bottom = def.tiles.bottom or "tnt_bottom.png" local tnt_side = def.tiles.side or "tnt_side.png" local tnt_burning = def.tiles.burning or "tnt_top_burning.png" if not def.damage_radius then def.damage_radius = def.radius * 2 end minetest.register_node(":" .. name, { description = def.description, tiles = {tnt_top, tnt_bottom, tnt_side}, is_ground_content = false, groups = {dig_immediate = 2, mesecon = 2, tnt = 1}, sounds = default.node_sound_wood_defaults(), on_punch = function(pos, node, puncher) if puncher:get_wielded_item():get_name() == "default:torch" then minetest.sound_play("tnt_ignite", {pos=pos}) minetest.set_node(pos, {name = name .. "_burning"}) minetest.get_node_timer(pos):start(4) end end, on_blast = function(pos, intensity) tnt.burn(pos) end, mesecons = {effector = {action_on = function (pos) tnt.boom(pos, def.radius, def.damage_radius, def.disable_drops) end } }, }) minetest.register_node(":" .. name .. "_burning", { tiles = { { name = tnt_burning, animation = {type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 1} }, tnt_bottom, tnt_side }, light_source = 5, drop = "", sounds = default.node_sound_wood_defaults(), on_timer = function (pos, elapsed) tnt.boom(pos, def.radius, def.damage_radius, def.disable_drops) end, -- unaffected by explosions on_blast = function() end, }) end tnt.register_tnt("tnt:tnt", { description = "TNT", radius = radius, tiles = {burning = "tnt_top_burning_animated.png"}, }) minetest.register_craft({ output = "tnt:gunpowder", type = "shapeless", recipe = {"default:coal_lump", "default:gravel"} }) minetest.register_craft({ output = "tnt:tnt", recipe = { {"", "group:wood", ""}, {"group:wood", "tnt:gunpowder", "group:wood"}, {"", "group:wood", ""} } })
gpl-3.0
Scavenge/darkstar
scripts/globals/regimereward.lua
36
9093
------------------------------------------------- -- Regime Reward Database(s) ------------------------------------------------- -- ------------------------------------ -- FoV rewards -- ------------------------------------ function getFoVregimeReward(regimeid) local reward = { [1] = 270, [2] = 285, [3] = 300, [4] = 315, [5] = 330, [6] = 390, [7] = 475, [8] = 500, [9] = 525, [10] = 550, [11] = 540, [12] = 570, [13] = 600, [14] = 630, [15] = 670, [16] = 270, [17] = 285, [18] = 300, [19] = 315, [20] = 330, [21] = 540, [22] = 570, [23] = 600, [24] = 630, [25] = 690, [26] = 270, [27] = 285, [28] = 300, [29] = 315, [30] = 330, [31] = 450, [32] = 475, [33] = 500, [34] = 525, [35] = 550, [36] = 540, [37] = 570, [38] = 600, [39] = 630, [40] = 690, [41] = 630, [42] = 665, [43] = 700, [44] = 735, [45] = 770, [46] = 810, [47] = 855, [48] = 900, [49] = 945, [50] = 990, [51] = 900, [52] = 950, [53] = 1000, [54] = 1050, [55] = 1100, [56] = 330, [57] = 575, [58] = 480, [59] = 330, [60] = 660, [61] = 330, [62] = 575, [63] = 660, [64] = 270, [65] = 285, [66] = 300, [67] = 315, [68] = 330, [69] = 360, [70] = 420, [71] = 450, [72] = 630, [73] = 650, [74] = 700, [75] = 730, [76] = 270, [77] = 285, [78] = 300, [79] = 315, [80] = 330, [81] = 340, [82] = 360, [83] = 380, [84] = 400, [85] = 670, [86] = 710, [87] = 740, [88] = 800, [89] = 270, [90] = 285, [91] = 300, [92] = 315, [93] = 330, [94] = 315, [95] = 370, [96] = 475, [97] = 710, [98] = 710, [99] = 730, [100] = 770, [101] = 350, [102] = 400, [103] = 450, [104] = 1300, [105] = 1320, [106] = 1340, [107] = 1390, [108] = 1450, [109] = 810, [110] = 830, [111] = 870, [112] = 950, [113] = 970, [114] = 900, [115] = 940, [116] = 980, [117] = 1020, [118] = 1100, [119] = 1300, [120] = 1330, [121] = 1360, [122] = 1540, [123] = 1540, [124] = 820, [125] = 840, [126] = 860, [127] = 880, [128] = 920, [129] = 840, [130] = 880, [131] = 920, [132] = 940, [133] = 1000, [134] = 920, [135] = 980, [136] = 1020, [137] = 1080, [138] = 1140, [139] = 1220, [140] = 1260, [141] = 1300, [142] = 1450, [143] = 1500, [144] = 1550, [145] = 1600, [146] = 1600, }; if reward[regimeid] then return reward[regimeid]; else --print("Warning: Regime ID not found! Returning reward as 10."); return 10; end end; -- ------------------------------------ -- Placeholder for Hunt Registry -- ------------------------------------ -- function getHuntRegistryReward(registryid) -- end ----------------------------------- -- Fetch GoV base rewards -- -- I know, its ugly but until the missing reward values are -- corrected I'm not messing with it further (neither wiki had them all). -- Once thats done maybe we can array this. ----------------------------------- function getGoVregimeReward(regimeid) local reward = { [602] = 270, [603] = 930, [604] = 860, [605] = 860, [606] = 970, [607] = 2260, [608] = 2260, [609] = 2260, [610] = 1110, [611] = 1320, [612] = 1430, [613] = 2050, [614] = 2300, [615] = 2300, [616] = 1960, [617] = 1960, [618] = 1260, [619] = 1410, [620] = 1500, [621] = 1690, [622] = 1690, [623] = 2170, [624] = 2250, [625] = 2250, [626] = 90, [627] = 110, [628] = 1640, [629] = 1600, [630] = 1700, [631] = 380, [632] = 420, [633] = 610, [634] = 590, [635] = 864, [636] = 1520, [637] = 1690, [638] = 1720, [639] = 280, [640] = 350, [641] = 490, [642] = 1830, [643] = 1650, [644] = 1840, [645] = 1860, [646] = 2260, [647] = 250, [648] = 270, [649] = 610, [650] = 840, [651] = 1750, [652] = 1760, [653] = 1770, [654] = 1780, [655] = 730, [656] = 840, [657] = 800, [658] = 850, [659] = 950, [660] = 830, [661] = 1810, [662] = 1560, [663] = 340, [664] = 450, [665] = 540, [666] = 590, [667] = 650, [668] = 700, [669] = 1840, [670] = 1850, [671] = 950, [672] = 1030, [673] = 1300, [674] = 1340, [675] = 1330, [676] = 1470, [677] = 1890, [678] = 1890, [679] = 660, [680] = 800, [681] = 790, [682] = 1050, [683] = 970, [684] = 1000, [685] = 1890, [686] = 2180, [687] = 1160, [688] = 1230, [689] = 1280, [690] = 1300, [691] = 1340, [692] = 1470, [693] = 2190, [694] = 2220, [695] = 550, [696] = 700, [697] = 840, [698] = 920, [699] = 820, [700] = 840, [701] = 1530, [702] = 1830, [703] = 1160, [704] = 1160, [705] = 1240, [706] = 1310, [707] = 1330, [708] = 1270, [709] = 1840, [710] = 2220, [711] = 1180, [712] = 1240, [713] = 1310, [714] = 1310, [715] = 1340, [716] = 1470, [717] = 2060, [718] = 2250, [719] = 1470, [720] = 1720, [721] = 1760, [722] = 1770, [723] = 1830, [724] = 1900, [725] = 1640, [726] = 2040, [727] = 780, [728] = 870, [729] = 950, [730] = 980, [731] = 930, [732] = 770, [733] = 1030, [734] = 2140, [735] = 1440, [736] = 1480, [737] = 1380, [738] = 1550, [739] = 1410, [740] = 1540, [741] = 1660, [742] = 1900, [743] = 2390, [744] = 1900, [745] = 1920, [746] = 2120, [747] = 2230, [748] = 2180, [749] = 2370, [750] = 2080, [751] = 1930, [752] = 2150, [753] = 2050, [754] = 2390, [755] = 1270, [756] = 1570, [757] = 1280, [758] = 1310, [759] = 1380, [760] = 1610, [761] = 1650, [762] = 1760, [763] = 1040, [764] = 1230, [765] = 1490, [766] = 1620, [767] = 1700, [768] = 1680, [769] = 1710, [770] = 2310, [771] = 1050, [772] = 1070, [773] = 1140, [774] = 1130, [775] = 1350, [776] = 1920, [777] = 900, [778] = 900, [779] = 930, [780] = 980, [781] = 940, [782] = 1090, [783] = 1090, [784] = 1290, [785] = 1010, [786] = 1520, [787] = 1520, [788] = 1540, [789] = 1540, [790] = 1450, [791] = 1450, [792] = 1450, [793] = 1630, [794] = 1650, [795] = 1660, [796] = 1370, [797] = 1500, [798] = 1820, [799] = 1640, [800] = 1650, -- estimating, no data available [801] = 1690, [802] = 1640, [803] = 1790, [804] = 1040, [805] = 1050, [806] = 1180, [807] = 1190, [808] = 1220, [809] = 1470, [810] = 1480, [811] = 1500, [821] = 1310, [813] = 1360, [814] = 1230, [815] = 1480, [816] = 1470, [817] = 1360, [818] = 1570, [819] = 1540, }; if reward[regimeid] then return reward[regimeid]; else -- print("Warning: Regime ID not found! Returning reward as 100."); return 100; end end; -- ------------------------------------ -- Placeholder for Dominion Regimes -- ------------------------------------ -- function getDominionReward(regimeid) -- end
gpl-3.0
Scavenge/darkstar
scripts/zones/Mhaura/npcs/Orlando.lua
14
3537
----------------------------------- -- Area: Mhaura -- NPC: Orlando -- Type: Standard NPC -- @pos -37.268 -9 58.047 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); local itemID = trade:getItemId(); local itemList = { {564, 200}, -- Fingernail Sack {565, 250}, -- Teeth Sack {566, 200}, -- Goblin Cup {568, 120}, -- Goblin Die {656, 600}, -- Beastcoin {748, 900}, -- Gold Beastcoin {749, 800}, -- Mythril Beastcoin {750, 750}, -- Silver Beastcoin {898, 120}, -- Chicken Bone {900, 100}, -- Fish Bone {16995, 150}, -- Rotten Meat }; for x, item in pairs(itemList) do if (QuestStatus == QUEST_ACCEPTED) or (player:getLocalVar("OrlandoRepeat") == 1) then if (item[1] == itemID) then if (trade:hasItemQty(itemID, 8) and trade:getItemCount() == 8) then -- Correct amount, valid item. player:setVar("ANTIQUE_PAYOUT", (GIL_RATE*item[2])); player:startEvent(0x0066, GIL_RATE*item[2], itemID); elseif (trade:getItemCount() < 8) then -- Wrong amount, but valid item. player:startEvent(0x0068); end end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); if (player:getFameLevel(WINDURST) >= 2) then if (player:hasKeyItem(CHOCOBO_LICENSE)) then if (QuestStatus ~= QUEST_AVAILABLE) then player:startEvent(0x0067); elseif (QuestStatus == QUEST_AVAILABLE) then player:startEvent(0x0065); end else player:startEvent(0x0064); end else player:startEvent(0x006A); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local QuestStatus = player:getQuestStatus(OTHER_AREAS, ORLANDO_S_ANTIQUES); local payout = player:getVar("ANTIQUE_PAYOUT"); if (csid == 0x0065) then player:addQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES); elseif (csid == 0x0066) then player:tradeComplete(); player:addFame(WINDURST,10); player:addGil(payout); player:messageSpecial(GIL_OBTAINED,payout); player:completeQuest(OTHER_AREAS, ORLANDO_S_ANTIQUES); player:setVar("ANTIQUE_PAYOUT", 0); player:setLocalVar("OrlandoRepeat", 0); elseif (csid == 0x0067) then if (QuestStatus == QUEST_COMPLETED) then player:setLocalVar("OrlandoRepeat", 1); end end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Windurst_Waters/npcs/Foi-Mui.lua
14
1402
----------------------------------- -- Area: Windurst Waters -- NPC: Foi-Mui -- Involved in Quest: Making the Grade -- Working 100% -- @zone = 238 -- @pos = 126 -6 162 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then player:startEvent(0x01c1); -- During Making the GRADE else player:startEvent(0x01ae); -- Standard conversation end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Labyrinth_of_Onzozo/mobs/Labyrinth_Manticore.lua
14
1061
----------------------------------- -- Area: Labyrinth of Onzozo -- MOB: Labyrinth Manticore -- Note: Place holder Narasimha ----------------------------------- require("scripts/globals/groundsofvalor"); require("scripts/zones/Labyrinth_of_Onzozo/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, player, isKiller) checkGoVregime(player,mob,775,2); end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) local mobID = mob:getID(); if (Narasimha_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Narasimha"); if (ToD <= os.time(t) and GetMobAction(Narasimha) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Narasimha); GetMobByID(Narasimha):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Narasimha", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
sleep/mal
lua/printer.lua
45
1770
local string = require('string') local table = require('table') local types = require('types') local utils = require('utils') local M = {} function M._pr_str(obj, print_readably) local _r = print_readably if utils.instanceOf(obj, types.Symbol) then return obj.val elseif types._list_Q(obj) then return "(" .. table.concat(utils.map(function(e) return M._pr_str(e,_r) end, obj), " ") .. ")" elseif types._vector_Q(obj) then return "[" .. table.concat(utils.map(function(e) return M._pr_str(e,_r) end, obj), " ") .. "]" elseif types._hash_map_Q(obj) then local res = {} for k,v in pairs(obj) do res[#res+1] = M._pr_str(k, _r) res[#res+1] = M._pr_str(v, _r) end return "{".. table.concat(res, " ").."}" elseif type(obj) == 'string' then if string.sub(obj,1,1) == "\177" then return ':' .. string.sub(obj,2) else if _r then local sval = obj:gsub('\\', '\\\\') sval = sval:gsub('"', '\\"') sval = sval:gsub('\n', '\\n') return '"' .. sval .. '"' else return obj end end elseif obj == types.Nil then return "nil" elseif obj == true then return "true" elseif obj == false then return "false" elseif types._malfunc_Q(obj) then return "(fn* "..M._pr_str(obj.params).." "..M._pr_str(obj.ast)..")" elseif types._atom_Q(obj) then return "(atom "..M._pr_str(obj.val)..")" elseif type(obj) == 'function' or types._functionref_Q(obj) then return "#<function>" else return string.format("%s", obj) end end return M
mpl-2.0
Scavenge/darkstar
scripts/zones/Port_Jeuno/npcs/Narsha.lua
27
1730
----------------------------------- -- Area: Port Jeuno -- NPC: Narsha -- Type: Chocobo Renter ----------------------------------- require("scripts/globals/chocobo"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local level = player:getMainLvl(); local gil = player:getGil(); if (player:hasKeyItem(CHOCOBO_LICENSE) and level >= 20) then local price = getChocoboPrice(player); player:setLocalVar("chocoboPriceOffer",price); player:startEvent(0x2713,price,gil); else player:startEvent(0x2716); 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); local price = player:getLocalVar("chocoboPriceOffer"); if (csid == 0x2713 and option == 0) then if (player:delGil(price)) then updateChocoboPrice(player, price); local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60) player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,duration,true); player:setPos(-574,2,400,0,0x78); end end end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
gamedata/modularcomms/weapons/heavymachinegun.lua
6
1413
local name = "commweapon_heavymachinegun" local weaponDef = { name = [[Heavy Machine Gun]], accuracy = 1024, alphaDecay = 0.7, areaOfEffect = 96, burnblow = true, craterBoost = 0.15, craterMult = 0.3, customParams = { slot = [[5]], muzzleEffectShot = [[custom:WARMUZZLE]], miscEffectShot = [[custom:DEVA_SHELLS]], altforms = { lime = { explosionGenerator = [[custom:BEAMWEAPON_HIT_GREEN]], rgbColor = [[0.2 1 0]], }, }, light_color = [[0.8 0.76 0.38]], light_radius = 180, }, damage = { default = 30, planes = 30, subs = 1.5, }, edgeEffectiveness = 0.5, explosionGenerator = [[custom:EMG_HIT_HE]], firestarter = 70, impulseBoost = 0, impulseFactor = 0.2, intensity = 0.7, interceptedByShieldType = 1, noSelfDamage = true, range = 285, reloadtime = 5/30, rgbColor = [[1 0.95 0.4]], separation = 1.5, soundHit = [[weapon/cannon/emg_hit]], soundStart = [[weapon/sd_emgv7]], soundStartVolume = 7, stages = 10, turret = true, weaponType = [[Cannon]], weaponVelocity = 550, } return name, weaponDef
gpl-2.0
xebecnan/UniLua
Assets/StreamingAssets/LuaRoot/lib/unity_engine.lua
4
1453
local ffi = require("lib.ffi") local function _init(_ENV) assembly("mscorlib") assembly("UnityEngine") using("System") using("UnityEngine") class("Object") class("Vector3") :constructor("Vector3(float, float, float)") :field("float x") :field("float y") :field("float z") class("GameObject") :constructor("GameObject(String)") :method("Component AddComponent(Type)") :property("Transform transform") class("Transform") :property("Vector3 localScale") :property("Vector3 localPosition") class("Input") :static_method("float GetAxis(String)") class("Material") class("Shader") class("MeshFilter") :method("String ToString()") :property("Mesh mesh") :property("Mesh sharedMesh") class("MeshRenderer") :property("bool castShadows") :property("bool receiveShadows") :property("Material material") class("Resources") :static_method("Object Load(String,Type)") class("Mesh") class("Component") end return ffi.build(_init) --[[ ffi.using("System") ffi.using("UnityEngine") local GameObject = ffi.class("UnityEngine.GameObject") :constructor("string") :method("AddComponent") :build() local Input = ffi.class("UnityEngine.Input") :static_method("GetAxis") :build() return { GameObject = GameObject, Input = Input, } ]]
mit
angking0802wu/UniLua
Assets/StreamingAssets/LuaRoot/lib/unity_engine.lua
4
1453
local ffi = require("lib.ffi") local function _init(_ENV) assembly("mscorlib") assembly("UnityEngine") using("System") using("UnityEngine") class("Object") class("Vector3") :constructor("Vector3(float, float, float)") :field("float x") :field("float y") :field("float z") class("GameObject") :constructor("GameObject(String)") :method("Component AddComponent(Type)") :property("Transform transform") class("Transform") :property("Vector3 localScale") :property("Vector3 localPosition") class("Input") :static_method("float GetAxis(String)") class("Material") class("Shader") class("MeshFilter") :method("String ToString()") :property("Mesh mesh") :property("Mesh sharedMesh") class("MeshRenderer") :property("bool castShadows") :property("bool receiveShadows") :property("Material material") class("Resources") :static_method("Object Load(String,Type)") class("Mesh") class("Component") end return ffi.build(_init) --[[ ffi.using("System") ffi.using("UnityEngine") local GameObject = ffi.class("UnityEngine.GameObject") :constructor("string") :method("AddComponent") :build() local Input = ffi.class("UnityEngine.Input") :static_method("GetAxis") :build() return { GameObject = GameObject, Input = Input, } ]]
mit
smanolache/kong
spec/plugins/response-transformer/filter_spec.lua
1
2296
local spec_helper = require "spec.spec_helpers" local http_client = require "kong.tools.http_client" local cjson = require "cjson" local STUB_GET_URL = spec_helper.PROXY_URL.."/get" local STUB_HEADERS_URL = spec_helper.PROXY_URL.."/response-headers" describe("Response Transformer Plugin #proxy", function() setup(function() spec_helper.prepare_db() spec_helper.insert_fixtures { api = { {name = "tests-response-transformer", request_host = "response.com", upstream_url = "http://httpbin.org"}, {name = "tests-response-transformer-2", request_host = "response2.com", upstream_url = "http://httpbin.org"} }, plugin = { { name = "response-transformer", config = { remove = { headers = {"Access-Control-Allow-Origin"}, json = {"url"} } }, __api = 1 }, { name = "response-transformer", config = { replace = { json = {"headers:/hello/world", "args:this is a / test", "url:\"wot\""} } }, __api = 2 } } } spec_helper.start_kong() end) teardown(function() spec_helper.stop_kong() end) describe("Test transforming parameters", function() it("should remove a parameter", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "response.com"}) assert.equal(200, status) local body = cjson.decode(response) assert.falsy(body.url) end) end) describe("Test transforming headers", function() it("should remove a header", function() local _, status, headers = http_client.get(STUB_HEADERS_URL, {}, {host = "response.com"}) assert.equal(200, status) assert.falsy(headers["access-control-allow-origin"]) end) end) describe("Test replace", function() it("should replace a body parameter on GET", function() local response, status = http_client.get(STUB_GET_URL, {}, {host = "response2.com"}) assert.equal(200, status) local body = cjson.decode(response) assert.equals([[/hello/world]], body.headers) assert.equals([[this is a / test]], body.args) assert.equals([["wot"]], body.url) end) end) end)
apache-2.0
novokrest/chdkptp
lua/errutil.lua
6
3282
--[[ Copyright (C) 2014 <reyalp (at) gmail dot com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --]] --[[ error handling utilities ]] local m={ last_traceback='', -- when to include a traceback 'always', 'never', 'critical' -- crit means string errors (thrown with error(...) rather than throw) -- or error objects with crit set do_traceback='critical', } --[[ handler for xpcall formats the error message with or without a traceback depending on settings if thrown error object includes traceback, uses it, otherwise attempts to get a new one --]] function m.format(err) return m.format_f(err,m.do_traceback) end function m.format_traceback(err) return m.format_f(err,'always') end function m.format_f(err,do_traceback) -- not an error object, try to backtrace if do_traceback == 'never' then return tostring(err) end if type(err) == 'string' then m.last_traceback = debug.traceback('',3) return err .. m.last_traceback end if type(err) ~= 'table' then err = string.format('unexpected error type %s [%s]',type(err),tostring(err)) m.last_traceback = debug.traceback('',3) return err .. m.last_traceback end if not err.traceback or type(err.traceback) ~= 'string' then err.traceback = debug.traceback('',3) end m.last_traceback = err.traceback if do_traceback == 'always' or err.critical then return tostring(err) .. err.traceback end return tostring(err) end --[[ wrap in function that calls with xpcall and prints errors, or returns values opts:{ err_default:value - value other than nil to return on error output:function - receives formatted error messages, default util.errf("%s\n",err) handler:function - handles/formats error, default m.format ]] function m.default_err_output(err) util.errf('%s\n',tostring(err)) end function m.wrap(f,opts) opts=util.extend_table({ output=m.default_err_output, handler=m.format, },opts) -- in 5.1, xpcall can't pass args if util.is_lua_ver(5,1) then return function(...) local args = {...} local r={xpcall(function() return f(unpack(args,1,table.maxn(args))) end,opts.handler)} if not r[1] then if opts.output then opts.output(tostring(r[2])) end if type(opts.err_default) ~= 'nil' then return opts.err_default end return end if table.maxn(r) > 1 then return unpack(r,2,table.maxn(r)) end end else return function(...) local r={xpcall(f,opts.handler,...)} if not r[1] then if opts.output then opts.output(tostring(r[2])) end if type(opts.err_default) ~= 'nil' then return opts.err_default end return end if table.maxn(r) > 1 then return unpack(r,2,table.maxn(r)) end end end end return m
gpl-2.0
taxler/radish
lua/exports/xiph/vorbis/init.lua
1
6423
local ffi = require 'ffi' require 'exports.xiph.ogg' ffi.cdef [[ const char* vorbis_version_string(); ]] local lib -- attempt to load statically-linked version, otherwise try dynamically-linked if pcall(function() assert(ffi.C.vorbis_version_string ~= nil) end) then lib = ffi.C else lib = ffi.load 'libvorbis' end ffi.cdef [[ enum { OV_FALSE = -1, OV_EOF = -2, OV_HOLE = -3, OV_EREAD = -128, OV_EFAULT = -129, OV_EIMPL = -130, OV_EINVAL = -131, OV_ENOTVORBIS = -132, OV_EBADHEADER = -133, OV_EVERSION = -134, OV_ENOTAUDIO = -135, OV_EBADPACKET = -136, OV_EBADLINK = -137, OV_ENOSEEK = -138 }; typedef struct vorbis_info { int version; int channels; long rate; /* The below bitrate declarations are *hints*. Combinations of the three values carry the following implications: all three set to the same value: implies a fixed rate bitstream only nominal set: implies a VBR stream that averages the nominal bitrate. No hard upper/lower limit upper and/or lower set: implies a VBR bitstream that obeys the bitrate limits. nominal may also be set to give a nominal rate. none set: the coder does not care to speculate. */ long bitrate_upper; long bitrate_nominal; long bitrate_lower; long bitrate_window; void* codec_setup; } vorbis_info; /* vorbis_dsp_state buffers the current vorbis audio analysis/synthesis state. The DSP state belongs to a specific logical bitstream */ typedef struct vorbis_dsp_state { int analysisp; vorbis_info* vi; float** pcm; float** pcmret; int pcm_storage; int pcm_current; int pcm_returned; int preextrapolate; int eofflag; long lW; long W; long nW; long centerW; int64_t granulepos; int64_t sequence; int64_t glue_bits; int64_t time_bits; int64_t floor_bits; int64_t res_bits; void* backend_state; } vorbis_dsp_state; typedef struct vorbis_block { /* necessary stream state for linking to the framing abstraction */ float** pcm; /* this is a pointer into local storage */ oggpack_buffer opb; long lW; long W; long nW; int pcmend; int mode; int eofflag; int64_t granulepos; int64_t sequence; vorbis_dsp_state* vd; /* For read-only access of configuration */ /* local storage to avoid remallocing; it's up to the mapping to structure it */ void* localstore; long localtop; long localalloc; long totaluse; struct alloc_chain *reap; /* bitmetrics for the frame */ long glue_bits; long time_bits; long floor_bits; long res_bits; void *internal; } vorbis_block; /* vorbis_block is a single block of data to be processed as part of the analysis/synthesis stream; it belongs to a specific logical bitstream, but is independent from other vorbis_blocks belonging to that logical bitstream. *************************************************/ struct alloc_chain { void *ptr; struct alloc_chain *next; }; /* vorbis_info contains all the setup information specific to the specific compression/decompression mode in progress (eg, psychoacoustic settings, channel setup, options, codebook etc). vorbis_info and substructures are in backends.h. *********************************************************************/ /* the comments are not part of vorbis_info so that vorbis_info can be static storage */ typedef struct vorbis_comment { /* unlimited user comment fields. libvorbis writes 'libvorbis' whatever vendor is set to in encode */ char** user_comments; int* comment_lengths; int comments; char* vendor; } vorbis_comment; /* libvorbis encodes in two abstraction layers; first we perform DSP and produce a packet (see docs/analysis.txt). The packet is then coded into a framed OggSquish bitstream by the second layer (see docs/framing.txt). Decode is the reverse process; we sync/frame the bitstream and extract individual packets, then decode the packet back into PCM audio. The extra framing/packetizing is used in streaming formats, such as files. Over the net (such as with UDP), the framing and packetization aren't necessary as they're provided by the transport and the streaming layer is not used */ void vorbis_info_init(vorbis_info*); void vorbis_info_clear(vorbis_info*); int vorbis_info_blocksize(vorbis_info*, int zo); void vorbis_comment_init(vorbis_comment*); void vorbis_comment_add(vorbis_comment*, const char *comment); void vorbis_comment_add_tag(vorbis_comment*, const char *tag, const char *contents); char* vorbis_comment_query(vorbis_comment*, const char *tag, int count); int vorbis_comment_query_count(vorbis_comment*, const char *tag); void vorbis_comment_clear(vorbis_comment*); int vorbis_block_init(vorbis_dsp_state*, vorbis_block*); int vorbis_block_clear(vorbis_block*); void vorbis_dsp_clear(vorbis_dsp_state*); double vorbis_granule_time(vorbis_dsp_state*, int64_t granulepos); // analysis/DSP layer int vorbis_analysis_init(vorbis_dsp_state*, vorbis_info*); int vorbis_commentheader_out(vorbis_comment*, ogg_packet*); int vorbis_analysis_headerout( vorbis_dsp_state*, vorbis_comment*, ogg_packet* op, ogg_packet* op_comm, ogg_packet* op_code); float** vorbis_analysis_buffer(vorbis_dsp_state*, int vals); int vorbis_analysis_wrote(vorbis_dsp_state*, int vals); int vorbis_analysis_blockout(vorbis_dsp_state*, vorbis_block*); int vorbis_analysis(vorbis_block*, ogg_packet*); int vorbis_bitrate_addblock(vorbis_block*); int vorbis_bitrate_flushpacket(vorbis_dsp_state*, ogg_packet*); // synthesis layer int vorbis_synthesis_idheader(ogg_packet*); int vorbis_synthesis_headerin(vorbis_info*, vorbis_comment*, ogg_packet*); int vorbis_synthesis_init(vorbis_dsp_state*, vorbis_info*); int vorbis_synthesis_restart(vorbis_dsp_state*); int vorbis_synthesis(vorbis_block*, ogg_packet*); int vorbis_synthesis_trackonly(vorbis_block*, ogg_packet*); int vorbis_synthesis_blockin(vorbis_dsp_state*, vorbis_block*); int vorbis_synthesis_pcmout(vorbis_dsp_state*, float*** pcm); int vorbis_synthesis_lapout(vorbis_dsp_state*, float*** pcm); int vorbis_synthesis_read(vorbis_dsp_state*, int samples); long vorbis_packet_blocksize(vorbis_info*, ogg_packet*); int vorbis_synthesis_halfrate(vorbis_info*, int flag); int vorbis_synthesis_halfrate_p(vorbis_info*); ]] return lib
mit
purebn/secure
plugins/youtube.lua
644
1722
do local google_config = load_from_file('data/google.lua') local function httpsRequest(url) print(url) local res,code = https.request(url) if code ~= 200 then return nil end return json:decode(res) end function get_yt_data (yt_code) local url = 'https://www.googleapis.com/youtube/v3/videos?' url = url .. 'id=' .. URL.escape(yt_code) .. '&part=snippet' if google_config.api_keys then local i = math.random(#google_config.api_keys) local api_key = google_config.api_keys[i] if api_key then url = url.."&key="..api_key end end return httpsRequest(url) end function send_youtube_data(data, receiver) local title = data.title local description = data.description local uploader = data.channelTitle local text = title..' ('..uploader..')\n'..description local image_url = data.thumbnails.high.url or data.thumbnails.default.url local cb_extra = { receiver = receiver, url = image_url } send_msg(receiver, text, send_photo_from_url_callback, cb_extra) end function run(msg, matches) local yt_code = matches[1] local data = get_yt_data(yt_code) if data == nil or #data.items == 0 then return "I didn't find info about that video." end local senddata = data.items[1].snippet local receiver = get_receiver(msg) send_youtube_data(senddata, receiver) end return { description = "Sends YouTube info and image.", usage = "", patterns = { "youtu.be/([_A-Za-z0-9-]+)", "youtube.com/watch%?v=([_A-Za-z0-9-]+)", }, run = run } end
gpl-2.0
Joker-Developer/jokersuper
plugins/help2.lua
4
3487
--[[ # For More Information ....! # Developer : Aziz < @devss_bot > #Dev # our channel: @help_tele ]] do local function run(msg, matches) if is_momod(msg) and matches[1]== "م 1" then return [[🏆🏆 - اوامر العامه في الكروب👑👑 💯💯💯💯💯💯💯💯💯💯💯💯💯 اوامر الحماية 🌒-فتح🔔قفل🔕 الاضافه 🌖-فتح🔔قفل🔕البوتات 🌒-فتح🔔قفل🔕 المجموعه 🌖-فتح🔔قفل🔕 الدردشه 🌒-فتح🔔قفل🔕 الصور 🌖-فتح🔔قفل🔕 الصوت 🌘-فتح🔔قفل🔕 الفيديو 🌖-فتح🔔قفل🔕 الروابط 🌘-فتح🔔قفل🔕 التكرار 🌖-فتح🔔قفل🔕 الملصقات 🌘-فتح🔔قفل🔕 الصور المتحركه 🌖-فتح🔔قفل🔕 الفايلات 🌘-فتح🔔قفل🔕 الكلايش 🌖-فتح🔔قفل🔕 الاضافه الجماعيه 🌘-فتح🔔قفل🔕 العربيه 🌖-فتح🔔قفل🔕اعاده توجيه الجيوش🌖-فتح🔔قفل🔕 〰〰〰〰〰〰〰〰〰〰 مسح+وضع 🌗-ضع التكرار⚙ لوضع التكرار بين 5 الى 20♻️ 🌓مسح رسائل المجموعه :لحذف جميع رسائل الكروب 🌗-مسح رسائل العضو: مسح جميع رسائل العضو بالرد ️🌓-مسح الادمنية : لحذف الادمنية ️🌗-مسح الوصف : لحذف الوصف ️🌓-مسح القوانين : لحذف القوانين ️🌗-مسح المعرف : لحذف معرف المجموعة 💥 -مسح : لمسح اي كلمه بل رد 💥 -ضع قوانين : اضافه قوانين 💥 -ضع وصف : اضافة حول 💥 -وضع اسم : لاضافة اسم 💥 -ضع معرف: لوضع معرف للكروب 💥 -وضع صوره : لاضافة صورة الانستا مع � -ايدي : لضهار ايدي الشخص بلرد 💥 -الرابط خاص : لجلب الرابط خاص 💥 -الرابط : لعرض الرابط 💥 -تغير الرابط : لصنع الرابط 🌕 مطور البوت : لمعرفه مطور البوت 💥 -صوره: لتحويل الملصق الى صورة ️🌓-انستا : + يوزر : يستعمل لجلب معلومات حساب الانستا مع الصور 💥-ايدي : لعرض ايدي المجموعه 💥 -معلوماتي :اضهار المعلومات الخاصه بك 💥 -معلومات المجموعه : لاضهار معلومات المجموعه 💥 -القوانين : لاضهار القوانين 💥-انستا : + يوزر : يستعمل لجلب معلومات حساب 💥-الطقس : + البلد لمعرفه درجه الحرارة وغيرها 💥-الاذان : + البلد لمعرفه اوقات صلاة 💥-خريطه: +البلد لظهار الخرائط 💥 زخرفه+ النص : لزخرفه بالعربيه 💥زخرف+ النص: لزخرفه بالنكليزيه 💥اسمي : لظهار اسمك الحالي 💥اسم الكروب : لظهار اسم الكروب بلفعل 💥رقمي ؛ لظهار رقمك الخاص بك :للتواصل مع المطور __________________ 🗯️ - Dev - @devss_bot من فضلك ان تابع القناة @help_tele ]] end if not is_momod(msg) then return "مو شغلك ودعبل 😎🖕🏿" end end return { description = "Help list", usage = "Help list", patterns = { "(م 1)" }, run = run } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
LuaRules/Gadgets/CAI/ScoutHandler.lua
9
1249
--[[ Handles the scouting unit job * Add units to this handler to have them controled by it. * Maintains a heatmap of locations to scout. * Requires perdiodic UpdateHeatmap and RunJobHandler. * Only one of these is needed per teamID. --]] local UnitListHandler = VFS.Include("LuaRules/Gadgets/CAI/UnitListHandler.lua") local spIsPosInLos = Spring.IsPosInLos local spGetCommandQueue = Spring.GetCommandQueue local GiveClampedOrderToUnit = Spring.Utilities.GiveClampedOrderToUnit local CMD_FIGHT = CMD.FIGHT local scoutHandler = {} function scoutHandler.CreateScoutHandler(scoutHeatmap) local scoutList = UnitListHandler.CreateUnitList() local function RunJobHandler() if scoutHeatmap.IsScoutingRequired() then for unitID,_ in scoutList.Iterator() do local cQueue = spGetCommandQueue(unitID, 1) if cQueue then if #cQueue == 0 then GiveClampedOrderToUnit(unitID, CMD_FIGHT, scoutHeatmap.GetPositionToScount(), {}) end else scoutList.RemoveUnit(unitID) end end end end local newScoutHandler = { AddUnit = scoutList.AddUnit, RemoveUnit = scoutList.RemoveUnit, GetTotalCost = scoutList.GetTotalCost, RunJobHandler = RunJobHandler, } return newScoutHandler end return scoutHandler
gpl-2.0
Scavenge/darkstar
scripts/zones/Ship_bound_for_Selbina/Zone.lua
17
1653
----------------------------------- -- -- Zone: Ship_bound_for_Selbina (220) -- ----------------------------------- package.loaded["scripts/zones/Ship_bound_for_Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Ship_bound_for_Selbina/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then local position = math.random(-2,2) + 0.150; player:setPos(position,-2.100,3.250,64); end if (player:hasKeyItem(SEANCE_STAFF) and player:getVar("Enagakure_Killed") == 0) then SpawnMob(17678351); end return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x00ff); 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 == 0x00ff) then player:setPos(0,0,0,0,248); end end;
gpl-3.0
angking0802wu/UniLua
Assets/StreamingAssets/LuaRoot/test/gc.lua
6
13779
print('testing garbage collection') collectgarbage() assert(collectgarbage("isrunning")) local function gcinfo () return collectgarbage"count" * 1024 end -- test weird parameters do -- save original parameters local a = collectgarbage("setpause", 200) local b = collectgarbage("setstepmul", 200) local t = {0, 2, 10, 90, 100, 500, 5000, 30000} for i = 1, #t do local p = t[i] for j = 1, #t do local m = t[j] collectgarbage("setpause", p) collectgarbage("setstepmul", m) collectgarbage("step", 0) collectgarbage("step", 10000) end end -- restore original parameters collectgarbage("setpause", a) collectgarbage("setstepmul", b) end _G["while"] = 234 limit = 5000 local function GC1 () local u local b -- must be declared after 'u' (to be above it in the stack) local finish = false u = setmetatable({}, {__gc = function () finish = true end}) b = {34} repeat u = {} until finish assert(b[1] == 34) -- 'u' was collected, but 'b' was not finish = false; local i = 1 u = setmetatable({}, {__gc = function () finish = true end}) repeat i = i + 1; u = i .. i until finish assert(b[1] == 34) -- 'u' was collected, but 'b' was not finish = false u = setmetatable({}, {__gc = function () finish = true end}) repeat local i; u = function () return i end until finish assert(b[1] == 34) -- 'u' was collected, but 'b' was not end local function GC() GC1(); GC1() end contCreate = 0 print('tables') while contCreate <= limit do local a = {}; a = nil contCreate = contCreate+1 end a = "a" contCreate = 0 print('strings') while contCreate <= limit do a = contCreate .. "b"; a = string.gsub(a, '(%d%d*)', string.upper) a = "a" contCreate = contCreate+1 end contCreate = 0 a = {} print('functions') function a:test () while contCreate <= limit do load(string.format("function temp(a) return 'a%d' end", contCreate))() assert(temp() == string.format('a%d', contCreate)) contCreate = contCreate+1 end end a:test() -- collection of functions without locals, globals, etc. do local f = function () end end print("functions with errors") prog = [[ do a = 10; function foo(x,y) a = sin(a+0.456-0.23e-12); return function (z) return sin(%x+z) end end local x = function (w) a=a+w; end end ]] do local step = 1 if _soft then step = 13 end for i=1, string.len(prog), step do for j=i, string.len(prog), step do pcall(load(string.sub(prog, i, j))) end end end foo = nil print('long strings') x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789" assert(string.len(x)==80) s = '' n = 0 k = 300 while n < k do s = s..x; n=n+1; j=tostring(n) end assert(string.len(s) == k*80) s = string.sub(s, 1, 20000) s, i = string.gsub(s, '(%d%d%d%d)', math.sin) assert(i==20000/4) s = nil x = nil assert(_G["while"] == 234) local k,b = collectgarbage("count") assert(k*1024 == math.floor(k)*1024 + b) print("steps") local bytes = gcinfo() while 1 do local nbytes = gcinfo() if nbytes < bytes then break end -- run until gc bytes = nbytes a = {} end print("steps (2)") local function dosteps (siz) assert(not collectgarbage("isrunning")) collectgarbage() assert(not collectgarbage("isrunning")) local a = {} for i=1,100 do a[i] = {{}}; local b = {} end local x = gcinfo() local i = 0 repeat -- do steps until it completes a collection cycle i = i+1 until collectgarbage("step", siz) assert(gcinfo() < x) return i end collectgarbage"stop" if not _port then -- test the "size" of basic GC steps (whatever they mean...) assert(dosteps(0) > 10) assert(dosteps(10) < dosteps(2)) end -- collector should do a full collection with so many steps assert(dosteps(100000) == 1) assert(collectgarbage("step", 1000000) == true) assert(collectgarbage("step", 1000000) == true) assert(not collectgarbage("isrunning")) collectgarbage"restart" assert(collectgarbage("isrunning")) if not _port then -- test the pace of the collector collectgarbage(); collectgarbage() local x = gcinfo() collectgarbage"stop" assert(not collectgarbage("isrunning")) repeat local a = {} until gcinfo() > 3 * x collectgarbage"restart" assert(collectgarbage("isrunning")) repeat local a = {} until gcinfo() <= x * 2 end print("clearing tables") lim = 15 a = {} -- fill a with `collectable' indices for i=1,lim do a[{}] = i end b = {} for k,v in pairs(a) do b[k]=v end -- remove all indices and collect them for n in pairs(b) do a[n] = nil assert(type(n) == 'table' and next(n) == nil) collectgarbage() end b = nil collectgarbage() for n in pairs(a) do error'cannot be here' end for i=1,lim do a[i] = i end for i=1,lim do assert(a[i] == i) end print('weak tables') a = {}; setmetatable(a, {__mode = 'k'}); -- fill a with some `collectable' indices for i=1,lim do a[{}] = i end -- and some non-collectable ones for i=1,lim do a[i] = i end for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end collectgarbage() local i = 0 for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end assert(i == 2*lim) a = {}; setmetatable(a, {__mode = 'v'}); a[1] = string.rep('b', 21) collectgarbage() assert(a[1]) -- strings are *values* a[1] = nil -- fill a with some `collectable' values (in both parts of the table) for i=1,lim do a[i] = {} end for i=1,lim do a[i..'x'] = {} end -- and some non-collectable ones for i=1,lim do local t={}; a[t]=t end for i=1,lim do a[i+lim]=i..'x' end collectgarbage() local i = 0 for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end assert(i == 2*lim) a = {}; setmetatable(a, {__mode = 'vk'}); local x, y, z = {}, {}, {} -- keep only some items a[1], a[2], a[3] = x, y, z a[string.rep('$', 11)] = string.rep('$', 11) -- fill a with some `collectable' values for i=4,lim do a[i] = {} end for i=1,lim do a[{}] = i end for i=1,lim do local t={}; a[t]=t end collectgarbage() assert(next(a) ~= nil) local i = 0 for k,v in pairs(a) do assert((k == 1 and v == x) or (k == 2 and v == y) or (k == 3 and v == z) or k==v); i = i+1 end assert(i == 4) x,y,z=nil collectgarbage() assert(next(a) == string.rep('$', 11)) -- 'bug' in 5.1 a = {} local t = {x = 10} local C = setmetatable({key = t}, {__mode = 'v'}) local C1 = setmetatable({[t] = 1}, {__mode = 'k'}) a.x = t -- this should not prevent 't' from being removed from -- weak table 'C' by the time 'a' is finalized setmetatable(a, {__gc = function (u) assert(C.key == nil) assert(type(next(C1)) == 'table') end}) a, t = nil collectgarbage() collectgarbage() assert(next(C) == nil and next(C1) == nil) C, C1 = nil -- ephemerons local mt = {__mode = 'k'} a = {10,20,30,40}; setmetatable(a, mt) x = nil for i = 1, 100 do local n = {}; a[n] = {k = {x}}; x = n end GC() local n = x local i = 0 while n do n = a[n].k[1]; i = i + 1 end assert(i == 100) x = nil GC() for i = 1, 4 do assert(a[i] == i * 10); a[i] = nil end assert(next(a) == nil) local K = {} a[K] = {} for i=1,10 do a[K][i] = {}; a[a[K][i]] = setmetatable({}, mt) end x = nil local k = 1 for j = 1,100 do local n = {}; local nk = k%10 + 1 a[a[K][nk]][n] = {x, k = k}; x = n; k = nk end GC() local n = x local i = 0 while n do local t = a[a[K][k]][n]; n = t[1]; k = t.k; i = i + 1 end assert(i == 100) K = nil GC() assert(next(a) == nil) -- testing errors during GC do collectgarbage("stop") -- stop collection local u = {} local s = {}; setmetatable(s, {__mode = 'k'}) setmetatable(u, {__gc = function (o) local i = s[o] s[i] = true assert(not s[i - 1]) -- check proper finalization order if i == 8 then error("here") end -- error during GC end}) for i = 6, 10 do local n = setmetatable({}, getmetatable(u)) s[n] = i end assert(not pcall(collectgarbage)) for i = 8, 10 do assert(s[i]) end for i = 1, 5 do local n = setmetatable({}, getmetatable(u)) s[n] = i end collectgarbage() for i = 1, 10 do assert(s[i]) end getmetatable(u).__gc = false -- __gc errors with non-string messages setmetatable({}, {__gc = function () error{} end}) local a, b = pcall(collectgarbage) assert(not a and type(b) == "string" and string.find(b, "error in __gc")) end print '+' -- testing userdata if T==nil then (Message or print)('\a\n >>> testC not active: skipping userdata GC tests <<<\n\a') else local function newproxy(u) return debug.setmetatable(T.newuserdata(0), debug.getmetatable(u)) end collectgarbage("stop") -- stop collection local u = newproxy(nil) debug.setmetatable(u, {__gc = true}) local s = 0 local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'}) for i=1,10 do a[newproxy(u)] = i end for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end local a1 = {}; for k,v in pairs(a) do a1[k] = v end for k,v in pairs(a1) do a[v] = k end for i =1,10 do assert(a[i]) end getmetatable(u).a = a1 getmetatable(u).u = u do local u = u getmetatable(u).__gc = function (o) assert(a[o] == 10-s) assert(a[10-s] == nil) -- udata already removed from weak table assert(getmetatable(o) == getmetatable(u)) assert(getmetatable(o).a[o] == 10-s) s=s+1 end end a1, u = nil assert(next(a) ~= nil) collectgarbage() assert(s==11) collectgarbage() assert(next(a) == nil) -- finalized keys are removed in two cycles end -- __gc x weak tables local u = setmetatable({}, {__gc = true}) -- __gc metamethod should be collected before running setmetatable(getmetatable(u), {__mode = "v"}) getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen u = nil collectgarbage() local u = setmetatable({}, {__gc = true}) local m = getmetatable(u) m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"}); m.__gc = function (o) assert(next(getmetatable(o).x) == nil) m = 10 end u, m = nil collectgarbage() assert(m==10) -- errors during collection u = setmetatable({}, {__gc = function () error "!!!" end}) u = nil assert(not pcall(collectgarbage)) if not _soft then print("deep structures") local a = {} for i = 1,200000 do a = {next = a} end collectgarbage() end -- create many threads with self-references and open upvalues local thread_id = 0 local threads = {} local function fn (thread) local x = {} threads[thread_id] = function() thread = x end coroutine.yield() end while thread_id < 1000 do local thread = coroutine.create(fn) coroutine.resume(thread, thread) thread_id = thread_id + 1 end do collectgarbage() collectgarbage"stop" local x = gcinfo() repeat for i=1,1000 do _ENV.a = {} end collectgarbage("step", 1) -- steps should not unblock the collector until gcinfo() > 2 * x collectgarbage"restart" end if T then -- tests for weird cases collecting upvalues local a = 1200 local f = function () return a end -- create upvalue for 'a' assert(f() == 1200) -- erase reference to upvalue 'a', mark it as dead, but does not collect it T.gcstate("pause"); collectgarbage("stop") f = nil T.gcstate("sweepstring") -- this function will reuse that dead upvalue... f = function () return a end assert(f() == 1200) -- create coroutine with local variable 'b' local co = coroutine.wrap(function() local b = 150 coroutine.yield(function () return b end) end) T.gcstate("pause") assert(co()() == 150) -- create upvalue for 'b' -- mark upvalue 'b' as dead, but does not collect it T.gcstate("sweepstring") co() -- finish coroutine, "closing" that dead upvalue assert(f() == 1200) collectgarbage("restart") print"+" end if T then local debug = require "debug" collectgarbage("generational"); collectgarbage("stop") x = T.newuserdata(0) T.gcstate("propagate") -- ensure 'x' is old T.gcstate("sweepstring") T.gcstate("propagate") assert(string.find(T.gccolor(x), "/old")) local y = T.newuserdata(0) debug.setmetatable(y, {__gc = true}) -- bless the new udata before... debug.setmetatable(x, {__gc = true}) -- ...the old one assert(string.find(T.gccolor(y), "white")) T.checkmemory() collectgarbage("incremental"); collectgarbage("restart") end if T then print("emergency collections") collectgarbage() collectgarbage() T.totalmem(T.totalmem() + 200) for i=1,200 do local a = {} end T.totalmem(1000000000) collectgarbage() local t = T.totalmem("table") local a = {{}, {}, {}} -- create 4 new tables assert(T.totalmem("table") == t + 4) t = T.totalmem("function") a = function () end -- create 1 new closure assert(T.totalmem("function") == t + 1) t = T.totalmem("thread") a = coroutine.create(function () end) -- create 1 new coroutine assert(T.totalmem("thread") == t + 1) end -- create an object to be collected when state is closed do local setmetatable,assert,type,print,getmetatable = setmetatable,assert,type,print,getmetatable local tt = {} tt.__gc = function (o) assert(getmetatable(o) == tt) -- create new objects during GC local a = 'xuxu'..(10+3)..'joao', {} ___Glob = o -- ressurect object! setmetatable({}, tt) -- creates a new one with same metatable print(">>> closing state " .. "<<<\n") end local u = setmetatable({}, tt) ___Glob = {u} -- avoid object being collected before program end end -- create several objects to raise errors when collected while closing state do local mt = {__gc = function (o) return o + 1 end} for i = 1,10 do -- create object and preserve it until the end table.insert(___Glob, setmetatable({}, mt)) end end -- just to make sure assert(collectgarbage'isrunning') print('OK')
mit
xincun/nginx-openresty-windows
LuaJIT-2.1-20150622/dynasm/dasm_x86.lua
116
58970
------------------------------------------------------------------------------ -- DynASM x86/x64 module. -- -- Copyright (C) 2005-2015 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.3.0", vernum = 10300, release = "2011-05-05", 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 = table.concat, table.sort local bit = bit or require("bit") local band, shl, shr = bit.band, 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", -- !x64: VREG support NYI. -- 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 ------------------------------------------------------------------------------ -- 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 -- 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" then name = format("xmm%d", 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 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") -- Operand size prefixes to codes. local map_opsize = { byte = "b", word = "w", dword = "d", qword = "q", oword = "o", tword = "t", aword = addrsize, } -- Operand size code to number. local map_opsizenum = { b = 1, w = 2, d = 4, q = 8, o = 16, t = 10, } -- Operand size code to name. local map_opsizename = { b = "byte", w = "word", d = "dword", q = "qword", o = "oword", 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) local r if rex ~= 0 and not x64 then werror("bad operand size") end 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 end end wputb(shr(op, 16)); op = band(op, 0xffff) end if op >= 256 then local b = shr(op, 8) if b == 15 and rex ~= 0 then wputb(64 + band(rex, 15)); rex = 0 end wputb(b) op = band(op, 255) end if rex ~= 0 then wputb(64 + band(rex, 15)) end if sz == "b" then op = op - 1 end wputb(op) 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) 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) if vsreg then waction("VREG", vsreg); wputxb(2) end if vreg then waction("VREG", vreg); wputxb(0) end 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 if vsreg then waction("VREG", vsreg); wputxb(2) end wputmodrm(t.xsc, xreg, 5) if vxreg then waction("VREG", vxreg); wputxb(3) end else -- Pure 32 bit displacement. if x64 and tdisp ~= "table" then wputmodrm(0, s, 4) -- [disp] -> (0, s, esp) (0, esp, ebp) if imark == "I" then waction("MARK") end wputmodrm(0, 4, 5) else riprel = x64 wputmodrm(0, s, 5) -- [disp|rip-label] -> (0, s, ebp) if imark == "I" then waction("MARK") end end if vsreg then waction("VREG", vsreg); wputxb(2) 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 if vsreg then waction("VREG", vsreg); wputxb(2) end wputmodrm(t.xsc or 0, xreg or 4, reg) -- SIB. if vxreg then waction("VREG", vxreg); wputxb(3) end if vreg then waction("VREG", vreg); wputxb(1) end 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 if vsreg then waction("VREG", vsreg); wputxb(2) end if vreg then waction("VREG", vreg); wputxb(1) end 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. -- -- 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 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|mrCqdw:0FA5Rm", shrd_3 = "mriqdw:0FACRmU|mrCqdw:0FADRm", rdtsc_0 = "0F31", -- P1+ 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:F20F2CrM|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", packssdw_2 = "rmo:660F6BrM", packsswb_2 = "rmo:660F63rM", packuswb_2 = "rmo:660F67rM", paddb_2 = "rmo:660FFCrM", paddd_2 = "rmo:660FFErM", paddq_2 = "rmo:660FD4rM", paddsb_2 = "rmo:660FECrM", paddsw_2 = "rmo:660FEDrM", paddusb_2 = "rmo:660FDCrM", paddusw_2 = "rmo:660FDDrM", paddw_2 = "rmo:660FFDrM", pand_2 = "rmo:660FDBrM", pandn_2 = "rmo:660FDFrM", pause_0 = "F390", pavgb_2 = "rmo:660FE0rM", pavgw_2 = "rmo:660FE3rM", pcmpeqb_2 = "rmo:660F74rM", pcmpeqd_2 = "rmo:660F76rM", pcmpeqw_2 = "rmo:660F75rM", pcmpgtb_2 = "rmo:660F64rM", pcmpgtd_2 = "rmo:660F66rM", pcmpgtw_2 = "rmo:660F65rM", pextrw_3 = "rri/do:660FC5rMU|xri/wo:660F3A15nrMU", -- Mem op: SSE4.1 only. pinsrw_3 = "rri/od:660FC4rMU|rxi/ow:", pmaddwd_2 = "rmo:660FF5rM", pmaxsw_2 = "rmo:660FEErM", pmaxub_2 = "rmo:660FDErM", pminsw_2 = "rmo:660FEArM", pminub_2 = "rmo:660FDArM", pmovmskb_2 = "rr/do:660FD7rM", pmulhuw_2 = "rmo:660FE4rM", pmulhw_2 = "rmo:660FE5rM", pmullw_2 = "rmo:660FD5rM", pmuludq_2 = "rmo:660FF4rM", por_2 = "rmo:660FEBrM", prefetchnta_1 = "xb:n0F180m", prefetcht0_1 = "xb:n0F181m", prefetcht1_1 = "xb:n0F182m", prefetcht2_1 = "xb:n0F183m", psadbw_2 = "rmo:660FF6rM", 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", psubb_2 = "rmo:660FF8rM", psubd_2 = "rmo:660FFArM", psubq_2 = "rmo:660FFBrM", psubsb_2 = "rmo:660FE8rM", psubsw_2 = "rmo:660FE9rM", psubusb_2 = "rmo:660FD8rM", psubusw_2 = "rmo:660FD9rM", psubw_2 = "rmo:660FF9rM", punpckhbw_2 = "rmo:660F68rM", punpckhdq_2 = "rmo:660F6ArM", punpckhqdq_2 = "rmo:660F6DrM", punpckhwd_2 = "rmo:660F69rM", punpcklbw_2 = "rmo:660F60rM", punpckldq_2 = "rmo:660F62rM", punpcklqdq_2 = "rmo:660F6CrM", punpcklwd_2 = "rmo:660F61rM", pxor_2 = "rmo:660FEFrM", 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 = "rmo: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 } ------------------------------------------------------------------------------ -- 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 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) end ------------------------------------------------------------------------------ -- Process pattern string. local function dopattern(pat, args, sz, op, needrex) local digit, addin 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 5 positions. if secpos+5 > 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 == "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 wputop(szov, opcode, rex); 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) addin = nil 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 wputop(szov, opcode - 7, rex) waction("VREG", addin.vreg); wputxb(0) else if addin and addin.reg > 7 then rex = rex + 1 end wputop(szov, opcode, rex) 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 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 -- Match both operand sizes. if args[1].opsize == sub(szm, 2, 2) and args[2].opsize == sub(szm, 3, 3) then dopattern(pat, args, sz, params.op, needrex) -- Process pattern. return 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 wputop(sz, opcode, rex) if vreg then waction("VREG", vreg); wputxb(0) end 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 ------------------------------------------------------------------------------
bsd-2-clause
Scavenge/darkstar
scripts/globals/items/boiled_crab.lua
12
1307
----------------------------------------- -- ID: 4456 -- Item: Boiled Crab -- Food Effect: 30Min, All Races ----------------------------------------- -- Vitality 2 -- defense % 27 -- defense % 50 ----------------------------------------- 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,4456); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_VIT, 2); target:addMod(MOD_FOOD_DEFP, 27); target:addMod(MOD_FOOD_DEF_CAP, 50); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_VIT, 2); target:delMod(MOD_FOOD_DEFP, 27); target:delMod(MOD_FOOD_DEF_CAP, 50); end;
gpl-3.0
cyclonetm/XmakanX
plugins/stats.lua
1
4166
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'cyclone' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /cyclone ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "cyclone" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/#$&@-+.*]([Ss]tats)$", "^([Ss]tats)$", "^[!/#$&@-+.*]([Ss]tatslist)$", "^([Ss]tatslist)$", "^[!/#$&@-+.*]([Ss]tats) (group) (%d+)", "^([Ss]tats) (group) (%d+)", "^[!/#$&@-+.*]([Ss]tats) (cyclone)",-- Put everything you like :) "^([Ss]tats) (cyclone)", "^[!/]([Cc]yclone)"-- Put everything you like :) "^([Cc]yclone)" }, run = run } end
gpl-2.0
jchuang1977/openwrt
package/lean/luci-app-adbyby-plus/luasrc/controller/adbyby.lua
1
3143
module("luci.controller.adbyby", package.seeall) function index() if not nixio.fs.access("/etc/config/adbyby") then return end entry({"admin", "services", "adbyby"}, alias("admin", "services", "adbyby", "base"), _("ADBYBY Plus +"), 9).dependent = true entry({"admin", "services", "adbyby", "base"}, cbi("adbyby/base"), _("Base Setting"), 10).leaf = true entry({"admin", "services", "adbyby", "advanced"}, cbi("adbyby/advanced"), _("Advance Setting"), 20).leaf = true entry({"admin", "services", "adbyby", "help"}, form("adbyby/help"), _("Plus+ Domain List"), 30).leaf = true entry({"admin", "services", "adbyby", "esc"}, form("adbyby/esc"), _("Bypass Domain List"), 40).leaf = true entry({"admin", "services", "adbyby", "black"}, form("adbyby/black"), _("Block Domain List"), 50).leaf = true entry({"admin", "services", "adbyby", "block"}, form("adbyby/block"), _("Block IP List"), 60).leaf = true entry({"admin", "services", "adbyby", "user"}, form("adbyby/user"), _("User-defined Rule"), 70).leaf = true entry({"admin", "services", "adbyby", "refresh"}, call("refresh_data")) entry({"admin", "services", "adbyby", "run"}, call("act_status")).leaf = true end function act_status() local e={} e.running=luci.sys.call("pgrep adbyby >/dev/null")==0 luci.http.prepare_content("application/json") luci.http.write_json(e) end function refresh_data() local set =luci.http.formvalue("set") local icount =0 if set == "rule_data" then luci.sys.exec("/usr/share/adbyby/rule-update") icount = luci.sys.exec("/usr/share/adbyby/rule-count '/tmp/rules/'") if tonumber(icount)>0 then if nixio.fs.access("/usr/share/adbyby/rules/") then oldcount=luci.sys.exec("/usr/share/adbyby/rule-count '/usr/share/adbyby/rules/'") else oldcount=0 end else retstring ="-1" end if tonumber(icount) ~= tonumber(oldcount) then luci.sys.exec("rm -f /usr/share/adbyby/rules/data/* /usr/share/adbyby/rules/host/* && cp -a /tmp/rules /usr/share/adbyby/") luci.sys.exec("/etc/init.d/adbyby restart &") retstring=tostring(math.ceil(tonumber(icount))) else retstring ="0" end else refresh_cmd="wget-ssl -q --no-check-certificate -O - 'https://easylist-downloads.adblockplus.org/easylistchina+easylist.txt' > /tmp/adnew.conf" sret=luci.sys.call(refresh_cmd .. " 2>/dev/null") if sret== 0 then luci.sys.call("/usr/share/adbyby/ad-update") icount = luci.sys.exec("cat /tmp/ad.conf | wc -l") if tonumber(icount)>0 then if nixio.fs.access("/usr/share/adbyby/dnsmasq.adblock") then oldcount=luci.sys.exec("cat /usr/share/adbyby/dnsmasq.adblock | wc -l") else oldcount=0 end if tonumber(icount) ~= tonumber(oldcount) then luci.sys.exec("cp -f /tmp/ad.conf /usr/share/adbyby/dnsmasq.adblock") luci.sys.exec("cp -f /tmp/ad.conf /tmp/etc/dnsmasq-adbyby.d/adblock") luci.sys.exec("/etc/init.d/adbyby restart &") retstring=tostring(math.ceil(tonumber(icount))) else retstring ="0" end else retstring ="-1" end luci.sys.exec("rm -f /tmp/ad.conf") else retstring ="-1" end end luci.http.prepare_content("application/json") luci.http.write_json({ ret=retstring ,retcount=icount}) end
gpl-2.0
novokrest/chdkptp
lua/gui_live.lua
5
17624
--[[ Copyright (C) 2010-2014 <reyalp (at) gmail dot com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ]] --[[ module for live view gui ]] local stats=require'gui_live_stats' local m={ vp_par = 2, -- pixel aspect ratio for viewport 1:n, n=1,2 bm_par = 1, -- pixel aspect ratio for bitmap 1:n, n=1,2 vp_aspect_factor = 1, -- correction factor for height values when scaling for aspect --[[ note - these are 'private' but exposed in the module for easier debugging container -- outermost widget icnv -- iup canvas vp_active -- viewport streaming selected bm_active -- bitmap streaming selected timer -- timer for fetching updates statslabel -- text for stats ]] skip_frames = 0, -- number of frames to drop based on how much longer than desired rate the last one took skip_count = 0, -- total number skipped } local screen_aspects = { [0]=4/3, 16/9, } function m.live_support() local caps = guisys.caps() return (caps.CD and caps.LIVEVIEW) end function m.get_current_frame_data() if m.dump_replay then return m.dump_replay_frame end return con.live end local vp_toggle=iup.toggle{ title="Viewfinder", action=function(self,state) m.vp_active = (state == 1) end, } local bm_toggle = iup.toggle{ title="UI Overlay", action=function(self,state) m.bm_active = (state == 1) end, } local aspect_toggle = iup.toggle{ title="Scale for A/R", value="ON", } local function get_fb_selection() local what=0 if m.vp_active then what = 1 end if m.bm_active then what = what + 4 what = what + 8 -- palette TODO shouldn't request if we don't understand type, but palette type is in dynamic data end return what end --[[ update canvas size from frame ]] local function update_canvas_size() local lv = m.get_current_frame_data() if not lv then return end local vp_w = lv.vp:get_screen_width()/m.vp_par local vp_h if aspect_toggle.value == 'ON' then vp_h = vp_w/screen_aspects[lv.lcd_aspect_ratio] m.vp_aspect_factor = vp_h/lv.vp:get_screen_height() else m.vp_aspect_factor = 1 vp_h = lv.vp:get_screen_height() end local w,h = gui.parsesize(m.icnv.rastersize) local update if w ~= vp_w then update = true end if h ~= vp_h then update = true end if update then m.icnv.rastersize = vp_w.."x"..vp_h iup.Refresh(m.container) gui.resize_for_content() end end local vp_par_toggle = iup.toggle{ title="Viewfinder 1:1", action=function(self,state) if state == 1 then m.vp_par = 1 else m.vp_par = 2 end end, } local bm_par_toggle = iup.toggle{ title="Overlay 1:1", value="1", action=function(self,state) if state == 1 then m.bm_par = 1 else m.bm_par = 2 end end, } local bm_fit_toggle = iup.toggle{ title="Overlay fit", value="ON", } local function update_should_run() -- is the tab current? if m.tabs.value ~= m.container then return false end -- is any view active if not (m.vp_active or m.bm_active) then return false end -- in dump replay if m.dump_replay then return true end if not m.live_con_valid then return false end -- return soft status, connection errors will reset quickly return gui.last_connection_status end local last_frame_fields = {} local last_fb_fields = { vp={}, bm={} } local last_bm_fields = {} local palette_size_for_type={ 16*4, 16*4, 256*4, 16*4, } -- reset last frame fields so reload or new connection will be a "change" local function reset_last_frame_vals() for i,f in ipairs(chdku.live_fields) do last_frame_fields[f]=nil end for j,fb in ipairs({'vp','bm'}) do for i,f in ipairs(chdku.live_fb_desc_fields) do last_fb_fields[fb][f]=nil end end end local function update_frame_data(frame) local dirty for i,f in ipairs(chdku.live_fields) do local v = frame[f] if v ~= last_frame_fields[f] then dirty = true end end for j,fb in ipairs({'vp','bm'}) do for i,f in ipairs(chdku.live_fb_desc_fields) do local v = frame[fb][f] if v ~= last_fb_fields[fb][f] then dirty = true end end end if dirty then gui.dbgmsg('update_frame_data: changed\n') for i,f in ipairs(chdku.live_fields) do local v = frame[f] gui.dbgmsg("%s:%s->%s\n",f,tostring(last_frame_fields[f]),v) last_frame_fields[f]=v end for j,fb in ipairs({'vp','bm'}) do for i,f in ipairs(chdku.live_fb_desc_fields) do local v = frame[fb][f] gui.dbgmsg("%s.%s:%s->%s\n",fb,f,tostring(last_fb_fields[fb][f]),v) last_fb_fields[fb][f]=v end end -- for big palettes this lags, optional if prefs.gui_dump_palette and last_frame_fields.palette_data_start > 0 then printf('palette:\n') local c=0 local bytes = {frame._frame:byte(last_frame_fields.palette_data_start+1, last_frame_fields.palette_data_start+palette_size_for_type[last_frame_fields.palette_type])} for i,v in ipairs(bytes) do printf("0x%02x,",v) c = c + 1 if c == 16 then printf('\n') c=0 else printf(' ') end end end end end -- TODO this is just to allow us to read/write a binary integer record size local dump_recsize = lbuf.new(4) --[[ lbuf - optional lbuf to re-use, if possible fh - file handle returns (possibly new) lbuf or nil on eof ]] local function read_dump_rec(lb,fh) if not dump_recsize:fread(fh) then return end local len = dump_recsize:get_u32() if not lb or lb:len() ~= len then lb = lbuf.new(len) end if lb:fread(fh) then -- on EOF, return nil return lb end end local function init_dump_replay() m.dump_replay = false m.dump_replay_file = io.open(m.dump_replay_filename,"rb") if not m.dump_replay_file then printf("failed to open dumpfile\n") return end local magic = m.dump_replay_file:read(4) if magic ~= 'chlv' then printf("unrecognized file\n") return end reset_last_frame_vals() -- m.dump_replay_file:seek('set',4) local header = read_dump_rec(nil,m.dump_replay_file) if not header then printf("failed to read header\n") return end -- TODO should be defined somewhere if header:get_u32() ~= 1 then printf("incompatible version %s\n",tostring(header:get_u32())) return end gui.infomsg("loading dump ver %s.%s\n",tostring(header:get_u32()),tostring(header:get_u32(4))) m.dump_replay = true if not m.dump_replay_frame then m.dump_replay_frame = chdku.live_wrap() end end local function end_dump_replay() m.dump_replay = false m.dump_replay_file:close() m.dump_replay_file=nil m.dump_replay_frame=nil stats:stop() end local function read_dump_frame() stats:start() stats:start_xfer() local data = read_dump_rec(m.dump_replay_frame._frame,m.dump_replay_file) -- EOF, loop if not data then end_dump_replay() init_dump_replay() data = read_dump_rec(m.dump_replay_frame._frame,m.dump_replay_file) end m.dump_replay_frame._frame = data if prefs.gui_force_replay_palette ~= -1 then m.dump_replay_frame._frame:set_u32(chdku.live_frame_map.palette_type,prefs.gui_force_replay_palette) end update_frame_data(m.dump_replay_frame) stats:end_xfer(m.dump_replay_frame._frame:len()) -- TODO update_canvas_size() end local function end_dump() if con.live and con.live.dump_fh then gui.infomsg('%d bytes recorded to %s\n',tonumber(con.live.dump_size),tostring(con.live.dump_fn)) con:live_dump_end() end end local function record_dump() if not m.dump_active then return end if not con.live.dump_fh then local status,err = con:live_dump_start() if not status then printf('error starting dump:%s\n',tostring(err)) m.dump_active = false -- TODO update checkbox return end printf('recording to %s\n',con.live.dump_fn) end local status,err = con:live_dump_frame() if not status then printf('error dumping frame:%s\n',tostring(err)) end_dump() m.dump_active = false end end local function toggle_dump(ih,state) m.dump_active = (state == 1) -- TODO this should be called on disconnect etc if not m.dumpactive then end_dump() end end local function toggle_play_dump(self,state) if state == 1 then local filedlg = iup.filedlg{ dialogtype = "OPEN", title = "File to play", filter = "*.lvdump", } filedlg:popup (iup.ANYWHERE, iup.ANYWHERE) local status = filedlg.status local value = filedlg.value if status ~= "0" then gui.dbgmsg('play dump canceled\n') self.value = "OFF" return end gui.infomsg('playing %s\n',tostring(value)) m.dump_replay_filename = value init_dump_replay() else end_dump_replay() end end local function timer_action(self) if update_should_run() then -- not keeping up, skip if m.skip_frames > 0 then m.skip_count = m.skip_count + 1 m.skip_frames = m.skip_frames - 1 return end if m.dump_replay then read_dump_frame() m.icnv:action() else stats:start() local what=get_fb_selection() if what == 0 then return end stats:start_xfer() local status,err = con:live_get_frame(what) if not status then end_dump() printf('error getting frame: %s\n',tostring(err)) gui.update_connection_status() -- update connection status on error, to prevent spamming stats:stop() else stats:end_xfer(con.live._frame:len()) update_frame_data(con.live) record_dump() update_canvas_size() end end m.icnv:action() local total_time = stats:get_last_total_ms() if prefs.gui_live_dropframes and total_time > m.frame_time then -- skipping ones seems to be enough, just letting the normal -- gui run for a short time would probably do it too m.skip_frames = 1 end else stats:stop() end m.statslabel.title = stats:get() .. string.format('\nDropped: %d',m.skip_count) end function m.set_frame_time(time) m.frame_time = time if prefs.gui_live_sched then if m.timer then iup.Destroy(m.timer) m.timer=nil end if not m.sched then m.sched=gui.sched.run_repeat(m.frame_time,function() local cstatus,msg = xpcall(timer_action,errutil.format) if not cstatus then printf('live timer update error\n%s',tostring(msg)) -- TODO could stop live updates here, for now just spam the console end end) else m.sched.time = m.frame_time end else if m.sched then m.sched:cancel() m.sched=nil end if m.timer then iup.Destroy(m.timer) end m.timer = iup.timer{ time = tostring(m.frame_time), action_cb = function() -- use xpcall so we don't get a popup every frame local cstatus,msg = xpcall(timer_action,errutil.format) if not cstatus then printf('live timer update error\n%s',tostring(msg)) -- TODO could stop live updates here, for now just spam the console end end, } end m.update_run_state() end local function update_fps(val) val = tonumber(val) if val == 0 then return end val = math.floor(1000/val) if val ~= m.frame_time then stats:stop() m.set_frame_time(val) end end local function redraw_canvas(self) if m.tabs.value ~= m.container then return; end local ccnv = self.dccnv stats:start_frame() ccnv:Activate() ccnv:Clear() local lv = m.get_current_frame_data() if lv and lv._frame then if m.vp_active then m.vp_img = liveimg.get_viewport_pimg(m.vp_img,lv._frame,m.vp_par == 2) if m.vp_img then if aspect_toggle.value == "ON" then m.vp_img:put_to_cd_canvas(ccnv, lv.vp.margin_left/m.vp_par, lv.vp.margin_bot*m.vp_aspect_factor, m.vp_img:width(), m.vp_img:height()*m.vp_aspect_factor) else m.vp_img:put_to_cd_canvas(ccnv, lv.vp.margin_left/m.vp_par, lv.vp.margin_bot) end end end if m.bm_active then m.bm_img = liveimg.get_bitmap_pimg(m.bm_img,lv._frame,m.bm_par == 2) if m.bm_img then -- NOTE bitmap assumed fullscreen, margins ignored if bm_fit_toggle.value == "ON" then m.bm_img:blend_to_cd_canvas(ccnv, 0, 0, lv.vp:get_screen_width()/m.vp_par, lv.vp:get_screen_height()*m.vp_aspect_factor) else m.bm_img:blend_to_cd_canvas(ccnv, 0, lv.vp:get_screen_height() - lv.bm.visible_height) end else print('no bm') end end end ccnv:Flush() stats:end_frame() end function m.init() if not m.live_support() then return false end local icnv = iup.canvas{rastersize="360x240",border="NO",expand="NO"} m.icnv = icnv m.statslabel = iup.label{size="90x64",alignment="ALEFT:ATOP"} m.container = iup.hbox{ iup.frame{ icnv, }, iup.vbox{ iup.frame{ iup.vbox{ vp_toggle, bm_toggle, vp_par_toggle, bm_par_toggle, bm_fit_toggle, aspect_toggle, iup.hbox{ iup.label{title="Target FPS"}, iup.text{ spin="YES", spinmax="30", spinmin="1", spininc="1", value="10", action=function(self,c,newval) local v = tonumber(newval) local min = tonumber(self.spinmin) local max = tonumber(self.spinmax) if v and v >= min and v <= max then self.value = tostring(v) self.caretpos = string.len(tostring(v)) update_fps(self.value) end return iup.IGNORE end, spin_cb=function(self,newval) update_fps(newval) end }, }, iup.button{ title="Screenshot", action=function(self) -- quick n dirty screenshot local cnv = icnv.dccnv local w,h = cnv:GetSize() local bm = cd.CreateBitmap(w,h,cd.RGB) cnv:GetBitmap(bm,0,0) local lb=lbuf.new(w*h*3) local o=0 for y=h-1,0,-1 do for x=0,w-1 do lb:set_u8(o,bm.r[y*w + x]) o=o+1 lb:set_u8(o,bm.g[y*w + x]) o=o+1 lb:set_u8(o,bm.b[y*w + x]) o=o+1 end end cd.KillBitmap(bm) local filename = 'chdkptp_'..os.date('%Y%m%d_%H%M%S')..'.ppm' local fh, err = io.open(filename,'wb') if not fh then warnf("failed to open %s: %s",tostring(filename),tostring(err)) return end fh:write(string.format('P6\n%d\n%d\n%d\n', w, h,255)) lb:fwrite(fh) fh:close() gui.infomsg('wrote %dx%d ppm %s\n',w,h,tostring(filename)) end }, }, title="Stream" }, iup.tabs{ iup.vbox{ m.statslabel, tabtitle="Statistics", }, iup.vbox{ tabtitle="Debug", iup.toggle{title="Dump to file",action=toggle_dump}, iup.toggle{title="Play from file",action=toggle_play_dump}, iup.button{ title="Quick dump", action=function() add_status(cli:execute('lvdump')) end, }, }, }, }, margin="4x4", ngap="4" } function icnv:map_cb() if prefs.gui_context_plus then -- TODO UseContextPlus seems harmless if not built with plus support if guisys.caps().CDPLUS then cd.UseContextPlus(true) gui.infomsg("ContexIsPlus iup:%s cd:%s\n",tostring(cd.ContextIsPlus(cd.IUP)),tostring(cd.ContextIsPlus(cd.DBUFFER))) else gui.infomsg("context_plus requested but not available\n") end end self.ccnv = cd.CreateCanvas(cd.IUP,self) self.dccnv = cd.CreateCanvas(cd.DBUFFER,self.ccnv) if prefs.gui_context_plus and guisys.caps().CDPLUS then cd.UseContextPlus(false) end self.dccnv:SetBackground(cd.EncodeColor(32,32,32)) end icnv.action=redraw_canvas function icnv:unmap_cb() self.dccnv:Kill() self.ccnv:Kill() end function icnv:resize_cb(w,h) gui.dbgmsg("Resize: Width="..w.." Height="..h..'\n') end m.container_title='Live' end function m.set_tabs(tabs) m.tabs = tabs end function m.get_container() return m.container end function m.get_container_title() return m.container_title end function m.on_connect_change(lcon) m.live_con_valid = false if con:is_connected() then reset_last_frame_vals() if con:live_is_api_compatible() then m.live_con_valid = true else warnf('camera live view protocol not supported by this client, live view disabled') end end end -- check whether we should be running, update timer function m.update_run_state(state) if state == nil then state = (m.tabs.value == m.container) end if state then if m.timer then m.timer.run = "YES" end m.skip_frames = 0 m.skip_count = 0 stats:start() else if m.timer then m.timer.run = "NO" end stats:stop() end end function m.on_tab_change(new,old) if not m.live_support() then return end if new == m.container then m.update_run_state(true) else m.update_run_state(false) end end -- for anything that needs to be intialized when everything is started function m.on_dlg_run() m.set_frame_time(100) end prefs._add('gui_live_sched','boolean','use scheduler for live updates',false, nil, function(self,val) self.value = val if m.frame_time then m.set_frame_time(m.frame_time) end end ) -- windows degrades gracefully if req rate is too high prefs._add('gui_live_dropframes','boolean','drop frames if target fps too high',(sys.ostype() ~= 'Windows')) prefs._add('gui_dump_palette','boolean','dump live palette data on state change') prefs._add('gui_context_plus','boolean','use IUP context plus if available') prefs._add('gui_force_replay_palette','number','override palette type dump replay, -1 disable',-1) return m
gpl-2.0
Scavenge/darkstar
scripts/zones/Dangruf_Wadi/npcs/_5b1.lua
14
2971
----------------------------------- -- Area: Dangruf Wadi -- NPC: Strange Apparatus -- @pos -494 -4 -100 191 ----------------------------------- package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil; require("scripts/zones/Dangruf_Wadi/TextIDs"); require("scripts/globals/strangeapparatus"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local trade = tradeToStrApp(player, trade); if (trade ~= nil) then if ( trade == 1) then -- good trade local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor end player:startEvent(0x0003, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0); else -- wrong chip, spawn elemental nm spawnElementalNM(player); delStrAppDocStatus(player); player:messageSpecial(SYS_OVERLOAD); player:messageSpecial(YOU_LOST_THE, trade); end else -- Invalid trade, lose doctor status delStrAppDocStatus(player); player:messageSpecial(DEVICE_NOT_WORKING); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local docStatus = 0; -- Assistant if (hasStrAppDocStatus(player)) then docStatus = 1; -- Doctor else player:setLocalVar( "strAppPass", 1); end player:startEvent(0x0001, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u", option); if (csid == 0x0001) then if (hasStrAppDocStatus(player) == false) then local docStatus = 1; -- Assistant if ( option == strAppPass(player)) then -- Good password docStatus = 0; -- Doctor giveStrAppDocStatus(player); end player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0003) then local drop = player:getLocalVar("strAppDrop"); local dropQty = player:getLocalVar("strAppDropQty"); if (drop ~= 0) then if ( dropQty == 0) then dropQty = 1; end player:addItem(drop, dropQty); player:setLocalVar("strAppDrop", 0); player:setLocalVar("strAppDropQty", 0); end end end;
gpl-3.0
Kyklas/luci-proto-hso
applications/luci-ntpc/luasrc/model/cbi/ntpc/ntpc.lua
68
1501
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("ntpclient", translate("Time Synchronisation"), translate("Synchronizes the system time")) s = m:section(TypedSection, "ntpclient", translate("General")) s.anonymous = true s.addremove = false s:option(DummyValue, "_time", translate("Current system time")).value = os.date("%c") interval = s:option(Value, "interval", translate("Update interval (in seconds)")) interval.datatype = "and(uinteger,min(1))" interval.rmempty = true count = s:option(Value, "count", translate("Count of time measurements"), translate("empty = infinite")) count.datatype = "and(uinteger,min(1))" count.rmempty = true s2 = m:section(TypedSection, "ntpdrift", translate("Clock Adjustment")) s2.anonymous = true s2.addremove = false freq = s2:option(Value, "freq", translate("Offset frequency")) freq.datatype = "integer" freq.rmempty = true s3 = m:section(TypedSection, "ntpserver", translate("Time Servers")) s3.anonymous = true s3.addremove = true s3.template = "cbi/tblsection" s3:option(Value, "hostname", translate("Hostname")) port = s3:option(Value, "port", translate("Port")) port.datatype = "port" port.rmempty = true return m
apache-2.0
1yvT0s/luvit
examples/stream/libs/wait.lua
11
1307
local coroutine = require('coroutine') local debug = require 'debug' local fiber = {} function fiber.new(block) return function (callback) local paused local co = coroutine.create(block) local function formatError(err) local stack = debug.traceback(co, tostring(err)) if type(err) == "table" then err.message = stack return err end return stack end local function check(success, ...) if not success then if callback then return callback(formatError(...)) else error(formatError(...)) end end if not paused then return callback and callback(nil, ...) end paused = false end local function wait(fn) if type(fn) ~= "function" then error("can only wait on functions") end local sync, ret fn(function (...) if sync == nil then sync = true ret = {...} return end check(coroutine.resume(co, ...)) end) if sync then return unpack(ret) end sync = false paused = true return coroutine.yield() end local function await(fn) local results = {wait(fn)} if results[1] then error(results[1]) end return unpack(results, 2) end check(coroutine.resume(co, wait, await)) end end return fiber
apache-2.0
Scavenge/darkstar
scripts/zones/Caedarva_Mire/npcs/Seaprince_s_Tombstone.lua
14
1026
----------------------------------- -- Area: Caedarva Mire -- NPC: Seaprince's Tombstone -- Involved in quest: Forging a New Myth -- @pos -433 7 -586 79 ----------------------------------- package.loaded["scripts/zones/Caedarva_Mire/TextIDs"] = nil; require("scripts/zones/Caedarva_Mire/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SEAPRINCES_TOMBSTONE); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/weaponskills/aeolian_edge.lua
24
1470
-- Aeolian Edge -- Dagger weapon skill -- Delivers an area attack that deals wind elemental damage. Damage varies with TP. -- Skill Level: 290 -- Aligned with the Breeze Gorget, Soil Gorget & Thunder Gorget. -- Aligned with the Breeze Belt, Soil Belt & Thunder Belt. -- Element: Wind -- Skillchain Properties: Impaction / Scission / Detonation -- Modifiers: DEX:28%; INT:28% -- 100%TP 200%TP 300%TP -- 2.75 3.50 4 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.ftp100 = 2.75; params.ftp200 = 3.50; params.ftp300 = 4; params.str_wsc = 0.0; params.dex_wsc = 0.28; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.28; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_WIND; params.skill = SKILL_DAG; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 2; params.ftp200 = 3; params.ftp300 = 4.5; -- https://www.bg-wiki.com/bg/Aeolian_Edge params.dex_wsc = 0.4;params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
xincun/nginx-openresty-windows
lua-resty-mysql-0.15/lib/resty/mysql.lua
9
20190
-- Copyright (C) 2012 Yichun Zhang (agentzh) local bit = require "bit" local sub = string.sub local tcp = ngx.socket.tcp local strbyte = string.byte local strchar = string.char local strfind = string.find local format = string.format local strrep = string.rep local null = ngx.null local band = bit.band local bxor = bit.bxor local bor = bit.bor local lshift = bit.lshift local rshift = bit.rshift local tohex = bit.tohex local sha1 = ngx.sha1_bin local concat = table.concat local unpack = unpack local setmetatable = setmetatable local error = error local tonumber = tonumber if not ngx.config or not ngx.config.ngx_lua_version or ngx.config.ngx_lua_version < 9011 then error("ngx_lua 0.9.11+ required") end local ok, new_tab = pcall(require, "table.new") if not ok then new_tab = function (narr, nrec) return {} end end local _M = { _VERSION = '0.15' } -- constants local STATE_CONNECTED = 1 local STATE_COMMAND_SENT = 2 local COM_QUERY = 0x03 local CLIENT_SSL = 0x0800 local SERVER_MORE_RESULTS_EXISTS = 8 -- 16MB - 1, the default max allowed packet size used by libmysqlclient local FULL_PACKET_SIZE = 16777215 local mt = { __index = _M } -- mysql field value type converters local converters = new_tab(0, 8) for i = 0x01, 0x05 do -- tiny, short, long, float, double converters[i] = tonumber end -- converters[0x08] = tonumber -- long long converters[0x09] = tonumber -- int24 converters[0x0d] = tonumber -- year converters[0xf6] = tonumber -- newdecimal local function _get_byte2(data, i) local a, b = strbyte(data, i, i + 1) return bor(a, lshift(b, 8)), i + 2 end local function _get_byte3(data, i) local a, b, c = strbyte(data, i, i + 2) return bor(a, lshift(b, 8), lshift(c, 16)), i + 3 end local function _get_byte4(data, i) local a, b, c, d = strbyte(data, i, i + 3) return bor(a, lshift(b, 8), lshift(c, 16), lshift(d, 24)), i + 4 end local function _get_byte8(data, i) local a, b, c, d, e, f, g, h = strbyte(data, i, i + 7) -- XXX workaround for the lack of 64-bit support in bitop: local lo = bor(a, lshift(b, 8), lshift(c, 16), lshift(d, 24)) local hi = bor(e, lshift(f, 8), lshift(g, 16), lshift(h, 24)) return lo + hi * 4294967296, i + 8 -- return bor(a, lshift(b, 8), lshift(c, 16), lshift(d, 24), lshift(e, 32), -- lshift(f, 40), lshift(g, 48), lshift(h, 56)), i + 8 end local function _set_byte2(n) return strchar(band(n, 0xff), band(rshift(n, 8), 0xff)) end local function _set_byte3(n) return strchar(band(n, 0xff), band(rshift(n, 8), 0xff), band(rshift(n, 16), 0xff)) end local function _set_byte4(n) return strchar(band(n, 0xff), band(rshift(n, 8), 0xff), band(rshift(n, 16), 0xff), band(rshift(n, 24), 0xff)) end local function _from_cstring(data, i) local last = strfind(data, "\0", i, true) if not last then return nil, nil end return sub(data, i, last), last + 1 end local function _to_cstring(data) return data .. "\0" end local function _to_binary_coded_string(data) return strchar(#data) .. data end local function _dump(data) local len = #data local bytes = new_tab(len, 0) for i = 1, len do bytes[i] = format("%x", strbyte(data, i)) end return concat(bytes, " ") end local function _dumphex(data) local len = #data local bytes = new_tab(len, 0) for i = 1, len do bytes[i] = tohex(strbyte(data, i), 2) end return concat(bytes, " ") end local function _compute_token(password, scramble) if password == "" then return "" end local stage1 = sha1(password) local stage2 = sha1(stage1) local stage3 = sha1(scramble .. stage2) local n = #stage1 local bytes = new_tab(n, 0) for i = 1, n do bytes[i] = strchar(bxor(strbyte(stage3, i), strbyte(stage1, i))) end return concat(bytes) end local function _send_packet(self, req, size) local sock = self.sock self.packet_no = self.packet_no + 1 -- print("packet no: ", self.packet_no) local packet = _set_byte3(size) .. strchar(self.packet_no) .. req -- print("sending packet: ", _dump(packet)) -- print("sending packet... of size " .. #packet) return sock:send(packet) end local function _recv_packet(self) local sock = self.sock local data, err = sock:receive(4) -- packet header if not data then return nil, nil, "failed to receive packet header: " .. err end --print("packet header: ", _dump(data)) local len, pos = _get_byte3(data, 1) --print("packet length: ", len) if len == 0 then return nil, nil, "empty packet" end if len > self._max_packet_size then return nil, nil, "packet size too big: " .. len end local num = strbyte(data, pos) --print("recv packet: packet no: ", num) self.packet_no = num data, err = sock:receive(len) --print("receive returned") if not data then return nil, nil, "failed to read packet content: " .. err end --print("packet content: ", _dump(data)) --print("packet content (ascii): ", data) local field_count = strbyte(data, 1) local typ if field_count == 0x00 then typ = "OK" elseif field_count == 0xff then typ = "ERR" elseif field_count == 0xfe then typ = "EOF" elseif field_count <= 250 then typ = "DATA" end return data, typ end local function _from_length_coded_bin(data, pos) local first = strbyte(data, pos) --print("LCB: first: ", first) if not first then return nil, pos end if first >= 0 and first <= 250 then return first, pos + 1 end if first == 251 then return null, pos + 1 end if first == 252 then pos = pos + 1 return _get_byte2(data, pos) end if first == 253 then pos = pos + 1 return _get_byte3(data, pos) end if first == 254 then pos = pos + 1 return _get_byte8(data, pos) end return false, pos + 1 end local function _from_length_coded_str(data, pos) local len len, pos = _from_length_coded_bin(data, pos) if len == nil or len == null then return null, pos end return sub(data, pos, pos + len - 1), pos + len end local function _parse_ok_packet(packet) local res = new_tab(0, 5) local pos res.affected_rows, pos = _from_length_coded_bin(packet, 2) --print("affected rows: ", res.affected_rows, ", pos:", pos) res.insert_id, pos = _from_length_coded_bin(packet, pos) --print("insert id: ", res.insert_id, ", pos:", pos) res.server_status, pos = _get_byte2(packet, pos) --print("server status: ", res.server_status, ", pos:", pos) res.warning_count, pos = _get_byte2(packet, pos) --print("warning count: ", res.warning_count, ", pos: ", pos) local message = sub(packet, pos) if message and message ~= "" then res.message = message end --print("message: ", res.message, ", pos:", pos) return res end local function _parse_eof_packet(packet) local pos = 2 local warning_count, pos = _get_byte2(packet, pos) local status_flags = _get_byte2(packet, pos) return warning_count, status_flags end local function _parse_err_packet(packet) local errno, pos = _get_byte2(packet, 2) local marker = sub(packet, pos, pos) local sqlstate if marker == '#' then -- with sqlstate pos = pos + 1 sqlstate = sub(packet, pos, pos + 5 - 1) pos = pos + 5 end local message = sub(packet, pos) return errno, message, sqlstate end local function _parse_result_set_header_packet(packet) local field_count, pos = _from_length_coded_bin(packet, 1) local extra extra = _from_length_coded_bin(packet, pos) return field_count, extra end local function _parse_field_packet(data) local col = new_tab(0, 2) local catalog, db, table, orig_table, orig_name, charsetnr, length local pos catalog, pos = _from_length_coded_str(data, 1) --print("catalog: ", col.catalog, ", pos:", pos) db, pos = _from_length_coded_str(data, pos) table, pos = _from_length_coded_str(data, pos) orig_table, pos = _from_length_coded_str(data, pos) col.name, pos = _from_length_coded_str(data, pos) orig_name, pos = _from_length_coded_str(data, pos) pos = pos + 1 -- ignore the filler charsetnr, pos = _get_byte2(data, pos) length, pos = _get_byte4(data, pos) col.type = strbyte(data, pos) --[[ pos = pos + 1 col.flags, pos = _get_byte2(data, pos) col.decimals = strbyte(data, pos) pos = pos + 1 local default = sub(data, pos + 2) if default and default ~= "" then col.default = default end --]] return col end local function _parse_row_data_packet(data, cols, compact) local pos = 1 local ncols = #cols local row if compact then row = new_tab(ncols, 0) else row = new_tab(0, ncols) end for i = 1, ncols do local value value, pos = _from_length_coded_str(data, pos) local col = cols[i] local typ = col.type local name = col.name --print("row field value: ", value, ", type: ", typ) if value ~= null then local conv = converters[typ] if conv then value = conv(value) end end if compact then row[i] = value else row[name] = value end end return row end local function _recv_field_packet(self) local packet, typ, err = _recv_packet(self) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ ~= 'DATA' then return nil, "bad field packet type: " .. typ end -- typ == 'DATA' return _parse_field_packet(packet) end function _M.new(self) local sock, err = tcp() if not sock then return nil, err end return setmetatable({ sock = sock }, mt) end function _M.set_timeout(self, timeout) local sock = self.sock if not sock then return nil, "not initialized" end return sock:settimeout(timeout) end function _M.connect(self, opts) local sock = self.sock if not sock then return nil, "not initialized" end local max_packet_size = opts.max_packet_size if not max_packet_size then max_packet_size = 1024 * 1024 -- default 1 MB end self._max_packet_size = max_packet_size local ok, err self.compact = opts.compact_arrays local database = opts.database or "" local user = opts.user or "" local pool = opts.pool local host = opts.host if host then local port = opts.port or 3306 if not pool then pool = user .. ":" .. database .. ":" .. host .. ":" .. port end ok, err = sock:connect(host, port, { pool = pool }) else local path = opts.path if not path then return nil, 'neither "host" nor "path" options are specified' end if not pool then pool = user .. ":" .. database .. ":" .. path end ok, err = sock:connect("unix:" .. path, { pool = pool }) end if not ok then return nil, 'failed to connect: ' .. err end local reused = sock:getreusedtimes() if reused and reused > 0 then self.state = STATE_CONNECTED return 1 end local packet, typ, err = _recv_packet(self) if not packet then return nil, err end if typ == "ERR" then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end self.protocol_ver = strbyte(packet) --print("protocol version: ", self.protocol_ver) local server_ver, pos = _from_cstring(packet, 2) if not server_ver then return nil, "bad handshake initialization packet: bad server version" end --print("server version: ", server_ver) self._server_ver = server_ver local thread_id, pos = _get_byte4(packet, pos) --print("thread id: ", thread_id) local scramble = sub(packet, pos, pos + 8 - 1) if not scramble then return nil, "1st part of scramble not found" end pos = pos + 9 -- skip filler -- two lower bytes local capabilities -- server capabilities capabilities, pos = _get_byte2(packet, pos) -- print(format("server capabilities: %#x", capabilities)) self._server_lang = strbyte(packet, pos) pos = pos + 1 --print("server lang: ", self._server_lang) self._server_status, pos = _get_byte2(packet, pos) --print("server status: ", self._server_status) local more_capabilities more_capabilities, pos = _get_byte2(packet, pos) capabilities = bor(capabilities, lshift(more_capabilities, 16)) --print("server capabilities: ", capabilities) -- local len = strbyte(packet, pos) local len = 21 - 8 - 1 --print("scramble len: ", len) pos = pos + 1 + 10 local scramble_part2 = sub(packet, pos, pos + len - 1) if not scramble_part2 then return nil, "2nd part of scramble not found" end scramble = scramble .. scramble_part2 --print("scramble: ", _dump(scramble)) local client_flags = 0x3f7cf; local ssl_verify = opts.ssl_verify local use_ssl = opts.ssl or ssl_verify if use_ssl then if band(capabilities, CLIENT_SSL) == 0 then return nil, "ssl disabled on server" end -- send a SSL Request Packet local req = _set_byte4(bor(client_flags, CLIENT_SSL)) .. _set_byte4(self._max_packet_size) .. "\0" -- TODO: add support for charset encoding .. strrep("\0", 23) local packet_len = 4 + 4 + 1 + 23 local bytes, err = _send_packet(self, req, packet_len) if not bytes then return nil, "failed to send client authentication packet: " .. err end local ok, err = sock:sslhandshake(false, nil, ssl_verify) if not ok then return nil, "failed to do ssl handshake: " .. (err or "") end end local password = opts.password or "" local token = _compute_token(password, scramble) --print("token: ", _dump(token)) local req = _set_byte4(client_flags) .. _set_byte4(self._max_packet_size) .. "\0" -- TODO: add support for charset encoding .. strrep("\0", 23) .. _to_cstring(user) .. _to_binary_coded_string(token) .. _to_cstring(database) local packet_len = 4 + 4 + 1 + 23 + #user + 1 + #token + 1 + #database + 1 -- print("packet content length: ", packet_len) -- print("packet content: ", _dump(concat(req, ""))) local bytes, err = _send_packet(self, req, packet_len) if not bytes then return nil, "failed to send client authentication packet: " .. err end --print("packet sent ", bytes, " bytes") local packet, typ, err = _recv_packet(self) if not packet then return nil, "failed to receive the result packet: " .. err end if typ == 'ERR' then local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ == 'EOF' then return nil, "old pre-4.1 authentication protocol not supported" end if typ ~= 'OK' then return nil, "bad packet type: " .. typ end self.state = STATE_CONNECTED return 1 end function _M.set_keepalive(self, ...) local sock = self.sock if not sock then return nil, "not initialized" end if self.state ~= STATE_CONNECTED then return nil, "cannot be reused in the current connection state: " .. (self.state or "nil") end self.state = nil return sock:setkeepalive(...) end function _M.get_reused_times(self) local sock = self.sock if not sock then return nil, "not initialized" end return sock:getreusedtimes() end function _M.close(self) local sock = self.sock if not sock then return nil, "not initialized" end self.state = nil return sock:close() end function _M.server_ver(self) return self._server_ver end local function send_query(self, query) if self.state ~= STATE_CONNECTED then return nil, "cannot send query in the current context: " .. (self.state or "nil") end local sock = self.sock if not sock then return nil, "not initialized" end self.packet_no = -1 local cmd_packet = strchar(COM_QUERY) .. query local packet_len = 1 + #query local bytes, err = _send_packet(self, cmd_packet, packet_len) if not bytes then return nil, err end self.state = STATE_COMMAND_SENT --print("packet sent ", bytes, " bytes") return bytes end _M.send_query = send_query local function read_result(self, est_nrows) if self.state ~= STATE_COMMAND_SENT then return nil, "cannot read result in the current context: " .. self.state end local sock = self.sock if not sock then return nil, "not initialized" end local packet, typ, err = _recv_packet(self) if not packet then return nil, err end if typ == "ERR" then self.state = STATE_CONNECTED local errno, msg, sqlstate = _parse_err_packet(packet) return nil, msg, errno, sqlstate end if typ == 'OK' then local res = _parse_ok_packet(packet) if res and band(res.server_status, SERVER_MORE_RESULTS_EXISTS) ~= 0 then return res, "again" end self.state = STATE_CONNECTED return res end if typ ~= 'DATA' then self.state = STATE_CONNECTED return nil, "packet type " .. typ .. " not supported" end -- typ == 'DATA' --print("read the result set header packet") local field_count, extra = _parse_result_set_header_packet(packet) --print("field count: ", field_count) local cols = new_tab(field_count, 0) for i = 1, field_count do local col, err, errno, sqlstate = _recv_field_packet(self) if not col then return nil, err, errno, sqlstate end cols[i] = col end local packet, typ, err = _recv_packet(self) if not packet then return nil, err end if typ ~= 'EOF' then return nil, "unexpected packet type " .. typ .. " while eof packet is " .. "expected" end -- typ == 'EOF' local compact = self.compact local rows = new_tab(est_nrows or 4, 0) local i = 0 while true do --print("reading a row") packet, typ, err = _recv_packet(self) if not packet then return nil, err end if typ == 'EOF' then local warning_count, status_flags = _parse_eof_packet(packet) --print("status flags: ", status_flags) if band(status_flags, SERVER_MORE_RESULTS_EXISTS) ~= 0 then return rows, "again" end break end -- if typ ~= 'DATA' then -- return nil, 'bad row packet type: ' .. typ -- end -- typ == 'DATA' local row = _parse_row_data_packet(packet, cols, compact) i = i + 1 rows[i] = row end self.state = STATE_CONNECTED return rows end _M.read_result = read_result function _M.query(self, query, est_nrows) local bytes, err = send_query(self, query) if not bytes then return nil, "failed to send query: " .. err end return read_result(self, est_nrows) end function _M.set_compact_arrays(self, value) self.compact = value end return _M
bsd-2-clause
BlockMen/minetest_next
mods/default/player.lua
2
5423
-- Minetest 0.4 mod: player -- See README.txt for licensing and other information. -- Player animation blending -- Note: This is currently broken due to a bug in Irrlicht, leave at 0 local animation_blend = 0 default.registered_player_models = { } -- Local for speed. local models = default.registered_player_models function default.player_register_model(name, def) models[name] = def end -- Default player appearance default.player_register_model("character.b3d", { animation_speed = 30, textures = {"character.png", "default_armor_blank.png", "16x_blank.png"}, animations = { -- Standard animations. stand = { x= 0, y= 79, }, lay = { x=162, y=166, }, walk = { x=168, y=187, }, mine = { x=189, y=198, }, walk_mine = { x=200, y=219, }, -- Extra animations (not currently used by the game). sit = { x= 81, y=160, }, }, }) -- Player stats and animations local player_model = {} local player_textures = {} local player_anim = {} local player_sneak = {} default.player_attached = {} function default.player_get_animation(player) local name = player:get_player_name() return { model = player_model[name], textures = player_textures[name], animation = player_anim[name], } end -- Called when a player's appearance needs to be updated function default.player_set_model(player, model_name) local name = player:get_player_name() local model = models[model_name] if model then if player_model[name] == model_name then return end player_textures[name] = player_textures[name] or model.textures player:set_properties({ mesh = model_name, textures = player_textures[name], visual = "mesh", visual_size = model.visual_size or {x = 1, y =1}, }) default.player_set_animation(player, "stand") else player:set_properties({ textures = {"player.png", "player_back.png"}, visual = "upright_sprite", }) end player_model[name] = model_name end function default.player_set_armor_texture(player, texture) local name = player:get_player_name() player_textures[name][2] = texture player:set_properties({textures = player_textures[name]}) end function default.player_set_skin(player, texture) local name = player:get_player_name() player_textures[name][1] = texture player:set_properties({textures = player_textures[name]}) end function default.player_set_textures(player, textures) local name = player:get_player_name() if textures[2] == nil or textures[3] == nil then textures = {textures[1], "default_armor_blank.png", "16x_blank.png"} minetest.log("error", "Deprecated use of 'default.player_set_textures()'. Use 'default.player_set_skin()' instead.") end player_textures[name] = textures player:set_properties({textures = textures}) end function default.player_set_animation(player, anim_name, speed) local name = player:get_player_name() if player_anim[name] == anim_name then return end local model = player_model[name] and models[player_model[name]] if not (model and model.animations[anim_name]) then return end local anim = model.animations[anim_name] player_anim[name] = anim_name player:set_animation(anim, speed or model.animation_speed, animation_blend) end -- Update appearance when the player joins minetest.register_on_joinplayer(function(player) default.player_attached[player:get_player_name()] = false default.player_set_model(player, "character.b3d") player:set_local_animation({x=0, y=79}, {x=168, y=187}, {x=189, y=198}, {x=200, y=219}, 30) -- set GUI if not minetest.setting_getbool("creative_mode") then player:set_inventory_formspec(default.gui_survival_form) end player:hud_set_hotbar_image("gui_hotbar.png") player:hud_set_hotbar_selected_image("gui_hotbar_selected.png") end) minetest.register_on_leaveplayer(function(player) local name = player:get_player_name() player_model[name] = nil player_anim[name] = nil player_textures[name] = nil end) -- Localize for better performance. local player_set_animation = default.player_set_animation local player_attached = default.player_attached -- Check each player and apply animations minetest.register_globalstep(function(dtime) for _, player in pairs(minetest.get_connected_players()) do local name = player:get_player_name() local model_name = player_model[name] local model = model_name and models[model_name] if model and not player_attached[name] then local controls = player:get_player_control() local walking = false local animation_speed_mod = model.animation_speed or 30 -- Determine if the player is walking if controls.up or controls.down or controls.left or controls.right then walking = true end -- Determine if the player is sneaking, and reduce animation speed if so if controls.sneak then animation_speed_mod = animation_speed_mod / 2 end -- Apply animations based on what the player is doing if player:get_hp() == 0 then player_set_animation(player, "lay") elseif walking then if player_sneak[name] ~= controls.sneak then player_anim[name] = nil player_sneak[name] = controls.sneak end if controls.LMB then player_set_animation(player, "walk_mine", animation_speed_mod) else player_set_animation(player, "walk", animation_speed_mod) end elseif controls.LMB then player_set_animation(player, "mine") else player_set_animation(player, "stand", animation_speed_mod) end end end end)
gpl-3.0
Scavenge/darkstar
scripts/zones/Port_Bastok/npcs/_6kt.lua
61
1067
----------------------------------- -- Area: Port Bastok -- NPC: Drawbridge ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onSpawn ----------------------------------- function onSpawn(npc) local elevator = { id = ELEVATOR_PORT_BASTOK_DRWBRDG, -- id is usually 0, but 2 for port bastok drawbridge since it's special lowerDoor = npc:getID(), -- lowerDoor's npcid upperDoor = npc:getID() - 1, -- upperDoor usually has a smaller id than lowerDoor elevator = npc:getID() - 2, -- actual elevator npc's id is usually the smallest started = 1, -- is the elevator already running regime = 1 -- }; npc:setElevator(elevator.id, elevator.lowerDoor, elevator.upperDoor, elevator.elevator, elevator.started, elevator.regime); end;
gpl-3.0
smanolache/kong
kong/plugins/datadog/statsd_logger.lua
1
2153
local ngx_socket_udp = ngx.socket.udp local ngx_log = ngx.log local table_concat = table.concat local setmetatable = setmetatable local NGX_ERR = ngx.ERR local NGX_DEBUG = ngx.DEBUG local tostring = tostring local statsd_mt = {} statsd_mt.__index = statsd_mt function statsd_mt:new(conf) local sock = ngx_socket_udp() sock:settimeout(conf.timeout) local _, err = sock:setpeername(conf.host, conf.port) if err then return nil, "failed to connect to "..conf.host..":"..tostring(conf.port)..": "..err end local statsd = { host = conf.host, port = conf.port, socket = sock, } return setmetatable(statsd, statsd_mt) end function statsd_mt:create_statsd_message(stat, delta, kind, sample_rate) local rate = "" if sample_rate and sample_rate ~= 1 then rate = "|@"..sample_rate end local message = { "kong.", stat, ":", delta, "|", kind, rate } return table_concat(message, "") end function statsd_mt:close_socket() local ok, err = self.socket:close() if not ok then ngx_log(NGX_ERR, "failed to close connection from "..self.host..":"..tostring(self.port)..": ", err) return end end function statsd_mt:send_statsd(stat, delta, kind, sample_rate) local udp_message = self:create_statsd_message(stat, delta, kind, sample_rate) ngx_log(NGX_DEBUG, "Sending data to statsd server: "..udp_message) local ok, err = self.socket:send(udp_message) if not ok then ngx_log(NGX_ERR, "failed to send data to "..self.host..":"..tostring(self.port)..": ", err) end end function statsd_mt:gauge(stat, value, sample_rate) return self:send_statsd(stat, value, "g", sample_rate) end function statsd_mt:counter(stat, value, sample_rate) return self:send_statsd(stat, value, "c", sample_rate) end function statsd_mt:timer(stat, ms) return self:send_statsd(stat, ms, "ms") end function statsd_mt:histogram(stat, value) return self:send_statsd(stat, value, "h") end function statsd_mt:meter(stat, value) return self:send_statsd(stat, value, "m") end function statsd_mt:set(stat, value) return self:send_statsd(stat, value, "s") end return statsd_mt
apache-2.0
Scavenge/darkstar
scripts/globals/spells/raptor_mazurka.lua
27
1161
----------------------------------------- -- Spell: Raptor Mazurka -- Gives party members enhanced movement ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 12; local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then duration = duration * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then duration = duration * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_MAZURKA; end;
gpl-3.0
Scavenge/darkstar
scripts/globals/spells/voidstorm.lua
32
1182
-------------------------------------- -- Spell: Voidstorm -- Changes the weather around target party member to "gloomy." -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) target:delStatusEffectSilent(EFFECT_FIRESTORM); target:delStatusEffectSilent(EFFECT_SANDSTORM); target:delStatusEffectSilent(EFFECT_RAINSTORM); target:delStatusEffectSilent(EFFECT_WINDSTORM); target:delStatusEffectSilent(EFFECT_HAILSTORM); target:delStatusEffectSilent(EFFECT_THUNDERSTORM); target:delStatusEffectSilent(EFFECT_AURORASTORM); target:delStatusEffectSilent(EFFECT_VOIDSTORM); local merit = caster:getMerit(MERIT_STORMSURGE); local power = 0; if merit > 0 then power = merit + caster:getMod(MOD_STORMSURGE_EFFECT) + 2; end target:addStatusEffect(EFFECT_VOIDSTORM,power,0,180); return EFFECT_VOIDSTORM; end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/roast_pipira.lua
12
1574
----------------------------------------- -- ID: 4538 -- Item: roast_pipira -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 3 -- Mind -3 -- Attack % 14 -- Attack Cap 75 -- Ranged ATT % 14 -- Ranged ATT Cap 75 ----------------------------------------- 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,4538); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 3); target:addMod(MOD_MND, -3); target:addMod(MOD_FOOD_ATTP, 14); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 14); target:addMod(MOD_FOOD_RATT_CAP, 75); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 3); target:delMod(MOD_MND, -3); target:delMod(MOD_FOOD_ATTP, 14); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 14); target:delMod(MOD_FOOD_RATT_CAP, 75); end;
gpl-3.0
jchuang1977/openwrt
package/lean/luci-app-vsftpd/luasrc/model/cbi/vsftpd/users.lua
6
1402
--[[ LuCI - Lua Configuration Interface Copyright 2016 Weijie Gao <hackpascal@gmail.com> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("vsftpd", translate("FTP Server - Virtual User Settings")) sv = m:section(NamedSection, "vuser", "vuser", translate("Settings")) o = sv:option(Flag, "enabled", translate("Enabled")) o.default = false o = sv:option(Value, "username", translate("Username"), translate("An actual local user to handle virtual users")) o.default = "ftp" s = m:section(TypedSection, "user", translate("User lists")) s.template = "cbi/tblsection" s.extedit = luci.dispatcher.build_url("admin/nas/vsftpd/item/%s") s.addremove = true s.anonymous = true function s.create(...) local id = TypedSection.create(...) luci.http.redirect(s.extedit % id) end function s.remove(self, section) return TypedSection.remove(self, section) end o = s:option(DummyValue, "username", translate("Username")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or ("<%s>" % translate("Unknown")) return v end o.rmempty = false o = s:option(DummyValue, "home", translate("Home directory")) function o.cfgvalue(...) local v = Value.cfgvalue(...) or ("/home/ftp") return v end o.rmempty = false return m
gpl-2.0
1yvT0s/wax
tools/Tests/scripts/tests/base64Test.lua
17
1466
describe["Base64 encoding"] = function() it["should be able to round trip tricky combinations of two bytes"] = function() for a = 0,255 do for _,b in ipairs({0,1,2,252,253,254}) do local s = string.char(a)..string.char(b) expect(wax.base64.decode(wax.base64.encode(s))).should_be(s) end end end it["should get the same results as tclsh's base64"] = function() local data = string.char(unpack({ 0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81, 85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154, 171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191 })) expect(wax.base64.encode(data)).should_be("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/") end end describe["Base64 decoding"] = function() it["should pass ASCII NULs"] = function() local ans = wax.base64.decode("AAA=") expect(#ans).should_be(2) expect(string.byte(ans, 1)).should_be(0) expect(string.byte(ans, 2)).should_be(0) end it["should get the same results as tclsh's base64"] = function() local data = string.char(unpack({ 0,16,131,16,81,135,32,146,139,48,211,143,65,20,147,81, 85,151,97,150,155,113,215,159,130,24,163,146,89,167,162,154, 171,178,219,175,195,28,179,211,93,183,227,158,187,243,223,191 })) expect(wax.base64.decode("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/")).should_be(data) end end
mit
Scavenge/darkstar
scripts/globals/spells/bluemagic/feather_storm.lua
32
2005
----------------------------------------- -- Spell: Feather Storm -- Additional effect: Poison. Chance of effect varies with TP -- Spell cost: 12 MP -- Monster Type: Beastmen -- Spell Type: Physical (Piercing) -- Blue Magic Points: 3 -- Stat Bonus: CHR+2, HP+5 -- Level: 12 -- Casting Time: 0.5 seconds -- Recast Time: 10 seconds -- Skillchain Element(s): Light (can open Compression, Reverberation, or Distortion; can close Transfixion) -- Combos: Rapid Shot ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_CRITICAL; params.dmgtype = DMGTYPE_PIERCE; params.scattr = SC_LIGHT; params.numhits = 1; params.multiplier = 1.25; params.tp150 = 1.25; params.tp300 = 1.25; params.azuretp = 1.25; params.duppercap = 12; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.30; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); local chance = math.random(); if (damage > 0 and chance > 70) then local typeEffect = EFFECT_POISON; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,3,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Hall_of_Transference/npcs/_0e5.lua
14
1358
----------------------------------- -- Area: Hall of Transference -- NPC: Large Apparatus (Left) - Dem -- @pos -239 -41 -270 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then player:startEvent(0x00A0); else player:messageSpecial(NO_RESPONSE_OFFSET); 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 == 0x00A0) then player:setPos(185.891, 0, -52.331, 128, 18); -- To Promyvion Dem {R} end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Valley_of_Sorrows/npcs/qm1.lua
14
2266
----------------------------------- -- Area: Valley of Sorrows -- NPC: qm1 (???) -- Spawns Adamantoise or Aspidochelone -- @pos 0 0 -37 59 ----------------------------------- package.loaded["scripts/zones/Valley_of_Sorrows/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Valley_of_Sorrows/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onSpawn Action ----------------------------------- function onSpawn(npc) if (LandKingSystem_NQ < 1 and LandKingSystem_HQ < 1) then npc:setStatus(STATUS_DISAPPEAR); end end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Adamantoise = GetMobAction(17301537); local Aspidochelone = GetMobAction(17301538); if ((Aspidochelone == ACTION_NONE or Aspidochelone == ACTION_SPAWN) and (Adamantoise == ACTION_NONE or Adamantoise == ACTION_SPAWN)) then -- Trade Clump of Blue Pondweed if (trade:hasItemQty(3343,1) and trade:getItemCount() == 1) then if (LandKingSystem_NQ ~= 0) then player:tradeComplete(); SpawnMob(17301537):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end -- Trade Clump of Red Pondweed elseif (trade:hasItemQty(3344,1) and trade:getItemCount() == 1) then if (LandKingSystem_HQ ~= 0) then player:tradeComplete(); SpawnMob(17301538):updateClaim(player); npc:setStatus(STATUS_DISAPPEAR); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_ORDINARY); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/abilities/drain_samba_iii.lua
25
1439
----------------------------------- -- Ability: Drain Samba III -- Inflicts the next target you strike with Drain daze, allowing party members engaged in battle with it to drain its HP. -- Obtained: Dancer Level 65 -- TP Required: 40% -- Recast Time: 1:00 -- Duration: 1:30 ----------------------------------- 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() < 400) 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(400); 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,3,0,duration); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/items/loaf_of_goblin_bread.lua
12
1277
----------------------------------------- -- ID: 4458 -- Item: loaf_of_goblin_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 7 -- Vitality 1 -- Charisma -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4458); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 7); target:addMod(MOD_VIT, 1); target:addMod(MOD_CHR, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 7); target:delMod(MOD_VIT, 1); target:delMod(MOD_CHR, -5); end;
gpl-3.0
Scavenge/darkstar
scripts/globals/mobskills/Amon_Drive.lua
33
1211
--------------------------------------------- -- Amon Drive -- -- Description: Performs an area of effect weaponskill. Additional effect: Paralysis + Petrification + Poison -- Type: Physical -- 2-3 Shadows? -- Range: Melee range radial -- Special weaponskill unique to Ark Angel TT. Deals ~100-400 damage. --------------------------------------------- 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_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW); MobStatusEffectMove(mob, target, EFFECT_PARALYSIS, 25, 0, 60); MobStatusEffectMove(mob, target, EFFECT_PETRIFICATION, 1, 0, math.random(8, 15) + mob:getMainLvl()/3); MobStatusEffectMove(mob, target, EFFECT_POISON, math.ceil(mob:getMainLvl() / 5), 3, 60); target:delHP(dmg); return dmg; end;
gpl-3.0
lordporya1/6985
plugins/invite.lua
24
2328
--[[ Invite other user to the chat group. Use !invite ********* (where ********* is id_number) to invite a user by id_number. This is the most reliable method. Use !invite @username to invite a user by @username. Less reliable. Some users don't have @username. Use !invite Type print_name Here to invite a user by print_name. Unreliable. Avoid if possible. ]]-- do -- Think it's kind of useless. Just to suppress '*** lua: attempt to call a nil value' local function callback(extra, success, result) if success == 1 and extra ~= false then return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function resolve_username(extra, success, result) local chat = extra.chat if success == 1 then local user = 'user#id'..result.id chat_add_user(chat, user, callback, false) return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function action_by_reply(extra, success, result) if success == 1 then chat_add_user('chat#id'..result.to.id, 'user#id'..result.from.id, callback, false) else return send_large_msg('chat#id'..result.to.id, "Can't invite user to this group.") end end local function run(msg, matches) local user_id = matches[1] local chat = 'chat#id'..msg.to.id local text = "Add: "..user_id.." to "..chat if msg.to.type == 'chat' then if msg.reply_id and msg.text == "!invite" then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if string.match(user_id, '^%d+$') then user = 'user#id'..user_id chat_add_user(chat, user, callback, {chat=chat, text=text}) elseif string.match(user_id, '^@.+$') then username = string.gsub(user_id, '@', '') msgr = res_user(username, resolve_username, {chat=chat, text=text}) else user = string.gsub(user_id, ' ', '_') chat_add_user(chat, user, callback, {chat=chat, text=text}) end else return 'This isnt a chat group!' end end return { description = 'Invite other user to the chat group.', usage = { -- Need space in front of this, so bot won't consider it as a command ' !invite [id|user_name|name]' }, patterns = { "^!invite$", "^!invite (.*)$", "^!invite (%d+)$" }, run = run, privileged = true } end
gpl-2.0
takaaptech/Moses
spec/table_spec.lua
3
18984
require 'luacov' local _ = require 'moses' context('Table functions specs', function() context('each', function() test('provides values and iteration count ', function() local t = {1,2,3} local inc = 0 _.each(t,function(i,v) inc = inc+1 assert_equal(i,inc) assert_equal(t[i],v) end) end) test('can reference the given table', function() local t = {1,2,3} _.each(t,function(i,v,mul) t[i] = v*mul end,5) assert_true(_.isEqual(t,{5,10,15})) end) test('iterates over non-numeric keys and objects', function() local t = {one = 1, two = 2, three = 3} local copy = {} _.each(t,function(i,v) copy[i] = v end) assert_true(_.isEqual(t,copy)) end) end) context('eachi', function() test('provides values and iteration count for integer keys only, in a sorted way', function() local t = {1,2,3} local inc = 0 _.eachi(t,function(i,v) inc = inc+1 assert_equal(i,inc) assert_equal(t[i],v) end) end) test('ignores non-integer keys', function() local t = {a = 1, b = 2, [0] = 1, [-1] = 6, 3, x = 4, 5} local rk = {-1, 0, 1, 2} local rv = {6, 1, 3, 5} local inc = 0 _.eachi(t,function(i,v) inc = inc+1 assert_equal(i,rk[inc]) assert_equal(v,rv[inc]) end) end) end) context('at', function() test('returns an array of values at numeric keys', function() local t = {4,5,6} local values = _.at(t,1,2,3) assert_true(_.isEqual(values, t)) local t = {a = 4, bb = true, ccc = false} local values = _.at(t,'a', 'ccc') assert_true(_.isEqual(values, {4, false})) end) end) context('count', function() test('count the occurences of value in a list', function() assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},1),2) assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},2),3) assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},3),4) assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},4),1) assert_equal(_.count({1,1,2,3,3,3,2,4,3,2},5),0) assert_equal(_.count({false, false, true},false),2) assert_equal(_.count({false, false, true},true),1) assert_equal(_.count({{1,1},{1,1},{1,1},{2,2}},{1,1}),3) assert_equal(_.count({{1,1},{1,1},{1,1},{2,2}},{2,2}),1) end) test('defaults to size when value is not given', function() assert_equal(_.count({1,1,2,3,3,3,2,4,3,2}),_.size({1,1,2,3,3,3,2,4,3,2})) assert_equal(_.count({false, false, true}),_.size({false, false, true})) end) end) context('countf', function() test('count the occurences of values passing an iterator test in a list', function() assert_equal(_.countf({1,2,3,4,5,6}, function(i,v) return v%2==0 end),3) assert_equal(_.countf({print, pairs, os, assert, ipairs}, function(i,v) return type(v)=='function' end),4) end) end) context('cycle', function() test('loops n times on a list', function() local times = 3 local t = {1,2,3,4,5} local kv = {} for k,v in _.cycle(t,times) do assert_equal(t[k],v) kv[#kv+1] = v end for k,v in ipairs(kv) do assert_equal(_.count(kv,v),times) end end) test('support array-like and map-like tables', function() local times = 10 local t = {x = 1, z = 2} local keys = {} local values = {} for k,v in _.cycle(t,times) do assert_equal(t[k],v) keys[#keys+1] = k values[#values+1] = v end for k,v in ipairs(keys) do assert_equal(_.count(keys,v),times) end for k,v in ipairs(values) do assert_equal(_.count(values,v),times) end end) test('n defaults to 1, if not supplied', function() local t = {1,2,3,4,5} for k,v in _.cycle(t) do t[k] = v + 1 end _.each(t, function(k, v) assert_equal(v, k + 1) end) end) test('if n is negative or equal to 0, it does nothing', function() local t = {1,2,3,4,5} for k,v in _.cycle(t, 0) do t[k] = v + 1 end for k,v in _.cycle(t, -2) do t[k] = v + 1 end _.each(t, function(k, v) assert_equal(v, k) end) end) end) context('map', function() test('applies an iterator function over each key-value pair ', function() assert_true(_.isEqual(_.map({1,2,3},function(i,v) return v+10 end),{11,12,13})) end) test('iterates over non-numeric keys and objects', function() assert_true(_.isEqual(_.map({a = 1, b = 2},function(k,v) return k..v end),{a = 'a1',b = 'b2'})) end) end) context('reduce', function() test('folds a collection (left to right) from an initial state', function() assert_equal(_.reduce({1,2,3,4},function(memo,v) return memo+v end,0),10) end) test('initial state defaults to the first value when not given', function() assert_equal(_.reduce({'a','b','c'},function(memo,v) return memo..v end),'abc') end) test('supports arrays of booleans', function() assert_equal(_.reduce({true, false, true, true},function(memo,v) return memo and v end), false) assert_equal(_.reduce({true, true, true},function(memo,v) return memo and v end), true) assert_equal(_.reduce({false, false, false},function(memo,v) return memo and v end), false) assert_equal(_.reduce({false, false, true},function(memo,v) return memo or v end), true) end) end) context('reduceRight', function() test('folds a collection (right to left) from an initial state', function() assert_equal(_.reduceRight({1,2,4,16},function(memo,v) return memo/v end,256),2) end) test('initial state defaults to the first value when not given', function() assert_equal(_.reduceRight({'a','b','c'},function(memo,v) return memo..v end),'cba') end) end) context('mapReduce', function() test('folds a collection (left to right) saving intermediate states', function() assert_true(_.isEqual(_.mapReduce({1,2,4,16},function(memo,v) return memo*v end,0),{0,0,0,0})) end) test('initial state defaults to the first value when not given', function() assert_true(_.isEqual(_.mapReduce({'a','b','c'},function(memo,v) return memo..v end),{'a','ab','abc'})) end) end) context('mapReduceRight', function() test('folds a collection (right to left) saving intermediate states', function() assert_true(_.isEqual(_.mapReduceRight({1,2,4,16},function(memo,v) return memo/v end,256),{16,4,2,2})) end) test('initial state defaults to the first value when not given', function() assert_true(_.isEqual(_.mapReduceRight({'a','b','c'},function(memo,v) return memo..v end),{'c','cb','cba'})) end) end) context('include', function() test('looks for a value in a collection, returns true when found', function() assert_true(_.include({6,8,10,16,29},16)) end) test('returns false when value was not found', function() assert_false(_.include({6,8,10,16,29},1)) end) test('can lookup for a object', function() assert_true(_.include({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,{3}}})) end) test('given an iterator, return the first value passing a truth test', function() assert_true(_.include({'a','B','c'}, function(array_value) return (array_value:upper() == array_value) end)) end) end) context('detect', function() test('looks for the first occurence of value, returns the key where it was found', function() assert_equal(_.detect({6,8,10,16},8),2) end) test('returns nil when value was not found', function() assert_nil(_.detect({nil,true,0,true,true},false)) end) test('can lookup for a object', function() assert_equal(_.detect({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,6}}),2) end) test('given an iterator, return the key of the first value passing a truth test', function() assert_equal(_.detect({'a','B','c'}, function(array_value) return (array_value:upper() == array_value) end),2) end) end) context('contains', function() test('returns true if value is present in a list', function() assert_true(_.contains({6,8,10,16},8)) end) test('returns false when value was not found', function() assert_false(_.contains({nil,true,0,true,true},false)) end) test('can lookup for a object', function() assert_true(_.contains({6,{18,{2,6}},10,{18,{2,{3}}},29},{18,{2,6}})) end) test('accepts iterator functions', function() assert_true(_.contains({'a','B','c'}, function(array_value) return (array_value:upper() == array_value) end)) end) end) context('findWhere', function() test('Returns the first value in a list having all of some given set of properties', function() local a = {a = 1, b = 2} local b = {a = 2, b = 3} local c = {a = 3, b = 4} assert_equal(_.findWhere({a, b, c}, {a = 3, b = 4}), c) end) test('returns nil when value was not found', function() local a = {a = 1, b = 2} local b = {a = 2, b = 3} local c = {a = 3, b = 4} assert_nil(_.findWhere({a, b, c}, {a = 3, b = 0})) end) end) context('select', function() test('collects all values passing a truth test with an iterator', function() assert_true(_.isEqual(_.select({1,2,3,4,5,6,7}, function(key,value) return (value%2==0) end),{2,4,6})) assert_true(_.isEqual(_.select({1,2,3,4,5,6,7}, function(key,value) return (value%2~=0) end),{1,3,5,7})) end) end) context('reject', function() test('collects all values failing a truth test with an iterator', function() assert_true(_.isEqual(_.reject({1,2,3,4,5,6,7}, function(key,value) return (value%2==0) end),{1,3,5,7})) assert_true(_.isEqual(_.reject({1,2,3,4,5,6,7}, function(key,value) return (value%2~=0) end),{2,4,6})) end) end) context('all', function() test('returns whether all elements matches a truth test', function() assert_true(_.all({2,4,6}, function(key,value) return (value%2==0) end)) assert_false(_.all({false,true,false}, function(key,value) return value == false end)) end) end) context('invoke', function() test('calls an iterator over each object, passing it as a first arg', function() assert_true(_.isEqual(_.invoke({'a','bea','cdhza'},string.len), {1,3,5})) assert_true(_.isEqual(_.invoke({{2,3,2},{13,8,10},{0,-5}},_.sort), {{2,2,3},{8,10,13},{-5,0}})) assert_true(_.isEqual(_.invoke({{x = 1, y = 2},{x = 3, y=4}},'x'), {1,3})) end) test('given a string, calls the matching object property the same way', function() local a = {}; function a:call() return self end local b, c, d = {}, {}, {} b.call, c.call, d.call = a.call, a.call, a.call assert_true(_.isEqual(_.invoke({a,b,c,d},'call'), {a,b,c,d})) end) end) context('pluck', function() test('fetches a property value in a collection of objects', function() local peoples = { {name = 'John', age = 23},{name = 'Peter', age = 17}, {name = 'Steve', age = 15},{age = 33}} assert_true(_.isEqual(_.pluck(peoples,'age'), {23,17,15,33})) assert_true(_.isEqual(_.pluck(peoples,'name'), {'John','Peter','Steve'})) end) end) context('max', function() test('returns the maximum targetted property value in a collection of objects', function() local peoples = { {name = 'John', age = 23},{name = 'Peter', age = 17}, {name = 'Steve', age = 15},{age = 33}} assert_equal(_.max(_.pluck(peoples,'age')),33) assert_equal(_.max(peoples,function(people) return people.age end),33) end) test('directly compares items when given no iterator', function() assert_equal(_.max({'a','b','c'}),'c') end) end) context('min', function() test('returns the maximum targetted property value in a collection of objects', function() local peoples = { {name = 'John', age = 23},{name = 'Peter', age = 17}, {name = 'Steve', age = 15},{age = 33}} assert_equal(_.min(_.pluck(peoples,'age')),15) assert_equal(_.min(peoples,function(people) return people.age end),15) end) test('directly compares items when given no iterator', function() assert_equal(_.min({'a','b','c'}),'a') end) end) context('shuffle', function() test('shuffles values and objects in a collection', function() local values = {'a','b','c','d'} assert_true(_.same(_.shuffle (values),values)) end) test('can accept a seed value to init randomization', function() local values = {'a','b','c','d'} local seed = os.time() assert_true(_.same(_.shuffle(values,seed),values)) end) test('shuffled table has the same elements in a different order', function() local values = {'a','b','c','d'} assert_true(_.same(_.shuffle(values),values)) assert_true(_.same(_.shuffle(values),values)) end) end) context('same', function() test('returns whether all objects from both given tables exists in each other', function() local a = {'a','b','c','d'} local b = {'b','a','d','c'} assert_true(_.same(a,b)) b[#b+1] = 'e' assert_false(_.same(a,b)) end) end) context('sort', function() test('sorts a collection with respect to a given comparison function', function() assert_true(_.isEqual(_.sort({'b','a','d','c'}, function(a,b) return a:byte() < b:byte() end),{'a','b','c','d'})) end) test('uses "<" operator when no comparison function is given', function() assert_true(_.isEqual(_.sort({'b','a','d','c'}),{'a','b','c','d'})) end) end) context('groupBy', function() test('splits a collection into subsets of items behaving the same', function() assert_true(_.isEqual(_.groupBy({0,1,2,3,4,5,6},function(i,value) return value%2==0 and 'even' or 'odd' end),{even = {0,2,4,6},odd = {1,3,5}})) assert_true(_.isEqual(_.groupBy({0,'a',true, false,nil,b,0.5},function(i,value) return type(value) end),{number = {0,0.5},string = {'a'},boolean = {true,false}})) assert_true(_.isEqual(_.groupBy({'one','two','three','four','five'},function(i,value) return value:len() end),{[3] = {'one','two'},[4] = {'four','five'},[5] = {'three'}})) end) test('can takes extra-args', function() assert_true(_.isEqual(_.groupBy({3,9,10,12,15}, function(k,v,x) return v%x == 0 end,2), {[false] = {3,9,15}, [true] = {10,12}})) assert_true(_.isEqual(_.groupBy({3,9,10,12,15}, function(k,v,x) return v%x == 0 end,3), {[false] = {10}, [true] = {3,9,12,15}})) end) end) context('countBy', function() test('splits a collection in subsets and counts items inside', function() assert_true(_.isEqual(_.countBy({0,1,2,3,4,5,6},function(i,value) return value%2==0 and 'even' or 'odd' end),{even = 4,odd = 3})) assert_true(_.isEqual(_.countBy({0,'a',true, false,nil,b,0.5},function(i,value) return type(value) end),{number = 2,string = 1,boolean = 2})) assert_true(_.isEqual(_.countBy({'one','two','three','four','five'},function(i,value) return value:len() end),{[3] = 2,[4] = 2,[5] = 1})) end) end) context('size', function() test('counts the very number of objects in a collection', function() assert_equal(_.size {1,2,3},3) end) test('counts nested tables elements as a unique value', function() assert_equal(_.size {1,2,3,{4,5}},4) end) test('leaves nil values', function() assert_equal(_.size {1,2,3,nil,8},4) end) test('counts objects', function() assert_equal(_.size {one = 1,2,b = 3, [{}] = 'nil', 'c', [function() end] = 'foo'},6) end) test('returns the size of the first arg when it is a table', function() assert_equal(_.size ({1,2},3,4,5),2) end) test('counts the number of args when the first one is not a table', function() assert_equal(_.size (1,3,4,5),4) end) test('handles nil', function() assert_equal(_.size(),0) assert_equal(_.size(nil),0) end) end) context('containsKeys', function() test('returns whether a table has all the keys from a given list', function() assert_true(_.containsKeys({1,2,3},{1,2,3})) assert_true(_.containsKeys({x = 1, y = 2},{x = 1,y =2})) end) test('does not compare values', function() assert_true(_.containsKeys({1,2,3},{4,5,6})) assert_true(_.containsKeys({x = 1, y = 2},{x = 4,y = -1})) end) test('is not commutative', function() assert_true(_.containsKeys({1,2,3,4},{4,5,6})) assert_true(_.containsKeys({x = 1, y = 2,z = 5},{x = 4,y = -1})) assert_false(_.containsKeys({1,2,3},{4,5,6,7})) assert_false(_.containsKeys({x = 1, y = 2},{x = 4,y = -1,z = 0})) end) end) context('sameKeys', function() test('returns whether both tables features the same keys', function() assert_true(_.sameKeys({1,2,3},{1,2,3})) assert_true(_.sameKeys({x = 1, y = 2},{x = 1,y =2})) end) test('does not compare values', function() assert_true(_.sameKeys({1,2,3},{4,5,6})) assert_true(_.sameKeys({x = 1, y = 2},{x = 4,y = -1})) end) test('is commutative', function() assert_false(_.sameKeys({1,2,3,4},{4,5,6})) assert_false(_.sameKeys({x = 1, y = 2,z = 5},{x = 4,y = -1})) assert_false(_.sameKeys({1,2,3},{4,5,6,7})) assert_false(_.sameKeys({x = 1, y = 2},{x = 4,y = -1,z = 0})) end) end) end)
mit
Scavenge/darkstar
scripts/globals/weaponskills/refulgent_arrow.lua
15
1441
----------------------------------- -- Refulgent Arrow -- Archery weapon skill -- Skill level: 290 -- Delivers a twofold attack. Damage varies with TP. -- Aligned with the Aqua Gorget & Light Gorget. -- Aligned with the Aqua Belt & Light Belt. -- Element: None -- Modifiers: STR: 60% http://www.bg-wiki.com/bg/Refulgent_Arrow -- 100%TP 200%TP 300%TP -- 3.00 4.25 7.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {}; params.numHits = 2; params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 5; params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 3; params.ftp200 = 4.25; params.ftp300 = 7; params.str_wsc = 0.6; end local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
smanolache/kong
kong/dao/cassandra_db.lua
1
13041
local timestamp = require "kong.tools.timestamp" local Errors = require "kong.dao.errors" local BaseDB = require "kong.dao.base_db" local utils = require "kong.tools.utils" local uuid = require "lua_uuid" local ngx_stub = _G.ngx _G.ngx = nil local cassandra = require "cassandra" _G.ngx = ngx_stub local CassandraDB = BaseDB:extend() CassandraDB.dao_insert_values = { id = function() return uuid() end, timestamp = function() return timestamp.get_utc() end } function CassandraDB:new(options) local conn_opts = { shm = "cassandra", prepared_shm = "cassandra_prepared", contact_points = options.contact_points, keyspace = options.keyspace, protocol_options = { default_port = options.port }, query_options = { prepare = true }, ssl_options = { enabled = options.ssl.enabled, verify = options.ssl.verify, ca = options.ssl.certificate_authority } } if options.username and options.password then conn_opts.auth = cassandra.auth.PlainTextProvider(options.username, options.password) end CassandraDB.super.new(self, "cassandra", conn_opts) end function CassandraDB:infos() return { desc = "keyspace", name = self:_get_conn_options().keyspace } end -- Formatting local function serialize_arg(field, value) if value == nil then return cassandra.unset elseif field.type == "id" then return cassandra.uuid(value) elseif field.type == "timestamp" then return cassandra.timestamp(value) elseif field.type == "table" or field.type == "array" then local json = require "cjson" return json.encode(value) else return value end end local function deserialize_rows(rows, schema) local json = require "cjson" for i, row in ipairs(rows) do for col, value in pairs(row) do if schema.fields[col].type == "table" or schema.fields[col].type == "array" then rows[i][col] = json.decode(value) end end end end local function get_where(schema, filter_keys, args) args = args or {} local fields = schema.fields local where = {} for col, value in pairs(filter_keys) do where[#where + 1] = col.." = ?" args[#args + 1] = serialize_arg(fields[col], value) end return table.concat(where, " AND "), args end local function get_select_query(table_name, where, select_clause) local query = string.format("SELECT %s FROM %s", select_clause or "*", table_name) if where ~= nil then query = query.." WHERE "..where.." ALLOW FILTERING" end return query end --- Querying local function check_unique_constraints(self, table_name, constraints, values, primary_keys, update) local errors for col, constraint in pairs(constraints.unique) do -- Only check constraints if value is non-null if values[col] ~= nil then local where, args = get_where(constraint.schema, {[col] = values[col]}) local query = get_select_query(table_name, where) local rows, err = self:query(query, args, nil, constraint.schema) if err then return err elseif #rows > 0 then -- if in update, it's fine if the retrieved row is the same as the one updated if update then local same_row = true for col, val in pairs(primary_keys) do if val ~= rows[1][col] then same_row = false break end end if not same_row then errors = utils.add_error(errors, col, values[col]) end else errors = utils.add_error(errors, col, values[col]) end end end end return Errors.unique(errors) end local function check_foreign_constaints(self, values, constraints) local errors for col, constraint in pairs(constraints.foreign) do -- Only check foreign keys if value is non-null, if must not be null, field should be required if values[col] ~= nil then local res, err = self:find(constraint.table, constraint.schema, {[constraint.col] = values[col]}) if err then return err elseif res == nil then errors = utils.add_error(errors, col, values[col]) end end end return Errors.foreign(errors) end function CassandraDB:query(query, args, opts, schema, no_keyspace) CassandraDB.super.query(self, query, args) local conn_opts = self:_get_conn_options() if no_keyspace then conn_opts.keyspace = nil end local session, err = cassandra.spawn_session(conn_opts) if err then return nil, Errors.db(tostring(err)) end local res, err = session:execute(query, args, opts) session:set_keep_alive() if err then return nil, Errors.db(tostring(err)) end if schema ~= nil and res.type == "ROWS" then deserialize_rows(res, schema) end return res end function CassandraDB:insert(table_name, schema, model, constraints, options) local err = check_unique_constraints(self, table_name, constraints, model) if err then return nil, err end err = check_foreign_constaints(self, model, constraints) if err then return nil, err end local cols, binds, args = {}, {}, {} for col, value in pairs(model) do local field = schema.fields[col] cols[#cols + 1] = col args[#args + 1] = serialize_arg(field, value) binds[#binds + 1] = "?" end cols = table.concat(cols, ", ") binds = table.concat(binds, ", ") local query = string.format("INSERT INTO %s(%s) VALUES(%s)%s", table_name, cols, binds, (options and options.ttl) and string.format(" USING TTL %d", options.ttl) or "") local err = select(2, self:query(query, args)) if err then return nil, err end local primary_keys = model:extract_keys() local row, err = self:find(table_name, schema, primary_keys) if err then return nil, err end return row end function CassandraDB:find(table_name, schema, filter_keys) local where, args = get_where(schema, filter_keys) local query = get_select_query(table_name, where) local rows, err = self:query(query, args, nil, schema) if err then return nil, err elseif #rows > 0 then return rows[1] end end function CassandraDB:find_all(table_name, tbl, schema) local conn_opts = self:_get_conn_options() local session, err = cassandra.spawn_session(conn_opts) if err then return nil, Errors.db(tostring(err)) end local where, args if tbl ~= nil then where, args = get_where(schema, tbl) end local query = get_select_query(table_name, where) local res_rows, err = {}, nil for rows, page_err in session:execute(query, args, {auto_paging = true}) do if err then err = Errors.db(tostring(page_err)) res_rows = nil break end if schema ~= nil then deserialize_rows(rows, schema) end for _, row in ipairs(rows) do res_rows[#res_rows + 1] = row end end session:set_keep_alive() return res_rows, err end function CassandraDB:find_page(table_name, tbl, paging_state, page_size, schema) local where, args if tbl ~= nil then where, args = get_where(schema, tbl) end local query = get_select_query(table_name, where) local rows, err = self:query(query, args, {page_size = page_size, paging_state = paging_state}, schema) if err then return nil, err elseif rows ~= nil then local paging_state if rows.meta and rows.meta.has_more_pages then paging_state = rows.meta.paging_state end rows.meta = nil rows.type = nil return rows, nil, paging_state end end function CassandraDB:count(table_name, tbl, schema) local where, args if tbl ~= nil then where, args = get_where(schema, tbl) end local query = get_select_query(table_name, where, "COUNT(*)") local res, err = self:query(query, args) if err then return nil, err elseif res and #res > 0 then return res[1].count end end function CassandraDB:update(table_name, schema, constraints, filter_keys, values, nils, full, model, options) -- must check unique constaints manually too local err = check_unique_constraints(self, table_name, constraints, values, filter_keys, true) if err then return nil, err end err = check_foreign_constaints(self, values, constraints) if err then return nil, err end -- Cassandra TTL on update is per-column and not per-row, and TTLs cannot be updated on primary keys. -- Not only that, but TTL on other rows can only be incremented, and not decremented. Because of all -- of these limitations, the only way to make this happen is to do an upsert operation. -- This implementation can be changed once Cassandra closes this issue: https://issues.apache.org/jira/browse/CASSANDRA-9312 if options and options.ttl then if schema.primary_key and #schema.primary_key == 1 and filter_keys[schema.primary_key[1]] then local row, err = self:find(table_name, schema, filter_keys) if err then return nil, err elseif row then for k, v in pairs(row) do if not values[k] then model[k] = v -- Populate the model to be used later for the insert end end -- Insert without any contraint check, since the check has already been executed return self:insert(table_name, schema, model, {unique={}, foreign={}}, options) end else return nil, "Cannot update TTL on entities that have more than one primary_key" end end local sets, args, where = {}, {} for col, value in pairs(values) do local field = schema.fields[col] sets[#sets + 1] = col.." = ?" args[#args + 1] = serialize_arg(field, value) end -- unset nil fields if asked for if full then for col in pairs(nils) do sets[#sets + 1] = col.." = ?" args[#args + 1] = cassandra.unset end end sets = table.concat(sets, ", ") where, args = get_where(schema, filter_keys, args) local query = string.format("UPDATE %s%s SET %s WHERE %s", table_name, (options and options.ttl) and string.format(" USING TTL %d", options.ttl) or "", sets, where) local res, err = self:query(query, args) if err then return nil, err elseif res and res.type == "VOID" then return self:find(table_name, schema, filter_keys) end end local function cascade_delete(self, primary_keys, constraints) if constraints.cascade == nil then return end for f_entity, cascade in pairs(constraints.cascade) do local tbl = {[cascade.f_col] = primary_keys[cascade.col]} local rows, err = self:find_all(cascade.table, tbl, cascade.schema) if err then return nil, err end for _, row in ipairs(rows) do local primary_keys_to_delete = {} for _, primary_key in ipairs(cascade.schema.primary_key) do primary_keys_to_delete[primary_key] = row[primary_key] end local ok, err = self:delete(cascade.table, cascade.schema, primary_keys_to_delete) if not ok then return nil, err end end end end function CassandraDB:delete(table_name, schema, primary_keys, constraints) local row, err = self:find(table_name, schema, primary_keys) if err or row == nil then return nil, err end local where, args = get_where(schema, primary_keys) local query = string.format("DELETE FROM %s WHERE %s", table_name, where) local res, err = self:query(query, args) if err then return nil, err elseif res and res.type == "VOID" then if constraints ~= nil then cascade_delete(self, primary_keys, constraints) end return row end end -- Migrations function CassandraDB:queries(queries, no_keyspace) for _, query in ipairs(utils.split(queries, ";")) do if utils.strip(query) ~= "" then local err = select(2, self:query(query, nil, nil, nil, no_keyspace)) if err then return err end end end end function CassandraDB:drop_table(table_name) return select(2, self:query("DROP TABLE "..table_name)) end function CassandraDB:truncate_table(table_name) return select(2, self:query("TRUNCATE "..table_name)) end function CassandraDB:current_migrations() -- Check if keyspace exists local rows, err = self:query([[ SELECT * FROM system.schema_keyspaces WHERE keyspace_name = ? ]], {self.options.keyspace}, nil, nil, true) if err then return nil, err elseif #rows == 0 then return {} end -- Check if schema_migrations table exists first rows, err = self:query([[ SELECT COUNT(*) FROM system.schema_columnfamilies WHERE keyspace_name = ? AND columnfamily_name = ? ]], { self.options.keyspace, "schema_migrations" }) if err then return nil, err end if rows[1].count > 0 then return self:query "SELECT * FROM schema_migrations" else return {} end end function CassandraDB:record_migration(id, name) return select(2, self:query([[ UPDATE schema_migrations SET migrations = migrations + ? WHERE id = ? ]], { cassandra.list {name}, id })) end return CassandraDB
apache-2.0
maksym1221/nlp-rnn
convert_gpu_cpu_checkpoint.lua
4
2176
--[[ A quick patch for converting GPU checkpoints to CPU checkpoints until I implement a more long-term solution. Takes the path to the model and creates a file in the same location and path, but with _cpu.t7 appended. ]]-- require 'torch' require 'nn' require 'nngraph' require 'lfs' require 'util.OneHot' require 'util.misc' cmd = torch.CmdLine() cmd:text() cmd:text('Sample from a character-level language model') cmd:text() cmd:text('Options') cmd:argument('-model','GPU model checkpoint to convert') cmd:option('-gpuid',0,'which gpu to use. -1 = use CPU') cmd:option('-opencl',0,'use OpenCL (instead of CUDA)') cmd:text() -- parse input params opt = cmd:parse(arg) -- check that cunn/cutorch are installed if user wants to use the GPU if opt.gpuid >= 0 and opt.opencl == 0 then local ok, cunn = pcall(require, 'cunn') local ok2, cutorch = pcall(require, 'cutorch') if not ok then print('package cunn not found!') end if not ok2 then print('package cutorch not found!') end if ok and ok2 then print('using CUDA on GPU ' .. opt.gpuid .. '...') cutorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua else print('Error, no GPU available?') os.exit() end end -- check that clnn/cltorch are installed if user wants to use OpenCL if opt.gpuid >= 0 and opt.opencl == 1 then local ok, cunn = pcall(require, 'clnn') local ok2, cutorch = pcall(require, 'cltorch') if not ok then print('package clnn not found!') end if not ok2 then print('package cltorch not found!') end if ok and ok2 then print('using OpenCL on GPU ' .. opt.gpuid .. '...') cltorch.setDevice(opt.gpuid + 1) -- note +1 to make it 0 indexed! sigh lua else print('Error, no GPU available?') os.exit() end end print('loading ' .. opt.model) checkpoint = torch.load(opt.model) protos = checkpoint.protos -- convert the networks to be CPU models for k,v in pairs(protos) do print('converting ' .. k .. ' to CPU') protos[k]:double() end local savefile = opt.model .. '_cpu.t7' -- append "cpu.t7" to filename torch.save(savefile, checkpoint) print('saved ' .. savefile)
gpl-3.0
Scavenge/darkstar
scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm2.lua
30
1377
----------------------------------- -- Area: Alzadaal Undersea Ruins -- NPC: ??? (Spawn Cheese Hoarder Gigiroon(ZNM T1)) -- @pos -184 -8 24 72 ----------------------------------- package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"); require("scripts/globals/status"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local mobID = 17072172; if (trade:hasItemQty(2582,1) and trade:getItemCount() == 1) then -- Trade Rodent Cheese if (GetMobAction(mobID) == ACTION_NONE) then player:tradeComplete(); SpawnMob(mobID):updateClaim(player); end 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
Scavenge/darkstar
scripts/zones/Northern_San_dOria/npcs/Eugballion.lua
17
1713
----------------------------------- -- Area: Northern San d'Oria -- NPC: Eugballion -- Only sells when San d'Oria controlls Qufim Region ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/conquest"); require("scripts/globals/quests"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (GetRegionOwner(QUFIMISLAND) ~= NATION_SANDORIA) then player:showText(npc,EUGBALLION_CLOSED_DIALOG); else player:showText(npc,EUGBALLION_OPEN_DIALOG); local stock = {0x03ba,4121} -- Magic Pot Shard showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Zero-K-Experiments/Zero-K-Experiments
units/roostfac.lua
3
2713
unitDef = { unitname = [[roostfac]], name = [[Roost]], description = [[Spawns Big Chickens]], acceleration = 0, brakeRate = 0, buildCostEnergy = 0, buildCostMetal = 0, builder = true, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 11, buildingGroundDecalSizeY = 11, buildingGroundDecalType = [[roostfac_aoplane.dds]], buildoptions = { [[chicken_drone]], [[chickenf]], [[chicken_blimpy]], [[chicken_listener]], [[chickena]], [[chickenc]], [[chickenblobber]], [[chicken_spidermonkey]], [[chicken_tiamat]], [[chicken_dragon]], }, buildPic = [[roostfac.png]], buildTime = 200, canMove = true, canPatrol = true, canstop = [[1]], category = [[SINK UNARMED]], customParams = { description_de = [[Erzeugt große Chicken]], helptext = [[Roosts such as this one are where the more powerful Thunderbirds are hatched.]], helptext_de = [[Mächtige Kreaturen werden hier erzeugt und losgelassen.]], chickenFac = [[true]], }, energyMake = 1, energyStorage = 50, energyUse = 0, explodeAs = [[NOWEAPON]], footprintX = 8, footprintZ = 8, iconType = [[factory]], idleAutoHeal = 5, idleTime = 1800, maxDamage = 8000, maxSlope = 15, maxVelocity = 0, metalMake = 1.05, metalStorage = 50, minCloakDistance = 150, noAutoFire = false, objectName = [[roostfac_big]], power = 1000, seismicSignature = 4, selfDestructAs = [[NOWEAPON]], sfxtypes = { explosiongenerators = { [[custom:dirt2]], [[custom:dirt3]], [[custom:Nano]], }, }, showNanoSpray = false, sightDistance = 273, turnRate = 0, useBuildingGroundDecal = true, workerTime = 42, yardMap = [[ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ooccccoo ]], featureDefs = { }, } return lowerkeys({ roostfac = unitDef })
gpl-2.0
Scavenge/darkstar
scripts/zones/Lower_Jeuno/npcs/Bluffnix.lua
25
5561
----------------------------------- -- Area: Lower Jeuno -- NPC: Bluffnix -- Starts and Finishes Quests: Gobbiebags I-X -- @pos -43.099 5.900 -114.788 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local count = trade:getItemCount(); local gil = trade:getGil(); local inventorySize = player:getContainerSize(0); local TheGobbieBag = gobQuest(player,inventorySize); local pFame = player:getFameLevel(JEUNO); if (count == 4 and gil == 0 and player:getQuestStatus(JEUNO,TheGobbieBag[1]) == 1) then if (player:getContainerSize(0) < 80) then if (trade:hasItemQty(TheGobbieBag[3],1) and trade:hasItemQty(TheGobbieBag[4],1) and trade:hasItemQty(TheGobbieBag[5],1) and trade:hasItemQty(TheGobbieBag[6],1)) then if (pFame >= TheGobbieBag[2]) then player:startEvent(0x0049, inventorySize+1); offer = 1; else player:startEvent(0x002b,inventorySize+1,questStatus,offer); end end else player:startEvent(0x002b,81); -- You're bag's bigger than any gobbie bag I've ever seen...; end end end; --------------------------------------------- -- Current Quest, Required Fame and Items --------------------------------------------- function gobQuest(player,bagSize) currentQuest = {}; switch (bagSize) : caseof { [30] = function (x) currentQuest = {27,3,0848,0652,0826,0788}; end, --Gobbiebag I, Dhalmel Leather, Steel Ingot, Linen Cloth, Peridot [35] = function (x) currentQuest = {28,4,0851,0653,0827,0798}; end, --Gobbiebag II, Ram Leather, Mythril Ingot, Wool Cloth, Turquoise [40] = function (x) currentQuest = {29,5,0855,0745,0828,0797}; end, --Gobbiebag III, Tiger Leather, Gold Ingot, Velvet Cloth, Painite [45] = function (x) currentQuest = {30,5,0931,0654,0829,0808}; end, --Gobbiebag IV, Cermet Chunk, Darksteel Ingot, Silk Cloth, Goshenite [50] = function (x) currentQuest = {74,6,1637,1635,1636,1634}; end, --Gobbiebag V, Bugard Leather, Paktong Ingot, Moblinweave, Rhodonite [55] = function (x) currentQuest = {75,6,1741,1738,1739,1740}; end, --Gobbiebag VI, HQ Eft Skin, Shakudo Ingot, Balloon Cloth, Iolite [60] = function (x) currentQuest = {93,7,2530,0655,0830,0812}; end, --Gobbiebag VII, Lynx Leather, Adaman Ingot, Rainbow Cloth, Deathstone [65] = function (x) currentQuest = {94,7,2529,2536,2537,0813}; end, --Gobbiebag VIII, Smilodon Leather, Electrum Ingot, Square of Cilice, Angelstone [70] = function (x) currentQuest = {123,8,2538,0747,2704,2743}; end, --Gobbiebag IX, Peiste Leather, Orichalcum Ingot, Oil-Soaked Cloth, Oxblood Orb [75] = function (x) currentQuest = {124,9,1459,1711,2705,2744}; end, --Gobbiebag X, Griffon Leather, Molybdenum Ingot, Foulard, Angelskin Orb default = function (x) end, } return currentQuest; end; ---------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,12) == false) then player:startEvent(10056); elseif (player:getContainerSize(0) < 80) then local pFame = player:getFameLevel(JEUNO); local inventorySize = player:getContainerSize(0); local TheGobbieBag = gobQuest(player,inventorySize); local questStatus = player:getQuestStatus(JEUNO,TheGobbieBag[1]); offer = 0; if (pFame >= TheGobbieBag[2]) then offer = 1; end player:startEvent(0x002b,inventorySize+1,questStatus,offer); else player:startEvent(0x002b,81); -- You're bag's bigger than any gobbie bag I've ever seen...; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local TheGobbieBag = gobQuest(player,player:getContainerSize(0)); if (csid == 0x002b and option == 0) then if (player:getQuestStatus(JEUNO,TheGobbieBag[1]) == 0) then player:addQuest(JEUNO,TheGobbieBag[1]); end elseif (csid == 0x0049) then if (gobbieBag == 5) then player:addTitle(GREEDALOX); elseif (gobbieBag == 10) then player:addTitle(GRAND_GREEDALOX); end player:changeContainerSize(0,5); player:changeContainerSize(5,5); player:changeContainerSize(6,5); player:addFame(JEUNO, 30); player:tradeComplete(); player:completeQuest(JEUNO,TheGobbieBag[1]); player:messageSpecial(INVENTORY_INCREASED); elseif (csid == 10056) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",12,true); end end;
gpl-3.0
Scavenge/darkstar
scripts/globals/weaponskills/thunder_thrust.lua
23
1307
----------------------------------- -- Thunder Thrust -- Polearm weapon skill -- Skill Level: 30 -- Deals lightning elemental damage to enemy. Damage varies with TP. -- Aligned with the Light Gorget & Thunder Gorget. -- Aligned with the Light Belt & Thunder Belt. -- Element: Lightning -- Modifiers: STR:40% ; INT:40% -- 100%TP 200%TP 300%TP -- 1.50 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, tp, primary, action, taChar) local params = {}; params.ftp100 = 1.5; 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_LIGHTNING; params.skill = SKILL_POL; 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, wsID, tp, primary, action, params); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
1yvT0s/luvit
tests/test-fs-long-path.lua
11
1553
--[[ Copyright 2012-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local math = require('math') local string = require('string') local FS = require('fs') local Path = require('path') local JSON = require('json') local successes = 0 -- make a path that will be at least 260 chars long. local tmpDir = Path.join(module.dir, 'tmp') local fileNameLen = math.max(260 - #tmpDir - 1, 1) local fileName = Path.join(tmpDir, string.rep('x', fileNameLen)) test('fs longpoath', function() p('fileName=' .. fileName) p('fileNameLength=' .. #fileName) FS.writeFile(fileName, 'ok', function(err) if err then return err end successes = successes + 1 FS.stat(fileName, function(err, stats) if err then return err else successes = successes + 1 assert(successes == 2) if successes > 0 then FS.unlinkSync(fileName) end end end) end) end) end)
apache-2.0
novokrest/chdkptp
lua/chdku.lua
1
44872
--[[ Copyright (C) 2010-2014 <reyalp (at) gmail dot com> This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License version 2 as published by the Free Software Foundation. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA ]] --[[ lua helper functions for working with the chdk.* c api ]] local chdku={} chdku.rlibs = require('rlibs') chdku.sleep = sys.sleep -- to allow override -- format a script message in a human readable way function chdku.format_script_msg(msg) if msg.type == 'none' then return '' end local r=string.format("%d:%s:",msg.script_id,msg.type) -- for user messages, type is clear from value, strings quoted, others not if msg.type == 'user' or msg.type == 'return' then if msg.subtype == 'boolean' or msg.subtype == 'integer' or msg.subtype == 'nil' then r = r .. tostring(msg.value) elseif msg.subtype == 'string' then r = r .. string.format("'%s'",msg.value) else r = r .. msg.subtype .. ':' .. tostring(msg.value) end elseif msg.type == 'error' then r = r .. msg.subtype .. ':' .. tostring(msg.value) end return r end --[[ Camera timestamps are in seconds since Jan 1, 1970 in current camera time PC timestamps (linux, windows) are since Jan 1, 1970 UTC return offset of current PC time from UTC time, in seconds ]] function chdku.ts_get_offset() -- local timestamp, assumed to be seconds since unix epoch local tslocal=os.time() -- !*t returns a table of hours, minutes etc in UTC (without a timezone spec) -- the dst flag is overridden using the local value -- os.time turns this into a timestamp, treating as local time local ttmp = os.date('!*t',tslocal) ttmp.isdst = os.date('*t',tslocal).isdst return tslocal - os.time(ttmp) end --[[ covert a timestamp from the camera to the equivalent local time on the pc ]] function chdku.ts_cam2pc(tscam) local tspc = tscam - chdku.ts_get_offset() -- TODO -- on windows, a time < 0 causes os.date to return nil -- these can appear from the cam if you set 0 with utime and have a negative utc offset -- since this is a bogus date anyway, just force it to zero to avoid runtime errors if tspc > 0 then return tspc end return 0 end --[[ covert a timestamp from the pc to the equivalent on the camera default to current time if none given ]] function chdku.ts_pc2cam(tspc) if not tspc then tspc = os.time() end local tscam = tspc + chdku.ts_get_offset() -- TODO -- cameras handle < 0 times inconsistently (vxworks > 2100, dryos < 1970) if tscam > 0 then return tscam end return 0 end --[[ connection methods, added to the connection object ]] local con_methods = {} --[[ check whether this cameras model and serial number match those given assumes self.ptpdev is up to date bool = con:match_ptp_info(match) { model='model pattern' serial='serial number pattern' plain=bool -- plain text match } empty / false model or serial matches any ]] function con_methods:match_ptp_info(match) if match.model and not string.find(self.ptpdev.model,match.model,1,match.plain) then return false end -- older cams don't have serial local serial = '' if self.ptpdev.serial_number then serial = self.ptpdev.serial_number end if match.serial and not string.find(serial,match.serial,1,match.plain) then return false end return true end --[[ check if connection API is major and >= minor todo might want to allow major >= in some cases ]] function con_methods:is_ver_compatible(major,minor) -- API ver not initialized -- TODO maybe it should just be an error to call without connecting? if not self.apiver then return false end if self.apiver.MAJOR ~= major or self.apiver.MINOR < minor then return false end return true end --[[ return a list of remote directory contents dirlist=con:listdir(path,opts) path should be directory, without a trailing slash (except in the case of A/...) opts may be a table, or a string containing lua code for a table returns directory listing as table, throws on local or remote error note may return an empty table if target is not a directory ]] function con_methods:listdir(path,opts) if type(opts) == 'table' then opts = serialize(opts) elseif type(opts) ~= 'string' and type(opts) ~= 'nil' then return false, "invalid options" end if opts then opts = ','..opts else opts = '' end local results={} local i=1 local rstatus,err=self:execwait("return ls('"..path.."'"..opts..")",{ libs='ls', msgs=chdku.msg_unbatcher(results), }) if not rstatus then errlib.throw{etype='remote',msg=err} end return results end local function mdownload_single(lcon,finfo,lopts,src,dst) local st -- if not always overwrite, check local if lopts.overwrite ~= true then st = lfs.attributes(dst) end if st then local skip if not lopts.overwrite then skip=true elseif type(lopts.overwrite) == 'function' then skip = not lopts.overwrite(lcon,lopts,finfo,st,src,dst) else error("unexpected overwrite option") end if skip then -- TODO printf('skip existing %s\n',dst) return true end end -- ptp download fails on zero byte files (zero size data phase, possibly other problems) if finfo.st.size > 0 then lcon:download(src,dst) else local f,err=io.open(dst,"wb") if not f then error(err) end f:close() end if lopts.mtime then status,err = lfs.touch(dst,chdku.ts_cam2pc(finfo.st.mtime)); if not status then error(err) end end return true end --[[ download files and directories con:mdownload(srcpaths,dstpath,opts) opts: mtime=bool -- keep (default) or discard remote mtime NOTE files only for now overwrite=bool|function -- overwrite if existing found other opts are passed to find_files throws on error ]] function con_methods:mdownload(srcpaths,dstpath,opts) if not dstpath then dstpath = '.' end local lopts=extend_table({mtime=true,overwrite=true},opts) local ropts=extend_table({},opts) ropts.dirsfirst=true -- unset options that don't apply to remote ropts.mtime=nil ropts.overwrite=nil local dstmode = lfs.attributes(dstpath,'mode') if dstmode and dstmode ~= 'directory' then errlib.throw{etype='badparm',msg='mdownload: dest must be a directory'} end local files={} if lopts.dbgmem then files._dbg_fn=function(self,chunk) if chunk._dbg then printf("dbg: %s\n",tostring(chunk._dbg)) end end end local rstatus,rerr = self:execwait('return ff_mdownload('..serialize(srcpaths)..','..serialize(ropts)..')', {libs={'ff_mdownload'},msgs=chdku.msg_unbatcher(files)}) if not rstatus then errlib.throw{etype='remote',msg=rerr} end if #files == 0 then util.warnf("no matching files\n"); return true end local mkdir, download local function nop() return true end if lopts.pretend then mkdir=nop download=nop else mkdir=fsutil.mkdir_m download=mdownload_single end if not dstmode then mkdir(dstpath) end for i,finfo in ipairs(files) do local relpath local src,dst src = finfo.full if #finfo.path == 1 then relpath = finfo.name else if #finfo.path == 2 then relpath = finfo.path[2] else relpath = fsutil.joinpath(unpack(finfo.path,2)) end end dst=fsutil.joinpath(dstpath,relpath) if finfo.st.is_dir then mkdir(dst) else local dst_dir = fsutil.dirname(dst) if dst_dir ~= '.' then mkdir(dst_dir) end -- TODO this should be optional printf("%s->%s\n",src,dst); download(self,finfo,lopts,src,dst) end end end --[[ upload files and directories status[,err]=con:mupload(srcpaths,dstpath,opts) opts are as for find_files, plus pretend: just print what would be done mtime: preserve mtime of local files ]] local function mupload_fn(self,opts) local con=opts.con if #self.rpath == 0 and self.cur.st.mode == 'directory' then return end if self.cur.name == '.' or self.cur.name == '..' then return end local relpath local src=self.cur.full if #self.cur.path == 1 then relpath = self.cur.name else if #self.cur.path == 2 then relpath = self.cur.path[2] else relpath = fsutil.joinpath(unpack(self.cur.path,2)) end end local dst=fsutil.joinpath_cam(opts.mu_dst,relpath) if self.cur.st.mode == 'directory' then if opts.pretend then printf('remote mkdir_m(%s)\n',dst) else local status,err=con:mkdir_m(dst) if not status then errlib.throw{etype='remote',msg=tostring(err)} end end opts.lastdir = dst else local dst_dir=fsutil.dirname_cam(dst) -- cache target directory so we don't have an extra stat call for every file in that dir if opts.lastdir ~= dst_dir then local st,err=con:stat(dst_dir) if st then if not st.is_dir then errlib.throw{etype='remote',msg='not a directory: '..tostring(dst_dir)} end else if opts.pretend then printf('remote mkdir_m(%s)\n',dst_dir) else local status,err=con:mkdir_m(dst_dir) if not status then errlib.throw{etype='remote',msg=tostring(err)} end end end opts.lastdir = dst_dir end -- TODO stat'ing in batches would be faster local st,err=con:stat(dst) if st and not st.is_file then errlib.throw{etype='remote',msg='not a file: '..tostring(dst)} end -- TODO timestamp comparison printf('%s->%s\n',src,dst) if not opts.pretend then con:upload(src,dst) if opts.mtime then -- TODO updating times in batches would be faster local status,err = con:utime(dst,chdku.ts_pc2cam(self.cur.st.modification)) if not status then errlib.throw{etype='remote',msg=tostring(err)} end end end end end function con_methods:mupload(srcpaths,dstpath,opts) opts = util.extend_table({mtime=true},opts) opts.dirsfirst=true opts.mu_dst=dstpath opts.con=self fsutil.find_files(srcpaths,opts,mupload_fn) end --[[ delete files and directories opts are as for find_files, plus pretend:only return file name and action, don't delete skip_topdirs: top level directories passed in paths will not be removed e.g. mdelete({'A/FOO'},{skip_topdirs=true}) will delete everything in FOO, but not foo itself ignore_errors: ignore failed deletes ]] function con_methods:mdelete(paths,opts) opts=extend_table({},opts) opts.dirsfirst=false -- delete directories only after recursing into local results local msg_handler if opts.msg_handler then msg_handler = opts.msg_handler opts.msg_handler = nil -- don't pass to remote else results={} msg_handler = chdku.msg_unbatcher(results) end local status,err = self:call_remote('ff_mdelete',{libs={'ff_mdelete'},msgs=msg_handler},paths,opts) if not status then errlib.throw{etype='remote',msg=tostring(err)} end if results then return results end end --[[ wrapper for remote functions, serialize args, combine remote and local error status func must be a string that evaluates to a function on the camera returns remote function return values on success, throws on error ]] function con_methods:call_remote(func,opts,...) local args = {...} local argstrs = {} -- preserve nils between values (not trailing ones but shouldn't matter in most cases) for i = 1,table.maxn(args) do argstrs[i] = serialize(args[i]) end local code = "return "..func.."("..table.concat(argstrs,',')..")" -- printf("%s\n",code) local results = {self:execwait(code,opts)} return unpack(results,1,table.maxn(results)) -- maxn expression preserves nils end function con_methods:stat(path) return self:call_remote('os.stat',nil,path) end function con_methods:utime(path,mtime,atime) return self:call_remote('os.utime',nil,path,mtime,atime) end function con_methods:mdkir(path) return self:call_remote('os.mkdir',nil,path) end function con_methods:remove(path) return self:call_remote('os.remove',nil,path) end function con_methods:mkdir_m(path) return self:call_remote('mkdir_m',{libs='mkdir_m'},path) end --[[ sort an array of stat+name by directory status, name ]] function chdku.sortdir_stat(list) table.sort(list,function(a,b) if a.is_dir and not b.is_dir then return true end if not a.is_dir and b.is_dir then return false end return a.name < b.name end) end --[[ read pending messages and return error from current script, if available ]] function con_methods:get_error_msg() while true do local msg = self:read_msg() if msg.type == 'none' then return false end if msg.type == 'error' and msg.script_id == self:get_script_id() then return msg end util.warnf("chdku.get_error_msg: ignoring message %s\n",chdku.format_script_msg(msg)) end end --[[ format a remote lua error from chdku.exec using line number information ]] local function format_exec_error(libs,code,msg) local errmsg = msg.value local lnum=tonumber(string.match(errmsg,'^%s*:(%d+):')) if not lnum then print('no match '..errmsg) return errmsg end local l = 0 local lprev, errlib, errlnum for i,lib in ipairs(libs.list) do lprev = l l = l + lib.lines + 1 -- TODO we add \n after each lib when building code if l >= lnum then errlib = lib errlnum = lnum - lprev break end end if errlib then return string.format("%s\nrlib %s:%d\n",errmsg,errlib.name,errlnum) else return string.format("%s\nuser code: %d\n",errmsg,lnum - l) end end --[[ read and discard all pending messages. throws on error ]] function con_methods:flushmsgs() repeat local msg=self:read_msg() until msg.type == 'none' end --[[ read all pending messages, processing as specified by opts opts { default=handler -- for all not matched by a specific handler user=handler return=handler error=handler } handler = table or function(msg,opts) throws on error returns true unless aborted by handler handler function may abort by returning false or throwing ]] function con_methods:read_all_msgs(opts) opts = util.extend_table({},opts) -- if an 'all' handler is given, use it for any that don't have a specific handler if opts.default then for i,mtype in ipairs({'user','return','error'}) do if not opts[mtype] then opts[mtype] = opts.default end end end while true do msg=self:read_msg() if msg.type == 'none' then break end local handler = opts[msg.type] if type(handler) == 'table' then table.insert(handler,msg) elseif type(handler) == 'function' then local status, err = handler(msg,opts) -- nil / no return value is NOT treated as an error if status == false then return false, err end elseif handler then -- nil or false = ignore error('invalid handler') end end return true end --[[ return a closure to be used with as a chdku.exec msgs function, which unbatches messages msg_batcher into t ]] function chdku.msg_unbatcher(t) local i=1 return function(msg) if msg.subtype ~= 'table' then return errlib.throw{etype='wrongmsg_sub',msg='wrong message subtype: ' ..tostring(msg.subtype)} end local chunk,err=unserialize(msg.value) if err then return errlib.throw{etype='unserialize',msg=tostring(err)} end for j,v in ipairs(chunk) do t[i]=v i=i+1 end if type(t._dbg_fn) == 'function' then t:_dbg_fn(chunk) end return true end end --[[ wrapper for chdk.execlua, using optional code from rlibs [remote results]=con:exec("code",opts) opts { libs={"rlib name1","rlib name2"...} -- rlib code to be prepended to "code" wait=bool -- wait for script to complete, return values will be returned after status if true nodefaultlib=bool -- don't automatically include default rlibs clobber=bool -- if false, will check script-status and refuse to execute if script is already running -- clobbering is likely to result in crashes / memory leaks in chdk prior to 1.3 flush_cam_msgs=bool -- if true (default) read and silently discard any pending messages from previous script before running script -- Prior to 1.3, ignored if clobber is true, since the running script could just spew messages indefinitely flush_host_msgs=bool -- Only supported in 1.3 and later, flush any message from the host unread by previous script -- below only apply if with wait msgs={table|callback} -- table or function to receive user script messages rets={table|callback} -- table or function to receive script return values, instead of returning them fdata={any lua value} -- data to be passed as second argument to callbacks initwait={ms|false} -- passed to wait_status, wait before first poll poll={ms} -- passed to wait_status, poll interval after ramp up pollstart={ms|false} -- passed to wait_status, initial poll interval, ramps up to poll } callbacks f(message,fdata) callbacks should throw an error to abort processing return value is ignored returns if wait is set and rets is not, returns values returned by remote code otherwise returns nothing throws on error ]] -- use serialize by default chdku.default_libs={ 'serialize_msgs', } -- script execute flags, for proto 2.6 and later chdku.execflags={ nokill=0x100, flush_cam_msgs=0x200, flush_host_msgs=0x400, } --[[ convenience, defaults wait=true ]] function con_methods:execwait(code,opts_in) return self:exec(code,extend_table({wait=true,initwait=5},opts_in)) end function con_methods:exec(code,opts_in) -- setup the options local opts = extend_table({flush_cam_msgs=true,flush_host_msgs=true},opts_in) local liblist={} -- add default libs, unless disabled -- TODO default libs should be per connection if not opts.nodefaultlib then extend_table(liblist,chdku.default_libs) end -- allow a single lib to be given as by name if type(opts.libs) == 'string' then liblist={opts.libs} else extend_table(liblist,opts.libs) end local execflags = 0 -- in protocol 2.6 and later, handle kill and message flush in script exec call if self:is_ver_compatible(2,6) then if not opts.clobber then execflags = chdku.execflags.nokill end -- TODO this doesn't behave the same as flushmsgs in pre 2.6 -- works whether or not clobber is set, flushes both inbound and outbound if opts.flush_cam_msgs then execflags = execflags + chdku.execflags.flush_cam_msgs end if opts.flush_host_msgs then execflags = execflags + chdku.execflags.flush_host_msgs end else -- check for already running script and flush messages if not opts.clobber then -- this requires an extra PTP round trip per exec call local status = self:script_status() if status.run then errlib.throw({etype='execlua_scriptrun',msg='a script is already running'}) end if opts.flush_cam_msgs and status.msg then self:flushmsgs() end end end -- build the complete script from user code and rlibs local libs = chdku.rlibs:build(liblist) code = libs:code() .. code -- try to start the script -- catch errors so we can handle compile errors local status,err=self:execlua_pcall(code,execflags) if not status then -- syntax error, try to fetch the error message if err.etype == 'execlua_compile' then local msg = self:get_error_msg() if msg then -- add full details to message -- TODO could just add to a new field and let caller deal with it -- but would need lib code err.msg = format_exec_error(libs,code,msg) end end -- other unspecified error, or fetching syntax/compile error message failed error(err) end -- if not waiting, we're done if not opts.wait then return end -- to collect return values local results={} local i=1 -- process messages and wait for script to end while true do status=self:wait_status{ msg=true, run=false, initwait=opts.initwait, poll=opts.poll, pollstart=opts.pollstart } if status.msg then local msg=self:read_msg() if msg.script_id ~= self:get_script_id() then util.warnf("chdku.exec: message from unexpected script %d %s\n",msg.script_id,chdku.format_script_msg(msg)) elseif msg.type == 'user' then if type(opts.msgs) == 'function' then opts.msgs(msg,opts.fdata) elseif type(opts.msgs) == 'table' then table.insert(opts.msgs,msg) else util.warnf("chdku.exec: unexpected user message %s\n",chdku.format_script_msg(msg)) end elseif msg.type == 'return' then if type(opts.rets) == 'function' then opts.rets(msg,opts.fdata) elseif type(opts.rets) == 'table' then table.insert(opts.rets,msg) else -- if serialize_msgs is not selected, table return values will be strings if msg.subtype == 'table' and libs.map['serialize_msgs'] then results[i] = unserialize(msg.value) else results[i] = msg.value end i=i+1 end elseif msg.type == 'error' then errlib.throw{etype='exec_runtime',msg=format_exec_error(libs,code,msg)} else errlib.throw({etype='wrongmsg',msg='unexpected msg type: '..tostring(msg.type)}) end -- script is completed and all messages have been processed elseif status.run == false then -- returns were handled by callback or table if opts.rets then return else return unpack(results,1,table.maxn(results)) -- maxn expression preserves nils end end end end --[[ convenience method, get a message of a specific type mtype=<string> - expected message type msubtype=<string|nil> - expected subtype, or nil for any munserialize=<bool> - unserialize and return the message value, only valid for user/return returns message|msg value ]] function con_methods:read_msg_strict(opts) opts=extend_table({},opts) local msg=self:read_msg() if msg.type == 'none' then errlib.throw({etype='nomsg',msg='read_msg_strict no message'}) end if msg.script_id ~= self:get_script_id() then errlib.throw({etype='bad_script_id',msg='msg from unexpected script id'}) end if msg.type ~= opts.mtype then if msg.type == 'error' then errlib.throw({etype='wrongmsg_error',msg='unexpected error: '..msg.value}) end errlib.throw({etype='wrongmsg',msg='unexpected msg type: '..tostring(msg.type)}) end if opts.msubtype and msg.subtype ~= opts.msubtype then errlib.throw({etype='wrongmsg_sub',msg='wrong message subtype: ' ..msg.subtype}) end if opts.munserialize then local v = util.unserialize(msg.value) if opts.msubtype and type(v) ~= opts.msubtype then errlib.throw({etype='unserialize',msg='unserialize error'}) end return v end return msg end --[[ convenience method, wait for a single message and return it throws if matching message is not available within timeout opts passed wait_status, and read_msg_strict ]] function con_methods:wait_msg(opts) opts=extend_table({},opts) opts.msg=true opts.run=nil local status=self:wait_status(opts) if status.timeout then errlib.throw({etype='timeout',msg='wait_msg timed out'}) end if not status.msg then errlib.throw({etype='nomsg',msg='wait_msg no message'}) end return self:read_msg_strict(opts) end -- bit number to ext + id mapping chdku.remotecap_dtypes={ [0]={ ext='jpg', id=1, -- actual limit isn't clear, sanity check so bad hook won't fill up disk -- MAX_CHUNKS_FOR_JPEG is per session, dryos > r50 can have multiple sessions max_chunks=100, }, { ext='raw', id=2, max_chunks=1, }, { ext='dng_hdr', -- header only id=4, max_chunks=1, }, } --[[ return a handler that stores collected chunks into an array or using a function ]] function chdku.rc_handler_store(store) return function(lcon,hdata) local store_fn if not store then store_fn = hdata.store_return elseif type(store) == 'function' then store_fn = store elseif type(store) == 'table' then store_fn = function(val) table.insert(store,val) end else return false,'invalid store target' end local chunk local n_chunks = 0 repeat local status,err cli.dbgmsg('rc chunk get %d %d\n',hdata.id,n_chunks) status,chunk=lcon:capture_get_chunk_pcall(hdata.id) if not status then return false,chunk end cli.dbgmsg('rc chunk size:%d offset:%s last:%s\n', chunk.size, tostring(chunk.offset), tostring(chunk.last)) chunk.imgnum = hdata.imgnum -- for convenience, store image number in chunk status,err = store_fn(chunk) if status==false then -- allow nil so simple functions don't need to return a value return false,err end n_chunks = n_chunks + 1 until chunk.last or n_chunks > hdata.max_chunks if n_chunks > hdata.max_chunks then return false, 'exceeded max_chunks' end return true end end function chdku.rc_build_path(hdata,dir,filename,ext) if not filename then filename = string.format('IMG_%04d',hdata.imgnum) end if ext then filename = filename..'.'..ext else filename = filename..'.'..hdata.ext end if dir then filename = fsutil.joinpath(dir,filename) end return filename end function chdku.rc_process_dng(dng_info,raw) local hdr,err=dng.bind_header(dng_info.hdr) if not hdr then return false, err end -- TODO makes assumptions about header layout local ifd=hdr:get_ifd{0,0} -- assume main image is first subifd of first ifd if not ifd then return false, 'ifd 0.0 not found' end local ifd0=hdr:get_ifd{0} -- assume thumb is first ifd if not ifd0 then return false, 'ifd 0 not found' end raw.data:reverse_bytes() local bpp = ifd.byname.BitsPerSample:getel() local width = ifd.byname.ImageWidth:getel() local height = ifd.byname.ImageLength:getel() cli.dbgmsg('dng %dx%dx%d\n',width,height,bpp) -- values are assumed to be valid -- sub-image, pad if dng_info.lstart ~= 0 or dng_info.lcount ~= 0 then -- TODO assume a single strip with full data local fullraw = lbuf.new(ifd.byname.StripByteCounts:getel()) local offset = (width * dng_info.lstart * bpp)/8; --local blacklevel = ifd.byname.BlackLevel:getel() -- filling with blacklevel would be nicer but max doesn't care about byte order fullraw:fill(string.char(0xff),0,offset) -- fill up to data -- copy fullraw:fill(raw.data,offset,1) fullraw:fill(string.char(0xff),offset+raw.data:len()) -- fill remainder -- replace original data raw.data=fullraw end local twidth = ifd0.byname.ImageWidth:getel() local theight = ifd0.byname.ImageLength:getel() local status, err = pcall(hdr.set_data,hdr,raw.data) if not status then cli.dbgmsg('not creating thumb: %s\n',tostring(err)) dng_info.thumb = lbuf.new(twidth*theight*3) return true -- thumb failure isn't fatal end if dng_info.badpix then cli.dbgmsg('patching badpixels: ') local bcount=hdr.img:patch_pixels(dng_info.badpix) -- TODO should use values from opcodes cli.dbgmsg('%d\n',bcount) end cli.dbgmsg('creating thumb: %dx%d\n',twidth,theight) -- TODO assumes header is set up for RGB uncompressed -- TODO could make a better / larger thumb than default and adjust entries dng_info.thumb = hdr.img:make_rgb_thumb(twidth,theight) return true end --[[ return a raw handler that will take a previously received dng header and build a DNG file dng_info: lstart=<number> sub image start lcount=<number> sub image lines hdr=<lbuf> dng header lbuf ]] function chdku.rc_handler_raw_dng_file(dir,filename_base,ext,dng_info) return function(lcon,hdata) local filename,err = chdku.rc_build_path(hdata,dir,filename_base,'dng') if not filename then return false, err end if not dng_info then return false, 'missing dng_info' end if not dng_info.hdr then return false, 'missing dng_hdr' end cli.dbgmsg('rc file %s %d\n',filename,hdata.id) local fh,err=io.open(filename,'wb') if not fh then return false, err end cli.dbgmsg('rc chunk get %s %d\n',filename,hdata.id) local status,raw=lcon:capture_get_chunk_pcall(hdata.id) if not status then return false, raw end cli.dbgmsg('rc chunk size:%d offset:%s last:%s\n', raw.size, tostring(raw.offset), tostring(raw.last)) dng_info.hdr:fwrite(fh) --fh:write(string.rep('\0',128*96*3)) -- TODO fake thumb local status, err = chdku.rc_process_dng(dng_info,raw) if status then dng_info.thumb:fwrite(fh) raw.data:fwrite(fh) end fh:close() return status,err end end --[[ return a handler function that just downloads the data to a file TODO should stream to disk in C code like download ]] function chdku.rc_handler_file(dir,filename_base,ext) return function(lcon,hdata) local filename,err = chdku.rc_build_path(hdata,dir,filename_base,ext) if not filename then return false, err end cli.dbgmsg('rc file %s %d\n',filename,hdata.id) local fh,err = io.open(filename,'wb') if not fh then return false, err end local chunk local n_chunks = 0 -- note only jpeg has multiple chunks repeat cli.dbgmsg('rc chunk get %s %d %d\n',filename,hdata.id,n_chunks) local status status,chunk=lcon:capture_get_chunk_pcall(hdata.id) if not status then fh:close() return false,chunk end cli.dbgmsg('rc chunk size:%d offset:%s last:%s\n', chunk.size, tostring(chunk.offset), tostring(chunk.last)) if chunk.offset then fh:seek('set',chunk.offset) end if chunk.size ~= 0 then chunk.data:fwrite(fh) else -- TODO zero size chunk could be valid but doesn't appear to show up in normal operation util.warnf('ignoring zero size chunk\n') end n_chunks = n_chunks + 1 until chunk.last or n_chunks > hdata.max_chunks fh:close() if n_chunks > hdata.max_chunks then return false, 'exceeded max_chunks' end return true end end function con_methods:capture_is_api_compatible() return self:is_ver_compatible(2,5) end -- --[[ fetch remote capture data rets,errmsg=con:capture_get_data(opts) opts: timeout, initwait, poll, pollstart -- passed to wait_status jpg=handler, raw=handler, dng_hdr=handler, handler: f(lcon,handler_data) handler_data: ext -- extension from remotecap dtypes id -- data type number opts -- options passed to capture_get_data imgnum -- image number store_return() -- a function that can be used to store values for the return value of capture_get_data rets true or array of store_return[bitnum][value] values on success throws on error ]] function con_methods:capture_get_data(opts) opts=util.extend_table({ timeout=20000, },opts) local wait_opts=util.extend_table({rsdata=true},opts,{keys={'timeout','initwait','poll','pollstart'}}) local toget = {} local handlers = {} if not self:capture_is_api_compatible() then error("camera does not support remote capture") end -- TODO can probably combine these if opts.jpg then toget[0] = true handlers[0] = opts.jpg end if opts.raw then toget[1] = true handlers[1] = opts.raw end if opts.dng_hdr then toget[2] = true handlers[2] = opts.dng_hdr end -- table to return chunks (or other values) sent by hdata.store_return local rets = {} local done while not done do local status = con:wait_status(wait_opts) if status.timeout then error('timed out') end if status.rsdata == 0x10000000 then error('remote shoot error') end local avail = util.bit_unpack(status.rsdata) local n_toget = 0 for i=0,2 do if avail[i] == 1 then if not toget[i] then -- TODO could have a nop handler error(string.format('unexpected type %d',i)) end local hdata = util.extend_table({ opts=opts, imgnum=status.rsimgnum, store_return=function(val) if rets[i] then table.insert(rets,val) else rets[i] = {val} end end, },chdku.remotecap_dtypes[i]) local status, err = handlers[i](self,hdata) if not status then error(tostring(err)) end toget[i] = nil end if toget[i] then n_toget = n_toget + 1 end end if n_toget == 0 then done = true end end if #rets > 0 then return rets end return true end --[[ sleep until specified status is matched status=con:wait_status(opts) opts: { -- msg/run bool values cause the function to return when the status matches the given value -- if not set, status of that item is ignored msg=bool run=bool rsdata=bool -- if true, return when remote capture data available, data in status.rsdata timeout=<number> -- timeout in ms timeout_error=bool -- if true, an error is thrown on timeout instead of returning it in status poll=<number> -- polling interval in ms pollstart=<number> -- if not false, start polling at pollstart, double interval each iteration until poll is reached initwait=<number> -- wait N ms before first poll. If this is long enough for call to finish, saves round trip } -- TODO should allow passing in a custom sleep in opts status: { msg:bool -- message status run:bool -- script status rsdata:number -- available remote capture data format rsimgnum:number -- remote capture image number timeout:bool -- true if timed out } rs values are only set if rsdata is requested in opts throws on error ]] function con_methods:wait_status(opts) opts = util.extend_table({ poll=250, pollstart=4, timeout=86400000 -- 1 day },opts) local timeleft = opts.timeout local sleeptime if opts.poll < 50 then opts.poll = 50 end if opts.pollstart then sleeptime = opts.pollstart else sleeptime = opts.poll end if opts.initwait then chdku.sleep(opts.initwait) timeleft = timeleft - opts.initwait end -- if waiting on remotecap state, make sure it's supported if opts.rsdata then if not self:capture_is_api_compatible() then error('camera does not support remote capture') end if type(self.capture_ready) ~= 'function' then error('client does not support remote capture') end end -- TODO timeout should be based on time, not adding up sleep times -- local t0=ustime.new() while true do -- TODO shouldn't poll script status if only waiting on rsdata local status = self:script_status() if opts.rsdata then local imgnum status.rsdata,imgnum = self:capture_ready() -- TODO may want to handle PTP_CHDK_CAPTURE_NOTSET differently if status.rsdata ~= 0 then status.rsimgnum = imgnum return status end end if status.run == opts.run or status.msg == opts.msg then return status end if timeleft > 0 then if opts.pollstart and sleeptime < opts.poll then sleeptime = sleeptime * 2 if sleeptime > opts.poll then sleeptime = opts.poll end end if timeleft < sleeptime then sleeptime = timeleft end chdku.sleep(sleeptime) timeleft = timeleft - sleeptime else if opts.timeout_error then errlib.throw{etype='timeout',msg='timed out'} end status.timeout=true return status end end end --[[ set condev, ptpdev apiver for current connection throws on error if CHDK extension not present, apiver is set to -1,-1 but no error is thrown ]] function con_methods:update_connection_info() -- this currently can't fail, devinfo is always stored in connection object self.condev=self:get_con_devinfo() self.ptpdev=self:get_ptp_devinfo() local status,major,minor=self:camera_api_version_pcall() if not status then local err = major -- device connected doesn't support PTP_OC_CHDK if err.ptp_rc == ptp.RC_OperationNotSupported then self.apiver={MAJOR=-1,MINOR=-1} return end error(err) -- re-throw end self.apiver={MAJOR=major,MINOR=minor} end --[[ override low level connect to gather some useful information that shouldn't change over life of connection opts{ raw:bool -- just call the low level connect (saves ~40ms) } ]] function con_methods:connect(opts) opts = util.extend_table({},opts) self.live = nil chdk_connection.connect(self._con) if opts.raw then return end self:update_connection_info() end --[[ attempt to reconnect to the device opts{ wait=<ms> -- amount of time to wait, default 2 sec to avoid probs with dev numbers changing strict=bool -- fail if model, pid or serial number changes } if strict is not set, reconnect to different device returns true, <message> ]] function con_methods:reconnect(opts) opts=util.extend_table({ wait=2000, strict=true, },opts) if self:is_connected() then self:disconnect() end local ptpdev = self.ptpdev local condev = self.condev -- appears to be needed to avoid device numbers changing (reset too soon ?) chdku.sleep(opts.wait) self:connect() if ptpdev.model ~= self.ptpdev.model or ptpdev.serial_number ~= self.ptpdev.serial_number or condev.product_id ~= self.condev.product_id then if opts.strict then self:disconnect() error('reconnected to a different device') else util.warnf('reconnected to a different device') end end end --[[ all assumed to be 32 bit signed ints for the moment ]] chdku.live_fields={ 'version_major', 'version_minor', 'lcd_aspect_ratio', 'palette_type', 'palette_data_start', 'vp_desc_start', 'bm_desc_start', } chdku.live_fb_desc_fields={ 'fb_type', 'data_start', 'buffer_width', 'visible_width', 'visible_height', 'margin_left', 'margin_top', 'margin_right', 'margin_bot', } chdku.live_frame_map={} chdku.live_fb_desc_map={} --[[ init name->offset mapping ]] local function live_init_maps() for i,name in ipairs(chdku.live_fields) do chdku.live_frame_map[name] = (i-1)*4 end for i,name in ipairs(chdku.live_fb_desc_fields) do chdku.live_fb_desc_map[name] = (i-1)*4 end end live_init_maps() function chdku.live_get_frame_field(frame,field) if not frame then return nil end return frame:get_i32(chdku.live_frame_map[field]) end local live_info_meta={ __index=function(t,key) local frame = rawget(t,'_frame') if frame and chdku.live_frame_map[key] then return chdku.live_get_frame_field(frame,key) end end } local live_fb_desc_meta={ __index=function(t,key) local frame = t._lv._frame if frame and chdku.live_fb_desc_map[key] then return frame:get_i32(t:offset()+chdku.live_fb_desc_map[key]) end end } local live_fb_desc_methods={ get_screen_width = function(self) return self.margin_left + self.visible_width + self.margin_right; end, get_screen_height = function(self) return self.margin_top + self.visible_height + self.margin_bot; end, offset = function(self) return chdku.live_get_frame_field(self._lv._frame,self._offset_name) end, } function chdku.live_fb_desc_wrap(lv,fb_pfx) local t=util.extend_table({ _offset_name = fb_pfx .. '_desc_start', _lv = lv, },live_fb_desc_methods); setmetatable(t,live_fb_desc_meta) return t end function chdku.live_wrap(frame) local t={_frame = frame} t.vp = chdku.live_fb_desc_wrap(t,'vp') t.bm = chdku.live_fb_desc_wrap(t,'bm') setmetatable(t,live_info_meta) return t end --[[ write viewport data to an unscaled pbm image vp_pimg and vp_lb are pimg and lbuf to re-use, if possible TODO should pass in a table instead of returning ]] function chdku.live_dump_vp_pbm(fpath,frame,vp_pimg,vp_lb) vp_pimg = liveimg.get_viewport_pimg(vp_pimg,frame,false) -- TODO may be null if video selected on startup if not vp_pimg then error('no viewport data') end vp_lb = vp_pimg:to_lbuf_packed_rgb(vp_lb) -- TODO ensure directory, pipe support local fh, err = io.open(fpath,'wb') if not fh then error(err) end fh:write(string.format('P6\n%d\n%d\n%d\n', vp_pimg:width(), vp_pimg:height(),255)) vp_lb:fwrite(fh) fh:close() return vp_pimg,vp_lb end --[[ write viewport data to an unscaled RGBA pam image bm_pimg and bm_lb are pimg and lbuf to re-use, if possible TODO should pass in a table instead of returning ]] function chdku.live_dump_bm_pam(fpath,frame,bm_pimg,bm_lb) bm_pimg = liveimg.get_bitmap_pimg(bm_pimg,frame,false) bm_lb = bm_pimg:to_lbuf_packed_rgba(bm_lb) -- TODO ensure directory, pipe support local fh, err = io.open(fpath,'wb') if not fh then error(err) end fh:write(string.format( 'P7\nWIDTH %d\nHEIGHT %d\nDEPTH %d\nMAXVAL %d\nTUPLTYPE RGB_ALPHA\nENDHDR\n', bm_pimg:width(), bm_pimg:height(), 4,255)) bm_lb:fwrite(fh) fh:close() return bm_pimg,vm_lb end --[[ NOTE this only tells if the CHDK protocol supports live view the live sub-protocol might not be fully compatible ]] function con_methods:live_is_api_compatible() return self:is_ver_compatible(2,3) end function con_methods:live_get_frame(what) if not self.live then self.live = chdku.live_wrap() end self.live._frame = self:get_live_data(self.live._frame,what) return true end function con_methods:live_dump_start(filename) if not self:is_connected() then return false,'not connected' end if not self:live_is_api_compatible() then return false,'api not compatible' end -- TODO if not self.live then self.live = chdku.live_wrap() end if not filename then filename = string.format('chdk_%x_%s.lvdump',tostring(con.condev.product_id),os.date('%Y%m%d_%H%M%S')) end --printf('recording to %s\n',dumpname) self.live.dump_fh = io.open(filename,"wb") if not self.live.dump_fh then return false, 'failed to open dumpfile' end -- used to write the size field of each frame self.live.dump_sz_buf = lbuf.new(4) -- header (magic, size of following data, version major, version minor) -- TODO this is ugly self.live.dump_fh:write('chlv') -- magic self.live.dump_sz_buf:set_u32(0,8) -- header size (version major, minor) self.live.dump_sz_buf:fwrite(self.live.dump_fh) self.live.dump_sz_buf:set_u32(0,1) -- version major self.live.dump_sz_buf:fwrite(self.live.dump_fh) self.live.dump_sz_buf:set_u32(0,0) -- version minor self.live.dump_sz_buf:fwrite(self.live.dump_fh) self.live.dump_size = 16; self.live.dump_fn = filename return true end function con_methods:live_dump_frame() if not self.live or not self.live.dump_fh then return false,'not initialized' end if not self.live._frame then return false,'no frame' end self.live.dump_sz_buf:set_u32(0,self.live._frame:len()) self.live.dump_sz_buf:fwrite(self.live.dump_fh) self.live._frame:fwrite(self.live.dump_fh) self.live.dump_size = self.live.dump_size + self.live._frame:len() + 4 return true end -- TODO should ensure this is automatically called when connection is closed, or re-connected function con_methods:live_dump_end() if self.live.dump_fh then self.live.dump_fh:close() self.live.dump_fh=nil end end --[[ meta table for wrapped connection object ]] local con_meta = { __index = function(t,key) return con_methods[key] end } --[[ proxy connection methods from low level object to chdku ]] local function init_connection_methods() for name,func in pairs(chdk_connection) do if con_methods[name] == nil and type(func) == 'function' then con_methods[name] = function(self,...) return chdk_connection[name](self._con,...) end -- pcall variants for things that want to catch errors con_methods[name..'_pcall'] = function(self,...) return pcall(chdk_connection[name],self._con,...) end end end end init_connection_methods() -- methods with pcall wrappers -- generally stuff you would expect to want to examine the error rather than just throwing -- or for direct use with cli:print_status local con_pcall_methods={ 'connect', 'exec', 'execwait', 'wait_status', 'capture_get_data', } local function init_pcall_wrappers() for i,name in ipairs(con_pcall_methods) do if type(con_methods[name]) ~= 'function' then error('tried to wrap non-function '..tostring(name)) end -- pcall variants for things that want to catch errors con_methods[name..'_pcall'] = function(self,...) return pcall(con_methods[name],self,...) end end end init_pcall_wrappers() -- host api version chdku.apiver = chdk.host_api_version() -- host progam version chdku.ver = chdk.program_version() --[[ bool = chdku.match_device(devinfo,match) attempt to find a device specified by the match table { bus='bus pattern' dev='device pattern' product_id = number plain = bool -- plain text match } empty / false dev or bus matches any ]] function chdku.match_device(devinfo,match) --[[ printf('try bus:%s (%s) dev:%s (%s) pid:%s (%s)\n', devinfo.bus, tostring(match.bus), devinfo.dev, tostring(match.dev), devinfo.product_id, tostring(match.product_id)) --]] if match.bus and not string.find(devinfo.bus,match.bus,1,match.plain) then return false end if match.dev and not string.find(devinfo.dev,match.dev,1,match.plain) then return false end return (match.product_id == nil or tonumber(match.product_id)==devinfo.product_id) end --[[ return a connection object wrapped with chdku methods devspec is a table specifying the bus and device name to connect to no checking is done on the existence of the device if devspec is null, a dummy connection is returned TODO this returns a *new* wrapper object, even if one already exist for the underlying object not clear if this is desirable, could cache a table of them ]] function chdku.connection(devspec) local con = {} setmetatable(con,con_meta) con._con = chdk.connection(devspec) return con end return chdku
gpl-2.0
Scavenge/darkstar
scripts/globals/items/choco-katana.lua
12
1197
----------------------------------------- -- ID: 5918 -- Item: Choco-katana -- Food Effect: 3 Min, All Races ----------------------------------------- -- Agility 1 -- Speed 12.5% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,180,5918); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_MOVE, 13); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_MOVE, 13); end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Windurst_Waters/npcs/Baehu-Faehu.lua
17
1582
----------------------------------- -- Area: Windurst Waters -- NPC: Baehu-Faehu -- Only sells when Windurst has control of Sarutabaruta -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(SARUTABARUTA); if (RegionOwner ~= NATION_WINDURST) then player:showText(npc,BAEHUFAEHU_CLOSED_DIALOG); else player:showText(npc,BAEHUFAEHU_OPEN_DIALOG); stock = { 0x115C, 22, --Rarab Tail 0x02B1, 33, --Lauan Log 0x026B, 43, --Popoto 0x1128, 29, --Saruta Orange 0x027B, 18 --Windurstian Tea Leaves } showShop(player,WINDURST,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
Scavenge/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Narito-Pettito.lua
14
1067
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Narito-Pettito -- Type: Standard NPC -- @zone 94 -- @pos -52.674 -5.999 90.403 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01a9); 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
vahidazizi/golbarg
plugins/tools.lua
1
21441
--Begin Tools.lua :) local SUDO = aa2 -- put Your ID here! <=== local function index_function(user_id) for k,v in pairs(_config.admins) do if user_id == v[1] then print(k) return k end end -- If not found return false end local function getindex(t,id) for i,v in pairs(t) do if v == id then return i end end return nil end local function already_sudo(user_id) for k,v in pairs(_config.sudo_users) do if user_id == v then return k end end -- If not found return false end local function reload_plugins( ) plugins = {} load_plugins() end local function sudolist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = "*List of sudo users :*\n" else text = "_لیست سودو های ربات :_\n" end for i=1,#sudo_users do text = text..i.." - "..sudo_users[i].."\n" end return text end local function adminlist(msg) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) local sudo_users = _config.sudo_users if not lang then text = '*List of bot admins :*\n' else text = "_لیست ادمین های ربات :_\n" end local compare = text local i = 1 for v,user in pairs(_config.admins) do text = text..i..'- '..(user[2] or '')..' ➣ ('..user[1]..')\n' i = i +1 end if compare == text then if not lang then text = '_No_ *admins* _available_' else text = '_ادمینی برای ربات تعیین نشده_' end end return text end local function action_by_reply(arg, data) local cmd = arg.cmd if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if cmd == "adminprom" then local function adminprom_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already an_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات بود_", 0, "md") end end table.insert(_config.admins, {tonumber(data.id_), user_name}) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been promoted as_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام ادمین ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, adminprom_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "admindem" then local function admindem_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local nameid = index_function(tonumber(data.id_)) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, admindem_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "visudo" then local function visudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, visudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "desudo" then local function desudo_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, desudo_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd if not tonumber(arg.user_id) then return false end if data.id_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "adminprom" then if is_admin1(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "admindem" then local nameid = index_function(tonumber(data.id_)) if not is_admin1(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل ادمین ربات نبود_", 0, "md") end end table.remove(_config.admins, nameid) save_config() if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been demoted from_ *admin*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام ادمین ربات برکنار شد_", 0, "md") end end if cmd == "visudo" then if already_sudo(tonumber(data.id_)) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات بود_", 0, "md") end end table.insert(_config.sudo_users, tonumber(data.id_)) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _به مقام سودو ربات منتصب شد_", 0, "md") end end if cmd == "desudo" then if not already_sudo(data.id_) then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از قبل سودو ربات نبود_", 0, "md") end end table.remove(_config.sudo_users, getindex( _config.sudo_users, tonumber(data.id_))) save_config() reload_plugins(true) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *sudoer*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* _از مقام سودو ربات برکنار شد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function run(msg, matches) local hash = "gp_lang:"..msg.chat_id_ local lang = redis:get(hash) if tonumber(msg.sender_user_id_) == SUDO then if matches[1] == "visudo" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="visudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="visudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="visudo"}) end end if matches[1] == "desudo" then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="desudo"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="desudo"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="desudo"}) end end end if matches[1] == "adminprom" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="adminprom"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="adminprom"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="adminprom"}) end end if matches[1] == "admindem" and is_sudo(msg) then if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.chat_id_, message_id_ = msg.reply_to_message_id_ }, action_by_reply, {chat_id=msg.chat_id_,cmd="admindem"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="admindem"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="admindem"}) end end if matches[1] == 'creategroup' and is_admin(msg) then local text = matches[2] tdcli.createNewGroupChat({[0] = msg.sender_user_id_}, text) if not lang then return '_Group Has Been Created!_' else return '_گروه ساخته شد!_' end end if matches[1] == 'createsuper' and is_admin(msg) then local text = matches[2] tdcli.createNewChannelChat({[0] = msg.sender_user_id_}, text) if not lang then return '_SuperGroup Has Been Created!_' else return '_سوپر گروه ساخته شد!_' end end if matches[1] == 'tosuper' and is_admin(msg) then local id = msg.chat_id_ tdcli.migrateGroupChatToChannelChat(id) if not lang then return '_Group Has Been Changed To SuperGroup!_' else return '_گروه به سوپر گروه تبدیل شد!_' end end if matches[1] == 'import' and is_admin(msg) then tdcli.importChatInviteLink(matches[2]) if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'setbotname' and is_sudo(msg) then tdcli.changeName(matches[2]) if not lang then return '_Bot Name Changed To:_ *'..matches[2]..'*' else return '_اسم ربات تغییر کرد به:_ \n*'..matches[2]..'*' end end if matches[1] == 'setbotusername' and is_sudo(msg) then tdcli.changeUsername(matches[2]) if not lang then return '_Bot Username Changed To:_ @'..matches[2] else return '_یوزرنیم ربات تغییر کرد به:_ \n@'..matches[2]..'' end end if matches[1] == 'delbotusername' and is_sudo(msg) then tdcli.changeUsername('') if not lang then return '*Done!*' else return '*انجام شد!*' end end if matches[1] == 'markread' then if matches[2] == 'on' then redis:set('markread','on') if not lang then return '_Markread >_ *ON*' else return '_تیک دوم >_ *روشن*' end end if matches[2] == 'off' then redis:set('markread','off') if not lang then return '_Markread >_ *OFF*' else return '_تیک دوم >_ *خاموش*' end end end if matches[1] == 'bc' and is_admin(msg) then tdcli.sendMessage(matches[2], 0, 0, matches[3], 0) end if matches[1] == 'broadcast' and is_sudo(msg) then local data = load_data(_config.moderation.data) local bc = matches[2] for k,v in pairs(data) do tdcli.sendMessage(k, 0, 0, bc, 0) end end if matches[1] == 'sudolist' and is_sudo(msg) then return sudolist(msg) end if matches[1] == 'golbarg' then return tdcli.sendMessage(msg.chat_id_, msg.id_, 1, _config.info_text, 1, 'html') end if matches[1] == 'adminlist' and is_admin(msg) then return adminlist(msg) end if matches[1] == 'leave' and is_admin(msg) then tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil) end if matches[1] == 'autoleave' and is_admin(msg) then local hash = 'auto_leave_bot' --Enable Auto Leave if matches[2] == 'enable' then redis:del(hash) return 'Auto leave has been enabled' --Disable Auto Leave elseif matches[2] == 'disable' then redis:set(hash, true) return 'Auto leave has been disabled' --Auto Leave Status elseif matches[2] == 'status' then if not redis:get(hash) then return 'Auto leave is enable' else return 'Auto leave is disable' end end end end return { patterns = { "^[!/#](visudo)$", "^[!/#](desudo)$", "^[!/#](sudolist)$", "^[!/#](visudo) (.*)$", "^[!/#](desudo) (.*)$", "^[!/#](adminprom)$", "^[!/#](admindem)$", "^[!/#](adminlist)$", "^[!/#](adminprom) (.*)$", "^[!/#](admindem) (.*)$", "^[!/#](leave)$", "^[!/#](autoleave) (.*)$", "^[!/#](golbarg)$", "^[!/#](creategroup) (.*)$", "^[!/#](createsuper) (.*)$", "^[!/#](tosuper)$", "^[!/#](import) (.*)$", "^[!/#](setbotname) (.*)$", "^[!/#](setbotusername) (.*)$", "^[!/#](delbotusername) (.*)$", "^[!/#](markread) (.*)$", "^[!/#](bc) (%d+) (.*)$", "^[!/#](broadcast) (.*)$", }, run = run } -- کد های پایین در ربات نشان داده نمیشوند -- @smsgolbarg1
gpl-3.0
Scavenge/darkstar
scripts/zones/Nashmau/npcs/Yohj_Dukonlhy.lua
17
1417
----------------------------------- -- Area: Nashmau -- NPC: Yohj Dukonlhy -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua local timer = 1152 - ((os.time() - 1009810800)%1152); local direction = 0; -- Arrive, 1 for depart local waiting = 431; -- Offset for Nashmau if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
smanolache/kong
spec/spec_helpers.lua
1
7351
-- This file offers helpers for dao and integration tests (migrate, start kong, stop, faker...) -- It is built so that it only needs to be required at the beginning of any spec file. -- It supports other environments by passing a configuration file. require "kong.tools.ngx_stub" local IO = require "kong.tools.io" local dao_loader = require "kong.tools.dao_loader" local Faker = require "kong.tools.faker" local config = require "kong.tools.config_loader" local Threads = require "llthreads2.ex" local Events = require "kong.core.events" local stringy = require "stringy" local _M = {} -- Constants local TEST_PROXY_PORT = 8100 local TEST_PROXY_URL = "http://localhost:"..tostring(TEST_PROXY_PORT) local TEST_PROXY_SSL_URL = "https://localhost:8543" _M.API_URL = "http://localhost:8101" _M.KONG_BIN = "bin/kong" _M.PROXY_URL = TEST_PROXY_URL _M.PROXY_SSL_URL = TEST_PROXY_SSL_URL _M.STUB_GET_URL = TEST_PROXY_URL.."/request" _M.STUB_GET_SSL_URL = TEST_PROXY_SSL_URL.."/request" _M.STUB_POST_URL = TEST_PROXY_URL.."/request" _M.TEST_CONF_FILE = "kong_TEST.yml" _M.DEFAULT_CONF_FILE = "kong.yml" _M.TEST_PROXY_PORT = TEST_PROXY_PORT _M.envs = {} -- When dealing with another configuration file for a few tests, this allows to add -- a factory/migrations/faker that are environment-specific to this new config. function _M.add_env(conf_file) local env_configuration = config.load(conf_file) local events = Events() local env_factory = dao_loader.load(env_configuration, events) _M.envs[conf_file] = { configuration = env_configuration, dao_factory = env_factory, events = events, conf_file = conf_file, faker = Faker(env_factory) } end -- Retrieve environment-specific tools. If no conf_file passed, -- default environment is TEST_CONF_FILE function _M.get_env(conf_file) return _M.envs[conf_file] and _M.envs[conf_file] or _M.envs[_M.TEST_CONF_FILE] end function _M.remove_env(conf_file) _M.envs[conf_file] = nil end local function wait_process(pid_file) while(IO.file_exists(pid_file)) do local pid = IO.read_file(pid_file) local _, code = IO.os_execute("kill -0 "..stringy.strip(pid)) if code and code ~= 0 then break end end end -- -- OS and bin/kong helpers -- local function kong_bin(signal, conf_file) local env = _M.get_env(conf_file) local result, exit_code = IO.os_execute(_M.KONG_BIN.." "..signal.." -c "..env.conf_file) if exit_code ~= 0 then error("spec_helper cannot "..signal.." kong: \n"..result) end -- Wait for processes to exit if signal == "stop" then wait_process(env.configuration.nginx_working_dir.."/nginx.pid") wait_process(env.configuration.nginx_working_dir.."/serf.pid") wait_process(env.configuration.nginx_working_dir.."/dnsmasq.pid") elseif signal == "quit" then wait_process(env.configuration.nginx_working_dir.."/nginx.pid") end return result, exit_code end for _, signal in ipairs({ "start", "stop", "restart", "reload", "quit", "status" }) do _M[signal.."_kong"] = function(conf_file) return kong_bin(signal, conf_file) end end -- -- TCP/UDP server helpers -- -- Finds an available port on the system -- @param `exclude` An array with the ports to exclude -- @return `number` The port number function _M.find_port(exclude) local socket = require "socket" if not exclude then exclude = {} end -- Reserving ports to exclude local servers = {} for _, v in ipairs(exclude) do table.insert(servers, assert(socket.bind("*", v))) end -- Finding an available port local handle = io.popen([[(netstat -atn | awk '{printf "%s\n%s\n", $4, $4}' | grep -oE '[0-9]*$'; seq 32768 61000) | sort -n | uniq -u]]) local result = (handle:read("*a") .. "\n"):match("^(.-)\n") handle:close() -- Closing the opened servers for _, v in ipairs(servers) do v:close() end return tonumber(result) end -- Starts a TCP server, accepting a single connection and then closes -- @param `port` The port where the server will be listening to -- @return `thread` A thread object function _M.start_tcp_server(port, ...) local thread = Threads.new({ function(port) local socket = require "socket" local server = assert(socket.tcp()) assert(server:setoption('reuseaddr', true)) assert(server:bind("*", port)) assert(server:listen()) local client = server:accept() local line, err = client:receive() if not err then client:send(line .. "\n") end client:close() server:close() return line end; }, port) return thread:start(...) end -- Starts a HTTP server, accepting a single connection and then closes -- @param `port` The port where the server will be listening to -- @return `thread` A thread object function _M.start_http_server(port, ...) local thread = Threads.new({ function(port) local socket = require "socket" local server = assert(socket.tcp()) assert(server:setoption('reuseaddr', true)) assert(server:bind("*", port)) assert(server:listen()) local client = server:accept() local lines = {} local line, err while #lines < 7 do line, err = client:receive() if err then break else table.insert(lines, line) end end if #lines > 0 and lines[1] == "GET /delay HTTP/1.0" then os.execute("sleep 2") end if err then server:close() error(err) end client:send("HTTP/1.1 200 OK\r\nConnection: close\r\n\r\n") client:close() server:close() return lines end; }, port) return thread:start(...) end -- Starts a UDP server, accepting a single connection and then closes -- @param `port` The port where the server will be listening to -- @return `thread` A thread object function _M.start_udp_server(port, ...) local thread = Threads.new({ function(port) local socket = require "socket" local server = assert(socket.udp()) server:setoption('reuseaddr', true) server:setsockname("*", port) local data = server:receivefrom() server:close() return data end; }, port) return thread:start(...) end -- -- DAO helpers -- function _M.prepare_db(conf_file) local env = _M.get_env(conf_file) -- 1. Migrate our keyspace local ok, err = env.dao_factory:run_migrations() if not ok then error(err) end -- 2. Drop to run tests on a clean DB _M.drop_db(conf_file) end function _M.drop_db(conf_file) local env = _M.get_env(conf_file) env.dao_factory:truncate_tables() end function _M.seed_db(amount, conf_file) local env = _M.get_env(conf_file) return env.faker:seed(amount) end function _M.insert_fixtures(fixtures, conf_file) local env = _M.get_env(conf_file) return env.faker:insert_from_table(fixtures) end function _M.default_config() return config.default_config() end function _M.for_each_dao(f) local defaults = require "kong.tools.config_defaults" local env = _M.get_env() local databases = defaults.database.enum local DB_TYPES = {} for _, v in ipairs(databases) do DB_TYPES[v:upper()] = v end for _, v in ipairs(databases) do local properties = env.configuration[v] f(v, properties, DB_TYPES) end end -- Add the default env to our spec_helper _M.add_env(_M.TEST_CONF_FILE) return _M
apache-2.0
omidtarh/wbot
plugins/channels.lua
4
1726
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Channel isn\'t disabled' end _config.disabled_channels[receiver] = false save_config() return "Channel re-enabled" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Channel disabled" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod then if msg.text == "!channel enable" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'enable' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'disable' then return disable_channel(receiver) end end return { description = "Plugin to manage channels. Enable or disable channel.", usage = { "!channel enable: enable current channel", "!channel disable: disable current channel" }, patterns = { "^!channel? (enable)", "^!channel? (disable)" }, run = run, --privileged = true, moderated = true, pre_process = pre_process }
gpl-2.0
Scavenge/darkstar
scripts/zones/Kazham/npcs/Cha_Tigunalhgo.lua
17
1072
----------------------------------- -- Area: Kazham -- NPC: Cha Tigunalhgo -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getVar("BathedInScent") == 1) then player:startEvent(0x00B9); -- scent from Blue Rafflesias else player:startEvent(0x0064); 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
Scavenge/darkstar
scripts/globals/items/bowl_of_loach_soup.lua
12
1799
----------------------------------------- -- ID: 5671 -- Item: Bowl of Loach Soup -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- Dexterity 4 -- Agility 4 -- Accuracy 7% Cap 50 -- Ranged Accuracy 7% Cap 50 -- HP 7% Cap 50 -- Evasion 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5671); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_AGI, 4); target:addMod(MOD_FOOD_ACCP, 7); target:addMod(MOD_FOOD_ACC_CAP, 50); target:addMod(MOD_FOOD_RACCP, 7); target:addMod(MOD_FOOD_RACC_CAP, 50); target:addMod(MOD_FOOD_HPP, 7); target:addMod(MOD_FOOD_HP_CAP, 50); target:addMod(MOD_EVA, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_AGI, 4); target:delMod(MOD_FOOD_ACCP, 7); target:delMod(MOD_FOOD_ACC_CAP, 50); target:delMod(MOD_FOOD_RACCP, 7); target:delMod(MOD_FOOD_RACC_CAP, 50); target:delMod(MOD_FOOD_HPP, 7); target:delMod(MOD_FOOD_HP_CAP, 50); target:delMod(MOD_EVA, 5); end;
gpl-3.0
Brenin/PJ-3100
Working Launchers/Games/Stepmania/StepMania 5/NoteSkins/dance/easyV2/NoteSkin.lua
2
3642
--I am the bone of my noteskin --Arrows are my body, and explosions are my blood --I have created over a thousand noteskins --Unknown to death --Nor known to life --Have withstood pain to create many noteskins --Yet these hands will never hold anything --So as I pray, Unlimited Stepman Works local ret = ... or {}; --Defining on which direction the other directions should be bassed on --This will let us use less files which is quite handy to keep the noteskin directory nice --Do remember this will Redirect all the files of that Direction to the Direction its pointed to --If you only want some files to be redirected take a look at the "custom hold/roll per direction" ret.RedirTable = { --PIU Center = "Center", DownLeft = "DownLeft", -- for PIU and dance DownRight = "DownLeft", -- for PIU and dance UpLeft = "DownLeft", UpRight = "DownLeft", --Dance Down = "Down", Up = "Down", Left = "Down", Right = "Down", }; -- < --Between here we usally put all the commands the noteskin.lua needs to do, some are extern in other files --If you need help with lua go to http://kki.ajworld.net/lua/ssc/Lua.xml there are a bunch of codes there --Also check out commen it has a load of lua codes in files there --Just play a bit with lua its not that hard if you understand coding --But SM can be an ass in some cases, and some codes jut wont work if you dont have the noteskin on FallbackNoteSkin=common in the metric.ini local OldRedir = ret.Redir; ret.Redir = function(sButton, sElement) sButton, sElement = OldRedir(sButton, sElement); sButton = ret.RedirTable[sButton]; if not string.find(sElement, "Head") and not string.find(sElement, "Explosion") then if string.find(sElement, "Hold") or string.find(sElement, "Roll") then if Var "Button" == "Down" or Var "Button" == "Up" or Var "Button" == "Left" or Var "Button" == "Right" then sButton = "Down"; else sButton = "Center"; end end end -- Instead of separate hold heads, use the tap note graphics. if sElement == "Hold Head Inactive" or sElement == "Hold Head Active" or sElement == "Roll Head Inactive" or sElement == "Roll Head Active" or sElement == "Tap Fake" then sElement = "Tap Note"; end if sElement == "Tap Explosion Dim" or sElement == "Hold Explosion" or sElement == "Roll Explosion" then sElement = "Tap Explosion Bright"; end if sElement == "Tap Mine" then sButton = "Down"; end return sButton, sElement; end local OldFunc = ret.Load; function ret.Load() local t = OldFunc(); --Explosion should not be rotated; it calls other actors. if Var "Element" == "Explosion" then t.BaseRotationZ = nil; end return t; end -- > -- Parts of noteskins which we want to rotate ret.PartsToRotate = { ["Receptor"] = true, ["Tap Explosion Bright"] = true, ["Tap Explosion Dim"] = true, ["Tap Note"] = true, ["Tap Fake"] = true, ["Tap Addition"] = true, ["Hold Explosion"] = true, ["Hold Head Active"] = true, ["Hold Head Inactive"] = true, ["Roll Explosion"] = true, ["Roll Head Active"] = true, ["Roll Head Inactive"] = true, }; -- Defined the parts to be rotated at which degree ret.Rotate = { --PIU Center = 0, DownLeft = 0, DownRight = -90, UpLeft = 90, UpRight = 180, --Dance Down = 0, Up = 180, Left = 90, Right = -90, }; -- Parts that should be Redirected to _Blank.png -- you can add/remove stuff if you want ret.Blank = { ["HitMine Explosion"] = true, ["Hold Tail Active"] = true, ["Hold Tail Inactive"] = true, ["Roll Tail Active"] = true, ["Roll Tail Inactive"] = true, }; -- dont forget to close the ret cuz else it wont work ;> return ret;
mit
Scavenge/darkstar
scripts/zones/Bastok_Markets/npcs/Salimah.lua
25
3318
----------------------------------- -- Area: Bastok Markets -- NPC: Salimah -- Notes: Start & Finishes Quest: Gourmet -- @pos -31.687 -6.824 -73.282 235 ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/zones/Bastok_Markets/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Gourmet = player:getQuestStatus(BASTOK,GOURMET); if (Gourmet ~= QUEST_AVAILABLE and player:needToZone() == false) then local count = trade:getItemCount(); local hasSleepshroom = trade:hasItemQty(4374,1); local hasTreantBulb = trade:hasItemQty(953,1); local hasWildOnion = trade:hasItemQty(4387,1); if (hasSleepshroom or hasTreantBulb or hasWildOnion) then if (count == 1) then local vanatime = VanadielHour(); local item = 0; local event = 203; if (hasSleepshroom) then item = 4374; if (vanatime>=18 or vanatime<6) then event = 201; end elseif (hasTreantBulb) then item = 953; if (vanatime>=6 and vanatime<12) then event = 201; end elseif (hasWildOnion) then item = 4387; if (vanatime>=12 and vanatime<18) then event = 202; end end player:startEvent(event,item); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(BASTOK,GOURMET) ~= QUEST_AVAILABLE and player:needToZone()) then player:startEvent(0x0079); else player:startEvent(0x00c8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local Gourmet = player:getQuestStatus(BASTOK,GOURMET); if (csid == 0x00c8) then if (Gourmet == QUEST_AVAILABLE) then player:addQuest(BASTOK,GOURMET); end elseif (csid ~= 0x0079) then player:tradeComplete(); if (Gourmet == QUEST_ACCEPTED) then player:completeQuest(BASTOK,GOURMET); end local gil=350; local fame=120; if (csid == 201) then gil=200; elseif (csid == 203) then gil=100; fame=60; end player:addGil(gil*GIL_RATE); player:messageSpecial(GIL_OBTAINED,gil*GIL_RATE); player:addFame(BASTOK,fame); player:addTitle(MOMMYS_HELPER); player:needToZone(true); end end;
gpl-3.0
Scavenge/darkstar
scripts/zones/Silver_Sea_route_to_Nashmau/npcs/Map.lua
14
1039
----------------------------------- -- Area: Silver_Sea_route_to_Nashmau -- NPC: Map -- @pos 0.340 -12.232 -4.120 58 ----------------------------------- package.loaded["scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Silver_Sea_route_to_Nashmau/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0400); 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
smanolache/kong
kong/plugins/basic-auth/api.lua
1
1638
local crud = require "kong.api.crud_helpers" return { ["/consumers/:username_or_id/basic-auth/"] = { before = function(self, dao_factory, helpers) crud.find_consumer_by_username_or_id(self, dao_factory, helpers) self.params.consumer_id = self.consumer.id end, GET = function(self, dao_factory) crud.paginated_set(self, dao_factory.basicauth_credentials) end, PUT = function(self, dao_factory) crud.put(self.params, dao_factory.basicauth_credentials) end, POST = function(self, dao_factory) crud.post(self.params, dao_factory.basicauth_credentials) end }, ["/consumers/:username_or_id/basic-auth/:id"] = { before = function(self, dao_factory, helpers) crud.find_consumer_by_username_or_id(self, dao_factory, helpers) self.params.consumer_id = self.consumer.id local credentials, err = dao_factory.basicauth_credentials:find_all { consumer_id = self.params.consumer_id, id = self.params.id } if err then return helpers.yield_error(err) elseif next(credentials) == nil then return helpers.responses.send_HTTP_NOT_FOUND() end self.basicauth_credential = credentials[1] end, GET = function(self, dao_factory, helpers) return helpers.responses.send_HTTP_OK(self.basicauth_credential) end, PATCH = function(self, dao_factory) crud.patch(self.params, dao_factory.basicauth_credentials, self.basicauth_credential) end, DELETE = function(self, dao_factory) crud.delete(self.basicauth_credential, dao_factory.basicauth_credentials) end } }
apache-2.0
Scavenge/darkstar
scripts/zones/Den_of_Rancor/npcs/Treasure_Coffer.lua
14
3874
----------------------------------- -- Area: Den of Rancor -- NPC: Treasure Coffer -- @zone 160 -- @pos ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/globals/quests"); require("scripts/zones/Den_of_Rancor/TextIDs"); local TreasureType = "Coffer"; local TreasureLvL = 53; local TreasureMinLvL = 43; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1050,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(1050,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then -- IMPORTANT ITEM: AF Keyitems, AF Items, & Map ----------- local zone = player:getZoneID(); if (player:hasKeyItem(MAP_OF_THE_DEN_OF_RANCOR) == false) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(MAP_OF_THE_DEN_OF_RANCOR); player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_DEN_OF_RANCOR); -- Map of the Den of Rancor (KI) else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = cofferLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); else player:messageSpecial(CHEST_MIMIC); spawnMimic(zone,npc,player); UpdateTreasureSpawnPoint(npc:getID(), true); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1050); 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
purebn/secure
plugins/location.lua
625
1564
-- Implement a command !loc [area] which uses -- the static map API to get a location image -- Not sure if this is the proper way -- Intent: get_latlong is in time.lua, we need it here -- loadfile "time.lua" -- Globals -- If you have a google api key for the geocoding/timezone api do local api_key = nil local base_api = "https://maps.googleapis.com/maps/api" function get_staticmap(area) local api = base_api .. "/staticmap?" -- Get a sense of scale local lat,lng,acc,types = get_latlong(area) local scale = types[1] if scale=="locality" then zoom=8 elseif scale=="country" then zoom=4 else zoom = 13 end local parameters = "size=600x300" .. "&zoom=" .. zoom .. "&center=" .. URL.escape(area) .. "&markers=color:red"..URL.escape("|"..area) if api_key ~=nil and api_key ~= "" then parameters = parameters .. "&key="..api_key end return lat, lng, api..parameters end function run(msg, matches) local receiver = get_receiver(msg) local lat,lng,url = get_staticmap(matches[1]) -- Send the actual location, is a google maps link send_location(receiver, lat, lng, ok_cb, false) -- Send a picture of the map, which takes scale into account send_photo_from_url(receiver, url) -- Return a link to the google maps stuff is now not needed anymore return nil end return { description = "Gets information about a location, maplink and overview", usage = "!loc (location): Gets information about a location, maplink and overview", patterns = {"^!loc (.*)$"}, run = run } end
gpl-2.0
Zero-K-Experiments/Zero-K-Experiments
gamedata/modularcomms/weapons/napalmgrenade.lua
6
1452
local name = "commweapon_napalmgrenade" local weaponDef = { name = [[Hellfire Grenade]], accuracy = 256, areaOfEffect = 256, --cegTag = [[torpedo_trail]], commandFire = true, craterBoost = 0, craterMult = 0, customParams = { slot = [[3]], setunitsonfire = "1", burntime = [[90]], muzzleEffectFire = [[custom:RAIDMUZZLE]], manualfire = 1, area_damage = 1, area_damage_radius = 128, area_damage_dps = 40, area_damage_duration = 45, light_camera_height = 3500, light_color = [[0.75 0.4 0.15]], light_radios = 520, }, damage = { default = 200, planes = 200, subs = 10, }, explosionGenerator = [[custom:napalm_hellfire]], firestarter = 180, impulseBoost = 0, impulseFactor = 0, interceptedByShieldType = 2, model = [[wep_b_fabby.s3o]], noSelfDamage = false, range = 450, reloadtime = 25, smokeTrail = true, soundHit = [[weapon/cannon/wolverine_hit]], soundHitVolume = 8, soundStart = [[weapon/cannon/cannon_fire3]], --startVelocity = 350, --trajectoryHeight = 0.3, turret = true, weaponType = [[Cannon]], weaponVelocity = 350, } return name, weaponDef
gpl-2.0
kankaristo/premake-core
tests/actions/vstudio/vc2010/test_item_def_group.lua
16
1563
-- -- tests/actions/vstudio/vc2010/test_item_def_group.lua -- Check the item definition groups, containing compile and link flags. -- Copyright (c) 2013 Jason Perkins and the Premake project -- local suite = test.declare("vs2010_item_def_group") local vc2010 = premake.vstudio.vc2010 local project = premake.project -- -- Setup -- local wks, prj function suite.setup() wks, prj = test.createWorkspace() end local function prepare(buildcfg) local cfg = test.getconfig(prj, buildcfg or "Debug") vc2010.itemDefinitionGroup(cfg) end -- -- Check generation of opening element for typical C++ project. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> ]] end -- -- Makefile projects omit the condition and all contents. -- function suite.structureIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <ItemDefinitionGroup> </ItemDefinitionGroup> ]] end function suite.structureIsCorrect_onNone() kind "Makefile" prepare() test.capture [[ <ItemDefinitionGroup> </ItemDefinitionGroup> ]] end -- -- Because the item definition group for makefile projects is not -- tied to a particular condition, it should only get written for -- the first configuration. -- function suite.skipped_onSubsequentConfigs() kind "Makefile" prepare("Release") test.isemptycapture() end function suite.skipped_onSubsequentConfigs_onNone() kind "None" prepare("Release") test.isemptycapture() end
bsd-3-clause
PredatorMF/Urho3D
bin/Data/LuaScripts/30_LightAnimation.lua
24
9498
-- Light animation example. -- This sample is base on StaticScene, and it demonstrates: -- - Usage of attribute animation for light color & UI animation require "LuaScripts/Utilities/Sample" function Start() -- Execute the common startup for samples SampleStart() -- Create the UI content CreateInstructions() -- Create the scene content CreateScene() -- Setup the viewport for displaying the scene SetupViewport() -- Set the mouse mode to use in the sample SampleInitMouseMode(MM_RELATIVE) -- Hook up to the frame update events SubscribeToEvents() end function CreateScene() scene_ = Scene() -- Create the Octree component to the scene. This is required before adding any drawable components, or else nothing will -- show up. The default octree volume will be from (-1000, -1000, -1000) to (1000, 1000, 1000) in world coordinates it -- is also legal to place objects outside the volume but their visibility can then not be checked in a hierarchically -- optimizing manner scene_:CreateComponent("Octree") -- Create a child scene node (at world origin) and a StaticModel component into it. Set the StaticModel to show a simple -- plane mesh with a "stone" material. Note that naming the scene nodes is optional. Scale the scene node larger -- (100 x 100 world units) local planeNode = scene_:CreateChild("Plane") planeNode.scale = Vector3(100.0, 1.0, 100.0) local planeObject = planeNode:CreateComponent("StaticModel") planeObject.model = cache:GetResource("Model", "Models/Plane.mdl") planeObject.material = cache:GetResource("Material", "Materials/StoneTiled.xml") -- Create a point light to the world so that we can see something. local lightNode = scene_:CreateChild("DirectionalLight") local light = lightNode:CreateComponent("Light") light.lightType = LIGHT_POINT light.range = 10.0 -- Create light color animation local colorAnimation = ValueAnimation:new() colorAnimation:SetKeyFrame(0.0, Variant(Color(1,1,1))) colorAnimation:SetKeyFrame(1.0, Variant(Color(1,0,0))) colorAnimation:SetKeyFrame(2.0, Variant(Color(1,1,0))) colorAnimation:SetKeyFrame(3.0, Variant(Color(0,1,0))) colorAnimation:SetKeyFrame(4.0, Variant(Color(1,1,1))) light:SetAttributeAnimation("Color", colorAnimation) -- Create text animation local textAnimation = ValueAnimation:new() textAnimation:SetKeyFrame(0.0, Variant("WHITE")) textAnimation:SetKeyFrame(1.0, Variant("RED")) textAnimation:SetKeyFrame(2.0, Variant("YELLOW")) textAnimation:SetKeyFrame(3.0, Variant("GREEN")) textAnimation:SetKeyFrame(4.0, Variant("WHITE")) ui.root:GetChild("animatingText"):SetAttributeAnimation("Text", textAnimation) -- Create UI element animation -- (note: a spritesheet and "Image Rect" attribute should be used in real use cases for better performance) local spriteAnimation = ValueAnimation:new() spriteAnimation:SetKeyFrame(0.0, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/1.png"))) spriteAnimation:SetKeyFrame(0.1, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/2.png"))) spriteAnimation:SetKeyFrame(0.2, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/3.png"))) spriteAnimation:SetKeyFrame(0.3, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/4.png"))) spriteAnimation:SetKeyFrame(0.4, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/5.png"))) spriteAnimation:SetKeyFrame(0.5, Variant(ResourceRef("Texture2D", "Urho2D/GoldIcon/1.png"))) ui.root:GetChild("animatingSprite"):SetAttributeAnimation("Texture", spriteAnimation) -- Create light position animation local positionAnimation = ValueAnimation:new() -- Use spline interpolation method positionAnimation.interpolationMethod = IM_SPLINE -- Set spline tension positionAnimation.splineTension = 0.7 positionAnimation:SetKeyFrame(0.0, Variant(Vector3(-30.0, 5.0, -30.0))) positionAnimation:SetKeyFrame(1.0, Variant(Vector3( 30.0, 5.0, -30.0))) positionAnimation:SetKeyFrame(2.0, Variant(Vector3( 30.0, 5.0, 30.0))) positionAnimation:SetKeyFrame(3.0, Variant(Vector3(-30.0, 5.0, 30.0))) positionAnimation:SetKeyFrame(4.0, Variant(Vector3(-30.0, 5.0, -30.0))) lightNode:SetAttributeAnimation("Position", positionAnimation) -- Create more StaticModel objects to the scene, randomly positioned, rotated and scaled. For rotation, we construct a -- quaternion from Euler angles where the Y angle (rotation about the Y axis) is randomized. The mushroom model contains -- LOD levels, so the StaticModel component will automatically select the LOD level according to the view distance (you'll -- see the model get simpler as it moves further away). Finally, rendering a large number of the same object with the -- same material allows instancing to be used, if the GPU supports it. This reduces the amount of CPU work in rendering the -- scene. local NUM_OBJECTS = 200 for i = 1, NUM_OBJECTS do local mushroomNode = scene_:CreateChild("Mushroom") mushroomNode.position = Vector3(Random(90.0) - 45.0, 0.0, Random(90.0) - 45.0) mushroomNode.rotation = Quaternion(0.0, Random(360.0), 0.0) mushroomNode:SetScale(0.5 + Random(2.0)) local mushroomObject = mushroomNode:CreateComponent("StaticModel") mushroomObject.model = cache:GetResource("Model", "Models/Mushroom.mdl") mushroomObject.material = cache:GetResource("Material", "Materials/Mushroom.xml") end -- Create a scene node for the camera, which we will move around -- The camera will use default settings (1000 far clip distance, 45 degrees FOV, set aspect ratio automatically) cameraNode = scene_:CreateChild("Camera") cameraNode:CreateComponent("Camera") -- Set an initial position for the camera scene node above the plane cameraNode.position = Vector3(0.0, 5.0, 0.0) end function CreateInstructions() -- Construct new Text object, set string to display and font to use local instructionText = ui.root:CreateChild("Text") instructionText:SetText("Use WASD keys and mouse to move") local font = cache:GetResource("Font", "Fonts/Anonymous Pro.ttf") instructionText:SetFont(font, 15) -- Position the text relative to the screen center instructionText.horizontalAlignment = HA_CENTER instructionText.verticalAlignment = VA_CENTER instructionText:SetPosition(0, ui.root.height / 4) -- Animating text local text = ui.root:CreateChild("Text", "animatingText") text:SetFont(font, 15) text.horizontalAlignment = HA_CENTER text.verticalAlignment = VA_CENTER text:SetPosition(0, ui.root.height / 4 + 20) -- Animating sprite in the top left corner local sprite = ui.root:CreateChild("Sprite", "animatingSprite") sprite:SetPosition(8, 8) sprite:SetSize(64, 64) end function SetupViewport() -- Set up a viewport to the Renderer subsystem so that the 3D scene can be seen. We need to define the scene and the camera -- at minimum. Additionally we could configure the viewport screen size and the rendering path (eg. forward / deferred) to -- use, but now we just use full screen and default render path configured in the engine command line options local viewport = Viewport:new(scene_, cameraNode:GetComponent("Camera")) renderer:SetViewport(0, viewport) end function MoveCamera(timeStep) -- Do not move if the UI has a focused element (the console) if ui.focusElement ~= nil then return end -- Movement speed as world units per second local MOVE_SPEED = 20.0 -- Mouse sensitivity as degrees per pixel local MOUSE_SENSITIVITY = 0.1 -- Use this frame's mouse motion to adjust camera node yaw and pitch. Clamp the pitch between -90 and 90 degrees local mouseMove = input.mouseMove yaw = yaw +MOUSE_SENSITIVITY * mouseMove.x pitch = pitch + MOUSE_SENSITIVITY * mouseMove.y pitch = Clamp(pitch, -90.0, 90.0) -- Construct new orientation for the camera scene node from yaw and pitch. Roll is fixed to zero cameraNode.rotation = Quaternion(pitch, yaw, 0.0) -- Read WASD keys and move the camera scene node to the corresponding direction if they are pressed -- Use the Translate() function (default local space) to move relative to the node's orientation. if input:GetKeyDown(KEY_W) then cameraNode:Translate(Vector3(0.0, 0.0, 1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_S) then cameraNode:Translate(Vector3(0.0, 0.0, -1.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_A) then cameraNode:Translate(Vector3(-1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end if input:GetKeyDown(KEY_D) then cameraNode:Translate(Vector3(1.0, 0.0, 0.0) * MOVE_SPEED * timeStep) end end function SubscribeToEvents() -- Subscribe HandleUpdate() function for processing update events SubscribeToEvent("Update", "HandleUpdate") end function HandleUpdate(eventType, eventData) -- Take the frame time step, which is stored as a float local timeStep = eventData["TimeStep"]:GetFloat() -- Move the camera, scale movement with time step MoveCamera(timeStep) end
mit
Arashbrsh/lifemaic
plugins/tweet.lua
634
7120
local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local twitter_url = "https://api.twitter.com/1.1/statuses/user_timeline.json" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token"}, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret}) local function send_generics_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path local f = cb_extra.func -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path, func = f } -- Send first and postpone the others as callback f(receiver, file_path, send_generics_from_url_callback, cb_extra) end local function send_generics_from_url(f, receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil, func = f } send_generics_from_url_callback(cb_extra) end local function send_gifs_from_url(receiver, urls) send_generics_from_url(send_document, receiver, urls) end local function send_videos_from_url(receiver, urls) send_generics_from_url(send_video, receiver, urls) end local function send_all_files(receiver, urls) local data = { images = { func = send_photos_from_url, urls = {} }, gifs = { func = send_gifs_from_url, urls = {} }, videos = { func = send_videos_from_url, urls = {} } } local table_to_insert = nil for i,url in pairs(urls) do local _, _, extension = string.match(url, "(https?)://([^\\]-([^\\%.]+))$") local mime_type = mimetype.get_content_type_no_sub(extension) if extension == 'gif' then table_to_insert = data.gifs.urls elseif mime_type == 'image' then table_to_insert = data.images.urls elseif mime_type == 'video' then table_to_insert = data.videos.urls else table_to_insert = nil end if table_to_insert then table.insert(table_to_insert, url) end end for k, v in pairs(data) do if #v.urls > 0 then end v.func(receiver, v.urls) end end local function check_keys() if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/tweet.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/tweet.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/tweet.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/tweet.lua" end return "" end local function analyze_tweet(tweet) local header = "Tweet from " .. tweet.user.name .. " (@" .. tweet.user.screen_name .. ")\n" -- "Link: https://twitter.com/statuses/" .. tweet.id_str local text = tweet.text -- replace short URLs if tweet.entities.url then for k, v in pairs(tweet.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove urls local urls = {} if tweet.extended_entities and tweet.extended_entities.media then for k, v in pairs(tweet.extended_entities.media) do if v.video_info and v.video_info.variants then -- If it's a video! table.insert(urls, v.video_info.variants[1].url) else -- If not, is an image table.insert(urls, v.media_url) end text = text:gsub(v.url, "") -- Replace the URL in text end end return header, text, urls end local function sendTweet(receiver, tweet) local header, text, urls = analyze_tweet(tweet) -- send the parts send_msg(receiver, header .. "\n" .. text, ok_cb, false) send_all_files(receiver, urls) return nil end local function getTweet(msg, base, all) local receiver = get_receiver(msg) local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url, base) if response_code ~= 200 then return "Can't connect, maybe the user doesn't exist." end local response = json:decode(response_body) if #response == 0 then return "Can't retrieve any tweets, sorry" end if all then for i,tweet in pairs(response) do sendTweet(receiver, tweet) end else local i = math.random(#response) local tweet = response[i] sendTweet(receiver, tweet) end return nil end function isint(n) return n==math.floor(n) end local function run(msg, matches) local checked = check_keys() if not checked:isempty() then return checked end local base = {include_rts = 1} if matches[1] == 'id' then local userid = tonumber(matches[2]) if userid == nil or not isint(userid) then return "The id of a user is a number, check this web: http://gettwitterid.com/" end base.user_id = userid elseif matches[1] == 'name' then base.screen_name = matches[2] else return "" end local count = 200 local all = false if #matches > 2 and matches[3] == 'last' then count = 1 if #matches == 4 then local n = tonumber(matches[4]) if n > 10 then return "You only can ask for 10 tweets at most" end count = matches[4] all = true end end base.count = count return getTweet(msg, base, all) end return { description = "Random tweet from user", usage = { "!tweet id [id]: Get a random tweet from the user with that ID", "!tweet id [id] last: Get a random tweet from the user with that ID", "!tweet name [name]: Get a random tweet from the user with that name", "!tweet name [name] last: Get a random tweet from the user with that name" }, patterns = { "^!tweet (id) ([%w_%.%-]+)$", "^!tweet (id) ([%w_%.%-]+) (last)$", "^!tweet (id) ([%w_%.%-]+) (last) ([%d]+)$", "^!tweet (name) ([%w_%.%-]+)$", "^!tweet (name) ([%w_%.%-]+) (last)$", "^!tweet (name) ([%w_%.%-]+) (last) ([%d]+)$" }, run = run }
gpl-2.0
purebn/secure
plugins/tweet.lua
634
7120
local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local twitter_url = "https://api.twitter.com/1.1/statuses/user_timeline.json" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token"}, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret}) local function send_generics_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path local f = cb_extra.func -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path, func = f } -- Send first and postpone the others as callback f(receiver, file_path, send_generics_from_url_callback, cb_extra) end local function send_generics_from_url(f, receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil, func = f } send_generics_from_url_callback(cb_extra) end local function send_gifs_from_url(receiver, urls) send_generics_from_url(send_document, receiver, urls) end local function send_videos_from_url(receiver, urls) send_generics_from_url(send_video, receiver, urls) end local function send_all_files(receiver, urls) local data = { images = { func = send_photos_from_url, urls = {} }, gifs = { func = send_gifs_from_url, urls = {} }, videos = { func = send_videos_from_url, urls = {} } } local table_to_insert = nil for i,url in pairs(urls) do local _, _, extension = string.match(url, "(https?)://([^\\]-([^\\%.]+))$") local mime_type = mimetype.get_content_type_no_sub(extension) if extension == 'gif' then table_to_insert = data.gifs.urls elseif mime_type == 'image' then table_to_insert = data.images.urls elseif mime_type == 'video' then table_to_insert = data.videos.urls else table_to_insert = nil end if table_to_insert then table.insert(table_to_insert, url) end end for k, v in pairs(data) do if #v.urls > 0 then end v.func(receiver, v.urls) end end local function check_keys() if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/tweet.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/tweet.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/tweet.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/tweet.lua" end return "" end local function analyze_tweet(tweet) local header = "Tweet from " .. tweet.user.name .. " (@" .. tweet.user.screen_name .. ")\n" -- "Link: https://twitter.com/statuses/" .. tweet.id_str local text = tweet.text -- replace short URLs if tweet.entities.url then for k, v in pairs(tweet.entities.urls) do local short = v.url local long = v.expanded_url text = text:gsub(short, long) end end -- remove urls local urls = {} if tweet.extended_entities and tweet.extended_entities.media then for k, v in pairs(tweet.extended_entities.media) do if v.video_info and v.video_info.variants then -- If it's a video! table.insert(urls, v.video_info.variants[1].url) else -- If not, is an image table.insert(urls, v.media_url) end text = text:gsub(v.url, "") -- Replace the URL in text end end return header, text, urls end local function sendTweet(receiver, tweet) local header, text, urls = analyze_tweet(tweet) -- send the parts send_msg(receiver, header .. "\n" .. text, ok_cb, false) send_all_files(receiver, urls) return nil end local function getTweet(msg, base, all) local receiver = get_receiver(msg) local response_code, response_headers, response_status_line, response_body = client:PerformRequest("GET", twitter_url, base) if response_code ~= 200 then return "Can't connect, maybe the user doesn't exist." end local response = json:decode(response_body) if #response == 0 then return "Can't retrieve any tweets, sorry" end if all then for i,tweet in pairs(response) do sendTweet(receiver, tweet) end else local i = math.random(#response) local tweet = response[i] sendTweet(receiver, tweet) end return nil end function isint(n) return n==math.floor(n) end local function run(msg, matches) local checked = check_keys() if not checked:isempty() then return checked end local base = {include_rts = 1} if matches[1] == 'id' then local userid = tonumber(matches[2]) if userid == nil or not isint(userid) then return "The id of a user is a number, check this web: http://gettwitterid.com/" end base.user_id = userid elseif matches[1] == 'name' then base.screen_name = matches[2] else return "" end local count = 200 local all = false if #matches > 2 and matches[3] == 'last' then count = 1 if #matches == 4 then local n = tonumber(matches[4]) if n > 10 then return "You only can ask for 10 tweets at most" end count = matches[4] all = true end end base.count = count return getTweet(msg, base, all) end return { description = "Random tweet from user", usage = { "!tweet id [id]: Get a random tweet from the user with that ID", "!tweet id [id] last: Get a random tweet from the user with that ID", "!tweet name [name]: Get a random tweet from the user with that name", "!tweet name [name] last: Get a random tweet from the user with that name" }, patterns = { "^!tweet (id) ([%w_%.%-]+)$", "^!tweet (id) ([%w_%.%-]+) (last)$", "^!tweet (id) ([%w_%.%-]+) (last) ([%d]+)$", "^!tweet (name) ([%w_%.%-]+)$", "^!tweet (name) ([%w_%.%-]+) (last)$", "^!tweet (name) ([%w_%.%-]+) (last) ([%d]+)$" }, run = run }
gpl-2.0
kirubz/Penlight
tests/test-list.lua
8
1658
local List = require 'pl.List' local class = require 'pl.class' local test = require 'pl.test' local asserteq, T = test.asserteq, test.tuple -- note that a _plain table_ is made directly into a list local t = {10,20,30} local ls = List(t) asserteq(t,ls) -- you may derive classes from pl.List, and the result is covariant. -- That is, slice() etc will return a list of the derived type, not List. local NA = class(List) local function mapm(a1,op,a2) local M = type(a2)=='table' and List.map2 or List.map return M(a1,op,a2) end --- elementwise arithmetric operations function NA.__unm(a) return a:map '|X|-X' end function NA.__pow(a,s) return a:map '|X,Y|X^Y' end function NA.__add(a1,a2) return mapm(a1,'|X,Y|X+Y',a2) end function NA.__sub(a1,a2) return mapm(a1,'|X,Y|X-Y',a2) end function NA.__div(a1,a2) return mapm(a1,'|X,Y|X/Y',a2) end function NA.__mul(a1,a2) return mapm(a2,'|X,Y|X*Y',a1) end function NA:minmax () local min,max = math.huge,-math.huge for i = 1,#self do local val = self[i] if val > max then max = val end if val < min then min = val end end return min,max end function NA:sum () local res = 0 for i = 1,#self do res = res + self[i] end return res end function NA:normalize () return self:transform('|X,Y|X/Y',self:sum()) end n1 = NA{10,20,30} n2 = NA{1,2,3} ns = n1 + 2*n2 asserteq(List:class_of(ns),true) asserteq(NA:class_of(ns),true) asserteq(ns:is_a(NA),true) asserteq(ns,{12,24,36}) min,max = ns:slice(1,2):minmax() asserteq(T(min,max),T(12,24)) asserteq(n1:normalize():sum(),1,1e-8)
mit
kirubz/Penlight
tests/test-config.lua
5
6179
require 'pl' asserteq = require 'pl.test'.asserteq function testconfig(test,tbl,cfg) local f = stringio.open(test) local c = config.read(f,cfg) f:close() if not tbl then print(pretty.write(c)) else asserteq(c,tbl) end end testconfig ([[ ; comment 2 (an ini file) [section!] bonzo.dog=20,30 config_parm=here we go again depth = 2 [another] felix="cat" ]],{ section_ = { bonzo_dog = { -- comma-sep values get split by default 20, 30 }, depth = 2, config_parm = "here we go again" }, another = { felix = "\"cat\"" } }) testconfig ([[ # this is a more Unix-y config file fred = 1 alice = 2 home.dog = /bonzo/dog/etc ]],{ home_dog = "/bonzo/dog/etc", -- note the default is {variablilize = true} fred = 1, alice = 2 }) -- backspace line continuation works, thanks to config.lines function testconfig ([[ foo=frodo,a,c,d, \ frank, alice, boyo ]], { foo = { "frodo", "a", "c", "d", "frank", "alice", "boyo" } } ) ------ options to control default behaviour ----- -- want to keep key names as is! testconfig ([[ alpha.dog=10 # comment here ]],{ ["alpha.dog"]=10 },{variabilize=false}) -- don't convert strings to numbers testconfig ([[ alpha.dog=10 ; comment here ]],{ alpha_dog="10" },{convert_numbers=false}) -- don't split comma-lists by setting the list delimiter to something else testconfig ([[ extra=10,'hello',42 ]],{ extra="10,'hello',42" },{list_delim='@'}) -- Unix-style password file testconfig([[ lp:x:7:7:lp:/var/spool/lpd:/bin/sh mail:x:8:8:mail:/var/mail:/bin/sh news:x:9:9:news:/var/spool/news:/bin/sh ]], { { "lp", "x", 7, 7, "lp", "/var/spool/lpd", "/bin/sh" }, { "mail", "x", 8, 8, "mail", "/var/mail", "/bin/sh" }, { "news", "x", 9, 9, "news", "/var/spool/news", "/bin/sh" } }, {list_delim=':'}) -- Unix updatedb.conf is in shell script form, but config.read -- copes by extracting the variables as keys and the export -- commands as the array part; there is an option to remove quotes -- from values testconfig([[ # Global options for invocations of find(1) FINDOPTIONS='-ignore_readdir_race' export FINDOPTIONS ]],{ "export FINDOPTIONS", FINDOPTIONS = "-ignore_readdir_race" },{trim_quotes=true}) -- Unix fstab format. No key/value assignments so use `ignore_assign`; -- list values are separated by a number of spaces testconfig([[ # <file system> <mount point> <type> <options> <dump> <pass> proc /proc proc defaults 0 0 /dev/sda1 / ext3 defaults,errors=remount-ro 0 1 ]], { { "proc", "/proc", "proc", "defaults", 0, 0 }, { "/dev/sda1", "/", "ext3", "defaults,errors=remount-ro", 0, 1 } }, {list_delim='%s+',ignore_assign=true} ) -- Linux procfs 'files' often use ':' as the key/pair separator; -- a custom convert_numbers handles the units properly! -- Here is the first two lines from /proc/meminfo testconfig([[ MemTotal: 1024748 kB MemFree: 220292 kB ]], { MemTotal = 1024748, MemFree = 220292 }, { keysep = ':', convert_numbers = function(s) s = s:gsub(' kB$','') return tonumber(s) end } ) -- altho this works, rather use pl.data.read for this kind of purpose. testconfig ([[ # this is just a set of comma-separated values 1000,444,222 44,555,224 ]],{ { 1000, 444, 222 }, { 44, 555, 224 } }) --- new with 1.0.3: smart configuration file reading -- handles a number of common Unix file formats automatically function smart(f) f = stringio.open(f) return config.read(f,{smart=true}) end -- /etc/fstab asserteq (smart[[ # /etc/fstab: static file system information. # # Use 'blkid -o value -s UUID' to print the universally unique identifier # for a device; this may be used with UUID= as a more robust way to name # devices that works even if disks are added and removed. See fstab(5). # # <file system> <mount point> <type> <options> <dump> <pass> proc /proc proc nodev,noexec,nosuid 0 0 /dev/sdb2 / ext2 errors=remount-ro 0 1 /dev/fd0 /media/floppy0 auto rw,user,noauto,exec,utf8 0 0 ]],{ proc = { "/proc", "proc", "nodev,noexec,nosuid", 0, 0 }, ["/dev/sdb2"] = { "/", "ext2", "errors=remount-ro", 0, 1 }, ["/dev/fd0"] = { "/media/floppy0", "auto", "rw,user,noauto,exec,utf8", 0, 0 } }) -- /proc/XXXX/status asserteq (smart[[ Name: bash State: S (sleeping) Tgid: 30071 Pid: 30071 PPid: 1587 TracerPid: 0 Uid: 1000 1000 1000 1000 Gid: 1000 1000 1000 1000 FDSize: 256 Groups: 4 20 24 46 105 119 122 1000 VmPeak: 6780 kB VmSize: 6716 kB ]],{ Pid = 30071, VmSize = 6716, PPid = 1587, Tgid = 30071, State = "S (sleeping)", Uid = "1000 1000 1000 1000", Name = "bash", Gid = "1000 1000 1000 1000", Groups = "4 20 24 46 105 119 122 1000", FDSize = 256, VmPeak = 6780, TracerPid = 0 }) -- ssh_config asserteq (smart[[ Host * # ForwardAgent no # ForwardX11 no # Tunnel no # TunnelDevice any:any # PermitLocalCommand no # VisualHostKey no SendEnv LANG LC_* HashKnownHosts yes GSSAPIAuthentication yes GSSAPIDelegateCredentials no ]],{ Host = "*", GSSAPIAuthentication = "yes", SendEnv = "LANG LC_*", HashKnownHosts = "yes", GSSAPIDelegateCredentials = "no" }) -- updatedb.conf asserteq (smart[[ PRUNE_BIND_MOUNTS="yes" # PRUNENAMES=".git .bzr .hg .svn" PRUNEPATHS="/tmp /var/spool /media" PRUNEFS="NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs shfs sysfs cifs lustre_lite tmpfs usbfs udf fuse.glusterfs fuse.sshfs ecryptfs fusesmb devtmpfs" ]],{ PRUNEPATHS = "/tmp /var/spool /media", PRUNE_BIND_MOUNTS = "yes", PRUNEFS = "NFS nfs nfs4 rpc_pipefs afs binfmt_misc proc smbfs autofs iso9660 ncpfs coda devpts ftpfs devfs mfs shfs sysfs cifs lustre_lite tmpfs usbfs udf fuse.glusterfs fuse.sshfs ecryptfs fusesmb devtmpfs" })
mit
Scavenge/darkstar
scripts/globals/items/chocolate_crepe.lua
12
1579
----------------------------------------- -- ID: 5775 -- Item: Chocolate Crepe -- Food Effect: 30 Min, All Races ----------------------------------------- -- HP +5% (cap 15) -- MP Healing 2 -- Magic Accuracy +20% (cap 35) -- Magic Defense +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,5775); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 5); target:addMod(MOD_FOOD_HP_CAP, 15); target:addMod(MOD_MPHEAL, 2); target:addMod(MOD_MDEF, 1); target:addMod(MOD_FOOD_MACCP, 20); target:addMod(MOD_FOOD_MACC_CAP, 35); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 5); target:delMod(MOD_FOOD_HP_CAP, 15); target:delMod(MOD_MPHEAL, 2); target:delMod(MOD_MDEF, 1); target:delMod(MOD_FOOD_MACCP, 20); target:delMod(MOD_FOOD_MACC_CAP, 35); end;
gpl-3.0