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 |
|---|---|---|---|---|---|
onlymellb/redis-3.0-annotated | deps/lua/test/sort.lua | 889 | 1494 | -- two implementations of a sort function
-- this is an example only. Lua has now a built-in function "sort"
-- extracted from Programming Pearls, page 110
function qsort(x,l,u,f)
if l<u then
local m=math.random(u-(l-1))+l-1 -- choose a random pivot in range l..u
x[l],x[m]=x[m],x[l] -- swap pivot to first position
local t=x[l] -- pivot value
m=l
local i=l+1
while i<=u do
-- invariant: x[l+1..m] < t <= x[m+1..i-1]
if f(x[i],t) then
m=m+1
x[m],x[i]=x[i],x[m] -- swap x[i] and x[m]
end
i=i+1
end
x[l],x[m]=x[m],x[l] -- swap pivot to a valid place
-- x[l+1..m-1] < x[m] <= x[m+1..u]
qsort(x,l,m-1,f)
qsort(x,m+1,u,f)
end
end
function selectionsort(x,n,f)
local i=1
while i<=n do
local m,j=i,i+1
while j<=n do
if f(x[j],x[m]) then m=j end
j=j+1
end
x[i],x[m]=x[m],x[i] -- swap x[i] and x[m]
i=i+1
end
end
function show(m,x)
io.write(m,"\n\t")
local i=1
while x[i] do
io.write(x[i])
i=i+1
if x[i] then io.write(",") end
end
io.write("\n")
end
function testsorts(x)
local n=1
while x[n] do n=n+1 end; n=n-1 -- count elements
show("original",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort",x)
selectionsort(x,n,function (x,y) return x>y end)
show("after reverse selection sort",x)
qsort(x,1,n,function (x,y) return x<y end)
show("after quicksort again",x)
end
-- array to be sorted
x={"Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"}
testsorts(x)
| bsd-3-clause |
gedads/Neodynamis | scripts/zones/Bastok_Markets/npcs/Degenhard.lua | 3 | 2110 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Degenhard
-- Starts & Ends Quest: The Bare Bones
-- Involved in Quests: Beat Around the Bushin
-- !pos -175 2 -135 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local BoneChip = trade:hasItemQty(880,1);
if (BoneChip == true and count == 1) then
local BareBones = player:getQuestStatus(BASTOK,THE_BARE_BONES);
if (BareBones == 1) then
player:tradeComplete();
player:completeQuest(BASTOK,THE_BARE_BONES);
player:startEvent(0x0102);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local BareBones = player:getQuestStatus(BASTOK,THE_BARE_BONES);
if (player:getVar("BeatAroundTheBushin") == 3) then
player:startEvent(0x0156);
elseif (BareBones == 0) then
player:startEvent(0x0100);
else
player:startEvent(0x00ff);
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 == 0x0156) then
player:setVar("BeatAroundTheBushin",4);
elseif (csid == 0x0100) then
player:addQuest(BASTOK,THE_BARE_BONES);
elseif (csid == 0x0102) then
player:addKeyItem(0x188);
player:messageSpecial(KEYITEM_OBTAINED,0x188);
player:addFame(BASTOK,60);
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Port_Jeuno/npcs/Imasuke.lua | 3 | 3287 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Imasuke
-- Starts and Finishes Quest: The Antique Collector
-- !pos -165 11 94 246
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local theAntiqueCollector = player:getQuestStatus(JEUNO,THE_ANTIQUE_COLLECTOR);
-- THE ANTIQUE COLLECTOR (kaiser sword)
if (theAntiqueCollector == QUEST_ACCEPTED and trade:hasItemQty(16631,1) and trade:getItemCount() == 1) then
player:startEvent(0x000f); -- End quest
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME);
local theAntiqueCollector = player:getQuestStatus(JEUNO,THE_ANTIQUE_COLLECTOR);
local circleProgress = player:getVar("circleTime");
-- CIRCLE OF TIME
if (circleOfTime == QUEST_ACCEPTED) then
if (circleProgress == 1) then
player:startEvent(0x1E);
elseif (circleProgress == 2) then
player:startEvent(0x1D);
elseif (circleProgress == 3) then
player:startEvent(0x20);
elseif (circleProgress == 4) then
player:startEvent(0x21);
elseif (circleProgress == 5) then
player:startEvent(0x1F);
end;
-- THE ANTIQUE COLLECTOR
elseif (theAntiqueCollector == QUEST_AVAILABLE and player:getFameLevel(JEUNO) >= 3) then
player:startEvent(0x000d); -- Start quest
elseif (theAntiqueCollector == QUEST_ACCEPTED) then
player:startEvent(0x000e); -- Mid CS
-- DEFAULT DIALOG
else
player:startEvent(0x000c);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- THE ANTIQUE COLLECTOR
if (csid == 0x000d and option == 1) then
player:addQuest(JEUNO,THE_ANTIQUE_COLLECTOR);
elseif (csid == 0x000f) then
player:addTitle(TRADER_OF_ANTIQUITIES);
if (player:hasKeyItem(MAP_OF_DELKFUTTS_TOWER) == false) then
player:addKeyItem(MAP_OF_DELKFUTTS_TOWER);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_DELKFUTTS_TOWER);
end;
player:addFame(JEUNO, 30);
player:tradeComplete(trade);
player:completeQuest(JEUNO,THE_ANTIQUE_COLLECTOR);
-- CIRCLE OF TIME
elseif (csid == 0x1D and option == 1) then
player:setVar("circleTime",3);
elseif (csid == 0x1E and option == 1) then
player:setVar("circleTime",3);
elseif (csid == 0x1E and option == 0) then
player:setVar("circleTime",2);
elseif (csid == 0x21) then
player:setVar("circleTime",5);
end;
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Rabao/npcs/Shupah_Mujuuk.lua | 12 | 3349 | -----------------------------------
-- Area: Rabao
-- NPC: Shupah Mujuuk
-- Title Change NPC
-- !pos 12 8 20 247
-----------------------------------
require("scripts/globals/titles")
-----------------------------------
local eventId = 1011
local titleInfo =
{
{
cost = 200,
title =
{
dsp.title.THE_IMMORTAL_FISHER_LU_SHANG,
dsp.title.INDOMITABLE_FISHER,
dsp.title.KUFTAL_TOURIST,
dsp.title.ACQUIRER_OF_ANCIENT_ARCANUM,
dsp.title.DESERT_HUNTER,
dsp.title.ROOKIE_HERO_INSTRUCTOR,
},
},
{
cost = 300,
title =
{
dsp.title.HEIR_OF_THE_GREAT_WIND,
},
},
{
cost = 400,
title =
{
dsp.title.FODDERCHIEF_FLAYER,
dsp.title.WARCHIEF_WRECKER,
dsp.title.DREAD_DRAGON_SLAYER,
dsp.title.OVERLORD_EXECUTIONER,
dsp.title.DARK_DRAGON_SLAYER,
dsp.title.ADAMANTKING_KILLER,
dsp.title.BLACK_DRAGON_SLAYER,
dsp.title.MANIFEST_MAULER,
dsp.title.BEHEMOTHS_BANE,
dsp.title.ARCHMAGE_ASSASSIN,
dsp.title.HELLSBANE,
dsp.title.GIANT_KILLER,
dsp.title.LICH_BANISHER,
dsp.title.JELLYBANE,
dsp.title.BOGEYDOWNER,
dsp.title.BEAKBENDER,
dsp.title.SKULLCRUSHER,
dsp.title.MORBOLBANE,
dsp.title.GOLIATH_KILLER,
dsp.title.MARYS_GUIDE,
},
},
{
cost = 500,
title =
{
dsp.title.SIMURGH_POACHER,
dsp.title.ROC_STAR,
dsp.title.SERKET_BREAKER,
dsp.title.CASSIENOVA,
dsp.title.THE_HORNSPLITTER,
dsp.title.TORTOISE_TORTURER,
dsp.title.MON_CHERRY,
dsp.title.BEHEMOTH_DETHRONER,
dsp.title.THE_VIVISECTOR,
dsp.title.DRAGON_ASHER,
dsp.title.EXPEDITIONARY_TROOPER,
},
},
{
cost = 600,
title =
{
dsp.title.ADAMANTKING_USURPER,
dsp.title.OVERLORD_OVERTHROWER,
dsp.title.DEITY_DEBUNKER,
dsp.title.FAFNIR_SLAYER,
dsp.title.ASPIDOCHELONE_SINKER,
dsp.title.NIDHOGG_SLAYER,
dsp.title.MAAT_MASHER,
dsp.title.KIRIN_CAPTIVATOR,
dsp.title.CACTROT_DESACELERADOR,
dsp.title.LIFTER_OF_SHADOWS,
dsp.title.TIAMAT_TROUNCER,
dsp.title.VRTRA_VANQUISHER,
dsp.title.WORLD_SERPENT_SLAYER,
dsp.title.XOLOTL_XTRAPOLATOR,
dsp.title.BOROKA_BELEAGUERER,
dsp.title.OURYU_OVERWHELMER,
dsp.title.VINEGAR_EVAPORATOR,
dsp.title.VIRTUOUS_SAINT,
dsp.title.BYEBYE_TAISAI,
dsp.title.TEMENOS_LIBERATOR,
dsp.title.APOLLYON_RAVAGER,
dsp.title.WYRM_ASTONISHER,
dsp.title.NIGHTMARE_AWAKENER,
},
},
}
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
dsp.title.changerOnTrigger(player, eventId, titleInfo)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
dsp.title.changerOnEventFinish(player, csid, option, eventId, titleInfo)
end | gpl-3.0 |
starlightknight/darkstar | scripts/globals/spells/distract_ii.lua | 12 | 1617 | -----------------------------------------
-- Spell: Distract II
-----------------------------------------
require("scripts/globals/magic")
require("scripts/globals/msg")
require("scripts/globals/status")
require("scripts/globals/utils")
-----------------------------------------
function onMagicCastingCheck(caster, target, spell)
return 0
end
function onSpellCast(caster, target, spell)
local dMND = caster:getStat(dsp.mod.MND) - target:getStat(dsp.mod.MND)
-- Base evasion reduction is determend by enfeebling skill
-- Caps at -40 evasion at 350 skill
local basePotency = utils.clamp(math.floor(caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC) * 4 / 35), 0, 40)
-- dMND is tacked on after
-- Min cap: 0 at 0 dMND
-- Max cap: 10 at 50 dMND
basePotency = basePotency + utils.clamp(math.floor(dMND / 5), 0, 10)
local power = calculatePotency(basePotency, spell:getSkillType(), caster, target)
local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target)
local params = {}
params.diff = dMND
params.skillType = dsp.skill.ENFEEBLING_MAGIC
params.bonus = 0
params.effect = dsp.effect.EVASION_DOWN
local resist = applyResistanceEffect(caster, target, spell, params)
if resist >= 0.5 then
if target:addStatusEffect(params.effect, power, 0, duration * resist) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
end
return params.effect
end | gpl-3.0 |
pedro-andrade-inpe/terrame | packages/base/tests/database/basics/Environment.lua | 3 | 9132 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
return{
loadNeighborhood = function(unitTest)
local cs = CellularSpace{
file = filePath("test/river.shp")
}
local cs2 = CellularSpace{
file = filePath("test/emas.shp"),
xy = {"Col", "Lin"}
}
local cs3 = CellularSpace{
file = filePath("test/Limit_pol.shp")
}
unitTest:assertEquals(208, #cs)
unitTest:assertEquals(1435, #cs2)
unitTest:assertEquals(1, #cs3)
local env = Environment{cs, cs2, cs3}
local countTest = 1
-- .gpm Regular CS x Irregular CS - without weights
env:loadNeighborhood{
file = filePath("gpmlinesDbEmas.gpm", "base"),
name = "my_neighborhood"..countTest
}
local sizes = {}
local minSize = math.huge
local maxSize = -math.huge
local sumWeight = 0
forEachCell(cs2, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assert(neighborhoodSize >= 0)
unitTest:assert(neighborhoodSize <= 9)
minSize = math.min(neighborhoodSize, minSize)
maxSize = math.max(neighborhoodSize, maxSize)
if(sizes[neighborhoodSize] == nil)then sizes[neighborhoodSize] = 0 end
sizes[neighborhoodSize] = sizes[neighborhoodSize] + 1
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assertEquals(1, weight)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(623, sumWeight)
unitTest:assertEquals(0, minSize)
unitTest:assertEquals(9, maxSize)
unitTest:assertEquals(242, sizes[1])
unitTest:assertEquals(28, sizes[2])
unitTest:assertEquals(60, sizes[3])
unitTest:assertEquals(11, sizes[4])
unitTest:assertEquals(8, sizes[5])
unitTest:assertEquals(4, sizes[6])
unitTest:assertEquals(4, sizes[7])
unitTest:assertEquals(1, sizes[9])
unitTest:assertEquals(1077, sizes[0])
-- .gpm Regular CS x Irregular CS - file with weight
countTest = countTest + 1
env:loadNeighborhood{
file = filePath("test/gpmAreaCellsPols.gpm", "base"),
name = "my_neighborhood"..countTest
}
local minWeight = math.huge
local maxWeight = -math.huge
sumWeight = 0
forEachCell(cs2, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(1, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assert(weight <= 1000000)
unitTest:assert(weight >= 304.628)
minWeight = math.min(weight, minWeight)
maxWeight = math.max(weight, maxWeight)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(1326705357.3888, sumWeight, 0.00001)
unitTest:assertEquals(304.628, minWeight, 0.00001)
unitTest:assertEquals(1000000, maxWeight)
-- .gpm Regular CS x Irregular CS - using 'bidirect' = false
countTest = countTest + 1
env:loadNeighborhood{
file = filePath("test/gpmAreaCellsPols.gpm", "base"),
name = "my_neighborhood"..countTest
}
minWeight = math.huge
maxWeight = -math.huge
sumWeight = 0
forEachCell(cs2, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(1, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assert(weight <= 1000000)
unitTest:assert(weight >= 304.628)
minWeight = math.min(weight, minWeight)
maxWeight = math.max(weight, maxWeight)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(1326705357.3888, sumWeight, 0.00001)
unitTest:assertEquals(304.628, minWeight, 0.00001)
unitTest:assertEquals(1000000, maxWeight)
-- .gpm Reg CS x Irreg CS - using 'bidirect' = true
countTest = countTest + 1
env:loadNeighborhood{
file = filePath("test/gpmAreaCellsPols.gpm", "base"),
name = "my_neighborhood"..countTest,
bidirect = true
}
minWeight = math.huge
maxWeight = -math.huge
sumWeight = 0
forEachCell(cs2, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(1, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assert(weight <= 1000000)
unitTest:assert(weight >= 304.628)
minWeight = math.min(weight, minWeight)
maxWeight = math.max(weight, maxWeight)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(1326705357.3888, sumWeight, 0.00001)
unitTest:assertEquals(304.628, minWeight, 0.00001)
unitTest:assertEquals(1000000, maxWeight)
-- Verifying the other side
minWeight = math.huge
maxWeight = -math.huge
sumWeight = 0
forEachCell(cs3, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(1435, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assert(1000000 >= weight)
unitTest:assert(304.628 <= weight)
minWeight = math.min(weight, minWeight)
maxWeight = math.max(weight, maxWeight)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(1326705357.3888, sumWeight, 0.00001)
unitTest:assertEquals(304.628, minWeight, 0.00001)
unitTest:assertEquals(1000000, maxWeight)
-- .gpm Irregular CS x Irregular CS - using bidirect = false
countTest = countTest + 1
env:loadNeighborhood{
file = filePath("test/emas-pollin.gpm", "base"),
name = "my_neighborhood"..countTest
}
sumWeight = 0
forEachCell(cs3, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(207, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(_, weight)
unitTest:assertEquals(weight, 1)
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(207, sumWeight)
-- .gpm Irregular CS x Irregular CS - using bidirect = true
countTest = countTest + 1
env:loadNeighborhood{
file = filePath("test/emas-pollin.gpm", "base"),
name = "my_neighborhood"..countTest,
bidirect = true
}
sumWeight = 0
forEachCell(cs3, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
unitTest:assertEquals(207, neighborhoodSize)
forEachNeighbor(cell, "my_neighborhood"..countTest, function(neigh, weight, c)
unitTest:assertEquals(weight, 1)
unitTest:assert(neigh:getNeighborhood("my_neighborhood"..countTest):isNeighbor(c))
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(207, sumWeight)
-- the other side
sizes = {}
sumWeight = 0
forEachCell(cs, function(cell)
local neighborhood = cell:getNeighborhood("my_neighborhood"..countTest)
unitTest:assertNotNil(neighborhood)
local neighborhoodSize = #neighborhood
if sizes[neighborhoodSize] == nil then sizes[neighborhoodSize] = 0 end
sizes[neighborhoodSize] = sizes[neighborhoodSize] + 1
forEachNeighbor(cell, "my_neighborhood"..countTest, function(neigh, weight, c)
unitTest:assertEquals(weight, 1)
unitTest:assert(neigh:getNeighborhood("my_neighborhood"..countTest):isNeighbor(c))
sumWeight = sumWeight + weight
end)
end)
unitTest:assertEquals(207, sumWeight)
unitTest:assertEquals(1, sizes[0])
unitTest:assertEquals(207, sizes[1])
end
}
| lgpl-3.0 |
LoPhatKao/GardenBot2 | scripts/harvestpools.lua | 1 | 3725 | -- LoPhatKao - July 2015
-- harvestpools.lua - compatibility addon for Gardenbot 2
-- a workaround til world.spawnTreasure() is implemented
-- uses same calling conventions
harvestPools = {}
function harvestPools.spawnTreasure (pos, poolname, level, seed) -- i'm ignoring level and seed
if type(pos) ~= "table" then return false end -- no spawn pos
if type(poolname) ~= "string" then return false end -- invalid name parameter
local tp = harvestPools.getPool(poolname)
if tp == nil then -- not listed
-- world.logInfo("Pool not found: %s",poolname)
return false
else -- is listed in known pools, generate dat bling
local didSpawn = false
if tp.fill ~= nil then -- spawn 'always drop' items
for i = 1,#tp.fill do
harvestPools.doSpawnItem(pos,tp.fill[i].item)
didSpawn = true
end
end
if tp.pool ~= nil then -- spawn 'maybe drop' items
local maxrnd = harvestPools.numRounds(tp.poolRounds)
for i = 1, maxrnd do
local ritem = tp.pool[math.random(1,#tp.pool)]
if math.random() <= harvestPools.poolWeight(ritem) or (i==maxrnd and not didSpawn) then
harvestPools.doSpawnItem(pos,ritem.item)
didSpawn = true
end
end
end
return didSpawn
end
return false
end
---------------------------------------------------------------------------------------
-------------- helper funcs
---------------------------------------------------------------------------------------
function harvestPools.numRounds(poolRounds)--randomize # rounds of pool spawning, returning 0 is ok
if type(poolRounds) == "table" then -- usually a table of tables
for i = #poolRounds,1,-1 do
if math.random() <= poolRounds[i][1] or i == 1 then return poolRounds[i][2] end
end
end
return 0
end
function harvestPools.poolWeight(pool)
if pool.weight ~= nil then return pool.weight end
return 1
end
function harvestPools.itemName(item)
if type(item) == "string" then return item end
if type(item) == "table" then return item[1] end
return "perfectlygenericitem" -- shouldnt ever get here..
end
function harvestPools.itemCount(item)
if type(item) == "table" and item[2] ~= nil then return item[2] end
return 1
end
function harvestPools.itemParams(item) -- for stuff with params, generated weps etc.
if type(item) == "table" and item[3] ~= nil then return item[3] end
return {}
end
function harvestPools.doSpawnItem(pos,item)
--world.logInfo("Spawning: %s",item)
pos[2] = math.floor(pos[2])+0.5
iName = harvestPools.itemName(item)
iCnt = harvestPools.itemCount(item)
iParam = harvestPools.itemParams(item)
if not world.spawnItem(iName,pos,iCnt,iParam) then
world.logInfo("Failed to spawn item: %s",item)
end
end
function harvestPools.getPool(poolname)
---------------------------------------------------------------------------------------
-- pool data - here comes the hugeness -.- lol - somewhere near 250kb
-- poolcounts: vanilla = 39(7 used), MFM = 27, FU = 174, OPP = 737
-- should add popular race crops - avali etc
-- gb2rc2.1 - move to local of spawnTreasure
-- gb2rc3.1 move to its own func in general cleanup of harvestpool lua
--gb2rc4 - removed all data, long unneeded - left legacy code for reference - also lazy to edit all the monstypes
---------------------------------------------------------------------------------------
local pools = {
-- kao's test seed
moneyHarvest = {fill={{item="moneyseed"}},pool={{weight=0.05,item={"moneyseed",1}},{weight=0.1,item={"voxel10k",1}},{weight=0.2,item={"voxel5k",1}},{weight=0.3,item={"voxel2k",1}},{weight=0.4,item={"voxel1k",1}},{item={"money",100}}},poolRounds={{0.7,1},{0.3,0}}},
} -- end of pool list
return pools[poolname]
end | apache-2.0 |
Jamanno/Zero-K-Infrastructure | Benchmarker/Benchmarks/Configs/ZKL_with_lights/LuaUI/Config/ZK_data.lua | 12 | 4681 | -- Widget Custom Data
return {
version = 9,
["Auto Group"] = {
version = "3.031",
groups = {},
},
["Chili Docking"] = {
Chat = {
[1] = 1055,
[2] = 0,
[3] = 1475,
[4] = 200,
},
Minimap = {
[1] = 0,
[2] = 0,
[3] = 565,
[4] = 316.95123291016,
},
["Player List"] = {
[1] = 1624,
[2] = 1050,
[3] = 1920,
[4] = 1200,
},
ResourceBars = {
[1] = 1490,
[2] = 0,
[3] = 1920,
[4] = 50,
},
chickenpanel = {
[1] = 1650,
[2] = 1011,
[3] = 1920,
[4] = 1200,
},
epicmenubar = {
[1] = 1475,
[2] = 50,
[3] = 1920,
[4] = 100,
},
integralwindow = {
[1] = 0,
[2] = 1020,
[3] = 450,
[4] = 1200,
},
real_window_corner = {
[1] = 0,
[2] = 890,
[3] = 450,
[4] = 1020,
},
rejoinProgress = {
[1] = 0,
[2] = 565,
[3] = 260,
[4] = 625,
},
selector_window = {
[1] = 450,
[2] = 1148,
[3] = 834,
[4] = 1200,
},
},
CustomFormations2 = {
maxHungarianUnits = 20,
},
["EPIC Menu"] = {
country = "CZ",
lang = "en",
music_volume = 0.5,
show_crudemenu = true,
sub_pos_x = 700,
sub_pos_y = 500,
versionmin = 50,
wl_h = 700,
wl_w = 300,
wl_x = 550,
wl_y = 150,
config = {
epic_Chili_Minimap_alwaysDisplayMexes = false,
["epic_Settings/Camera_Camera_Type"] = "Total Annihilation",
},
keybounditems = {
areaattack = {
key = "a",
mod = "A+",
},
areamex = {
key = "w",
mod = "C+",
},
attack = {
key = "a",
mod = "",
},
cloak = {
key = "k",
mod = "",
},
decreaseviewradius = {
key = "end",
mod = "",
},
epic_chili_integral_menu_tab_defence = {
key = "c",
mod = "",
},
epic_chili_integral_menu_tab_economy = {
key = "x",
mod = "",
},
epic_chili_integral_menu_tab_factory = {
key = "z",
mod = "",
},
epic_chili_integral_menu_tab_special = {
key = "v",
mod = "",
},
epic_chili_minimap_alwaysdisplaymexes = {
key = "f4",
mod = "",
},
epic_chili_widget_selector_widgetlist = {
key = "f11",
mod = "",
},
fight = {
key = "f",
mod = "",
},
guard = {
key = "g",
mod = "",
},
increaseviewradius = {
key = "home",
mod = "",
},
jump = {
key = "j",
mod = "",
},
lastmsgpos = {
key = "f3",
mod = "",
},
loadunits = {
key = "l",
mod = "",
},
["luaui tweakgui"] = {
key = "f11",
mod = "C+",
},
manualfire = {
key = "d",
mod = "",
},
move = {
key = "m",
mod = "",
},
oneclickwep = {
key = "d",
mod = "",
},
onoff = {
key = "x",
mod = "",
},
patrol = {
key = "p",
mod = "",
},
pause = {
key = "pause",
mod = "",
},
reclaim = {
key = "e",
mod = "",
},
repair = {
key = "r",
mod = "",
},
resurrect = {
key = "t",
mod = "",
},
screenshot = {
key = "f12",
mod = "",
},
["select AllMap++_ClearSelection_SelectAll+"] = {
key = "a",
mod = "C+",
},
["select AllMap+_Builder_Not_Building_Idle+_ClearSelection_SelectOne+"] = {
key = "v",
mod = "C+",
},
["select AllMap+_Builder_Not_Building_Not_Transport_Idle+_ClearSelection_SelectAll+"] = {
key = "b",
mod = "C+",
},
["select AllMap+_InPrevSel+_ClearSelection_SelectAll+"] = {
key = "z",
mod = "C+",
},
["select PrevSelection+_Idle+_ClearSelection_SelectAll+"] = {
key = "i",
mod = "C+",
},
["select Visible+_InPrevSel+_ClearSelection_SelectAll+"] = {
key = "x",
mod = "C+",
},
selectcomm = {
key = "c",
mod = "C+",
},
selfd = {
key = "d",
mod = "C+",
},
sharedialog = {
key = "h",
mod = "",
},
showelevation = {
key = "f1",
mod = "",
},
showmetalmap = {
key = "f4",
mod = "",
},
showpathtraversability = {
key = "f2",
mod = "",
},
stop = {
key = "s",
mod = "",
},
togglelos = {
key = "l",
mod = "",
},
unloadunits = {
key = "u",
mod = "",
},
viewta = {
key = "f2",
mod = "C+",
},
wait = {
key = "w",
mod = "",
},
},
widgets = {},
},
["Local Widgets Config"] = {
localWidgets = false,
localWidgetsFirst = false,
},
["Persistent Build Spacing"] = {
buildSpacing = {},
},
}
| gpl-3.0 |
CAAP/Lua | carlos/sites.lua | 1 | 2953 | -- module setup
local M = {}
-- Import Section
local fd = require'carlos.fold'
local concat = table.concat
local format = string.format
local remove = table.remove
local pairs = pairs
local type = type
local tonumber = tonumber
local tointeger = math.tointeger
local iolines = io.lines
-- No more external access after this point
_ENV = nil -- or M
-- Local Variables for module-only access
local REGEX = "(%$[%u_]+)"
--------------------------------
-- Local function definitions --
--------------------------------
local function wrap(txt, tag) return format("<%s>%s</%s>", tag, txt, tag) end
local function json( w )
-- assert(type(w) == 'table')
local ret = {}
for k,v in pairs(w) do
local u = type(v) == 'table' and json(v) or (tointeger(v) or v)
ret[#ret+1] = format('%q: %'..(tonumber(u) and 's' or 'q'), k, u)
end
return format( '{%s}', concat(ret, ', ') ):gsub('"%[', '['):gsub(']"',']'):gsub("'", '"')
end
local function line_space(iter) fd.first(fd.wrap(iter), function(x) return x:match'^[%s]+$' end) end
local function get_lines(iter, boundary) return concat(fd.conditional(function(l) return l:match(boundary) end, fd.wrap(iter), fd.into, {}), '\n') end
-- vars[nm] = fd.first(fd.wrap(lines), function(x) return x:match'[^%s]+' end)
local function post_form( path )
local vars = {}
local lines = iolines( path )
local boundary = fd.first(fd.wrap(lines), function(x) return x:match'Boundary' end)
local nm, line
repeat
line = lines()
nm = line:match'="([^=]+)"'
line_space(lines)
vars[nm] = get_lines(lines, boundary)
until nm == 'file'
return vars
end
---------------------------------
-- Public function definitions --
---------------------------------
M.REGEX = REGEX
M.wrap = wrap
M.json = json
M.post = post_form
function M.html()
local MM = {}
local scs = {after={}}
local scs2 = scs.after
local css = {}
local body = {}
local env = {}
local head = ''
local lang = 'es-MX'
function MM.add_jscript(txt, after)
if after then
scs2[#scs2+1] = txt
else
scs[#scs+1] = txt
end
return MM
end
function MM.add_css(txt) css[#css+1] = txt; return MM end
function MM.add_body(txt) body[#body+1] = txt; return MM end
function MM.set_head(txt) head = txt; return MM end
function MM.set_lang(txt) lang = txt; return MM end
function MM.asstr()
local ccc = #scs2 > 0 and format("(function() { let oldload = window.onload; window.onload = function() { oldload && oldload(); %s }; })();", concat(scs2, '\n')) or ''
local ret = '<!DOCTYPE html><html lang="$LANG">$ENV</html>'
env['$LANG'] = 'es-MX'
env[1] = wrap(concat({head, wrap(concat({'"use strict";', concat(scs, '\n'), ccc}, '\n'), 'script'), wrap(concat(css, '\n'), 'style')}, '\n'), 'head')
env[2] = wrap(concat(body, '\n'), 'body')
env['$ENV'] = concat(env, '\n')
return ret:gsub(REGEX, env)
end
return MM
end
return M
| gpl-2.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/applications/luci-diag-devinfo/luasrc/controller/luci_diag/netdiscover_common.lua | 76 | 3146 | --[[
Luci diag - Diagnostics controller module
(c) 2009 Daniel Dickinson
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
]]--
module("luci.controller.luci_diag.netdiscover_common", package.seeall)
require("luci.i18n")
require("luci.util")
require("luci.sys")
require("luci.cbi")
require("luci.model.uci")
local translate = luci.i18n.translate
local DummyValue = luci.cbi.DummyValue
local SimpleSection = luci.cbi.SimpleSection
function index()
return -- no-op
end
function get_params()
local netdiscover_uci = luci.model.uci.cursor()
netdiscover_uci:load("luci_devinfo")
local nettable = netdiscover_uci:get_all("luci_devinfo")
local i
local subnet
local netdout
local outnets = {}
i = next(nettable, nil)
while (i) do
if (netdiscover_uci:get("luci_devinfo", i) == "netdiscover_scannet") then
local scannet = netdiscover_uci:get_all("luci_devinfo", i)
if scannet["subnet"] and (scannet["subnet"] ~= "") and scannet["enable"] and ( scannet["enable"] == "1") then
local output = ""
local outrow = {}
outrow["interface"] = scannet["interface"]
outrow["timeout"] = 10
local timeout = tonumber(scannet["timeout"])
if timeout and ( timeout > 0 ) then
outrow["timeout"] = scannet["timeout"]
end
outrow["repeat_count"] = 1
local repcount = tonumber(scannet["repeat_count"])
if repcount and ( repcount > 0 ) then
outrow["repeat_count"] = scannet["repeat_count"]
end
outrow["sleepreq"] = 100
local repcount = tonumber(scannet["sleepreq"])
if repcount and ( repcount > 0 ) then
outrow["sleepreq"] = scannet["sleepreq"]
end
outrow["subnet"] = scannet["subnet"]
outrow["output"] = output
outnets[i] = outrow
end
end
i = next(nettable, i)
end
return outnets
end
function command_function(outnets, i)
local interface = luci.controller.luci_diag.devinfo_common.get_network_device(outnets[i]["interface"])
return "/usr/bin/netdiscover-to-devinfo " .. outnets[i]["subnet"] .. " " .. interface .. " " .. outnets[i]["timeout"] .. " -r " .. outnets[i]["repeat_count"] .. " -s " .. outnets[i]["sleepreq"] .. " </dev/null"
end
function action_links(netdiscovermap, mini)
s = netdiscovermap:section(SimpleSection, "", translate("Actions"))
b = s:option(DummyValue, "_config", translate("Configure Scans"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "network", "netdiscover_devinfo_config")
else
b.titleref = luci.dispatcher.build_url("admin", "network", "diag_config", "netdiscover_devinfo_config")
end
b = s:option(DummyValue, "_scans", translate("Repeat Scans (this can take a few minutes)"))
b.value = ""
if (mini) then
b.titleref = luci.dispatcher.build_url("mini", "diag", "netdiscover_devinfo")
else
b.titleref = luci.dispatcher.build_url("admin", "status", "netdiscover_devinfo")
end
end
| gpl-2.0 |
Amorph/premake-stable | tests/test_vs2002_sln.lua | 14 | 1629 | --
-- tests/test_vs2002_sln.lua
-- Automated test suite for Visual Studio 2002 solution generation.
-- Copyright (c) 2009 Jason Perkins and the Premake project
--
T.vs2002_sln = { }
local suite = T.vs2002_sln
local sln2002 = premake.vstudio.sln2002
--
-- Configure a solution for testing
--
local sln
function suite.setup()
_ACTION = 'vs2002'
sln = solution "MySolution"
configurations { "Debug", "Release" }
platforms {}
prj = project "MyProject"
language "C++"
kind "ConsoleApp"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
premake.bake.buildconfigs()
end
--
-- Make sure I've got the basic layout correct
--
function suite.BasicLayout()
sln2002.generate(sln)
test.capture [[
Microsoft Visual Studio Solution File, Format Version 7.00
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MyProject", "MyProject.vcproj", "{AE61726D-187C-E440-BD07-2556188A6565}"
EndProject
Global
GlobalSection(SolutionConfiguration) = preSolution
ConfigName.0 = Debug
ConfigName.1 = Release
EndGlobalSection
GlobalSection(ProjectDependencies) = postSolution
EndGlobalSection
GlobalSection(ProjectConfiguration) = postSolution
{AE61726D-187C-E440-BD07-2556188A6565}.Debug.ActiveCfg = Debug|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Debug.Build.0 = Debug|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Release.ActiveCfg = Release|Win32
{AE61726D-187C-E440-BD07-2556188A6565}.Release.Build.0 = Release|Win32
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
EndGlobalSection
GlobalSection(ExtensibilityAddIns) = postSolution
EndGlobalSection
EndGlobal
]]
end
| bsd-3-clause |
mahdib9/54 | plugins/time.lua | 94 | 3004 | -- Implement a command !time [area] which uses
-- 2 Google APIs to get the desired result:
-- 1. Geocoding to get from area to a lat/long pair
-- 2. Timezone to get the local time in that lat/long location
-- Globals
-- If you have a google api key for the geocoding/timezone api
api_key = nil
base_api = "https://maps.googleapis.com/maps/api"
dateFormat = "%A %d %B - %H:%M:%S"
-- Need the utc time for the google api
function utctime()
return os.time(os.date("!*t"))
end
-- Use the geocoding api to get the lattitude and longitude with accuracy specifier
-- CHECKME: this seems to work without a key??
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Get the data
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
-- Use timezone api to get the time in the lat,
-- Note: this needs an API key
function get_time(lat,lng)
local api = base_api .. "/timezone/json?"
-- Get a timestamp (server time is relevant here)
local timestamp = utctime()
local parameters = "location=" ..
URL.escape(lat) .. "," ..
URL.escape(lng) ..
"×tamp="..URL.escape(timestamp)
if api_key ~=nil then
parameters = parameters .. "&key="..api_key
end
local res,code = https.request(api..parameters)
if code ~= 200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
-- Construct what we want
-- The local time in the location is:
-- timestamp + rawOffset + dstOffset
local localTime = timestamp + data.rawOffset + data.dstOffset
return localTime, data.timeZoneId
end
return localTime
end
function getformattedLocalTime(area)
if area == nil then
return "The time in nowhere is never"
end
lat,lng,acc = get_latlong(area)
if lat == nil and lng == nil then
return 'It seems that in "'..area..'" they do not have a concept of time.'
end
local localTime, timeZoneId = get_time(lat,lng)
return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime)
end
function run(msg, matches)
return getformattedLocalTime(matches[1])
end
return {
description = "Displays the local time in an area",
usage = "!time [area]: Displays the local time in that area",
patterns = {"^!time (.*)$"},
run = run
}
--Copyright and edit; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Base-Team/BaseBot | plugins/all.lua | 184 | 4452 | do
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)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_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
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.\nUse /type in the group to set type.'
end
return group_type
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(msg,target,receiver)
local data = load_data(_config.moderation.data)
if not data[tostring(target)] then
return
end
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
if group_type == "Group" or group_type == "Realm" then
local settings = show_group_settingsmod(msg,target)
text = text.."\n\n"..settings
elseif group_type == "SuperGroup" then
local settings = show_supergroup_settingsmod(msg,target)
text = text..'\n\n'..settings
end
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local mutes_list = mutes_list(target)
text = text.."\n\n"..mutes_list
local muted_user_list = muted_user_list(target)
text = text.."\n\n"..muted_user_list
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
local function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(msg,target,receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
return all(msg,msg.to.id,receiver)
end
end
return {
patterns = {
"^[#!/](all)$",
"^[#!/](all) (%d+)$"
},
run = run
}
end | agpl-3.0 |
starlightknight/darkstar | scripts/globals/mobskills/optic_induration.lua | 11 | 1404 | ---------------------------------------------
-- Optic Induration
--
-- Description: Charges up a powerful, calcifying beam directed at targets in a fan-shaped area of effect. Additional effect: Petrification & enmity reset
-- Type: Magical
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: Unknown cone
-- Notes: Charges up (three times) before actually being used (except Jailer of Temperance, who doesn't need to charge it up). The petrification lasts a very long time.
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:AnimationSub() == 2 or mob:AnimationSub() == 3) then
return 1
end
return 0
end
function onMobWeaponSkill(target, mob, skill)
local typeEffect = dsp.effect.PETRIFICATION
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 60)
local dmgmod = 1
local accmod = 1
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*3,dsp.magic.ele.DARK,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.DARK,MOBPARAM_IGNORE_SHADOWS)
target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.DARK)
mob:resetEnmity(target)
return dmg
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Dynamis-Qufim/mobs/Antaeus.lua | 23 | 2217 | -----------------------------------
-- Area: Dynamis Qufim
-- MOB: Antaeus
-----------------------------------
package.loaded["scripts/zones/Dynamis-Qufim/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Qufim/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (GetServerVariable("[DynaQufim]Boss_Trigger")==0) then
--spwan additional mob :
for Nightmare_Stirge = 16945407, 16945420, 1 do
SpawnMob(Nightmare_Stirge);
end
for Nightmare_Diremite = 16945422, 16945430, 1 do
SpawnMob(Nightmare_Diremite);
end
for Nightmare_Gaylas = 16945431, 16945442, 1 do
SpawnMob(Nightmare_Gaylas);
end
for Nightmare_Kraken = 16945443, 16945456, 1 do
SpawnMob(Nightmare_Kraken);
end
for Nightmare_Snoll = 16945458, 16945469, 1 do
SpawnMob(Nightmare_Snoll);
end
for Nightmare_Tiger = 16945510, 16945521, 1 do
SpawnMob(Nightmare_Tiger);
end
for Nightmare_Weapon = 16945549, 16945558, 1 do
SpawnMob(Nightmare_Weapon);
end
for Nightmare_Raptor = 16945589, 16945598, 1 do
SpawnMob(Nightmare_Raptor);
end
SetServerVariable("[DynaQufim]Boss_Trigger",1);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
if (player:hasKeyItem(DYNAMIS_QUFIM_SLIVER ) == false) then
player:addKeyItem(DYNAMIS_QUFIM_SLIVER);
player:messageSpecial(KEYITEM_OBTAINED,DYNAMIS_QUFIM_SLIVER);
end
player:addTitle(DYNAMISQUFIM_INTERLOPER);
end; | gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/uskumru.lua | 12 | 1322 | -----------------------------------------
-- ID: 5452
-- Item: Uskumru
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5452);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Bastok-Jeuno_Airship/IDs.lua | 12 | 1290 | -----------------------------------
-- Area: Bastok-Jeuno_Airship
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.BASTOK_JEUNO_AIRSHIP] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
WILL_REACH_JEUNO = 7208, -- The airship will reach Jeuno in [less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] (# [minute/minutes] in Earth time).
WILL_REACH_BASTOK = 7209, -- The airship will reach Bastok in [less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] (# [minute/minutes] in Earth time).
IN_JEUNO_MOMENTARILY = 7210, -- We will be arriving in Jeuno momentarily.
IN_BASTOK_MOMENTARILY = 7211, -- We will be arriving in Bastok momentarily.
},
mob =
{
},
npc =
{
},
}
return zones[dsp.zone.BASTOK_JEUNO_AIRSHIP] | gpl-3.0 |
sebastianlis/OOP-Samples-for-Corona-SDK | classes/samples/Storage/SQLite.lua | 1 | 2913 | require "classes.constants.screen"
require "sqlite3"
SQLite={}
function SQLite:new()
local this = display.newGroup()
local public = this
local private = {}
local background = display.newImageRect("img/backgroundNotifications.png", 360, 570)
local labelTitle = display.newText("SQLite demo", 20, 30, native.systemFontBold, 20)
local labelSubtitle = display.newText("Creates or opens a local database", 20, 50, native.systemFont, 14)
local labelInfo = display.newText("(Data is shown below)", 20, 90, native.systemFont, 14)
local db = sqlite3.open(system.pathForFile("data.db", system.DocumentsDirectory))
local word = {'Hello', 'World', 'Lua'}
function private.SQLite()
background.x = screen.centerX
background.y = screen.centerY
labelTitle.anchorX = 0
labelTitle.anchorY = 0
labelTitle:setFillColor(190/255, 190/255, 255/255)
labelSubtitle.anchorX = 0
labelSubtitle.anchorY = 0
labelSubtitle:setFillColor(190/255, 190/255, 255/255)
labelInfo.anchorX = 0
labelInfo.anchorY = 0
labelInfo:setFillColor(255/255, 255/255, 255/255)
this:insert(background)
this:insert(labelTitle)
this:insert(labelSubtitle)
this:insert(labelInfo)
db:exec([[
CREATE TABLE IF NOT EXISTS WordsTable(id INTEGER PRIMARY KEY, word1, word2);
]])
db:exec([[
INSERT INTO WordsTable VALUES (NULL, ']]..word[1]..[[',']]..word[2]..[[');
]])
db:exec([[
INSERT INTO WordsTable VALUES (NULL, ']]..word[2]..[[',']]..word[1]..[[');
]])
db:exec([[
INSERT INTO WordsTable VALUES (NULL, ']]..word[1]..[[',']]..word[3]..[[');
]])
for row in db:nrows("SELECT * FROM WordsTable") do
local textTwoWords = row.word1.." "..row.word2
local labelTwoWords = display.newText(textTwoWords, 20, 120 + (20 * row.id), native.systemFont, 16)
labelTwoWords.anchorX=0
labelTwoWords.anchorY=0
labelTwoWords:setFillColor(255/255, 0/255, 255/255)
this:insert(labelTwoWords)
end
Runtime:addEventListener("system", private.onApplicationExit)
end
function private.onApplicationExit(event)
if event.type == "applicationExit" then
db:close()
end
end
function public:destroy()
Runtime:removeEventListener("system", private.onApplicationExit)
background:removeSelf()
background = nil
labelTitle:removeSelf()
labelTitle = nil
labelSubtitle:removeSelf()
labelSubtitle = nil
labelInfo:removeSelf()
labelInfo = nil
this:removeSelf()
this = nil
end
private.SQLite()
return this
end
return SQLite
| mit |
O-P-E-N/CC-ROUTER | feeds/luci/build/luadoc/luadoc/util.lua | 46 | 5858 | -------------------------------------------------------------------------------
-- General utilities.
-- @release $Id: util.lua,v 1.16 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local posix = require "nixio.fs"
local type, table, string, io, assert, tostring, setmetatable, pcall = type, table, string, io, assert, tostring, setmetatable, pcall
-------------------------------------------------------------------------------
-- Module with several utilities that could not fit in a specific module
module "luadoc.util"
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string
-- @param s string to be trimmed
-- @return trimmed string
function trim (s)
return (string.gsub(s, "^%s*(.-)%s*$", "%1"))
end
-------------------------------------------------------------------------------
-- Removes spaces from the begining and end of a given string, considering the
-- string is inside a lua comment.
-- @param s string to be trimmed
-- @return trimmed string
-- @see trim
-- @see string.gsub
function trim_comment (s)
s = string.gsub(s, "^%s*%-%-+%[%[(.*)$", "%1")
s = string.gsub(s, "^%s*%-%-+(.*)$", "%1")
return s
end
-------------------------------------------------------------------------------
-- Checks if a given line is empty
-- @param line string with a line
-- @return true if line is empty, false otherwise
function line_empty (line)
return (string.len(trim(line)) == 0)
end
-------------------------------------------------------------------------------
-- Appends two string, but if the first one is nil, use to second one
-- @param str1 first string, can be nil
-- @param str2 second string
-- @return str1 .. " " .. str2, or str2 if str1 is nil
function concat (str1, str2)
if str1 == nil or string.len(str1) == 0 then
return str2
else
return str1 .. " " .. str2
end
end
-------------------------------------------------------------------------------
-- Split text into a list consisting of the strings in text,
-- separated by strings matching delim (which may be a pattern).
-- @param delim if delim is "" then action is the same as %s+ except that
-- field 1 may be preceeded by leading whitespace
-- @usage split(",%s*", "Anna, Bob, Charlie,Dolores")
-- @usage split(""," x y") gives {"x","y"}
-- @usage split("%s+"," x y") gives {"", "x","y"}
-- @return array with strings
-- @see table.concat
function split(delim, text)
local list = {}
if string.len(text) > 0 then
delim = delim or ""
local pos = 1
-- if delim matches empty string then it would give an endless loop
if string.find("", delim, 1) and delim ~= "" then
error("delim matches empty string!")
end
local first, last
while 1 do
if delim ~= "" then
first, last = string.find(text, delim, pos)
else
first, last = string.find(text, "%s+", pos)
if first == 1 then
pos = last+1
first, last = string.find(text, "%s+", pos)
end
end
if first then -- found?
table.insert(list, string.sub(text, pos, first-1))
pos = last+1
else
table.insert(list, string.sub(text, pos))
break
end
end
end
return list
end
-------------------------------------------------------------------------------
-- Comments a paragraph.
-- @param text text to comment with "--", may contain several lines
-- @return commented text
function comment (text)
text = string.gsub(text, "\n", "\n-- ")
return "-- " .. text
end
-------------------------------------------------------------------------------
-- Wrap a string into a paragraph.
-- @param s string to wrap
-- @param w width to wrap to [80]
-- @param i1 indent of first line [0]
-- @param i2 indent of subsequent lines [0]
-- @return wrapped paragraph
function wrap(s, w, i1, i2)
w = w or 80
i1 = i1 or 0
i2 = i2 or 0
assert(i1 < w and i2 < w, "the indents must be less than the line width")
s = string.rep(" ", i1) .. s
local lstart, len = 1, string.len(s)
while len - lstart > w do
local i = lstart + w
while i > lstart and string.sub(s, i, i) ~= " " do i = i - 1 end
local j = i
while j > lstart and string.sub(s, j, j) == " " do j = j - 1 end
s = string.sub(s, 1, j) .. "\n" .. string.rep(" ", i2) ..
string.sub(s, i + 1, -1)
local change = i2 + 1 - (i - j)
lstart = j + change
len = len + change
end
return s
end
-------------------------------------------------------------------------------
-- Opens a file, creating the directories if necessary
-- @param filename full path of the file to open (or create)
-- @param mode mode of opening
-- @return file handle
function posix.open (filename, mode)
local f = io.open(filename, mode)
if f == nil then
filename = string.gsub(filename, "\\", "/")
local dir = ""
for d in string.gfind(filename, ".-/") do
dir = dir .. d
posix.mkdir(dir)
end
f = io.open(filename, mode)
end
return f
end
----------------------------------------------------------------------------------
-- Creates a Logger with LuaLogging, if present. Otherwise, creates a mock logger.
-- @param options a table with options for the logging mechanism
-- @return logger object that will implement log methods
function loadlogengine(options)
local logenabled = pcall(function()
require "logging"
require "logging.console"
end)
local logging = logenabled and logging
if logenabled then
if options.filelog then
logger = logging.file("luadoc.log") -- use this to get a file log
else
logger = logging.console("[%level] %message\n")
end
if options.verbose then
logger:setLevel(logging.INFO)
else
logger:setLevel(logging.WARN)
end
else
noop = {__index=function(...)
return function(...)
-- noop
end
end}
logger = {}
setmetatable(logger, noop)
end
return logger
end
| gpl-2.0 |
O-P-E-N/CC-ROUTER | feeds/luci/applications/luci-app-coovachilli/luasrc/model/cbi/coovachilli_radius.lua | 79 | 1554 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
m = Map("coovachilli")
-- radius server
s1 = m:section(TypedSection, "radius")
s1.anonymous = true
s1:option( Value, "radiusserver1" )
s1:option( Value, "radiusserver2" )
s1:option( Value, "radiussecret" ).password = true
s1:option( Value, "radiuslisten" ).optional = true
s1:option( Value, "radiusauthport" ).optional = true
s1:option( Value, "radiusacctport" ).optional = true
s1:option( Value, "radiusnasid" ).optional = true
s1:option( Value, "radiusnasip" ).optional = true
s1:option( Value, "radiuscalled" ).optional = true
s1:option( Value, "radiuslocationid" ).optional = true
s1:option( Value, "radiuslocationname" ).optional = true
s1:option( Value, "radiusnasporttype" ).optional = true
s1:option( Flag, "radiusoriginalurl" )
s1:option( Value, "adminuser" ).optional = true
rs = s1:option( Value, "adminpassword" )
rs.optional = true
rs.password = true
s1:option( Flag, "swapoctets" )
s1:option( Flag, "openidauth" )
s1:option( Flag, "wpaguests" )
s1:option( Flag, "acctupdate" )
s1:option( Value, "coaport" ).optional = true
s1:option( Flag, "coanoipcheck" )
-- radius proxy
s2 = m:section(TypedSection, "proxy")
s2.anonymous = true
s2:option( Value, "proxylisten" ).optional = true
s2:option( Value, "proxyport" ).optional = true
s2:option( Value, "proxyclient" ).optional = true
ps = s2:option( Value, "proxysecret" )
ps.optional = true
ps.password = true
return m
| gpl-2.0 |
gedads/Neodynamis | scripts/globals/spells/sinewy_etude.lua | 5 | 1810 | -----------------------------------------
-- Spell: Sinewy Etude
-- Static STR Boost, BRD 24
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 0;
if (sLvl+iLvl <= 181) then
power = 3;
elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then
power = 4;
elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then
power = 5;
elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then
power = 6;
elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then
power = 7;
elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then
power = 8;
elseif (sLvl+iLvl >= 450) then
power = 9;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,0,duration,caster:getID(), MOD_STR, 1)) then
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
end
return EFFECT_ETUDE;
end;
| gpl-3.0 |
ironjade/DevStack | LanCom/DesignPattern/LUA/SparseMatrixAsVector.lua | 1 | 7603 | #!/usr/local/bin/lua
--[[
Copyright (c) 2004 by Bruno R. Preiss, P.Eng.
$Author: brpreiss $
$Date: 2004/11/25 01:28:16 $
$RCSfile: SparseMatrixAsVector.lua,v $
$Revision: 1.7 $
$Id: SparseMatrixAsVector.lua,v 1.7 2004/11/25 01:28:16 brpreiss Exp $
--]]
require "SparseMatrix"
require "Array"
-- Sparse matrix implemented as a vector of non-zero entries.
SparseMatrixAsVector = Class.new("SparseMatrixAsVector", SparseMatrix)
SparseMatrixAsVector.Entry = Class.new("SparseMatrixAsVector.Entry")
-- Constructs an entry with the given row and column indices
-- and data value.
-- @param row Row index.
-- @param column Column index.
-- @param datum A value.
function SparseMatrixAsVector.Entry.methods:initialize(row, column, datum)
SparseMatrixAsVector.Entry.super(self)
self.row = row
self.column = column
self.datum = datum
end
-- The row index.
SparseMatrixAsVector.Entry:attr_accessor("row")
-- The column index.
SparseMatrixAsVector.Entry:attr_accessor("column")
-- The value.
SparseMatrixAsVector.Entry:attr_accessor("datum")
-- Constructs a sparse matrix with the given number of
-- rows, columns, and non-zero elements.
-- @param dimensions The dimensions.
-- @param numberOfElements The number of non-zero elements.
function SparseMatrixAsVector.methods:initialize(dimensions, numberOfElements)
SparseMatrixAsVector.super(self, dimensions[1], dimensions[2])
self.numberOfElements = numberOfElements
self.array = Array.new(numberOfElements)
for i = 0, self.numberOfElements - 1 do
self.array[i] = SparseMatrixAsVector.Entry.new(0, 0, 0)
end
end
-- The array of non-zero elements.
SparseMatrixAsVector:attr_accessor("array")
-- The number of non-zero elements.
SparseMatrixAsVector:attr_accessor("numberOfElements")
-- Returns the position in the vector of the entry with the given indices.
-- @param i Row index.
-- @param j Column index.
function SparseMatrixAsVector.methods:findPosition(i, j)
local target = i * self.numberOfColumns + j
local left = 0
local right = self.numberOfElements - 1
while left <= right do
local middle = math.floor((left + right) / 2)
local probe = self.array[middle]:get_row() * self.numberOfColumns
+ self.array[middle]:get_column()
if target > probe then
left = middle + 1
elseif target < probe then
right = middle - 1
else
return middle
end
end
return -1
end
-- Returns the matrix entry at the given indices.
-- @param indices The indices.
function SparseMatrixAsVector.methods:getitem(indices)
local i = indices[1]
if i < 0 or i >= self.numberOfRows then
error "IndexError"
end
local j = indices[2]
if j < 0 or j >= self.numberOfColumns then
error "IndexError"
end
local position = self:findPosition(i, j)
if position >= 0 then
return self.array[position]:get_datum()
else
return 0
end
end
-- Sets the matrix entry at the given indices to the given (non-zero) value.
-- @param indices The indices.
-- @param value A value.
function SparseMatrixAsVector.methods:setitem(indices, value)
local i = indices[1]
if i < 0 or i >= self.numberOfRows then
error "IndexError"
end
local j = indices[2]
if j < 0 or j >= self.numberOfColumns then
error "IndexError"
end
local position = self:findPosition(i, j)
if position >= 0 then
self.array[position].datum = value
else
if self.array:get_length() == self.numberOfElements then
local newArray = Array.new(2 * self.array:get_length())
for p = 0, self.array:get_length() - 1 do
newArray[p] = self.array[p]
end
for p = self.array:get_length(), newArray:get_length() - 1 do
newArray[p] = SparseMatrixAsVector.Entry.new(0, 0, 0)
end
self.array = newArray
end
k = self.numberOfElements
while k > 0 and (self.array[k - 1]:get_row() > i or
self.array[k - 1]:get_row() == i and
self.array[k - 1]:get_column() >= j) do
self.array[k] = self.array[k - 1]
k = k - 1
end
self.array[k] = SparseMatrixAsVector.Entry.new(i, j, value)
self.numberOfElements = self.numberOfElements + 1
end
end
-- Sets the matrix entry at the given indices to zero.
-- @param i Row index.
-- @param j Column index.
function SparseMatrixAsVector.methods:putZero(i, j)
if i < 0 or i >= self.numberOfRows then
error "IndexError"
end
if j < 0 or j >= self.numberOfColumns then
error "IndexError"
end
local position = self:findPosition(i, j)
if position >= 0 then
self.numberOfElements = self.numberOfElements - 1
for k = position, self.numberOfElements - 1 do
self.array[k] = self.array[k + 1]
end
self.array[k] = SparseMatrixAsVector.Entry.new(i, j, 0)
end
end
-- Returns the transpose of this sparse matrix.
function SparseMatrixAsVector.methods:transpose()
local result = SparseMatrixAsVector.new(
{self.numberOfColumns, self.numberOfRows}, self.numberOfElements)
offset = Array.new(self.numberOfColumns)
for i = 0, self.numberOfColumns - 1 do
offset[i] = 0
end
for i = 0, self.numberOfElements - 1 do
offset[self.array[i]:get_column()] =
offset[self.array[i]:get_column()] + 1
end
local sum = 0
for i = 0, self.numberOfColumns - 1 do
local tmp = offset[i]
offset[i] = sum
sum = sum + tmp
end
for i = 0, self.numberOfElements - 1 do
result.array[offset[self.array[i].column]] =
SparseMatrixAsVector.Entry.new(
self.array[i]:get_column(),
self.array[i]:get_row(),
self.array[i]:get_datum())
offset[self.array[i]:get_column()] =
offset[self.array[i]:get_column()] + 1
end
result.numberOfElements = self.numberOfElements
return result
end
-- Multiplication operator.
-- Returns the product of this sparse matrix and the given sparse matrix.
-- @param mat A sparse matrix.
function SparseMatrixAsVector.methods:mul(mat)
assert(self.numberOfColumns == mat.numberOfRows, "DomainError")
local matT = mat:transpose()
local result = SparseMatrixAsVector.new(
{self.numberOfRows, matT.numberOfRows},
self.numberOfRows + matT.numberOfRows)
local iPosition = 0
while iPosition < self.numberOfElements do
local i = self.array[iPosition]:get_row()
local jPosition = 0
while jPosition < matT.numberOfElements do
local j = matT.array[jPosition]:get_row()
local sum = 0
local k1 = iPosition
local k2 = jPosition
while k1 < self.numberOfElements
and self.array[k1]:get_row() == i
and k2 < matT.numberOfElements
and matT.array[k2]:get_row() == j do
if self.array[k1]:get_column()
< matT.array[k2]:get_column() then
k1 = k1 + 1
elseif self.array[k1]:get_column()
> matT.array[k2]:get_column() then
k2 = k2 + 1
else
sum = sum + self.array[k1]:get_datum()
* matT.array[k2]:get_datum()
k1 = k1 + 1
k2 = k2 + 1
end
end
if sum ~= 0 then
result[{i, j}] = sum
end
while jPosition < matT.numberOfElements and
matT.array[jPosition]:get_row() == j do
jPosition = jPosition + 1
end
end
while iPosition < self.numberOfElements and
self.array[iPosition]:get_row() == i do
iPosition = iPosition + 1
end
end
return result
end
-- SparseMatrixAsVector test program.
-- @param arg Command-line arguments.
function SparseMatrixAsVector.main(arg)
print "SparseMatrixAsVector test program."
local mat = SparseMatrixAsVector.new({6, 6}, 12)
--Matrix:TestMatrix(mat)
Matrix.testTranspose(mat)
Matrix.testTimes(mat, mat)
return 0
end
if _REQUIREDNAME == nil then
os.exit( SparseMatrixAsVector.main(arg) )
end
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Bastok_Mines/npcs/Azette.lua | 5 | 1979 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Azette
-- Type: Chocobo Renter
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/chocobo");
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 >= 15) then
local price = getChocoboPrice(player);
player:setLocalVar("chocoboPriceOffer",price);
if (level >= 20) then
level = 0;
end
player:startEvent(0x003D,price,gil,level);
else
player:startEvent(0x0040);
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 == 0x003D and option == 0) then
if (player:delGil(price)) then
updateChocoboPrice(player, price);
if (player:getMainLvl() >= 20) then
local duration = 1800 + (player:getMod(MOD_CHOCOBO_RIDING_TIME) * 60)
player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,duration,true);
else
player:addStatusEffectEx(EFFECT_MOUNTED,EFFECT_MOUNTED,0,0,900,true);
end
player:setPos(580,0,-305,0x40,0x6B);
end
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Lower_Jeuno/npcs/_l07.lua | 3 | 2850 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- !pos -51 0 -59 245
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/NPCIDs");
require("scripts/zones/Lower_Jeuno/TextIDs");
-- lamp id vary from 17780881 to 17780892
-- lamp cs vary from 0x0078 to 0x0083 (120 to 131)
local lampNum = 7;
local lampId = lampIdOffset + lampNum;
local cs = lampCsOffset + lampNum;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local playerOnQuest = GetServerVariable("[JEUNO]CommService");
-- player is on the quest
if playerOnQuest == player:getID() then
if hour >= 20 and hour < 21 then
player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock.
elseif hour >= 21 or hour < 1 then
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,2); -- The lamp is already lit.
else
player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No
end
else
player:startEvent(cs,3); -- You have failed to light the lamps in time.
end
-- player is not on the quest
else
if npc:getAnimation() == ANIMATION_OPEN_DOOR then
player:startEvent(cs,5); -- The lamp is lit.
else
player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually.
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if csid == cs and option == 1 then
-- lamp is now lit
GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR);
-- tell player how many remain
local lampsRemaining = 12;
for i=0,11 do
local lamp = GetNPCByID(lampIdOffset + i);
if lamp:getAnimation() == ANIMATION_OPEN_DOOR then
lampsRemaining = lampsRemaining - 1;
end
end
if lampsRemaining == 0 then
player:messageSpecial(LAMP_MSG_OFFSET);
else
player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining);
end
end
end;
| gpl-3.0 |
pedro-andrade-inpe/terrame | packages/base/lua/Jump.lua | 3 | 2236 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
--- Control a discrete transition between States. If the method in the first argument returns
-- true, the target becomes the new active State.
-- @arg data.1st a function that returns a boolean value and takes as arguments an Event,
-- an Agent or Automaton, and a Cell, respectively.
-- @arg data.target a string with another State id.
-- @usage Jump{
-- function(ev, agent, c)
-- return c.water > c.capInf
-- end,
-- target = "wet"
-- }
function Jump(data)
if type(data) ~= "table" then
customError(tableArgumentMsg())
end
local cObj = TeJump()
data.rule = cObj
if type(data[1]) ~= "function" then
customError("Jump constructor expected a function as first argument.")
end
if type(data.target) ~= "string" then
data.target = "st1"
end
cObj:setTargetControlModeName(data.target)
cObj:setReference(data)
return cObj
end
| lgpl-3.0 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/modules/base/luasrc/i18n.lua | 77 | 3182 | --[[
LuCI - Internationalisation
Description:
A very minimalistic but yet effective internationalisation module
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
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.
]]--
--- LuCI translation library.
module("luci.i18n", package.seeall)
require("luci.util")
local tparser = require "luci.template.parser"
table = {}
i18ndir = luci.util.libpath() .. "/i18n/"
loaded = {}
context = luci.util.threadlocal()
default = "en"
--- Clear the translation table.
function clear()
end
--- Load a translation and copy its data into the translation table.
-- @param file Language file
-- @param lang Two-letter language code
-- @param force Force reload even if already loaded (optional)
-- @return Success status
function load(file, lang, force)
end
--- Load a translation file using the default translation language.
-- Alternatively load the translation of the fallback language.
-- @param file Language file
-- @param force Force reload even if already loaded (optional)
function loadc(file, force)
end
--- Set the context default translation language.
-- @param lang Two-letter language code
function setlanguage(lang)
context.lang = lang:gsub("_", "-")
context.parent = (context.lang:match("^([a-z][a-z])_"))
if not tparser.load_catalog(context.lang, i18ndir) then
if context.parent then
tparser.load_catalog(context.parent, i18ndir)
return context.parent
end
end
return context.lang
end
--- Return the translated value for a specific translation key.
-- @param key Default translation text
-- @return Translated string
function translate(key)
return tparser.translate(key) or key
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function translatef(key, ...)
return tostring(translate(key)):format(...)
end
--- Return the translated value for a specific translation key
-- and ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translate(...))</code>
-- @param key Default translation text
-- @return Translated string
function string(key)
return tostring(translate(key))
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- Ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translatef(...))</code>
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function stringf(key, ...)
return tostring(translate(key)):format(...)
end
| gpl-2.0 |
MasonLeeBack/PolyEngine | thirdparty/vulkan/shaderc/third_party/spirv-tools/external/spirv-headers/include/spirv/1.0/spirv.lua | 7 | 25777 | -- Copyright (c) 2014-2017 The Khronos Group Inc.
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and/or associated documentation files (the "Materials"),
-- to deal in the Materials without restriction, including without limitation
-- the rights to use, copy, modify, merge, publish, distribute, sublicense,
-- and/or sell copies of the Materials, and to permit persons to whom the
-- Materials are furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Materials.
--
-- MODIFICATIONS TO THIS FILE MAY MEAN IT NO LONGER ACCURATELY REFLECTS KHRONOS
-- STANDARDS. THE UNMODIFIED, NORMATIVE VERSIONS OF KHRONOS SPECIFICATIONS AND
-- HEADER INFORMATION ARE LOCATED AT https://www.khronos.org/registry/
--
-- THE MATERIALS ARE PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-- OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
-- THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
-- FROM,OUT OF OR IN CONNECTION WITH THE MATERIALS OR THE USE OR OTHER DEALINGS
-- IN THE MATERIALS.
-- This header is automatically generated by the same tool that creates
-- the Binary Section of the SPIR-V specification.
-- Enumeration tokens for SPIR-V, in various styles:
-- C, C++, C++11, JSON, Lua, Python
--
-- - C will have tokens with a "Spv" prefix, e.g.: SpvSourceLanguageGLSL
-- - C++ will have tokens in the "spv" name space, e.g.: spv::SourceLanguageGLSL
-- - C++11 will use enum classes in the spv namespace, e.g.: spv::SourceLanguage::GLSL
-- - Lua will use tables, e.g.: spv.SourceLanguage.GLSL
-- - Python will use dictionaries, e.g.: spv['SourceLanguage']['GLSL']
--
-- Some tokens act like mask values, which can be OR'd together,
-- while others are mutually exclusive. The mask-like ones have
-- "Mask" in their name, and a parallel enum that has the shift
-- amount (1 << x) for each corresponding enumerant.
spv = {
MagicNumber = 0x07230203,
Version = 0x00010000,
Revision = 12,
OpCodeMask = 0xffff,
WordCountShift = 16,
SourceLanguage = {
Unknown = 0,
ESSL = 1,
GLSL = 2,
OpenCL_C = 3,
OpenCL_CPP = 4,
HLSL = 5,
},
ExecutionModel = {
Vertex = 0,
TessellationControl = 1,
TessellationEvaluation = 2,
Geometry = 3,
Fragment = 4,
GLCompute = 5,
Kernel = 6,
},
AddressingModel = {
Logical = 0,
Physical32 = 1,
Physical64 = 2,
},
MemoryModel = {
Simple = 0,
GLSL450 = 1,
OpenCL = 2,
},
ExecutionMode = {
Invocations = 0,
SpacingEqual = 1,
SpacingFractionalEven = 2,
SpacingFractionalOdd = 3,
VertexOrderCw = 4,
VertexOrderCcw = 5,
PixelCenterInteger = 6,
OriginUpperLeft = 7,
OriginLowerLeft = 8,
EarlyFragmentTests = 9,
PointMode = 10,
Xfb = 11,
DepthReplacing = 12,
DepthGreater = 14,
DepthLess = 15,
DepthUnchanged = 16,
LocalSize = 17,
LocalSizeHint = 18,
InputPoints = 19,
InputLines = 20,
InputLinesAdjacency = 21,
Triangles = 22,
InputTrianglesAdjacency = 23,
Quads = 24,
Isolines = 25,
OutputVertices = 26,
OutputPoints = 27,
OutputLineStrip = 28,
OutputTriangleStrip = 29,
VecTypeHint = 30,
ContractionOff = 31,
PostDepthCoverage = 4446,
StencilRefReplacingEXT = 5027,
},
StorageClass = {
UniformConstant = 0,
Input = 1,
Uniform = 2,
Output = 3,
Workgroup = 4,
CrossWorkgroup = 5,
Private = 6,
Function = 7,
Generic = 8,
PushConstant = 9,
AtomicCounter = 10,
Image = 11,
StorageBuffer = 12,
},
Dim = {
Dim1D = 0,
Dim2D = 1,
Dim3D = 2,
Cube = 3,
Rect = 4,
Buffer = 5,
SubpassData = 6,
},
SamplerAddressingMode = {
None = 0,
ClampToEdge = 1,
Clamp = 2,
Repeat = 3,
RepeatMirrored = 4,
},
SamplerFilterMode = {
Nearest = 0,
Linear = 1,
},
ImageFormat = {
Unknown = 0,
Rgba32f = 1,
Rgba16f = 2,
R32f = 3,
Rgba8 = 4,
Rgba8Snorm = 5,
Rg32f = 6,
Rg16f = 7,
R11fG11fB10f = 8,
R16f = 9,
Rgba16 = 10,
Rgb10A2 = 11,
Rg16 = 12,
Rg8 = 13,
R16 = 14,
R8 = 15,
Rgba16Snorm = 16,
Rg16Snorm = 17,
Rg8Snorm = 18,
R16Snorm = 19,
R8Snorm = 20,
Rgba32i = 21,
Rgba16i = 22,
Rgba8i = 23,
R32i = 24,
Rg32i = 25,
Rg16i = 26,
Rg8i = 27,
R16i = 28,
R8i = 29,
Rgba32ui = 30,
Rgba16ui = 31,
Rgba8ui = 32,
R32ui = 33,
Rgb10a2ui = 34,
Rg32ui = 35,
Rg16ui = 36,
Rg8ui = 37,
R16ui = 38,
R8ui = 39,
},
ImageChannelOrder = {
R = 0,
A = 1,
RG = 2,
RA = 3,
RGB = 4,
RGBA = 5,
BGRA = 6,
ARGB = 7,
Intensity = 8,
Luminance = 9,
Rx = 10,
RGx = 11,
RGBx = 12,
Depth = 13,
DepthStencil = 14,
sRGB = 15,
sRGBx = 16,
sRGBA = 17,
sBGRA = 18,
ABGR = 19,
},
ImageChannelDataType = {
SnormInt8 = 0,
SnormInt16 = 1,
UnormInt8 = 2,
UnormInt16 = 3,
UnormShort565 = 4,
UnormShort555 = 5,
UnormInt101010 = 6,
SignedInt8 = 7,
SignedInt16 = 8,
SignedInt32 = 9,
UnsignedInt8 = 10,
UnsignedInt16 = 11,
UnsignedInt32 = 12,
HalfFloat = 13,
Float = 14,
UnormInt24 = 15,
UnormInt101010_2 = 16,
},
ImageOperandsShift = {
Bias = 0,
Lod = 1,
Grad = 2,
ConstOffset = 3,
Offset = 4,
ConstOffsets = 5,
Sample = 6,
MinLod = 7,
},
ImageOperandsMask = {
MaskNone = 0,
Bias = 0x00000001,
Lod = 0x00000002,
Grad = 0x00000004,
ConstOffset = 0x00000008,
Offset = 0x00000010,
ConstOffsets = 0x00000020,
Sample = 0x00000040,
MinLod = 0x00000080,
},
FPFastMathModeShift = {
NotNaN = 0,
NotInf = 1,
NSZ = 2,
AllowRecip = 3,
Fast = 4,
},
FPFastMathModeMask = {
MaskNone = 0,
NotNaN = 0x00000001,
NotInf = 0x00000002,
NSZ = 0x00000004,
AllowRecip = 0x00000008,
Fast = 0x00000010,
},
FPRoundingMode = {
RTE = 0,
RTZ = 1,
RTP = 2,
RTN = 3,
},
LinkageType = {
Export = 0,
Import = 1,
},
AccessQualifier = {
ReadOnly = 0,
WriteOnly = 1,
ReadWrite = 2,
},
FunctionParameterAttribute = {
Zext = 0,
Sext = 1,
ByVal = 2,
Sret = 3,
NoAlias = 4,
NoCapture = 5,
NoWrite = 6,
NoReadWrite = 7,
},
Decoration = {
RelaxedPrecision = 0,
SpecId = 1,
Block = 2,
BufferBlock = 3,
RowMajor = 4,
ColMajor = 5,
ArrayStride = 6,
MatrixStride = 7,
GLSLShared = 8,
GLSLPacked = 9,
CPacked = 10,
BuiltIn = 11,
NoPerspective = 13,
Flat = 14,
Patch = 15,
Centroid = 16,
Sample = 17,
Invariant = 18,
Restrict = 19,
Aliased = 20,
Volatile = 21,
Constant = 22,
Coherent = 23,
NonWritable = 24,
NonReadable = 25,
Uniform = 26,
SaturatedConversion = 28,
Stream = 29,
Location = 30,
Component = 31,
Index = 32,
Binding = 33,
DescriptorSet = 34,
Offset = 35,
XfbBuffer = 36,
XfbStride = 37,
FuncParamAttr = 38,
FPRoundingMode = 39,
FPFastMathMode = 40,
LinkageAttributes = 41,
NoContraction = 42,
InputAttachmentIndex = 43,
Alignment = 44,
ExplicitInterpAMD = 4999,
OverrideCoverageNV = 5248,
PassthroughNV = 5250,
ViewportRelativeNV = 5252,
SecondaryViewportRelativeNV = 5256,
},
BuiltIn = {
Position = 0,
PointSize = 1,
ClipDistance = 3,
CullDistance = 4,
VertexId = 5,
InstanceId = 6,
PrimitiveId = 7,
InvocationId = 8,
Layer = 9,
ViewportIndex = 10,
TessLevelOuter = 11,
TessLevelInner = 12,
TessCoord = 13,
PatchVertices = 14,
FragCoord = 15,
PointCoord = 16,
FrontFacing = 17,
SampleId = 18,
SamplePosition = 19,
SampleMask = 20,
FragDepth = 22,
HelperInvocation = 23,
NumWorkgroups = 24,
WorkgroupSize = 25,
WorkgroupId = 26,
LocalInvocationId = 27,
GlobalInvocationId = 28,
LocalInvocationIndex = 29,
WorkDim = 30,
GlobalSize = 31,
EnqueuedWorkgroupSize = 32,
GlobalOffset = 33,
GlobalLinearId = 34,
SubgroupSize = 36,
SubgroupMaxSize = 37,
NumSubgroups = 38,
NumEnqueuedSubgroups = 39,
SubgroupId = 40,
SubgroupLocalInvocationId = 41,
VertexIndex = 42,
InstanceIndex = 43,
SubgroupEqMaskKHR = 4416,
SubgroupGeMaskKHR = 4417,
SubgroupGtMaskKHR = 4418,
SubgroupLeMaskKHR = 4419,
SubgroupLtMaskKHR = 4420,
BaseVertex = 4424,
BaseInstance = 4425,
DrawIndex = 4426,
DeviceIndex = 4438,
ViewIndex = 4440,
BaryCoordNoPerspAMD = 4992,
BaryCoordNoPerspCentroidAMD = 4993,
BaryCoordNoPerspSampleAMD = 4994,
BaryCoordSmoothAMD = 4995,
BaryCoordSmoothCentroidAMD = 4996,
BaryCoordSmoothSampleAMD = 4997,
BaryCoordPullModelAMD = 4998,
FragStencilRefEXT = 5014,
ViewportMaskNV = 5253,
SecondaryPositionNV = 5257,
SecondaryViewportMaskNV = 5258,
PositionPerViewNV = 5261,
ViewportMaskPerViewNV = 5262,
},
SelectionControlShift = {
Flatten = 0,
DontFlatten = 1,
},
SelectionControlMask = {
MaskNone = 0,
Flatten = 0x00000001,
DontFlatten = 0x00000002,
},
LoopControlShift = {
Unroll = 0,
DontUnroll = 1,
},
LoopControlMask = {
MaskNone = 0,
Unroll = 0x00000001,
DontUnroll = 0x00000002,
},
FunctionControlShift = {
Inline = 0,
DontInline = 1,
Pure = 2,
Const = 3,
},
FunctionControlMask = {
MaskNone = 0,
Inline = 0x00000001,
DontInline = 0x00000002,
Pure = 0x00000004,
Const = 0x00000008,
},
MemorySemanticsShift = {
Acquire = 1,
Release = 2,
AcquireRelease = 3,
SequentiallyConsistent = 4,
UniformMemory = 6,
SubgroupMemory = 7,
WorkgroupMemory = 8,
CrossWorkgroupMemory = 9,
AtomicCounterMemory = 10,
ImageMemory = 11,
},
MemorySemanticsMask = {
MaskNone = 0,
Acquire = 0x00000002,
Release = 0x00000004,
AcquireRelease = 0x00000008,
SequentiallyConsistent = 0x00000010,
UniformMemory = 0x00000040,
SubgroupMemory = 0x00000080,
WorkgroupMemory = 0x00000100,
CrossWorkgroupMemory = 0x00000200,
AtomicCounterMemory = 0x00000400,
ImageMemory = 0x00000800,
},
MemoryAccessShift = {
Volatile = 0,
Aligned = 1,
Nontemporal = 2,
},
MemoryAccessMask = {
MaskNone = 0,
Volatile = 0x00000001,
Aligned = 0x00000002,
Nontemporal = 0x00000004,
},
Scope = {
CrossDevice = 0,
Device = 1,
Workgroup = 2,
Subgroup = 3,
Invocation = 4,
},
GroupOperation = {
Reduce = 0,
InclusiveScan = 1,
ExclusiveScan = 2,
},
KernelEnqueueFlags = {
NoWait = 0,
WaitKernel = 1,
WaitWorkGroup = 2,
},
KernelProfilingInfoShift = {
CmdExecTime = 0,
},
KernelProfilingInfoMask = {
MaskNone = 0,
CmdExecTime = 0x00000001,
},
Capability = {
Matrix = 0,
Shader = 1,
Geometry = 2,
Tessellation = 3,
Addresses = 4,
Linkage = 5,
Kernel = 6,
Vector16 = 7,
Float16Buffer = 8,
Float16 = 9,
Float64 = 10,
Int64 = 11,
Int64Atomics = 12,
ImageBasic = 13,
ImageReadWrite = 14,
ImageMipmap = 15,
Pipes = 17,
Groups = 18,
DeviceEnqueue = 19,
LiteralSampler = 20,
AtomicStorage = 21,
Int16 = 22,
TessellationPointSize = 23,
GeometryPointSize = 24,
ImageGatherExtended = 25,
StorageImageMultisample = 27,
UniformBufferArrayDynamicIndexing = 28,
SampledImageArrayDynamicIndexing = 29,
StorageBufferArrayDynamicIndexing = 30,
StorageImageArrayDynamicIndexing = 31,
ClipDistance = 32,
CullDistance = 33,
ImageCubeArray = 34,
SampleRateShading = 35,
ImageRect = 36,
SampledRect = 37,
GenericPointer = 38,
Int8 = 39,
InputAttachment = 40,
SparseResidency = 41,
MinLod = 42,
Sampled1D = 43,
Image1D = 44,
SampledCubeArray = 45,
SampledBuffer = 46,
ImageBuffer = 47,
ImageMSArray = 48,
StorageImageExtendedFormats = 49,
ImageQuery = 50,
DerivativeControl = 51,
InterpolationFunction = 52,
TransformFeedback = 53,
GeometryStreams = 54,
StorageImageReadWithoutFormat = 55,
StorageImageWriteWithoutFormat = 56,
MultiViewport = 57,
SubgroupBallotKHR = 4423,
DrawParameters = 4427,
SubgroupVoteKHR = 4431,
StorageBuffer16BitAccess = 4433,
StorageUniformBufferBlock16 = 4433,
StorageUniform16 = 4434,
UniformAndStorageBuffer16BitAccess = 4434,
StoragePushConstant16 = 4435,
StorageInputOutput16 = 4436,
DeviceGroup = 4437,
MultiView = 4439,
VariablePointersStorageBuffer = 4441,
VariablePointers = 4442,
AtomicStorageOps = 4445,
SampleMaskPostDepthCoverage = 4447,
ImageGatherBiasLodAMD = 5009,
FragmentMaskAMD = 5010,
StencilExportEXT = 5013,
ImageReadWriteLodAMD = 5015,
SampleMaskOverrideCoverageNV = 5249,
GeometryShaderPassthroughNV = 5251,
ShaderViewportIndexLayerEXT = 5254,
ShaderViewportIndexLayerNV = 5254,
ShaderViewportMaskNV = 5255,
ShaderStereoViewNV = 5259,
PerViewAttributesNV = 5260,
SubgroupShuffleINTEL = 5568,
SubgroupBufferBlockIOINTEL = 5569,
SubgroupImageBlockIOINTEL = 5570,
},
Op = {
OpNop = 0,
OpUndef = 1,
OpSourceContinued = 2,
OpSource = 3,
OpSourceExtension = 4,
OpName = 5,
OpMemberName = 6,
OpString = 7,
OpLine = 8,
OpExtension = 10,
OpExtInstImport = 11,
OpExtInst = 12,
OpMemoryModel = 14,
OpEntryPoint = 15,
OpExecutionMode = 16,
OpCapability = 17,
OpTypeVoid = 19,
OpTypeBool = 20,
OpTypeInt = 21,
OpTypeFloat = 22,
OpTypeVector = 23,
OpTypeMatrix = 24,
OpTypeImage = 25,
OpTypeSampler = 26,
OpTypeSampledImage = 27,
OpTypeArray = 28,
OpTypeRuntimeArray = 29,
OpTypeStruct = 30,
OpTypeOpaque = 31,
OpTypePointer = 32,
OpTypeFunction = 33,
OpTypeEvent = 34,
OpTypeDeviceEvent = 35,
OpTypeReserveId = 36,
OpTypeQueue = 37,
OpTypePipe = 38,
OpTypeForwardPointer = 39,
OpConstantTrue = 41,
OpConstantFalse = 42,
OpConstant = 43,
OpConstantComposite = 44,
OpConstantSampler = 45,
OpConstantNull = 46,
OpSpecConstantTrue = 48,
OpSpecConstantFalse = 49,
OpSpecConstant = 50,
OpSpecConstantComposite = 51,
OpSpecConstantOp = 52,
OpFunction = 54,
OpFunctionParameter = 55,
OpFunctionEnd = 56,
OpFunctionCall = 57,
OpVariable = 59,
OpImageTexelPointer = 60,
OpLoad = 61,
OpStore = 62,
OpCopyMemory = 63,
OpCopyMemorySized = 64,
OpAccessChain = 65,
OpInBoundsAccessChain = 66,
OpPtrAccessChain = 67,
OpArrayLength = 68,
OpGenericPtrMemSemantics = 69,
OpInBoundsPtrAccessChain = 70,
OpDecorate = 71,
OpMemberDecorate = 72,
OpDecorationGroup = 73,
OpGroupDecorate = 74,
OpGroupMemberDecorate = 75,
OpVectorExtractDynamic = 77,
OpVectorInsertDynamic = 78,
OpVectorShuffle = 79,
OpCompositeConstruct = 80,
OpCompositeExtract = 81,
OpCompositeInsert = 82,
OpCopyObject = 83,
OpTranspose = 84,
OpSampledImage = 86,
OpImageSampleImplicitLod = 87,
OpImageSampleExplicitLod = 88,
OpImageSampleDrefImplicitLod = 89,
OpImageSampleDrefExplicitLod = 90,
OpImageSampleProjImplicitLod = 91,
OpImageSampleProjExplicitLod = 92,
OpImageSampleProjDrefImplicitLod = 93,
OpImageSampleProjDrefExplicitLod = 94,
OpImageFetch = 95,
OpImageGather = 96,
OpImageDrefGather = 97,
OpImageRead = 98,
OpImageWrite = 99,
OpImage = 100,
OpImageQueryFormat = 101,
OpImageQueryOrder = 102,
OpImageQuerySizeLod = 103,
OpImageQuerySize = 104,
OpImageQueryLod = 105,
OpImageQueryLevels = 106,
OpImageQuerySamples = 107,
OpConvertFToU = 109,
OpConvertFToS = 110,
OpConvertSToF = 111,
OpConvertUToF = 112,
OpUConvert = 113,
OpSConvert = 114,
OpFConvert = 115,
OpQuantizeToF16 = 116,
OpConvertPtrToU = 117,
OpSatConvertSToU = 118,
OpSatConvertUToS = 119,
OpConvertUToPtr = 120,
OpPtrCastToGeneric = 121,
OpGenericCastToPtr = 122,
OpGenericCastToPtrExplicit = 123,
OpBitcast = 124,
OpSNegate = 126,
OpFNegate = 127,
OpIAdd = 128,
OpFAdd = 129,
OpISub = 130,
OpFSub = 131,
OpIMul = 132,
OpFMul = 133,
OpUDiv = 134,
OpSDiv = 135,
OpFDiv = 136,
OpUMod = 137,
OpSRem = 138,
OpSMod = 139,
OpFRem = 140,
OpFMod = 141,
OpVectorTimesScalar = 142,
OpMatrixTimesScalar = 143,
OpVectorTimesMatrix = 144,
OpMatrixTimesVector = 145,
OpMatrixTimesMatrix = 146,
OpOuterProduct = 147,
OpDot = 148,
OpIAddCarry = 149,
OpISubBorrow = 150,
OpUMulExtended = 151,
OpSMulExtended = 152,
OpAny = 154,
OpAll = 155,
OpIsNan = 156,
OpIsInf = 157,
OpIsFinite = 158,
OpIsNormal = 159,
OpSignBitSet = 160,
OpLessOrGreater = 161,
OpOrdered = 162,
OpUnordered = 163,
OpLogicalEqual = 164,
OpLogicalNotEqual = 165,
OpLogicalOr = 166,
OpLogicalAnd = 167,
OpLogicalNot = 168,
OpSelect = 169,
OpIEqual = 170,
OpINotEqual = 171,
OpUGreaterThan = 172,
OpSGreaterThan = 173,
OpUGreaterThanEqual = 174,
OpSGreaterThanEqual = 175,
OpULessThan = 176,
OpSLessThan = 177,
OpULessThanEqual = 178,
OpSLessThanEqual = 179,
OpFOrdEqual = 180,
OpFUnordEqual = 181,
OpFOrdNotEqual = 182,
OpFUnordNotEqual = 183,
OpFOrdLessThan = 184,
OpFUnordLessThan = 185,
OpFOrdGreaterThan = 186,
OpFUnordGreaterThan = 187,
OpFOrdLessThanEqual = 188,
OpFUnordLessThanEqual = 189,
OpFOrdGreaterThanEqual = 190,
OpFUnordGreaterThanEqual = 191,
OpShiftRightLogical = 194,
OpShiftRightArithmetic = 195,
OpShiftLeftLogical = 196,
OpBitwiseOr = 197,
OpBitwiseXor = 198,
OpBitwiseAnd = 199,
OpNot = 200,
OpBitFieldInsert = 201,
OpBitFieldSExtract = 202,
OpBitFieldUExtract = 203,
OpBitReverse = 204,
OpBitCount = 205,
OpDPdx = 207,
OpDPdy = 208,
OpFwidth = 209,
OpDPdxFine = 210,
OpDPdyFine = 211,
OpFwidthFine = 212,
OpDPdxCoarse = 213,
OpDPdyCoarse = 214,
OpFwidthCoarse = 215,
OpEmitVertex = 218,
OpEndPrimitive = 219,
OpEmitStreamVertex = 220,
OpEndStreamPrimitive = 221,
OpControlBarrier = 224,
OpMemoryBarrier = 225,
OpAtomicLoad = 227,
OpAtomicStore = 228,
OpAtomicExchange = 229,
OpAtomicCompareExchange = 230,
OpAtomicCompareExchangeWeak = 231,
OpAtomicIIncrement = 232,
OpAtomicIDecrement = 233,
OpAtomicIAdd = 234,
OpAtomicISub = 235,
OpAtomicSMin = 236,
OpAtomicUMin = 237,
OpAtomicSMax = 238,
OpAtomicUMax = 239,
OpAtomicAnd = 240,
OpAtomicOr = 241,
OpAtomicXor = 242,
OpPhi = 245,
OpLoopMerge = 246,
OpSelectionMerge = 247,
OpLabel = 248,
OpBranch = 249,
OpBranchConditional = 250,
OpSwitch = 251,
OpKill = 252,
OpReturn = 253,
OpReturnValue = 254,
OpUnreachable = 255,
OpLifetimeStart = 256,
OpLifetimeStop = 257,
OpGroupAsyncCopy = 259,
OpGroupWaitEvents = 260,
OpGroupAll = 261,
OpGroupAny = 262,
OpGroupBroadcast = 263,
OpGroupIAdd = 264,
OpGroupFAdd = 265,
OpGroupFMin = 266,
OpGroupUMin = 267,
OpGroupSMin = 268,
OpGroupFMax = 269,
OpGroupUMax = 270,
OpGroupSMax = 271,
OpReadPipe = 274,
OpWritePipe = 275,
OpReservedReadPipe = 276,
OpReservedWritePipe = 277,
OpReserveReadPipePackets = 278,
OpReserveWritePipePackets = 279,
OpCommitReadPipe = 280,
OpCommitWritePipe = 281,
OpIsValidReserveId = 282,
OpGetNumPipePackets = 283,
OpGetMaxPipePackets = 284,
OpGroupReserveReadPipePackets = 285,
OpGroupReserveWritePipePackets = 286,
OpGroupCommitReadPipe = 287,
OpGroupCommitWritePipe = 288,
OpEnqueueMarker = 291,
OpEnqueueKernel = 292,
OpGetKernelNDrangeSubGroupCount = 293,
OpGetKernelNDrangeMaxSubGroupSize = 294,
OpGetKernelWorkGroupSize = 295,
OpGetKernelPreferredWorkGroupSizeMultiple = 296,
OpRetainEvent = 297,
OpReleaseEvent = 298,
OpCreateUserEvent = 299,
OpIsValidEvent = 300,
OpSetUserEventStatus = 301,
OpCaptureEventProfilingInfo = 302,
OpGetDefaultQueue = 303,
OpBuildNDRange = 304,
OpImageSparseSampleImplicitLod = 305,
OpImageSparseSampleExplicitLod = 306,
OpImageSparseSampleDrefImplicitLod = 307,
OpImageSparseSampleDrefExplicitLod = 308,
OpImageSparseSampleProjImplicitLod = 309,
OpImageSparseSampleProjExplicitLod = 310,
OpImageSparseSampleProjDrefImplicitLod = 311,
OpImageSparseSampleProjDrefExplicitLod = 312,
OpImageSparseFetch = 313,
OpImageSparseGather = 314,
OpImageSparseDrefGather = 315,
OpImageSparseTexelsResident = 316,
OpNoLine = 317,
OpAtomicFlagTestAndSet = 318,
OpAtomicFlagClear = 319,
OpImageSparseRead = 320,
OpSubgroupBallotKHR = 4421,
OpSubgroupFirstInvocationKHR = 4422,
OpSubgroupAllKHR = 4428,
OpSubgroupAnyKHR = 4429,
OpSubgroupAllEqualKHR = 4430,
OpSubgroupReadInvocationKHR = 4432,
OpGroupIAddNonUniformAMD = 5000,
OpGroupFAddNonUniformAMD = 5001,
OpGroupFMinNonUniformAMD = 5002,
OpGroupUMinNonUniformAMD = 5003,
OpGroupSMinNonUniformAMD = 5004,
OpGroupFMaxNonUniformAMD = 5005,
OpGroupUMaxNonUniformAMD = 5006,
OpGroupSMaxNonUniformAMD = 5007,
OpFragmentMaskFetchAMD = 5011,
OpFragmentFetchAMD = 5012,
OpSubgroupShuffleINTEL = 5571,
OpSubgroupShuffleDownINTEL = 5572,
OpSubgroupShuffleUpINTEL = 5573,
OpSubgroupShuffleXorINTEL = 5574,
OpSubgroupBlockReadINTEL = 5575,
OpSubgroupBlockWriteINTEL = 5576,
OpSubgroupImageBlockReadINTEL = 5577,
OpSubgroupImageBlockWriteINTEL = 5578,
},
}
| mit |
gedads/Neodynamis | scripts/globals/abilities/pets/daze.lua | 4 | 1423 | ---------------------------------------------------
-- Daze
---------------------------------------------------
require("scripts/globals/status")
require("scripts/globals/settings")
require("scripts/globals/automatonweaponskills")
---------------------------------------------------
function onMobSkillCheck(target, automaton, skill)
local master = automaton:getMaster()
return master:countEffect(EFFECT_THUNDER_MANEUVER)
end
function onPetAbility(target, automaton, skill, master, action)
local params = {
numHits = 1,
atkmulti = 1,
accBonus = 150,
ftp100 = 5.0,
ftp200 = 5.5,
ftp300 = 6.0,
acc100 = 0.0,
acc200 = 0.0,
acc300 = 0.0,
str_wsc = 0.0,
dex_wsc = 0.0,
vit_wsc = 0.0,
agi_wsc = 0.0,
int_wsc = 0.0,
mnd_wsc = 0.0,
chr_wsc = 0.0
}
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.dex_wsc = 1.0
params.ftp100 = 6.0
params.ftp200 = 8.5
params.ftp300 = 11.0
end
local damage = doAutoRangedWeaponskill(automaton, target, 0, params, skill:getTP(), true, skill, action)
if damage > 0 then
local chance = 0.033 * skill:getTP()
if not target:hasStatusEffect(EFFECT_STUN) and chance >= math.random()*100 then
target:addStatusEffect(EFFECT_STUN, 1, 0, 4)
end
end
return damage
end
| gpl-3.0 |
keplerproject/luarocks | spec/loader_spec.lua | 1 | 2866 | local test_env = require("spec.util.test_env")
local run = test_env.run
local testing_paths = test_env.testing_paths
local write_file = test_env.write_file
describe("luarocks.loader", function()
describe("#unit", function()
it("starts", function()
assert(run.lua_bool([[-e "require 'luarocks.loader'; print(package.loaded['luarocks.loaded'])"]]))
end)
end)
describe("#integration", function()
it("respects version constraints", function()
test_env.run_in_tmp(function(tmpdir)
write_file("rock_b_01.lua", "print('ROCK B 0.1'); return {}", finally)
write_file("rock_b-0.1-1.rockspec", [[
package = "rock_b"
version = "0.1-1"
source = {
url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/rock_b_01.lua"
}
build = {
type = "builtin",
modules = {
rock_b = "rock_b_01.lua"
}
}
]], finally)
write_file("rock_b_10.lua", "print('ROCK B 1.0'); return {}", finally)
write_file("rock_b-1.0-1.rockspec", [[
package = "rock_b"
version = "1.0-1"
source = {
url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/rock_b_10.lua"
}
build = {
type = "builtin",
modules = {
rock_b = "rock_b_10.lua"
}
}
]], finally)
write_file("rock_a.lua", "require('rock_b'); return {}", finally)
write_file("rock_a-2.0-1.rockspec", [[
package = "rock_a"
version = "2.0-1"
source = {
url = "file://]] .. tmpdir:gsub("\\", "/") .. [[/rock_a.lua"
}
dependencies = {
"rock_b < 1.0",
}
build = {
type = "builtin",
modules = {
rock_a = "rock_a.lua"
}
}
]], finally)
print(run.luarocks("make --server=" .. testing_paths.fixtures_dir .. "/a_repo --tree=" .. testing_paths.testing_tree .. " ./rock_b-0.1-1.rockspec"))
print(run.luarocks("make --server=" .. testing_paths.fixtures_dir .. "/a_repo --tree=" .. testing_paths.testing_tree .. " ./rock_b-1.0-1.rockspec --keep"))
print(run.luarocks("make --server=" .. testing_paths.fixtures_dir .. "/a_repo --tree=" .. testing_paths.testing_tree .. " ./rock_a-2.0-1.rockspec"))
local output = run.lua([[-e "require 'luarocks.loader'; require('rock_a')"]])
assert.matches("ROCK B 0.1", output, 1, true)
end)
end)
end)
end)
| mit |
starlightknight/darkstar | scripts/zones/Garlaige_Citadel_[S]/npcs/Fondactiont.lua | 11 | 1730 | -----------------------------------
-- Area: Garlaige Citadel [S]
-- NPC: Fondactiont
-- Starts and Finishes Quest: The Fumbling Friar
-- !pos -95 0 196 164
-----------------------------------
require("scripts/globals/npc_util")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local TheFumblingFriar = player:getQuestStatus(CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_FUMBLING_FRIAR)
-- Change to BRASS_RIBBON_OF_SERVICE later when Campaign has been added.
if TheFumblingFriar == QUEST_AVAILABLE and player:hasKeyItem(dsp.ki.BRONZE_RIBBON_OF_SERVICE) and player:getMainLvl() >= 30 then
player:startEvent(26) -- Start quest "The Fumbling Friar"
elseif TheFumblingFriar == QUEST_ACCEPTED then
if player:hasKeyItem(dsp.ki.ORNATE_PACKAGE) then
player:startEvent(28) -- During quest "The Fumbling Friar" (with Ornate Package KI)
else
player:startEvent(27) -- During quest "The Fumbling Friar" (before retrieving KI Ornate Package)
end
elseif TheFumblingFriar == QUEST_COMPLETED then
player:startEvent(29) -- New standard dialog after "The Fumbling Friar"
else
player:startEvent(25) -- Standard dialog
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 26 then
player:addQuest(CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_FUMBLING_FRIAR)
elseif csid == 28 and npcUtil.completeQuest(player, CRYSTAL_WAR, dsp.quest.id.crystalWar.THE_FUMBLING_FRIAR, {item = 4688}) then
player:delKeyItem(dsp.ki.ORNATE_PACKAGE)
end
end
| gpl-3.0 |
teleowner/TELEOWNER | plugins/on-off.lua | 1 | 1985 | -- 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 "ربات خاموش نمی باشد!"
end
_config.disabled_channels[receiver] = false
save_config()
return "ربات روشن شد!"
end
local function disable_channel( receiver )
if not _config.disabled_channels then
_config.disabled_channels = {}
end
_config.disabled_channels[receiver] = true
save_config()
return "ربات خاموش شد!"
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_owner(msg) then
if msg.text == "/bot on" or msg.text == "/Bot on" or msg.text == "#bot on" or msg.text == "#Bot on" 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
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_owner(msg) then
return 'شما صاحب گروه نمی باشید!'
end
if matches[1] == 'on' then
return enable_channel(receiver)
end
-- Disable a channel
if matches[1] == 'off' 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 = {
"^[#!/][Bb]ot (on)",
"^[#!/][Bb]ot (off)" },
run = run,
--privileged = true,
moderated = true,
pre_process = pre_process
}
| gpl-2.0 |
ghoss/Lightroom2Tumblr | src/LrSHA1.lua | 1 | 7228 | --[[----------------------------------------------------------------------------
Lightroom2Tumblr
LrSHA1.lua - SHA1 algorithm implementation with Lightroom bit functions.
Copyright (c) 2012-2017 by Guido Hoss.
Lightroom2Tumblr is free software: you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3
of the License, or (at your option) any later version.
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, see
<http://www.gnu.org/licenses/>.
Git repository home: <https://github.com/ghoss/Lightroom2Tumblr>
------------------------------------------------------------------------------]]
-- Lightroom SDK
local LrMath = import 'LrMath'
local bXOR = LrMath.bitXor
local bAND = LrMath.bitAnd
local bOR = LrMath.bitOr
-- local storing of global functions (minor speedup)
--
local floor,modf = math.floor,math.modf
local char,format,rep = string.char,string.format,string.rep
--------------------------------------------------------------------------------
-- bytes_to_w32()
--
-- merge 4 bytes to an 32 bit word
--------------------------------------------------------------------------------
local function bytes_to_w32 (a,b,c,d)
return a * 0x1000000 + b * 0x10000 + c * 0x100 + d
end
--------------------------------------------------------------------------------
-- shift32()
--
-- shift the bits of a 32 bit word. Don't use negative values for "bits"
--------------------------------------------------------------------------------
local function shift32 (bits, a)
local b2 = 2 ^ (32 - bits)
local a, b = modf(a / b2)
return a + b * b2 * (2 ^ (bits))
end
--------------------------------------------------------------------------------
-- add32()
--
-- adding 2 32bit numbers, cutting off the remainder on 33th bit
--------------------------------------------------------------------------------
local function add32 (a,b)
return (a + b) % 4294967296
end
--------------------------------------------------------------------------------
-- bNOT()
--
-- binary complement for 32bit numbers
--------------------------------------------------------------------------------
local function bNOT (a)
return 4294967295 - (a % 4294967296)
end
--------------------------------------------------------------------------------
-- w32_to_hexstring()
--
-- converting the number to a hexadecimal string
--------------------------------------------------------------------------------
local function w32_to_hexstring (w)
return format("%08x", w)
end
--------------------------------------------------------------------------------
-- hex_to_binary()
--------------------------------------------------------------------------------
local function hex_to_binary(hex)
return hex:gsub('..', function(hexval)
return string.char(tonumber(hexval, 16))
end)
end
-------------------------------------------------------------------------------
-- sha1(msg)
-------------------------------------------------------------------------------
function sha1(msg)
local H0,H1,H2,H3,H4 = 0x67452301,0xEFCDAB89,0x98BADCFE,0x10325476,0xC3D2E1F0
local msg_len_in_bits = #msg * 8
local first_append = char(0x80) -- append a '1' bit plus seven '0' bits
local non_zero_message_bytes = #msg +1 +8 -- the +1 is the appended bit 1, the +8 are for the final appended length
local current_mod = non_zero_message_bytes % 64
local second_append = current_mod>0 and rep(char(0), 64 - current_mod) or ""
-- now to append the length as a 64-bit number.
local B1, R1 = modf(msg_len_in_bits / 0x01000000)
local B2, R2 = modf( 0x01000000 * R1 / 0x00010000)
local B3, R3 = modf( 0x00010000 * R2 / 0x00000100)
local B4 = 0x00000100 * R3
local L64 = char( 0) .. char( 0) .. char( 0) .. char( 0) -- high 32 bits
.. char(B1) .. char(B2) .. char(B3) .. char(B4) -- low 32 bits
msg = msg .. first_append .. second_append .. L64
assert(#msg % 64 == 0)
local chunks = #msg / 64
local W = { }
local start, A, B, C, D, E, f, K, TEMP
local chunk = 0
while chunk < chunks do
--
-- break chunk up into W[0] through W[15]
--
start,chunk = chunk * 64 + 1,chunk + 1
for t = 0, 15 do
W[t] = bytes_to_w32(msg:byte(start, start + 3))
start = start + 4
end
--
-- build W[16] through W[79]
--
for t = 16, 79 do
-- For t = 16 to 79 let Wt = S1(Wt-3 XOR Wt-8 XOR Wt-14 XOR Wt-16).
W[t] = shift32(1, bXOR(bXOR(bXOR(W[t-3], W[t-8]), W[t-14]), W[t-16]))
end
A,B,C,D,E = H0,H1,H2,H3,H4
for t = 0, 79 do
if t <= 19 then
-- (B AND C) OR ((NOT B) AND D)
f = bOR(bAND(B, C), bAND(bNOT(B), D))
K = 0x5A827999
elseif t <= 39 then
-- B XOR C XOR D
f = bXOR(bXOR(B, C), D)
K = 0x6ED9EBA1
elseif t <= 59 then
-- (B AND C) OR (B AND D) OR (C AND D)
f = bOR(bAND(B, C), bOR(bAND(B, D), bAND(C, D)))
K = 0x8F1BBCDC
else
-- B XOR C XOR D
f = bXOR(bXOR(B, C), D)
K = 0xCA62C1D6
end
-- TEMP = S5(A) + ft(B,C,D) + E + Wt + Kt;
local tmp = add32(add32(add32(add32(shift32(5, A), f), E), W[t]), K)
A,B,C,D,E = tmp, A, shift32(30, B), C, D
end
-- Let H0 = H0 + A, H1 = H1 + B, H2 = H2 + C, H3 = H3 + D, H4 = H4 + E.
H0,H1,H2,H3,H4 = add32(H0, A), add32(H1, B), add32(H2, C), add32(H3, D), add32(H4, E)
end
local f = w32_to_hexstring
return f(H0) .. f(H1) .. f(H2) .. f(H3) .. f(H4)
end
-------------------------------------------------------------------------------
-- sha1_binary()
-------------------------------------------------------------------------------
function sha1_binary(msg)
return hex_to_binary(sha1(msg))
end
-------------------------------------------------------------------------------
-- hmac_sha1()
-------------------------------------------------------------------------------
local xor_with_0x5c = { }
local xor_with_0x36 = { }
-- building the lookuptables ahead of time (instead of littering the source code
-- with precalculated values)
--
for i= 0, 0xff do
xor_with_0x5c[char(i)] = char(bXOR(i, 0x5c))
xor_with_0x36[char(i)] = char(bXOR(i, 0x36))
end
local blocksize = 64 -- 512 bits
function hmac_sha1(key, text)
assert(type(key) == 'string', "key passed to hmac_sha1 should be a string")
assert(type(text) == 'string', "text passed to hmac_sha1 should be a string")
if #key > blocksize then
key = sha1_binary(key)
end
local key_xord_with_0x36 = key:gsub('.', xor_with_0x36) .. string.rep(string.char(0x36), blocksize - #key)
local key_xord_with_0x5c = key:gsub('.', xor_with_0x5c) .. string.rep(string.char(0x5c), blocksize - #key)
return sha1(key_xord_with_0x5c .. sha1_binary(key_xord_with_0x36 .. text))
end
-------------------------------------------------------------------------------
-- hmac_sha1_binary()
-------------------------------------------------------------------------------
function hmac_sha1_binary(key, text)
return hex_to_binary(hmac_sha1(key, text))
end
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Western_Altepa_Desert/npcs/Dreamrose.lua | 9 | 1199 | -----------------------------------
-- Area: Western Altepa Desert
-- NPC: Dreamrose
-- Involved in Mission: San D'Oria 6-1
-----------------------------------
local ID = require("scripts/zones/Western_Altepa_Desert/IDs")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if
player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.LEAUTE_S_LAST_WISHES and
player:getCharVar("MissionStatus") == 2 and
not GetMobByID(ID.mob.SABOTENDER_ENAMORADO):isSpawned()
then
if player:getCharVar("Mission6-1MobKilled") == 1 then
player:addKeyItem(dsp.ki.DREAMROSE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.DREAMROSE)
player:setCharVar("Mission6-1MobKilled", 0)
player:setCharVar("MissionStatus", 3)
else
SpawnMob(ID.mob.SABOTENDER_ENAMORADO):updateClaim(player)
end
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/cup_of_healing_tea.lua | 12 | 1466 | -----------------------------------------
-- ID: 4286
-- Item: cup_of_healing_tea
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Magic 10
-- Vitality -1
-- Charisma 3
-- Magic Regen While Healing 2
-- Sleep resistance -40
-----------------------------------------
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,4286);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_CHR, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_SLEEPRES, -40);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_CHR, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_SLEEPRES, -40);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/FeiYin/npcs/Dry_Fountain.lua | 3 | 1467 | -----------------------------------
-- Area: FeiYin
-- NPC: Dry Fountain
-- Involved In Quest: Peace for the Spirit
-- !pos -17 -16 71 204
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,PEACE_FOR_THE_SPIRIT) == QUEST_ACCEPTED) then
if (trade:hasItemQty(1093,1) and trade:getItemCount() == 1) then -- Trade Antique Coin
player:startEvent(0x0011);
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);
if (csid == 0x0011) then
player:tradeComplete();
player:setVar("peaceForTheSpiritCS",2);
end
end; | gpl-3.0 |
stumped2/infrastructure-puppet | modules/gitpubsub/files/app/config.lua | 5 | 2326 | local config = {}
function split(txt, delim)
local tbl = {}
for k in txt:gmatch("([^"..delim.."]+)" .. delim) do
table.insert(tbl, k)
end
return tbl
end
function config.read(file)
local f = io.open(file)
local cfg = {}
if f then
local name, key, value, pobj
while true do
local line = f:read("*l")
if not line then break end
if not line:match("^%s*#") then
local n = line:match("^%[(%S+)%]")
if n then
name = n
local o = cfg
for child in n:lower():gmatch("([^:]+)") do
o[child] = o[child] or {}
o = o[child]
end
pobj = o
else
local k, v = line:match("%s*(%S+):%s+([^#]*)")
if k and v then
if v:sub(#v,#v) == [[\]] then
v = v:sub(1,#v-1)
while true do
local line = f:read("*l")
if not line then break end
local b = (line:sub(#line, #line) ~= [[\]])
v = v .. (b and line or line:sub(1,#line-1))
if b then break end
end
end
v = v:gsub("\\n", "\n")
local fname = v:match("read%('([^']+)'%)")
if fname then
local i = io.open(fname)
if i then
v = i:read("*a")
i:close()
end
end
if v:match("^%d+$") then
v = tonumber(v)
else
if v == "true" then v = true elseif v == "false" then v = false end
end
pobj[k] = type(v) == "string" and v:gsub("%s+$", "") or v
end
end
end
end
f:close()
return cfg
else
return nil
end
end
return config
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Windurst_Walls/npcs/Tsuaora-Tsuora.lua | 3 | 1056 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Tsuaora-Tsuora
-- Type: Standard NPC
-- @zone 239
-- !pos 71.489 -3.418 -67.809
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002a);
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 |
pedro-andrade-inpe/terrame | packages/base/tests/database/basics/Society.lua | 3 | 2798 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2017 INPE and TerraLAB/UFOP -- www.terrame.org
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this software and its documentation.
--
-------------------------------------------------------------------------------------------
return{
Society = function(unitTest)
local nonFooAgent = Agent{
init = function(self)
self.immune = self.immune:lower():match("true")
end
}
local soc = Society {
instance = nonFooAgent,
file = filePath("agents.csv", "base")
}
unitTest:assertEquals(4, #soc)
local sum_age = 0
local sum_wealth = 0
local sum_vision = 0
local sum_metabolism = 0
local sum_immunes = 0
forEachAgent(soc, function(ag)
sum_age = sum_age + ag.age
sum_wealth = sum_wealth + ag.wealth
sum_vision = sum_vision + ag.vision
sum_metabolism = sum_metabolism + ag.metabolism
if ag.immune then
sum_immunes = sum_immunes + 1
end
end)
unitTest:assertEquals(105, sum_age)
unitTest:assertEquals(1000, sum_wealth)
unitTest:assertEquals(11, sum_vision)
unitTest:assertEquals(6, sum_metabolism)
unitTest:assertEquals(2, sum_immunes)
nonFooAgent = Agent{}
soc = Society{
instance = nonFooAgent,
file = filePath("brazilstates.shp", "base")
}
unitTest:assertEquals(#soc, 27)
local valuesDefault = {
2300000, 12600000, 2700000, 6700000, 5200000,
16500000, 1900000, 5400000, 7400000, 3300000,
8700000, 13300000, 2600000, 1300000, 300000,
9600000, 4800000, 1600000, 33700000, 1000000,
2700000, 2800000, 300000, 500000, 1700000,
4300000, 2300000
}
for i = 1, 27 do
unitTest:assertEquals(valuesDefault[i], soc.agents[i].POPUL)
end
end
}
| lgpl-3.0 |
pravsingh/Algorithm-Implementations | Hamming_Weight/Lua/Yonaba/hamming_weight.lua | 27 | 1422 | -- Hamming weight implementation
-- See: http://en.wikipedia.org/wiki/Hamming_weight
-- Assertion test for the bitwise implementation being used
local function checkBitImplementation(bit)
local msg = 'Failed testing bitwise implementation'
assert(bit.bnot ~= nil, msg)
assert(bit.lshift ~= nil, msg)
assert(bit.rshift ~= nil, msg)
assert(bit.bnot(0) == 4294967295, msg)
assert(bit.lshift(2, 16) == 131072, msg)
assert(bit.rshift(2, 16) == 0, msg)
return bit
end
-- Note: Lua versions prior to 5.2 does not have native
-- bitwise ops support. This implementation is shipped
-- with David Manura's bitwise op library [1]. The
-- following code will try to check the version of Lua.
-- If being 5.2, it will fallback to its native bit32 library.
-- If we are on LuaJit, it will default to its bitOp, otherwise
-- it will use 'numberlua' for bitwise support.
local bit = checkBitImplementation(
_VERSION:match('5.2') and bit32
or (jit ~= nil) and bit
or require 'numberlua'
)
-- Hamming weight evaluation function
-- i: integer value
-- returns: the hamming weight of the given input
return function (i)
i = i - (bit.band(bit.rshift(i,1), 0x55555555))
i = bit.band(i, 0x33333333) + bit.band(bit.rshift(i,2), 0x33333333)
return bit.rshift((bit.band((i + bit.rshift(i,4)), 0x0F0F0F0F) * 0x01010101), 24)
end
| mit |
starlightknight/darkstar | scripts/globals/abilities/hunters_roll.lua | 12 | 2949 | -----------------------------------
-- Ability: Hunter's Roll
-- Enhances accuracy and ranged accuracy for party members within area of effect
-- Optimal Job: Ranger
-- Lucky Number: 4
-- Unlucky Number: 8
-- Level: 11
-- Phantom Roll +1 Value: 5
--
-- Die Roll |Without RNG |With RNG
-- -------- ------------ -------
-- 1 |+10 |+25
-- 2 |+13 |+28
-- 3 |+15 |+30
-- 4 |+40 |+55
-- 5 |+18 |+33
-- 6 |+20 |+35
-- 7 |+25 |+40
-- 8 |+5 |+20
-- 9 |+27 |+42
-- 10 |+30 |+45
-- 11 |+50 |+65
-- Bust |-5 |-5
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/ability")
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = dsp.effect.HUNTERS_ROLL
ability:setRange(ability:getRange() + player:getMod(dsp.mod.ROLL_RANGE))
if (player:hasStatusEffect(effectID)) then
return dsp.msg.basic.ROLL_ALREADY_ACTIVE,0
elseif atMaxCorsairBusts(player) then
return dsp.msg.basic.CANNOT_PERFORM,0
else
return 0,0
end
end
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, dsp.effect.HUNTERS_ROLL, dsp.job.RNG)
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(dsp.merit.WINNING_STREAK) + caster:getMod(dsp.mod.PHANTOM_DURATION)
local effectpowers = {10, 13, 15, 40, 18, 20, 25, 5, 27, 30, 50, 5}
local effectpower = effectpowers[total]
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 15
end
-- Apply Additional Phantom Roll+ Buff
local phantomBase = 5 -- Base increment buff
local effectpower = effectpower + (phantomBase * phantombuffMultiple(caster))
-- Check if COR Main or Sub
if (caster:getMainJob() == dsp.job.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl())
elseif (caster:getSubJob() == dsp.job.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl())
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(dsp.merit.BUST_DURATION), dsp.effect.HUNTERS_ROLL, effectpower, 0, duration, caster:getID(), total, dsp.mod.ACC) == false) then
ability:setMsg(dsp.msg.basic.ROLL_MAIN_FAIL)
elseif total > 11 then
ability:setMsg(dsp.msg.basic.DOUBLEUP_BUST)
end
return total
end
| gpl-3.0 |
CAAP/Lua | carlos/pubsub.lua | 1 | 1070 |
-- Pub-Sub addresses an old messaging problem:
-- multicast or group messaging.
-- PUB sends each message to "all of many",
-- whereas PUSH and DEALER rotate messages to
-- "one of many".
-- Pub-Sub is aimed at scalability, large volumes
-- of data, sent rapidly to many recipients.
-- To get scalability, pub sub gets rid of
-- back-chatter. Recipients don't talk back
-- to senders. We remove any possibility to
-- coordinate senders and receivers. That is,
-- publishers can't tell when subscribers are
-- successfully connected. Subscribers can't
-- tell publishers anything that would allow
-- publishers to control the rate of messages
-- they send.
-- When we need back-chatter, we can either switch
-- to using ROUTER-DEALER or we can add a separate
-- channel for synchronization.
-- Pub-sub is like a radio broadcast, you miss
-- everything before you join. The classic
-- failure cases are: subscribers join late,
-- subscribers can fetch messages too slowly,
-- subscribers can drop off and lose messages,
-- networks can become overloaded, or too slow.
--
| gpl-2.0 |
starlightknight/darkstar | scripts/commands/addmission.lua | 11 | 1673 | ---------------------------------------------------------------------------------------------------
-- func: addmission <logID> <missionID> <player>
-- desc: Adds a mission to the GM or target players log.
---------------------------------------------------------------------------------------------------
require("scripts/globals/missions");
cmdprops =
{
permission = 1,
parameters = "sss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!addmission <logID> <missionID> {player}");
end;
function onTrigger(player, logId, missionId, target)
-- validate logId
local logName;
local logInfo = GetMissionLogInfo(logId);
if (logInfo == nil) then
error(player, "Invalid logID.");
return;
end
logName = logInfo.full_name;
logId = logInfo.mission_log;
-- validate missionId
local areaMissionIds = dsp.mission.id[dsp.mission.area[logId]]
if (missionId ~= nil) then
missionId = tonumber(missionId) or areaMissionIds[string.upper(missionId)] or _G[string.upper(missionId)];
end
if (missionId == nil or missionId < 0) then
error(player, "Invalid missionID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- add mission
targ:addMission(logId, missionId);
player:PrintToPlayer(string.format("Added %s mission %i to %s.", logName, missionId, targ:getName()));
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Dynamis-Xarcabard/mobs/Animated_Longbow.lua | 17 | 1494 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Animated Longbow
-----------------------------------
require("scripts/globals/status");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (mob:AnimationSub() == 3) then
SetDropRate(110,1583,1000);
else
SetDropRate(110,1583,0);
end
target:showText(mob,ANIMATED_LONGBOW_DIALOG);
SpawnMob(17330522):updateEnmity(target);
SpawnMob(17330523):updateEnmity(target);
SpawnMob(17330524):updateEnmity(target);
SpawnMob(17330525):updateEnmity(target);
SpawnMob(17330526):updateEnmity(target);
SpawnMob(17330527):updateEnmity(target);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
-- TODO: add battle dialog
end;
-----------------------------------
-- onMobDisengage
-----------------------------------
function onMobDisengage(mob)
mob:showText(mob,ANIMATED_LONGBOW_DIALOG+2);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
player:showText(mob,ANIMATED_LONGBOW_DIALOG+1);
DespawnMob(17330522);
DespawnMob(17330523);
DespawnMob(17330524);
DespawnMob(17330525);
DespawnMob(17330526);
DespawnMob(17330527);
end; | gpl-3.0 |
tommy3/Urho3D | Source/ThirdParty/toluapp/src/bin/lua/code.lua | 42 | 2520 | -- tolua: code class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1999
-- $Id: $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- global
code_n = 1
-- Code class
-- Represents Lua code to be compiled and included
-- in the initialization function.
-- The following fields are stored:
-- text = text code
classCode = {
text = '',
}
classCode.__index = classCode
setmetatable(classCode,classFeature)
-- register code
function classCode:register (pre)
pre = pre or ''
-- clean Lua code
local s = clean(self.text)
if not s then
--print(self.text)
error("parser error in embedded code")
end
-- get first line
local _, _, first_line=string.find(self.text, "^([^\n\r]*)")
if string.find(first_line, "^%s*%-%-") then
if string.find(first_line, "^%-%-##") then
first_line = string.gsub(first_line, "^%-%-##", "")
if flags['C'] then
s = string.gsub(s, "^%-%-##[^\n\r]*\n", "")
end
end
else
first_line = ""
end
-- pad to 16 bytes
local npad = 16 - (#s % 16)
local spad = ""
for i=1,npad do
spad = spad .. "-"
end
s = s..spad
-- convert to C
output('\n'..pre..'{ /* begin embedded lua code */\n')
output(pre..' int top = lua_gettop(tolua_S);')
output(pre..' static const unsigned char B[] = {\n ')
local t={n=0}
local b = gsub(s,'(.)',function (c)
local e = ''
t.n=t.n+1 if t.n==15 then t.n=0 e='\n'..pre..' ' end
return format('%3u,%s',strbyte(c),e)
end
)
output(b..strbyte(" "))
output('\n'..pre..' };\n')
if first_line and first_line ~= "" then
output(pre..' tolua_dobuffer(tolua_S,(char*)B,sizeof(B),"tolua embedded: '..first_line..'");')
else
output(pre..' tolua_dobuffer(tolua_S,(char*)B,sizeof(B),"tolua: embedded Lua code '..code_n..'");')
end
output(pre..' lua_settop(tolua_S, top);')
output(pre..'} /* end of embedded lua code */\n\n')
code_n = code_n +1
end
-- Print method
function classCode:print (ident,close)
print(ident.."Code{")
print(ident.." text = [["..self.text.."]],")
print(ident.."}"..close)
end
-- Internal constructor
function _Code (t)
setmetatable(t,classCode)
append(t)
return t
end
-- Constructor
-- Expects a string representing the code text
function Code (l)
return _Code {
text = l
}
end
| mit |
ABrandau/OpenRA | mods/cnc/maps/nod02a/nod02a.lua | 4 | 8127 | --[[
Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
NodUnits = { "bggy", "e1", "e1", "e1", "e1", "e1", "bggy", "e1", "e1", "e1", "bggy" }
NodBaseBuildings = { "hand", "fact", "nuke" }
DfndActorTriggerActivator = { Refinery, Barracks, Powerplant, Yard }
Atk3ActorTriggerActivator = { Guard1, Guard2, Guard3, Guard4, Guard5, Guard6, Guard7 }
Atk1CellTriggerActivator = { CPos.New(45,37), CPos.New(44,37), CPos.New(45,36), CPos.New(44,36), CPos.New(45,35), CPos.New(44,35), CPos.New(45,34), CPos.New(44,34) }
Atk4CellTriggerActivator = { CPos.New(50,47), CPos.New(49,47), CPos.New(48,47), CPos.New(47,47), CPos.New(46,47), CPos.New(45,47), CPos.New(44,47), CPos.New(43,47), CPos.New(42,47), CPos.New(41,47), CPos.New(40,47), CPos.New(39,47), CPos.New(38,47), CPos.New(37,47), CPos.New(50,46), CPos.New(49,46), CPos.New(48,46), CPos.New(47,46), CPos.New(46,46), CPos.New(45,46), CPos.New(44,46), CPos.New(43,46), CPos.New(42,46), CPos.New(41,46), CPos.New(40,46), CPos.New(39,46), CPos.New(38,46) }
Atk2TriggerFunctionTime = DateTime.Seconds(40)
Atk5TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(15)
Atk6TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(20)
Atk7TriggerFunctionTime = DateTime.Seconds(50)
Pat1TriggerFunctionTime = DateTime.Seconds(30)
Atk1Waypoints = { waypoint2, waypoint4, waypoint5, waypoint6 }
Atk2Waypoints = { waypoint2, waypoint5, waypoint7, waypoint6 }
Atk3Waypoints = { waypoint2, waypoint4, waypoint5, waypoint9 }
Atk4Waypoints = { waypoint0, waypoint8, waypoint9 }
Pat1Waypoints = { waypoint0, waypoint1, waypoint2, waypoint3 }
UnitToRebuild = 'e1'
GDIStartUnits = 0
getActors = function(owner, units)
local maxUnits = 0
local actors = { }
for type, count in pairs(units) do
local globalActors = Utils.Where(Map.ActorsInWorld, function(actor)
return actor.Owner == owner and actor.Type == type and not actor.IsDead
end)
if #globalActors < count then
maxUnits = #globalActors
else
maxUnits = count
end
for i = 1, maxUnits, 1 do
actors[#actors + 1] = globalActors[i]
end
end
return actors
end
InsertNodUnits = function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, NodUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
Reinforcements.Reinforce(player, { "mcv" }, { McvEntry.Location, McvRally.Location })
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
CheckForBase = function(player)
local buildings = 0
Utils.Do(NodBaseBuildings, function(name)
if #player.GetActorsByType(name) > 0 then
buildings = buildings + 1
end
end)
return buildings == #NodBaseBuildings
end
DfndTriggerFunction = function()
local list = enemy.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
Atk2TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
end
Atk3TriggerFunction = function()
if not Atk3TriggerSwitch then
Atk3TriggerSwitch = true
MyActors = getActors(enemy, { ['e1'] = 4 })
Utils.Do(MyActors, function(actor)
Atk3Movement(actor)
end)
end
end
Atk5TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
end
Atk6TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 4 })
Utils.Do(MyActors, function(actor)
Atk3Movement(actor)
end)
end
Atk7TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk4Movement(actor)
end)
end
Pat1TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Pat1Movement(actor)
end)
end
Atk1Movement = function(unit)
Utils.Do(Atk1Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk2Movement = function(unit)
Utils.Do(Atk2Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk3Movement = function(unit)
Utils.Do(Atk3Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk4Movement = function(unit)
Utils.Do(Atk4Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Pat1Movement = function(unit)
Utils.Do(Pat1Waypoints, function(waypoint)
unit.Move(waypoint.Location)
end)
IdleHunt(unit)
end
WorldLoaded = function()
player = Player.GetPlayer("Nod")
enemy = Player.GetPlayer("GDI")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
NodObjective1 = player.AddPrimaryObjective("Build a base.")
NodObjective2 = player.AddPrimaryObjective("Destroy the GDI base.")
GDIObjective = enemy.AddPrimaryObjective("Kill all enemies.")
OnAnyDamaged(Atk3ActorTriggerActivator, Atk3TriggerFunction)
Trigger.OnAllRemovedFromWorld(DfndActorTriggerActivator, DfndTriggerFunction)
Trigger.AfterDelay(Atk2TriggerFunctionTime, Atk2TriggerFunction)
Trigger.AfterDelay(Atk5TriggerFunctionTime, Atk5TriggerFunction)
Trigger.AfterDelay(Atk6TriggerFunctionTime, Atk6TriggerFunction)
Trigger.AfterDelay(Atk7TriggerFunctionTime, Atk7TriggerFunction)
Trigger.AfterDelay(Pat1TriggerFunctionTime, Pat1TriggerFunction)
Trigger.OnEnteredFootprint(Atk1CellTriggerActivator, function(a, id)
if a.Owner == player then
MyActors = getActors(enemy, { ['e1'] = 5 })
Utils.Do(MyActors, function(actor)
Atk1Movement(actor)
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Atk4CellTriggerActivator, function(a, id)
if a.Owner == player then
MyActors = getActors(enemy, { ['e1'] = 3 } )
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(0, getStartUnits)
InsertNodUnits()
end
Tick = function()
if enemy.HasNoRequiredUnits() then
player.MarkCompletedObjective(NodObjective2)
end
if player.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
enemy.MarkCompletedObjective(GDIObjective)
end
end
if DateTime.GameTime % DateTime.Seconds(1) == 0 and not player.IsObjectiveCompleted(NodObjective1) and CheckForBase(player) then
player.MarkCompletedObjective(NodObjective1)
end
if DateTime.GameTime % DateTime.Seconds(3) == 0 and Barracks.IsInWorld and Barracks.Owner == enemy then
checkProduction(enemy)
end
end
checkProduction = function(player)
local Units = Utils.Where(Map.ActorsInWorld, function(actor)
return actor.Owner == player and actor.Type == UnitToRebuild
end)
if #Units < GDIStartUnits then
local unitsToProduce = GDIStartUnits - #Units
if Barracks.IsInWorld and unitsToProduce > 0 then
local UnitsType = { }
for i = 1, unitsToProduce, 1 do
UnitsType[i] = UnitToRebuild
end
Barracks.Build(UnitsType)
end
end
end
getStartUnits = function()
local Units = Utils.Where(Map.ActorsInWorld, function(actor)
return actor.Owner == enemy
end)
Utils.Do(Units, function(unit)
if unit.Type == UnitToRebuild then
GDIStartUnits = GDIStartUnits + 1
end
end)
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
| gpl-3.0 |
alomina007/asli | plugins/filterworld.lua | 15 | 4162 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'فقط در گروه ممکن است'
end
if hash then
redis:hset(hash, name, value)
return "انجام شد"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'فقط در گروه'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات فیلتر شده:\n______________________________\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'کلمه ی کاربردی شما ممنوع است، در صورت تکرار با شما برخورد خواهد شد'
elseif value == 'kick' then
send_large_msg('chat#id'..msg.to.id, "به دلیل عدم رعایت قوانین گفتاری از ادامه ی گفتوگو محروم میشوید")
chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'اخطار و تذکر به این کلمه'
elseif value == 'kick' then
return 'این کلمه ممنوع است و حذف خواهید شد'
elseif value == 'none' then
return 'این کلمه از فیلتر خارج شده است'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "ilterlist" then
return list_filter(msg)
elseif matches[1] == "ilter" and matches[2] == ">" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "+" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "-" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "?" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
description = "Set and Get Variables",
usage = {
user = {
"filter ? (word) : مشاهده عکس العمل",
"filterlist : لیست فیلتر شده ها",
},
moderator = {
"filter > (word) : اخطار کردن لغت",
"filter + (word) : ممنوع کردن لغت",
"filter - (word) : حذف از فیلتر",
},
},
patterns = {
"^[Ff](ilter) (.+) (.*)$",
"^[Ff](ilterlist)$",
"(.*)",
},
run = run
}
| gpl-2.0 |
starlightknight/darkstar | scripts/globals/spells/curaga_ii.lua | 12 | 1393 | -----------------------------------------
-- Spell: Curaga II
-- Restores HP of all party members within area of effect.
-----------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/magic")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local minCure = 130
local divisor = 1
local constant = 70
local power = getCurePowerOld(caster)
if (power > 300) then
divisor = 15.6666
constant = 180.43
elseif (power > 180) then
divisor = 2
constant = 115
end
local final = getCureFinal(caster,spell,getBaseCureOld(power,divisor,constant),minCure,false)
final = final + (final * (target:getMod(dsp.mod.CURE_POTENCY_RCVD)/100))
--Applying server mods....
final = final * CURE_POWER
local diff = (target:getMaxHP() - target:getHP())
if (final > diff) then
final = diff
end
target:addHP(final)
target:wakeUp()
caster:updateEnmityFromCure(target,final)
spell:setMsg(dsp.msg.basic.AOE_HP_RECOVERY)
local mpBonusPercent = (final*caster:getMod(dsp.mod.CURE2MP_PERCENT))/100
if (mpBonusPercent > 0) then
caster:addMP(mpBonusPercent)
end
return final
end
| gpl-3.0 |
Craige/prosody-modules | mod_service_directories/mod_service_directories.lua | 32 | 5943 | -- Prosody IM
-- Copyright (C) 2011 Waqas Hussain
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- An implementation of [XEP-0309: Service Directories]
-- Imports and defines
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local adhoc_new = module:require "adhoc".new;
local to_ascii = require "util.encodings".idna.to_ascii;
local nameprep = require "util.encodings".stringprep.nameprep;
local dataforms_new = require "util.dataforms".new;
local pairs, ipairs = pairs, ipairs;
local module = module;
local hosts = hosts;
local subscription_from = {};
local subscription_to = {};
local contact_features = {};
local contact_vcards = {};
-- Advertise in disco
module:add_identity("server", "directory", module:get_option_string("name", "Prosody"));
module:add_feature("urn:xmpp:server-presence");
-- Handle subscriptions
module:hook("presence/host", function(event) -- inbound presence to the host
local origin, stanza = event.origin, event.stanza;
local node, host, resource = jid_split(stanza.attr.from);
if stanza.attr.from ~= host then return; end -- not from a host
local t = stanza.attr.type;
if t == "probe" then
module:send(st.presence({ from = module.host, to = host, id = stanza.attr.id }));
elseif t == "subscribe" then
subscription_from[host] = true;
module:send(st.presence({ from = module.host, to = host, id = stanza.attr.id, type = "subscribed" }));
module:send(st.presence({ from = module.host, to = host, id = stanza.attr.id }));
add_contact(host);
elseif t == "subscribed" then
subscription_to[host] = true;
query_host(host);
elseif t == "unsubscribe" then
subscription_from[host] = nil;
module:send(st.presence({ from = module.host, to = host, id = stanza.attr.id, type = "unsubscribed" }));
remove_contact(host);
elseif t == "unsubscribed" then
subscription_to[host] = nil;
remove_contact(host);
end
return true;
end, 10); -- priority over mod_presence
function remove_contact(host, id)
contact_features[host] = nil;
contact_vcards[host] = nil;
if subscription_to[host] then
subscription_to[host] = nil;
module:send(st.presence({ from = module.host, to = host, id = id, type = "unsubscribe" }));
end
if subscription_from[host] then
subscription_from[host] = nil;
module:send(st.presence({ from = module.host, to = host, id = id, type = "unsubscribed" }));
end
end
function add_contact(host, id)
if not subscription_to[host] then
module:send(st.presence({ from = module.host, to = host, id = id, type = "subscribe" }));
end
end
-- Admin ad-hoc command to subscribe
local function add_contact_handler(self, data, state)
local layout = dataforms_new{
title = "Adding a Server Buddy";
instructions = "Fill out this form to add a \"server buddy\".";
{ name = "FORM_TYPE", type = "hidden", value = "http://jabber.org/protocol/admin" };
{ name = "peerjid", type = "jid-single", required = true, label = "The server to add" };
};
if not state then
return { status = "executing", form = layout }, "executing";
elseif data.action == "canceled" then
return { status = "canceled" };
else
local fields = layout:data(data.form);
local peerjid = nameprep(fields.peerjid);
if not peerjid or peerjid == "" or #peerjid > 1023 or not to_ascii(peerjid) then
return { status = "completed", error = { message = "Invalid JID" } };
end
add_contact(peerjid);
return { status = "completed" };
end
end
local add_contact_command = adhoc_new("Adding a Server Buddy", "http://jabber.org/protocol/admin#server-buddy", add_contact_handler, "admin");
module:add_item("adhoc", add_contact_command);
-- Disco query remote host
function query_host(host)
local stanza = st.iq({ from = module.host, to = host, type = "get", id = "mod_service_directories:disco" })
:query("http://jabber.org/protocol/disco#info");
module:send(stanza);
end
-- Handle disco query result
module:hook("iq-result/bare/mod_service_directories:disco", function(event)
local origin, stanza = event.origin, event.stanza;
if not subscription_to[stanza.attr.from] then return; end -- not from a contact
local host = stanza.attr.from;
local query = stanza:get_child("query", "http://jabber.org/protocol/disco#info")
if not query then return; end
-- extract disco features
local features = {};
for _,tag in ipairs(query.tags) do
if tag.name == "feature" and tag.attr.var then
features[tag.attr.var] = true;
end
end
contact_features[host] = features;
if features["urn:ietf:params:xml:ns:vcard-4.0"] then
local stanza = st.iq({ from = module.host, to = host, type = "get", id = "mod_service_directories:vcard" })
:tag("vcard", { xmlns = "urn:ietf:params:xml:ns:vcard-4.0" });
module:send(stanza);
end
return true;
end);
-- Handle vcard result
module:hook("iq-result/bare/mod_service_directories:vcard", function(event)
local origin, stanza = event.origin, event.stanza;
if not subscription_to[stanza.attr.from] then return; end -- not from a contact
local host = stanza.attr.from;
local vcard = stanza:get_child("vcard", "urn:ietf:params:xml:ns:vcard-4.0");
if not vcard then return; end
contact_vcards[host] = st.clone(vcard);
return true;
end);
-- PubSub
-- TODO the following should be replaced by mod_pubsub
module:hook("iq-get/host/http://jabber.org/protocol/pubsub:pubsub", function(event)
local origin, stanza = event.origin, event.stanza;
local payload = stanza.tags[1];
local items = payload:get_child("items", "http://jabber.org/protocol/pubsub");
if items and items.attr.node == "urn:xmpp:contacts" then
local reply = st.reply(stanza)
:tag("pubsub", { xmlns = "http://jabber.org/protocol/pubsub" })
:tag("items", { node = "urn:xmpp:contacts" });
for host, vcard in pairs(contact_vcards) do
reply:tag("item", { id = host })
:add_child(vcard)
:up();
end
origin.send(reply);
return true;
end
end);
| mit |
starlightknight/darkstar | scripts/globals/besieged.lua | 8 | 9691 | -----------------------------------
--
-- Functions for Besieged system
--
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
require("scripts/globals/status")
require("scripts/globals/teleports")
-----------------------------------
dsp = dsp or {}
dsp.besieged = dsp.besieged or {}
dsp.besieged.onTrigger = function(player, npc, eventBase)
local mercRank = dsp.besieged.getMercenaryRank(player)
if mercRank == 0 then
player:startEvent(eventBase + 1, npc)
else
local maps = getMapBitmask(player)
player:startEvent(eventBase, player:getCurrency("imperial_standing"), maps, mercRank, 0, unpack(getImperialDefenseStats()))
end
end
dsp.besieged.onEventUpdate = function(player, csid, option)
local itemId = getISPItem(option)
if itemId and option < 0x40000000 then
local maps = getMapBitmask(player)
player:updateEvent(player:getCurrency("imperial_standing"), maps, dsp.besieged.getMercenaryRank(player), player:canEquipItem(itemId) and 2 or 1, unpack(getImperialDefenseStats()))
end
end
dsp.besieged.onEventFinish = function(player, csid, option)
local ID = zones[player:getZoneID()]
if option == 0 or option == 16 or option == 32 or option == 48 then
-- Sanction
if option ~= 0 then
player:delCurrency("imperial_standing", 100)
end
player:delStatusEffectsByFlag(dsp.effectFlag.INFLUENCE, true)
local duration = getSanctionDuration(player)
local subPower = 0 -- getImperialDefenseStats()
player:addStatusEffect(dsp.effect.SANCTION, option / 16, 0, duration, subPower)
player:messageSpecial(ID.text.SANCTION)
elseif bit.band(option, 0xFF) == 17 then
-- Player bought a map
local ki = dsp.ki.MAP_OF_MAMOOK + bit.rshift(option, 8)
npcUtil.giveKeyItem(player, ki)
player:delCurrency("imperial_standing", 1000)
elseif option < 0x40000000 then
-- Player bought an item
local item, price = getISPItem(option)
if item then
if npcUtil.giveItem(player, item) then
player:delCurrency("imperial_standing", price)
end
end
end
end
-----------------------------------------------------------------
-- Variable for addTeleport and getRegionPoint
-----------------------------------------------------------------
LEUJAOAM_ASSAULT_POINT = 0
MAMOOL_ASSAULT_POINT = 1
LEBROS_ASSAULT_POINT = 2
PERIQIA_ASSAULT_POINT = 3
ILRUSI_ASSAULT_POINT = 4
NYZUL_ISLE_ASSAULT_POINT = 5
dsp.besieged.addRunicPortal = function(player, portal)
player:addTeleport(dsp.teleport.type.RUNIC_PORTAL, portal)
end
dsp.besieged.hasRunicPortal = function(player, portal)
return player:hasTeleport(dsp.teleport.type.RUNIC_PORTAL, portal)
end
dsp.besieged.hasAssaultOrders = function(player)
local event = 0
local keyitem = 0
for i = 0, 4 do
local ki = dsp.ki.LEUJAOAM_ASSAULT_ORDERS + i
if player:hasKeyItem(ki) then
event = 120 + i
keyitem = ki
break
end
end
return event, keyitem
end
-- TODO: Implement Astral Candescence
dsp.besieged.getAstralCandescence = function()
return 1 -- Hardcoded to 1 for now
end
dsp.besieged.badges = { 780, 783, 784, 794, 795, 825, 826, 827, 894, 900, 909 }
dsp.besieged.getMercenaryRank = function(player)
local rank = 0
for _, v in ipairs(dsp.besieged.badges) do
if player:hasKeyItem(v) then
rank = rank + 1
end
end
return rank
end
local assaultLevels =
{
50, 50, 60, 60, 60, 70, 70, 70, 70, 70,
60, 60, 70, 60, 70, 50, 70, 70, 70, 70,
50, 60, 70, 70, 70, 60, 70, 70, 70, 70,
70, 70, 70, 60, 70, 50, 60, 70, 70, 70,
60, 70, 70, 50, 60, 70, 60, 70, 70, 70,
75, 99
}
function getRecommendedAssaultLevel(assaultid)
return assaultLevels[assaultid]
end
function getMapBitmask(player)
local mamook = player:hasKeyItem(dsp.ki.MAP_OF_MAMOOK) and 1 or 0 -- Map of Mammok
local halvung = player:hasKeyItem(dsp.ki.MAP_OF_HALVUNG) and 2 or 0 -- Map of Halvung
local arrapago = player:hasKeyItem(dsp.ki.MAP_OF_ARRAPAGO_REEF) and 4 or 0 -- Map of Arrapago Reef
local astral = bit.lshift(dsp.besieged.getAstralCandescence(), 31) -- Include astral candescence in the top byte
return bit.bor(mamook, halvung, arrapago, astral)
end
-----------------------------------------------------------------------------------
-- function getSanctionDuration(player) returns the duration of the sanction effect
-- in seconds. Duration is known to go up with mercenary rank but data published on
-- ffxi wiki (http://wiki.ffxiclopedia.org/wiki/Sanction) is unclear and even
-- contradictory (the page on the AC http://wiki.ffxiclopedia.org/wiki/Astral_Candescence
-- says that duration is 3-8 hours with the AC, 1-3 hours without the AC while the Sanction
-- page says it's 3-6 hours with th AC.)
--
-- I decided to use the formula duration (with AC) = 3 hours + (mercenary rank - 1) * 20 minutes.
-----------------------------------------------------------------------------------
function getSanctionDuration(player)
local duration = 10800 + 1200 * (dsp.besieged.getMercenaryRank(player) - 1)
if dsp.besieged.getAstralCandescence() == 0 then
duration = duration / 2
end
return duration
end
-----------------------------------------------------------------------------------
-- function getImperialDefenseStats() returns:
-- *how many successive times Al Zahbi has been defended
-- *Imperial Defense Value
-- *Total number of imperial victories
-- *Total number of beastmen victories.
-- hardcoded constants for now until we have a Besieged system.
-----------------------------------------------------------------------------------
function getImperialDefenseStats()
local successiveWins = 0
local defenseBonus = 0
local imperialWins = 0
local beastmanWins = 0
return { successiveWins, defenseBonus, imperialWins, beastmanWins }
end
------------------------------------------------------------------------------
-- function getISPItem(i) returns the item ID and cost of the imperial standing
-- points item indexed by i (the same value as that used by the vendor event.)
-------------------------------------------------------------------------------
function getISPItem(i)
local IS_item =
{
-- Common Items
[1] = {id = 4182, price = 7}, -- scroll of Instant Reraise
[4097] = {id = 4181, price = 10}, -- scroll of Instant Warp
[8193] = {id = 2230, price = 100}, -- lambent fire cell
[12289] = {id = 2231, price = 100}, -- lambent water cell
[16385] = {id = 2232, price = 100}, -- lambent earth cell
[20481] = {id = 2233, price = 100}, -- lambent wind cell
[24577] = {id = 19021, price = 20000}, -- katana strap
[28673] = {id = 19022, price = 20000}, -- axe grip
[32769] = {id = 19023, price = 20000}, -- staff strap
[36865] = {id = 3307, price = 5000}, -- heat capacitor
[40961] = {id = 3308, price = 5000}, -- power cooler
[45057] = {id = 3309, price = 5000}, -- barrage turbine
[53249] = {id = 3311, price = 5000}, -- galvanizer
[57345] = {id = 6409, price = 50000},
-- Private Second Class
-- Map Key Items (handled separately)
-- Private First Class
[33] = {id = 18689, price = 2000}, -- volunteer's dart
[289] = {id = 18690, price = 2000}, -- mercenary's dart
[545] = {id = 18691, price = 2000}, -- Imperial dart
-- Superior Private
[49] = {id = 18692, price = 4000}, -- Mamoolbane
[305] = {id = 18693, price = 4000}, -- Lamiabane
[561] = {id = 18694, price = 4000}, -- Trollbane
[817] = {id = 15810, price = 4000}, -- Luzaf's ring
-- Lance Corporal
[65] = {id = 15698, price = 8000}, -- sneaking boots
[321] = {id = 15560, price = 8000}, -- trooper's ring
[577] = {id = 16168, price = 8000}, -- sentinel shield
-- Corporal
[81] = {id = 18703, price = 16000}, -- shark gun
[337] = {id = 18742, price = 16000}, -- puppet claws
[593] = {id = 17723, price = 16000}, -- singh kilij
-- Sergeant
[97] = {id = 15622, price = 24000}, -- mercenary's trousers
[353] = {id = 15790, price = 24000}, -- multiple ring
[609] = {id = 15981, price = 24000}, -- haten earring
-- Sergeant Major
[113] = {id = 15623, price = 32000}, -- volunteer's brais
[369] = {id = 15982, price = 32000}, -- priest's earring
[625] = {id = 15983, price = 32000}, -- chaotic earring
-- Chief Sergeant
[129] = {id = 17741, price = 40000}, -- perdu hanger
[385] = {id = 18943, price = 40000}, -- perdu sickle
[641] = {id = 18850, price = 40000}, -- perdu wand
[897] = {id = 18717, price = 40000}, -- perdu bow
-- Second Lieutenant
[145] = {id = 16602, price = 48000}, -- perdu sword
[401] = {id = 18425, price = 48000}, -- perdu blade
[657] = {id = 18491, price = 48000}, -- perdu voulge
[913] = {id = 18588, price = 48000}, -- perdu staff
[1169] = {id = 18718, price = 48000}, -- perdu crossbow
-- First Lieutenant
[161] = {id = 16271, price = 56000}, -- lieutenant's gorget
[417] = {id = 15912, price = 56000}, -- lieutenant's sash
[673] = {id = 16230, price = 56000} -- lieutenant's cape
}
local item = IS_item[i]
if item then
return item.id, item.price
end
return nil
end | gpl-3.0 |
teleowner/TELEOWNER | plugins/webshot.lua | 2 | 1482 | --Shared by @BlackHatChannel
local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {h
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Website Screen Shot",
usage = {
"/web (url) : screen shot of website"
},
patterns = {
"^[!/]web (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
--Shared by @BlackHatChannel | gpl-2.0 |
starlightknight/darkstar | scripts/zones/The_Shrine_of_RuAvitau/IDs.lua | 9 | 2858 | -----------------------------------
-- Area: The_Shrine_of_RuAvitau
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.THE_SHRINE_OF_RUAVITAU] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
FISHING_MESSAGE_OFFSET = 7049, -- You can't fish here.
CONQUEST_BASE = 7149, -- Tallying conquest results...
SMALL_HOLE_HERE = 7336, -- There is a small hole here. It appears to be damp inside...
KIRIN_OFFSET = 7347, -- I am Kirin, master of the Shijin. The one who stands above all. You, who have risen above your mortal status to contend with the gods... It is time to reap your reward.
REGIME_REGISTERED = 10339, -- New training regime registered!
PLAYER_OBTAINS_ITEM = 11391, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 11392, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 11393, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 11394, -- You already possess that temporary item.
NO_COMBINATION = 11399, -- You were unable to enter a combination.
HOMEPOINT_SET = 11425, -- Home point set!
},
mob =
{
ULLIKUMMI = 17506418,
OLLAS_OFFSET = 17506667,
KIRIN = 17506670,
},
npc =
{
DOORS =
{
[ 0] = "y", [ 4] = "b",
[ 1] = "y", [ 5] = "b",
[ 2] = "y", [ 6] = "b",
[ 3] = "y", [ 7] = "b",
[ 8] = "y", [ 9] = "b",
[12] = "y", [10] = "b",
[13] = "y", [11] = "b",
[14] = "y", [16] = "b",
[15] = "y", [17] = "b",
[19] = "y", [18] = "b",
[21] = "y", [20] = "b",
},
MONOLITHS =
{
[ 0] = "y", [ 4] = "b",
[ 1] = "y", [ 5] = "b",
[ 2] = "y", [ 6] = "b",
[ 3] = "y", [ 7] = "b",
[ 9] = "y", [ 8] = "b",
[12] = "y", [10] = "b",
[13] = "y", [11] = "b",
[16] = "y", [14] = "b",
[17] = "y", [15] = "b",
[18] = "y", [19] = "b",
},
OLLAS_QM = 17506692,
CASKET_BASE = 17506695,
DOOR_OFFSET = 17506718,
MONOLITH_OFFSET = 17506741,
},
}
return zones[dsp.zone.THE_SHRINE_OF_RUAVITAU] | gpl-3.0 |
gedads/Neodynamis | scripts/globals/spells/hailstorm.lua | 32 | 1182 | --------------------------------------
-- Spell: Hailstorm
-- Changes the weather around target party member to "snowy."
--------------------------------------
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_HAILSTORM,power,0,180);
return EFFECT_HAILSTORM;
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Xarcabard/npcs/qm5.lua | 3 | 1396 | -----------------------------------
-- Area: Xarcabard
-- NPC: qm5 (???)
-- Involved in Quests: Breaking Barriers
-- !pos 179 -33 82 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Xarcabard/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(SANDORIA) == BREAKING_BARRIERS and player:getVar("MissionStatus") == 2) then
player:addKeyItem(FIGURE_OF_GARUDA);
player:messageSpecial(KEYITEM_OBTAINED,FIGURE_OF_GARUDA);
player:setVar("MissionStatus",3);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
pedro-andrade-inpe/terrame | ide/zerobrane/terrame-examples/gis/05-cellularspace.lua | 3 | 2438 | --[[ [previous](04-directory.lua) | [contents](00-contents.lua) | [next](06-fill.lua)
A cellular space is composed by a set of squared cells. It is internally
represented as polygons and can be opened in any GIS. Every cells within a
cellular space has the same resolution, such as of 1m x 1m, 500m x 500m, or
100km x 100km. The best resolution for a given cellular space depends on the
resolution of the available data, on the computing resources, and on the scale of
the process under study. Finding the best resolution can even be part of the
modeling process.
A cellular space is created as a Layer. It requires another Layer as reference for
its coverage area. If the selected reference layer has a polygonal representation,
cells will be created in such a way to fill all the space of the polygons,
considering only cells that have some overlay with some polygon of the reference
Layer. This means that some cells might be partially outside the study area.
A cellular space will have the same geographic projection of its reference layer.
If the reference layer uses cartesian coordinates, each created cell will have the
same area, which makes a model that uses such data simpler as it is not necessary
to take into account differences between areas. Because of that, it is usually
recommended to use a projection that uses cartesian coordinates instead of
geographic coordinates (latitude and longitude).
It is possible to create a cellular space using Layer constructor as shown in the
code below. The cellular space has 5000m of resolution, as the unit of measurement
of the input Layer is meters. Each created cell will have three attributes: "col",
"row", and "id". Note the option clean = true to delete the shapefile if it already
exists.
]]
import("gis")
itaituba = Project{
file = "itaituba.tview",
clean = true,
localities = "itaituba-localities.shp",
roads = "itaituba-roads.shp",
census = "itaituba-census.shp"
}
Layer{
project = itaituba,
name = "deforestation",
file = "itaituba-deforestation.tif",
epsg = 29191
}
Layer{
project = itaituba,
name = "elevation",
file = "itaituba-elevation.tif",
epsg = 29191
}
itaitubaCells = Layer{
project = itaituba,
name = "cells",
clean = true,
file = "itaituba.shp",
input = "census",
resolution = 5000 -- change this value to set the resolution
}
print("Number of cells: "..#itaitubaCells)
| lgpl-3.0 |
gedads/Neodynamis | scripts/zones/Al_Zahbi/npcs/Taten-Bilten.lua | 3 | 1178 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Taten-Bilten
-- Guild Merchant NPC: Clothcraft Guild
-- !pos 71.598 -6.000 -56.930 48
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Al_Zahbi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60430,6,21,0)) then
player:showText(npc,TATEN_BILTEN_SHOP_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);
end;
| gpl-3.0 |
mmaxs/pull_requests--ettercap | src/lua/share/third-party/stdlib/src/object.lua | 12 | 1911 | --- Prototype-based objects
-- <ul>
-- <li>Create an object/class:</li>
-- <ul>
-- <li>Either, if the <code>_init</code> field is a list:
-- <ul>
-- <li><code>object/Class = prototype {value, ...; field = value, ...}</code></li>
-- <li>Named values are assigned to the corresponding fields, and unnamed values
-- to the fields given by <code>_init</code>.</li>
-- </ul>
-- <li>Or, if the <code>_init</code> field is a function:
-- <ul>
-- <li><code>object/Class = prototype (value, ...)</code></li>
-- <li>The given values are passed as arguments to the <code>_init</code> function.</li>
-- </ul>
-- <li>An object's metatable is itself.</li>
-- <li>Private fields and methods start with "<code>_</code>".</li>
-- </ul>
-- <li>Access an object field: <code>object.field</code></li>
-- <li>Call an object method: <code>object:method (...)</code></li>
-- <li>Call a class method: <code>Class.method (object, ...)</code></li>
-- <li>Add a field: <code>object.field = x</code></li>
-- <li>Add a method: <code>function object:method (...) ... end</code></li>
-- </li>
require "table_ext"
--- Root object
-- @class table
-- @name Object
-- @field _init constructor method or list of fields to be initialised by the
-- constructor
-- @field _clone object constructor which provides the behaviour for <code>_init</code>
-- documented above
local Object = {
_init = {},
_clone = function (self, ...)
local object = table.clone (self)
if type (self._init) == "table" then
table.merge (object, table.clone_rename (self._init, ...))
else
object = self._init (object, ...)
end
return setmetatable (object, object)
end,
-- Sugar instance creation
__call = function (...)
-- First (...) gets first element of list
return (...)._clone (...)
end,
}
setmetatable (Object, Object)
return Object
| gpl-2.0 |
zzzaaiidd/TCHUKY | libs/lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-2.0 |
starlightknight/darkstar | scripts/zones/Sealions_Den/bcnms/warriors_path.lua | 9 | 1622 | -----------------------------------
-- Area: Sealion's Den
-- Name: The Warrior's Path
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/missions")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:getCurrentMission(COP) ~= dsp.mission.id.cop.THE_WARRIOR_S_PATH) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if player:getCurrentMission(COP) == dsp.mission.id.cop.THE_WARRIOR_S_PATH then
player:completeMission(COP, dsp.mission.id.cop.THE_WARRIOR_S_PATH)
player:addMission(COP, dsp.mission.id.cop.GARDEN_OF_ANTIQUITY)
player:setCharVar("PromathiaStatus", 0)
end
player:addExp(1000)
player:addTitle(dsp.title.THE_CHEBUKKIS_WORST_NIGHTMARE)
player:setPos(-25, -1, -620, 208, 33) -- Al'Taieu
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/spells/bluemagic/blood_drain.lua | 7 | 1651 | -----------------------------------------
-- Spell: Blood Drain
-- Steals an enemy's HP. Ineffective against undead
-- Spell cost: 10 MP
-- Monster Type: Giant Bats
-- Spell Type: Magical (Dark)
-- Blue Magic Points: 2
-- Stat Bonus: HP-5, MP+5
-- Level: 20
-- Casting Time: 4 seconds
-- Recast Time: 90 seconds
-- Magic Bursts on: Compression, Gravitation, Darkness
-- Combos: None
-----------------------------------------
require("scripts/globals/bluemagic");
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local dmg = 1 + (0.705 * caster:getSkillLevel(BLUE_SKILL));
local params = {};
params.diff = caster:getStat(MOD_MND)-target:getStat(MOD_MND);
params.attribute = MOD_MND;
params.skillType = BLUE_SKILL;
params.bonus = 1.0;
local resist = applyResistance(caster, target, spell, params);
dmg = dmg*resist;
dmg = addBonuses(caster,spell,target,dmg);
dmg = adjustForTarget(target,dmg,spell:getElement());
if (dmg > (caster:getSkillLevel(BLUE_SKILL) + 20)) then
dmg = (caster:getSkillLevel(BLUE_SKILL) + 20);
end
if (dmg < 0) then
dmg = 0
end
if (target:isUndead()) then
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
return dmg;
end
if (target:getHP() < dmg) then
dmg = target:getHP();
end
dmg = BlueFinalAdjustments(caster,target,spell,dmg);
caster:addHP(dmg);
return dmg;
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/East_Sarutabaruta/npcs/Pore-Ohre.lua | 9 | 1140 | -----------------------------------
-- Area: East Sarutabaruta
-- NPC: Pore-Ohre
-- Involved In Mission: The Heart of the Matter
-- !pos 261 -17 -458 116
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
local ID = require("scripts/zones/East_Sarutabaruta/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
-- Check if we are on Windurst Mission 1-2
if (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_HEART_OF_THE_MATTER) then
MissionStatus = player:getCharVar("MissionStatus");
if (MissionStatus == 1) then
player:startEvent(46);
elseif (MissionStatus == 2) then
player:startEvent(47);
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 46) then
player:setCharVar("MissionStatus",2);
player:addKeyItem(dsp.ki.SOUTHEASTERN_STAR_CHARM);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SOUTHEASTERN_STAR_CHARM);
end
end; | gpl-3.0 |
soccermitchy/heroku-lapis | opt/src/openresty/bundle/LuaJIT-2.1-20150223/dynasm/dasm_ppc.lua | 3 | 55128 | ------------------------------------------------------------------------------
-- DynASM PPC/PPC64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
--
-- Support for various extensions contributed by Caio Souza Oliveira.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "ppc",
description = "DynASM PPC module",
version = "1.3.0",
vernum = 10300,
release = "2015-01-14",
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, setmetatable = assert, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch = _s.match, _s.gmatch
local concat, sort = table.concat, table.sort
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local tohex = bit.tohex
-- 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 = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM",
}
-- 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.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- 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
------------------------------------------------------------------------------
-- 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
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0xffffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
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 > 2047 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=20,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=20,next_global-1 do
out:write(" ", prefix, 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=20,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 = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = { sp = "r1" } -- Ext. register name -> int. name.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
if s == "r1" then return "sp" end
return s
end
local map_cond = {
lt = 0, gt = 1, eq = 2, so = 3,
ge = 4, le = 5, ne = 6, ns = 7,
}
------------------------------------------------------------------------------
-- Template strings for PPC instructions.
local map_op = {
tdi_3 = "08000000ARI",
twi_3 = "0c000000ARI",
mulli_3 = "1c000000RRI",
subfic_3 = "20000000RRI",
cmplwi_3 = "28000000XRU",
cmplwi_2 = "28000000-RU",
cmpldi_3 = "28200000XRU",
cmpldi_2 = "28200000-RU",
cmpwi_3 = "2c000000XRI",
cmpwi_2 = "2c000000-RI",
cmpdi_3 = "2c200000XRI",
cmpdi_2 = "2c200000-RI",
addic_3 = "30000000RRI",
["addic._3"] = "34000000RRI",
addi_3 = "38000000RR0I",
li_2 = "38000000RI",
la_2 = "38000000RD",
addis_3 = "3c000000RR0I",
lis_2 = "3c000000RI",
lus_2 = "3c000000RU",
bc_3 = "40000000AAK",
bcl_3 = "40000001AAK",
bdnz_1 = "42000000K",
bdz_1 = "42400000K",
sc_0 = "44000000",
b_1 = "48000000J",
bl_1 = "48000001J",
rlwimi_5 = "50000000RR~AAA.",
rlwinm_5 = "54000000RR~AAA.",
rlwnm_5 = "5c000000RR~RAA.",
ori_3 = "60000000RR~U",
nop_0 = "60000000",
oris_3 = "64000000RR~U",
xori_3 = "68000000RR~U",
xoris_3 = "6c000000RR~U",
["andi._3"] = "70000000RR~U",
["andis._3"] = "74000000RR~U",
lwz_2 = "80000000RD",
lwzu_2 = "84000000RD",
lbz_2 = "88000000RD",
lbzu_2 = "8c000000RD",
stw_2 = "90000000RD",
stwu_2 = "94000000RD",
stb_2 = "98000000RD",
stbu_2 = "9c000000RD",
lhz_2 = "a0000000RD",
lhzu_2 = "a4000000RD",
lha_2 = "a8000000RD",
lhau_2 = "ac000000RD",
sth_2 = "b0000000RD",
sthu_2 = "b4000000RD",
lmw_2 = "b8000000RD",
stmw_2 = "bc000000RD",
lfs_2 = "c0000000FD",
lfsu_2 = "c4000000FD",
lfd_2 = "c8000000FD",
lfdu_2 = "cc000000FD",
stfs_2 = "d0000000FD",
stfsu_2 = "d4000000FD",
stfd_2 = "d8000000FD",
stfdu_2 = "dc000000FD",
ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4.
ldu_2 = "e8000001RD",
lwa_2 = "e8000002RD",
std_2 = "f8000000RD",
stdu_2 = "f8000001RD",
-- Primary opcode 4:
mulhhwu_3 = "10000010RRR.",
machhwu_3 = "10000018RRR.",
mulhhw_3 = "10000050RRR.",
nmachhw_3 = "1000005cRRR.",
machhwsu_3 = "10000098RRR.",
machhws_3 = "100000d8RRR.",
nmachhws_3 = "100000dcRRR.",
mulchwu_3 = "10000110RRR.",
macchwu_3 = "10000118RRR.",
mulchw_3 = "10000150RRR.",
macchw_3 = "10000158RRR.",
nmacchw_3 = "1000015cRRR.",
macchwsu_3 = "10000198RRR.",
macchws_3 = "100001d8RRR.",
nmacchws_3 = "100001dcRRR.",
mullhw_3 = "10000350RRR.",
maclhw_3 = "10000358RRR.",
nmaclhw_3 = "1000035cRRR.",
maclhwsu_3 = "10000398RRR.",
maclhws_3 = "100003d8RRR.",
nmaclhws_3 = "100003dcRRR.",
machhwuo_3 = "10000418RRR.",
nmachhwo_3 = "1000045cRRR.",
machhwsuo_3 = "10000498RRR.",
machhwso_3 = "100004d8RRR.",
nmachhwso_3 = "100004dcRRR.",
macchwuo_3 = "10000518RRR.",
macchwo_3 = "10000558RRR.",
nmacchwo_3 = "1000055cRRR.",
macchwsuo_3 = "10000598RRR.",
macchwso_3 = "100005d8RRR.",
nmacchwso_3 = "100005dcRRR.",
maclhwo_3 = "10000758RRR.",
nmaclhwo_3 = "1000075cRRR.",
maclhwsuo_3 = "10000798RRR.",
maclhwso_3 = "100007d8RRR.",
nmaclhwso_3 = "100007dcRRR.",
vaddubm_3 = "10000000VVV",
vmaxub_3 = "10000002VVV",
vrlb_3 = "10000004VVV",
vcmpequb_3 = "10000006VVV",
vmuloub_3 = "10000008VVV",
vaddfp_3 = "1000000aVVV",
vmrghb_3 = "1000000cVVV",
vpkuhum_3 = "1000000eVVV",
vmhaddshs_4 = "10000020VVVV",
vmhraddshs_4 = "10000021VVVV",
vmladduhm_4 = "10000022VVVV",
vmsumubm_4 = "10000024VVVV",
vmsummbm_4 = "10000025VVVV",
vmsumuhm_4 = "10000026VVVV",
vmsumuhs_4 = "10000027VVVV",
vmsumshm_4 = "10000028VVVV",
vmsumshs_4 = "10000029VVVV",
vsel_4 = "1000002aVVVV",
vperm_4 = "1000002bVVVV",
vsldoi_4 = "1000002cVVVP",
vpermxor_4 = "1000002dVVVV",
vmaddfp_4 = "1000002eVVVV~",
vnmsubfp_4 = "1000002fVVVV~",
vaddeuqm_4 = "1000003cVVVV",
vaddecuq_4 = "1000003dVVVV",
vsubeuqm_4 = "1000003eVVVV",
vsubecuq_4 = "1000003fVVVV",
vadduhm_3 = "10000040VVV",
vmaxuh_3 = "10000042VVV",
vrlh_3 = "10000044VVV",
vcmpequh_3 = "10000046VVV",
vmulouh_3 = "10000048VVV",
vsubfp_3 = "1000004aVVV",
vmrghh_3 = "1000004cVVV",
vpkuwum_3 = "1000004eVVV",
vadduwm_3 = "10000080VVV",
vmaxuw_3 = "10000082VVV",
vrlw_3 = "10000084VVV",
vcmpequw_3 = "10000086VVV",
vmulouw_3 = "10000088VVV",
vmuluwm_3 = "10000089VVV",
vmrghw_3 = "1000008cVVV",
vpkuhus_3 = "1000008eVVV",
vaddudm_3 = "100000c0VVV",
vmaxud_3 = "100000c2VVV",
vrld_3 = "100000c4VVV",
vcmpeqfp_3 = "100000c6VVV",
vcmpequd_3 = "100000c7VVV",
vpkuwus_3 = "100000ceVVV",
vadduqm_3 = "10000100VVV",
vmaxsb_3 = "10000102VVV",
vslb_3 = "10000104VVV",
vmulosb_3 = "10000108VVV",
vrefp_2 = "1000010aV-V",
vmrglb_3 = "1000010cVVV",
vpkshus_3 = "1000010eVVV",
vaddcuq_3 = "10000140VVV",
vmaxsh_3 = "10000142VVV",
vslh_3 = "10000144VVV",
vmulosh_3 = "10000148VVV",
vrsqrtefp_2 = "1000014aV-V",
vmrglh_3 = "1000014cVVV",
vpkswus_3 = "1000014eVVV",
vaddcuw_3 = "10000180VVV",
vmaxsw_3 = "10000182VVV",
vslw_3 = "10000184VVV",
vmulosw_3 = "10000188VVV",
vexptefp_2 = "1000018aV-V",
vmrglw_3 = "1000018cVVV",
vpkshss_3 = "1000018eVVV",
vmaxsd_3 = "100001c2VVV",
vsl_3 = "100001c4VVV",
vcmpgefp_3 = "100001c6VVV",
vlogefp_2 = "100001caV-V",
vpkswss_3 = "100001ceVVV",
vadduhs_3 = "10000240VVV",
vminuh_3 = "10000242VVV",
vsrh_3 = "10000244VVV",
vcmpgtuh_3 = "10000246VVV",
vmuleuh_3 = "10000248VVV",
vrfiz_2 = "1000024aV-V",
vsplth_3 = "1000024cVV3",
vupkhsh_2 = "1000024eV-V",
vminuw_3 = "10000282VVV",
vminud_3 = "100002c2VVV",
vcmpgtud_3 = "100002c7VVV",
vrfim_2 = "100002caV-V",
vcmpgtsb_3 = "10000306VVV",
vcfux_3 = "1000030aVVA~",
vaddshs_3 = "10000340VVV",
vminsh_3 = "10000342VVV",
vsrah_3 = "10000344VVV",
vcmpgtsh_3 = "10000346VVV",
vmulesh_3 = "10000348VVV",
vcfsx_3 = "1000034aVVA~",
vspltish_2 = "1000034cVS",
vupkhpx_2 = "1000034eV-V",
vaddsws_3 = "10000380VVV",
vminsw_3 = "10000382VVV",
vsraw_3 = "10000384VVV",
vcmpgtsw_3 = "10000386VVV",
vmulesw_3 = "10000388VVV",
vctuxs_3 = "1000038aVVA~",
vspltisw_2 = "1000038cVS",
vminsd_3 = "100003c2VVV",
vsrad_3 = "100003c4VVV",
vcmpbfp_3 = "100003c6VVV",
vcmpgtsd_3 = "100003c7VVV",
vctsxs_3 = "100003caVVA~",
vupklpx_2 = "100003ceV-V",
vsububm_3 = "10000400VVV",
["bcdadd._4"] = "10000401VVVy.",
vavgub_3 = "10000402VVV",
vand_3 = "10000404VVV",
["vcmpequb._3"] = "10000406VVV",
vmaxfp_3 = "1000040aVVV",
vsubuhm_3 = "10000440VVV",
["bcdsub._4"] = "10000441VVVy.",
vavguh_3 = "10000442VVV",
vandc_3 = "10000444VVV",
["vcmpequh._3"] = "10000446VVV",
vminfp_3 = "1000044aVVV",
vpkudum_3 = "1000044eVVV",
vsubuwm_3 = "10000480VVV",
vavguw_3 = "10000482VVV",
vor_3 = "10000484VVV",
["vcmpequw._3"] = "10000486VVV",
vpmsumw_3 = "10000488VVV",
["vcmpeqfp._3"] = "100004c6VVV",
["vcmpequd._3"] = "100004c7VVV",
vpkudus_3 = "100004ceVVV",
vavgsb_3 = "10000502VVV",
vavgsh_3 = "10000542VVV",
vorc_3 = "10000544VVV",
vbpermq_3 = "1000054cVVV",
vpksdus_3 = "1000054eVVV",
vavgsw_3 = "10000582VVV",
vsld_3 = "100005c4VVV",
["vcmpgefp._3"] = "100005c6VVV",
vpksdss_3 = "100005ceVVV",
vsububs_3 = "10000600VVV",
mfvscr_1 = "10000604V--",
vsum4ubs_3 = "10000608VVV",
vsubuhs_3 = "10000640VVV",
mtvscr_1 = "10000644--V",
["vcmpgtuh._3"] = "10000646VVV",
vsum4shs_3 = "10000648VVV",
vupkhsw_2 = "1000064eV-V",
vsubuws_3 = "10000680VVV",
vshasigmaw_4 = "10000682VVYp",
veqv_3 = "10000684VVV",
vsum2sws_3 = "10000688VVV",
vmrgow_3 = "1000068cVVV",
vshasigmad_4 = "100006c2VVYp",
vsrd_3 = "100006c4VVV",
["vcmpgtud._3"] = "100006c7VVV",
vupklsw_2 = "100006ceV-V",
vupkslw_2 = "100006ceV-V",
vsubsbs_3 = "10000700VVV",
vclzb_2 = "10000702V-V",
vpopcntb_2 = "10000703V-V",
["vcmpgtsb._3"] = "10000706VVV",
vsum4sbs_3 = "10000708VVV",
vsubshs_3 = "10000740VVV",
vclzh_2 = "10000742V-V",
vpopcnth_2 = "10000743V-V",
["vcmpgtsh._3"] = "10000746VVV",
vsubsws_3 = "10000780VVV",
vclzw_2 = "10000782V-V",
vpopcntw_2 = "10000783V-V",
["vcmpgtsw._3"] = "10000786VVV",
vsumsws_3 = "10000788VVV",
vmrgew_3 = "1000078cVVV",
vclzd_2 = "100007c2V-V",
vpopcntd_2 = "100007c3V-V",
["vcmpbfp._3"] = "100007c6VVV",
["vcmpgtsd._3"] = "100007c7VVV",
-- Primary opcode 19:
mcrf_2 = "4c000000XX",
isync_0 = "4c00012c",
crnor_3 = "4c000042CCC",
crnot_2 = "4c000042CC=",
crandc_3 = "4c000102CCC",
crxor_3 = "4c000182CCC",
crclr_1 = "4c000182C==",
crnand_3 = "4c0001c2CCC",
crand_3 = "4c000202CCC",
creqv_3 = "4c000242CCC",
crset_1 = "4c000242C==",
crorc_3 = "4c000342CCC",
cror_3 = "4c000382CCC",
crmove_2 = "4c000382CC=",
bclr_2 = "4c000020AA",
bclrl_2 = "4c000021AA",
bcctr_2 = "4c000420AA",
bcctrl_2 = "4c000421AA",
bctar_2 = "4c000460AA",
bctarl_2 = "4c000461AA",
blr_0 = "4e800020",
blrl_0 = "4e800021",
bctr_0 = "4e800420",
bctrl_0 = "4e800421",
-- Primary opcode 31:
cmpw_3 = "7c000000XRR",
cmpw_2 = "7c000000-RR",
cmpd_3 = "7c200000XRR",
cmpd_2 = "7c200000-RR",
tw_3 = "7c000008ARR",
lvsl_3 = "7c00000cVRR",
subfc_3 = "7c000010RRR.",
subc_3 = "7c000010RRR~.",
mulhdu_3 = "7c000012RRR.",
addc_3 = "7c000014RRR.",
mulhwu_3 = "7c000016RRR.",
isel_4 = "7c00001eRRRC",
isellt_3 = "7c00001eRRR",
iselgt_3 = "7c00005eRRR",
iseleq_3 = "7c00009eRRR",
mfcr_1 = "7c000026R",
mfocrf_2 = "7c100026RG",
mtcrf_2 = "7c000120GR",
mtocrf_2 = "7c100120GR",
lwarx_3 = "7c000028RR0R",
ldx_3 = "7c00002aRR0R",
lwzx_3 = "7c00002eRR0R",
slw_3 = "7c000030RR~R.",
cntlzw_2 = "7c000034RR~",
sld_3 = "7c000036RR~R.",
and_3 = "7c000038RR~R.",
cmplw_3 = "7c000040XRR",
cmplw_2 = "7c000040-RR",
cmpld_3 = "7c200040XRR",
cmpld_2 = "7c200040-RR",
lvsr_3 = "7c00004cVRR",
subf_3 = "7c000050RRR.",
sub_3 = "7c000050RRR~.",
lbarx_3 = "7c000068RR0R",
ldux_3 = "7c00006aRR0R",
dcbst_2 = "7c00006c-RR",
lwzux_3 = "7c00006eRR0R",
cntlzd_2 = "7c000074RR~",
andc_3 = "7c000078RR~R.",
td_3 = "7c000088ARR",
lvewx_3 = "7c00008eVRR",
mulhd_3 = "7c000092RRR.",
addg6s_3 = "7c000094RRR",
mulhw_3 = "7c000096RRR.",
dlmzb_3 = "7c00009cRR~R.",
ldarx_3 = "7c0000a8RR0R",
dcbf_2 = "7c0000ac-RR",
lbzx_3 = "7c0000aeRR0R",
lvx_3 = "7c0000ceVRR",
neg_2 = "7c0000d0RR.",
lharx_3 = "7c0000e8RR0R",
lbzux_3 = "7c0000eeRR0R",
popcntb_2 = "7c0000f4RR~",
not_2 = "7c0000f8RR~%.",
nor_3 = "7c0000f8RR~R.",
stvebx_3 = "7c00010eVRR",
subfe_3 = "7c000110RRR.",
sube_3 = "7c000110RRR~.",
adde_3 = "7c000114RRR.",
stdx_3 = "7c00012aRR0R",
["stwcx._3"] = "7c00012dRR0R.",
stwx_3 = "7c00012eRR0R",
prtyw_2 = "7c000134RR~",
stvehx_3 = "7c00014eVRR",
stdux_3 = "7c00016aRR0R",
["stqcx._3"] = "7c00016dR:R0R.",
stwux_3 = "7c00016eRR0R",
prtyd_2 = "7c000174RR~",
stvewx_3 = "7c00018eVRR",
subfze_2 = "7c000190RR.",
addze_2 = "7c000194RR.",
["stdcx._3"] = "7c0001adRR0R.",
stbx_3 = "7c0001aeRR0R",
stvx_3 = "7c0001ceVRR",
subfme_2 = "7c0001d0RR.",
mulld_3 = "7c0001d2RRR.",
addme_2 = "7c0001d4RR.",
mullw_3 = "7c0001d6RRR.",
dcbtst_2 = "7c0001ec-RR",
stbux_3 = "7c0001eeRR0R",
bpermd_3 = "7c0001f8RR~R",
lvepxl_3 = "7c00020eVRR",
add_3 = "7c000214RRR.",
lqarx_3 = "7c000228R:R0R",
dcbt_2 = "7c00022c-RR",
lhzx_3 = "7c00022eRR0R",
cdtbcd_2 = "7c000234RR~",
eqv_3 = "7c000238RR~R.",
lvepx_3 = "7c00024eVRR",
eciwx_3 = "7c00026cRR0R",
lhzux_3 = "7c00026eRR0R",
cbcdtd_2 = "7c000274RR~",
xor_3 = "7c000278RR~R.",
mfspefscr_1 = "7c0082a6R",
mfxer_1 = "7c0102a6R",
mflr_1 = "7c0802a6R",
mfctr_1 = "7c0902a6R",
lwax_3 = "7c0002aaRR0R",
lhax_3 = "7c0002aeRR0R",
mftb_1 = "7c0c42e6R",
mftbu_1 = "7c0d42e6R",
lvxl_3 = "7c0002ceVRR",
lwaux_3 = "7c0002eaRR0R",
lhaux_3 = "7c0002eeRR0R",
popcntw_2 = "7c0002f4RR~",
divdeu_3 = "7c000312RRR.",
divweu_3 = "7c000316RRR.",
sthx_3 = "7c00032eRR0R",
orc_3 = "7c000338RR~R.",
ecowx_3 = "7c00036cRR0R",
sthux_3 = "7c00036eRR0R",
or_3 = "7c000378RR~R.",
mr_2 = "7c000378RR~%.",
divdu_3 = "7c000392RRR.",
divwu_3 = "7c000396RRR.",
mtspefscr_1 = "7c0083a6R",
mtxer_1 = "7c0103a6R",
mtlr_1 = "7c0803a6R",
mtctr_1 = "7c0903a6R",
dcbi_2 = "7c0003ac-RR",
nand_3 = "7c0003b8RR~R.",
dsn_2 = "7c0003c6-RR",
stvxl_3 = "7c0003ceVRR",
divd_3 = "7c0003d2RRR.",
divw_3 = "7c0003d6RRR.",
popcntd_2 = "7c0003f4RR~",
cmpb_3 = "7c0003f8RR~R.",
mcrxr_1 = "7c000400X",
lbdx_3 = "7c000406RRR",
subfco_3 = "7c000410RRR.",
subco_3 = "7c000410RRR~.",
addco_3 = "7c000414RRR.",
ldbrx_3 = "7c000428RR0R",
lswx_3 = "7c00042aRR0R",
lwbrx_3 = "7c00042cRR0R",
lfsx_3 = "7c00042eFR0R",
srw_3 = "7c000430RR~R.",
srd_3 = "7c000436RR~R.",
lhdx_3 = "7c000446RRR",
subfo_3 = "7c000450RRR.",
subo_3 = "7c000450RRR~.",
lfsux_3 = "7c00046eFR0R",
lwdx_3 = "7c000486RRR",
lswi_3 = "7c0004aaRR0A",
sync_0 = "7c0004ac",
lwsync_0 = "7c2004ac",
ptesync_0 = "7c4004ac",
lfdx_3 = "7c0004aeFR0R",
lddx_3 = "7c0004c6RRR",
nego_2 = "7c0004d0RR.",
lfdux_3 = "7c0004eeFR0R",
stbdx_3 = "7c000506RRR",
subfeo_3 = "7c000510RRR.",
subeo_3 = "7c000510RRR~.",
addeo_3 = "7c000514RRR.",
stdbrx_3 = "7c000528RR0R",
stswx_3 = "7c00052aRR0R",
stwbrx_3 = "7c00052cRR0R",
stfsx_3 = "7c00052eFR0R",
sthdx_3 = "7c000546RRR",
["stbcx._3"] = "7c00056dRRR",
stfsux_3 = "7c00056eFR0R",
stwdx_3 = "7c000586RRR",
subfzeo_2 = "7c000590RR.",
addzeo_2 = "7c000594RR.",
stswi_3 = "7c0005aaRR0A",
["sthcx._3"] = "7c0005adRRR",
stfdx_3 = "7c0005aeFR0R",
stddx_3 = "7c0005c6RRR",
subfmeo_2 = "7c0005d0RR.",
mulldo_3 = "7c0005d2RRR.",
addmeo_2 = "7c0005d4RR.",
mullwo_3 = "7c0005d6RRR.",
dcba_2 = "7c0005ec-RR",
stfdux_3 = "7c0005eeFR0R",
stvepxl_3 = "7c00060eVRR",
addo_3 = "7c000614RRR.",
lhbrx_3 = "7c00062cRR0R",
lfdpx_3 = "7c00062eF:RR",
sraw_3 = "7c000630RR~R.",
srad_3 = "7c000634RR~R.",
lfddx_3 = "7c000646FRR",
stvepx_3 = "7c00064eVRR",
srawi_3 = "7c000670RR~A.",
sradi_3 = "7c000674RR~H.",
eieio_0 = "7c0006ac",
lfiwax_3 = "7c0006aeFR0R",
divdeuo_3 = "7c000712RRR.",
divweuo_3 = "7c000716RRR.",
sthbrx_3 = "7c00072cRR0R",
stfdpx_3 = "7c00072eF:RR",
extsh_2 = "7c000734RR~.",
stfddx_3 = "7c000746FRR",
divdeo_3 = "7c000752RRR.",
divweo_3 = "7c000756RRR.",
extsb_2 = "7c000774RR~.",
divduo_3 = "7c000792RRR.",
divwou_3 = "7c000796RRR.",
icbi_2 = "7c0007ac-RR",
stfiwx_3 = "7c0007aeFR0R",
extsw_2 = "7c0007b4RR~.",
divdo_3 = "7c0007d2RRR.",
divwo_3 = "7c0007d6RRR.",
dcbz_2 = "7c0007ec-RR",
["tbegin._1"] = "7c00051d1",
["tbegin._0"] = "7c00051d",
["tend._1"] = "7c00055dY",
["tend._0"] = "7c00055d",
["tendall._0"] = "7e00055d",
tcheck_1 = "7c00059cX",
["tsr._1"] = "7c0005dd1",
["tsuspend._0"] = "7c0005dd",
["tresume._0"] = "7c2005dd",
["tabortwc._3"] = "7c00061dARR",
["tabortdc._3"] = "7c00065dARR",
["tabortwci._3"] = "7c00069dARS",
["tabortdci._3"] = "7c0006ddARS",
["tabort._1"] = "7c00071d-R-",
["treclaim._1"] = "7c00075d-R",
["trechkpt._0"] = "7c0007dd",
lxsiwzx_3 = "7c000018QRR",
lxsiwax_3 = "7c000098QRR",
mfvsrd_2 = "7c000066-Rq",
mfvsrwz_2 = "7c0000e6-Rq",
stxsiwx_3 = "7c000118QRR",
mtvsrd_2 = "7c000166QR",
mtvsrwa_2 = "7c0001a6QR",
lxvdsx_3 = "7c000298QRR",
lxsspx_3 = "7c000418QRR",
lxsdx_3 = "7c000498QRR",
stxsspx_3 = "7c000518QRR",
stxsdx_3 = "7c000598QRR",
lxvw4x_3 = "7c000618QRR",
lxvd2x_3 = "7c000698QRR",
stxvw4x_3 = "7c000718QRR",
stxvd2x_3 = "7c000798QRR",
-- Primary opcode 30:
rldicl_4 = "78000000RR~HM.",
rldicr_4 = "78000004RR~HM.",
rldic_4 = "78000008RR~HM.",
rldimi_4 = "7800000cRR~HM.",
rldcl_4 = "78000010RR~RM.",
rldcr_4 = "78000012RR~RM.",
-- Primary opcode 56:
lq_2 = "e0000000R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 57:
lfdp_2 = "e4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 59:
fdivs_3 = "ec000024FFF.",
fsubs_3 = "ec000028FFF.",
fadds_3 = "ec00002aFFF.",
fsqrts_2 = "ec00002cF-F.",
fres_2 = "ec000030F-F.",
fmuls_3 = "ec000032FF-F.",
frsqrtes_2 = "ec000034F-F.",
fmsubs_4 = "ec000038FFFF~.",
fmadds_4 = "ec00003aFFFF~.",
fnmsubs_4 = "ec00003cFFFF~.",
fnmadds_4 = "ec00003eFFFF~.",
fcfids_2 = "ec00069cF-F.",
fcfidus_2 = "ec00079cF-F.",
dadd_3 = "ec000004FFF.",
dqua_4 = "ec000006FFFZ.",
dmul_3 = "ec000044FFF.",
drrnd_4 = "ec000046FFFZ.",
dscli_3 = "ec000084FF6.",
dquai_4 = "ec000086SF~FZ.",
dscri_3 = "ec0000c4FF6.",
drintx_4 = "ec0000c61F~FZ.",
dcmpo_3 = "ec000104XFF",
dtstex_3 = "ec000144XFF",
dtstdc_3 = "ec000184XF6",
dtstdg_3 = "ec0001c4XF6",
drintn_4 = "ec0001c61F~FZ.",
dctdp_2 = "ec000204F-F.",
dctfix_2 = "ec000244F-F.",
ddedpd_3 = "ec000284ZF~F.",
dxex_2 = "ec0002c4F-F.",
dsub_3 = "ec000404FFF.",
ddiv_3 = "ec000444FFF.",
dcmpu_3 = "ec000504XFF",
dtstsf_3 = "ec000544XFF",
drsp_2 = "ec000604F-F.",
dcffix_2 = "ec000644F-F.",
denbcd_3 = "ec000684YF~F.",
diex_3 = "ec0006c4FFF.",
-- Primary opcode 60:
xsaddsp_3 = "f0000000QQQ",
xsmaddasp_3 = "f0000008QQQ",
xxsldwi_4 = "f0000010QQQz",
xsrsqrtesp_2 = "f0000028Q-Q",
xssqrtsp_2 = "f000002cQ-Q",
xxsel_4 = "f0000030QQQQ",
xssubsp_3 = "f0000040QQQ",
xsmaddmsp_3 = "f0000048QQQ",
xxpermdi_4 = "f0000050QQQz",
xsresp_2 = "f0000068Q-Q",
xsmulsp_3 = "f0000080QQQ",
xsmsubasp_3 = "f0000088QQQ",
xxmrghw_3 = "f0000090QQQ",
xsdivsp_3 = "f00000c0QQQ",
xsmsubmsp_3 = "f00000c8QQQ",
xsadddp_3 = "f0000100QQQ",
xsmaddadp_3 = "f0000108QQQ",
xscmpudp_3 = "f0000118XQQ",
xscvdpuxws_2 = "f0000120Q-Q",
xsrdpi_2 = "f0000124Q-Q",
xsrsqrtedp_2 = "f0000128Q-Q",
xssqrtdp_2 = "f000012cQ-Q",
xssubdp_3 = "f0000140QQQ",
xsmaddmdp_3 = "f0000148QQQ",
xscmpodp_3 = "f0000158XQQ",
xscvdpsxws_2 = "f0000160Q-Q",
xsrdpiz_2 = "f0000164Q-Q",
xsredp_2 = "f0000168Q-Q",
xsmuldp_3 = "f0000180QQQ",
xsmsubadp_3 = "f0000188QQQ",
xxmrglw_3 = "f0000190QQQ",
xsrdpip_2 = "f00001a4Q-Q",
xstsqrtdp_2 = "f00001a8X-Q",
xsrdpic_2 = "f00001acQ-Q",
xsdivdp_3 = "f00001c0QQQ",
xsmsubmdp_3 = "f00001c8QQQ",
xsrdpim_2 = "f00001e4Q-Q",
xstdivdp_3 = "f00001e8XQQ",
xvaddsp_3 = "f0000200QQQ",
xvmaddasp_3 = "f0000208QQQ",
xvcmpeqsp_3 = "f0000218QQQ",
xvcvspuxws_2 = "f0000220Q-Q",
xvrspi_2 = "f0000224Q-Q",
xvrsqrtesp_2 = "f0000228Q-Q",
xvsqrtsp_2 = "f000022cQ-Q",
xvsubsp_3 = "f0000240QQQ",
xvmaddmsp_3 = "f0000248QQQ",
xvcmpgtsp_3 = "f0000258QQQ",
xvcvspsxws_2 = "f0000260Q-Q",
xvrspiz_2 = "f0000264Q-Q",
xvresp_2 = "f0000268Q-Q",
xvmulsp_3 = "f0000280QQQ",
xvmsubasp_3 = "f0000288QQQ",
xxspltw_3 = "f0000290QQg~",
xvcmpgesp_3 = "f0000298QQQ",
xvcvuxwsp_2 = "f00002a0Q-Q",
xvrspip_2 = "f00002a4Q-Q",
xvtsqrtsp_2 = "f00002a8X-Q",
xvrspic_2 = "f00002acQ-Q",
xvdivsp_3 = "f00002c0QQQ",
xvmsubmsp_3 = "f00002c8QQQ",
xvcvsxwsp_2 = "f00002e0Q-Q",
xvrspim_2 = "f00002e4Q-Q",
xvtdivsp_3 = "f00002e8XQQ",
xvadddp_3 = "f0000300QQQ",
xvmaddadp_3 = "f0000308QQQ",
xvcmpeqdp_3 = "f0000318QQQ",
xvcvdpuxws_2 = "f0000320Q-Q",
xvrdpi_2 = "f0000324Q-Q",
xvrsqrtedp_2 = "f0000328Q-Q",
xvsqrtdp_2 = "f000032cQ-Q",
xvsubdp_3 = "f0000340QQQ",
xvmaddmdp_3 = "f0000348QQQ",
xvcmpgtdp_3 = "f0000358QQQ",
xvcvdpsxws_2 = "f0000360Q-Q",
xvrdpiz_2 = "f0000364Q-Q",
xvredp_2 = "f0000368Q-Q",
xvmuldp_3 = "f0000380QQQ",
xvmsubadp_3 = "f0000388QQQ",
xvcmpgedp_3 = "f0000398QQQ",
xvcvuxwdp_2 = "f00003a0Q-Q",
xvrdpip_2 = "f00003a4Q-Q",
xvtsqrtdp_2 = "f00003a8X-Q",
xvrdpic_2 = "f00003acQ-Q",
xvdivdp_3 = "f00003c0QQQ",
xvmsubmdp_3 = "f00003c8QQQ",
xvcvsxwdp_2 = "f00003e0Q-Q",
xvrdpim_2 = "f00003e4Q-Q",
xvtdivdp_3 = "f00003e8XQQ",
xsnmaddasp_3 = "f0000408QQQ",
xxland_3 = "f0000410QQQ",
xscvdpsp_2 = "f0000424Q-Q",
xscvdpspn_2 = "f000042cQ-Q",
xsnmaddmsp_3 = "f0000448QQQ",
xxlandc_3 = "f0000450QQQ",
xsrsp_2 = "f0000464Q-Q",
xsnmsubasp_3 = "f0000488QQQ",
xxlor_3 = "f0000490QQQ",
xscvuxdsp_2 = "f00004a0Q-Q",
xsnmsubmsp_3 = "f00004c8QQQ",
xxlxor_3 = "f00004d0QQQ",
xscvsxdsp_2 = "f00004e0Q-Q",
xsmaxdp_3 = "f0000500QQQ",
xsnmaddadp_3 = "f0000508QQQ",
xxlnor_3 = "f0000510QQQ",
xscvdpuxds_2 = "f0000520Q-Q",
xscvspdp_2 = "f0000524Q-Q",
xscvspdpn_2 = "f000052cQ-Q",
xsmindp_3 = "f0000540QQQ",
xsnmaddmdp_3 = "f0000548QQQ",
xxlorc_3 = "f0000550QQQ",
xscvdpsxds_2 = "f0000560Q-Q",
xsabsdp_2 = "f0000564Q-Q",
xscpsgndp_3 = "f0000580QQQ",
xsnmsubadp_3 = "f0000588QQQ",
xxlnand_3 = "f0000590QQQ",
xscvuxddp_2 = "f00005a0Q-Q",
xsnabsdp_2 = "f00005a4Q-Q",
xsnmsubmdp_3 = "f00005c8QQQ",
xxleqv_3 = "f00005d0QQQ",
xscvsxddp_2 = "f00005e0Q-Q",
xsnegdp_2 = "f00005e4Q-Q",
xvmaxsp_3 = "f0000600QQQ",
xvnmaddasp_3 = "f0000608QQQ",
["xvcmpeqsp._3"] = "f0000618QQQ",
xvcvspuxds_2 = "f0000620Q-Q",
xvcvdpsp_2 = "f0000624Q-Q",
xvminsp_3 = "f0000640QQQ",
xvnmaddmsp_3 = "f0000648QQQ",
["xvcmpgtsp._3"] = "f0000658QQQ",
xvcvspsxds_2 = "f0000660Q-Q",
xvabssp_2 = "f0000664Q-Q",
xvcpsgnsp_3 = "f0000680QQQ",
xvnmsubasp_3 = "f0000688QQQ",
["xvcmpgesp._3"] = "f0000698QQQ",
xvcvuxdsp_2 = "f00006a0Q-Q",
xvnabssp_2 = "f00006a4Q-Q",
xvnmsubmsp_3 = "f00006c8QQQ",
xvcvsxdsp_2 = "f00006e0Q-Q",
xvnegsp_2 = "f00006e4Q-Q",
xvmaxdp_3 = "f0000700QQQ",
xvnmaddadp_3 = "f0000708QQQ",
["xvcmpeqdp._3"] = "f0000718QQQ",
xvcvdpuxds_2 = "f0000720Q-Q",
xvcvspdp_2 = "f0000724Q-Q",
xvmindp_3 = "f0000740QQQ",
xvnmaddmdp_3 = "f0000748QQQ",
["xvcmpgtdp._3"] = "f0000758QQQ",
xvcvdpsxds_2 = "f0000760Q-Q",
xvabsdp_2 = "f0000764Q-Q",
xvcpsgndp_3 = "f0000780QQQ",
xvnmsubadp_3 = "f0000788QQQ",
["xvcmpgedp._3"] = "f0000798QQQ",
xvcvuxddp_2 = "f00007a0Q-Q",
xvnabsdp_2 = "f00007a4Q-Q",
xvnmsubmdp_3 = "f00007c8QQQ",
xvcvsxddp_2 = "f00007e0Q-Q",
xvnegdp_2 = "f00007e4Q-Q",
-- Primary opcode 61:
stfdp_2 = "f4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 62:
stq_2 = "f8000002R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 63:
fdiv_3 = "fc000024FFF.",
fsub_3 = "fc000028FFF.",
fadd_3 = "fc00002aFFF.",
fsqrt_2 = "fc00002cF-F.",
fsel_4 = "fc00002eFFFF~.",
fre_2 = "fc000030F-F.",
fmul_3 = "fc000032FF-F.",
frsqrte_2 = "fc000034F-F.",
fmsub_4 = "fc000038FFFF~.",
fmadd_4 = "fc00003aFFFF~.",
fnmsub_4 = "fc00003cFFFF~.",
fnmadd_4 = "fc00003eFFFF~.",
fcmpu_3 = "fc000000XFF",
fcpsgn_3 = "fc000010FFF.",
fcmpo_3 = "fc000040XFF",
mtfsb1_1 = "fc00004cA",
fneg_2 = "fc000050F-F.",
mcrfs_2 = "fc000080XX",
mtfsb0_1 = "fc00008cA",
fmr_2 = "fc000090F-F.",
frsp_2 = "fc000018F-F.",
fctiw_2 = "fc00001cF-F.",
fctiwz_2 = "fc00001eF-F.",
ftdiv_2 = "fc000100X-F.",
fctiwu_2 = "fc00011cF-F.",
fctiwuz_2 = "fc00011eF-F.",
mtfsfi_2 = "fc00010cAA", -- NYI: upshift.
fnabs_2 = "fc000110F-F.",
ftsqrt_2 = "fc000140X-F.",
fabs_2 = "fc000210F-F.",
frin_2 = "fc000310F-F.",
friz_2 = "fc000350F-F.",
frip_2 = "fc000390F-F.",
frim_2 = "fc0003d0F-F.",
mffs_1 = "fc00048eF.",
-- NYI: mtfsf, mtfsb0, mtfsb1.
fctid_2 = "fc00065cF-F.",
fctidz_2 = "fc00065eF-F.",
fmrgow_3 = "fc00068cFFF",
fcfid_2 = "fc00069cF-F.",
fctidu_2 = "fc00075cF-F.",
fctiduz_2 = "fc00075eF-F.",
fmrgew_3 = "fc00078cFFF",
fcfidu_2 = "fc00079cF-F.",
daddq_3 = "fc000004F:F:F:.",
dquaq_4 = "fc000006F:F:F:Z.",
dmulq_3 = "fc000044F:F:F:.",
drrndq_4 = "fc000046F:F:F:Z.",
dscliq_3 = "fc000084F:F:6.",
dquaiq_4 = "fc000086SF:~F:Z.",
dscriq_3 = "fc0000c4F:F:6.",
drintxq_4 = "fc0000c61F:~F:Z.",
dcmpoq_3 = "fc000104XF:F:",
dtstexq_3 = "fc000144XF:F:",
dtstdcq_3 = "fc000184XF:6",
dtstdgq_3 = "fc0001c4XF:6",
drintnq_4 = "fc0001c61F:~F:Z.",
dctqpq_2 = "fc000204F:-F:.",
dctfixq_2 = "fc000244F:-F:.",
ddedpdq_3 = "fc000284ZF:~F:.",
dxexq_2 = "fc0002c4F:-F:.",
dsubq_3 = "fc000404F:F:F:.",
ddivq_3 = "fc000444F:F:F:.",
dcmpuq_3 = "fc000504XF:F:",
dtstsfq_3 = "fc000544XF:F:",
drdpq_2 = "fc000604F:-F:.",
dcffixq_2 = "fc000644F:-F:.",
denbcdq_3 = "fc000684YF:~F:.",
diexq_3 = "fc0006c4F:FF:.",
-- Primary opcode 4, SPE APU extension:
evaddw_3 = "10000200RRR",
evaddiw_3 = "10000202RAR~",
evsubw_3 = "10000204RRR~",
evsubiw_3 = "10000206RAR~",
evabs_2 = "10000208RR",
evneg_2 = "10000209RR",
evextsb_2 = "1000020aRR",
evextsh_2 = "1000020bRR",
evrndw_2 = "1000020cRR",
evcntlzw_2 = "1000020dRR",
evcntlsw_2 = "1000020eRR",
brinc_3 = "1000020fRRR",
evand_3 = "10000211RRR",
evandc_3 = "10000212RRR",
evxor_3 = "10000216RRR",
evor_3 = "10000217RRR",
evmr_2 = "10000217RR=",
evnor_3 = "10000218RRR",
evnot_2 = "10000218RR=",
eveqv_3 = "10000219RRR",
evorc_3 = "1000021bRRR",
evnand_3 = "1000021eRRR",
evsrwu_3 = "10000220RRR",
evsrws_3 = "10000221RRR",
evsrwiu_3 = "10000222RRA",
evsrwis_3 = "10000223RRA",
evslw_3 = "10000224RRR",
evslwi_3 = "10000226RRA",
evrlw_3 = "10000228RRR",
evsplati_2 = "10000229RS",
evrlwi_3 = "1000022aRRA",
evsplatfi_2 = "1000022bRS",
evmergehi_3 = "1000022cRRR",
evmergelo_3 = "1000022dRRR",
evcmpgtu_3 = "10000230XRR",
evcmpgtu_2 = "10000230-RR",
evcmpgts_3 = "10000231XRR",
evcmpgts_2 = "10000231-RR",
evcmpltu_3 = "10000232XRR",
evcmpltu_2 = "10000232-RR",
evcmplts_3 = "10000233XRR",
evcmplts_2 = "10000233-RR",
evcmpeq_3 = "10000234XRR",
evcmpeq_2 = "10000234-RR",
evsel_4 = "10000278RRRW",
evsel_3 = "10000278RRR",
evfsadd_3 = "10000280RRR",
evfssub_3 = "10000281RRR",
evfsabs_2 = "10000284RR",
evfsnabs_2 = "10000285RR",
evfsneg_2 = "10000286RR",
evfsmul_3 = "10000288RRR",
evfsdiv_3 = "10000289RRR",
evfscmpgt_3 = "1000028cXRR",
evfscmpgt_2 = "1000028c-RR",
evfscmplt_3 = "1000028dXRR",
evfscmplt_2 = "1000028d-RR",
evfscmpeq_3 = "1000028eXRR",
evfscmpeq_2 = "1000028e-RR",
evfscfui_2 = "10000290R-R",
evfscfsi_2 = "10000291R-R",
evfscfuf_2 = "10000292R-R",
evfscfsf_2 = "10000293R-R",
evfsctui_2 = "10000294R-R",
evfsctsi_2 = "10000295R-R",
evfsctuf_2 = "10000296R-R",
evfsctsf_2 = "10000297R-R",
evfsctuiz_2 = "10000298R-R",
evfsctsiz_2 = "1000029aR-R",
evfststgt_3 = "1000029cXRR",
evfststgt_2 = "1000029c-RR",
evfststlt_3 = "1000029dXRR",
evfststlt_2 = "1000029d-RR",
evfststeq_3 = "1000029eXRR",
evfststeq_2 = "1000029e-RR",
efsadd_3 = "100002c0RRR",
efssub_3 = "100002c1RRR",
efsabs_2 = "100002c4RR",
efsnabs_2 = "100002c5RR",
efsneg_2 = "100002c6RR",
efsmul_3 = "100002c8RRR",
efsdiv_3 = "100002c9RRR",
efscmpgt_3 = "100002ccXRR",
efscmpgt_2 = "100002cc-RR",
efscmplt_3 = "100002cdXRR",
efscmplt_2 = "100002cd-RR",
efscmpeq_3 = "100002ceXRR",
efscmpeq_2 = "100002ce-RR",
efscfd_2 = "100002cfR-R",
efscfui_2 = "100002d0R-R",
efscfsi_2 = "100002d1R-R",
efscfuf_2 = "100002d2R-R",
efscfsf_2 = "100002d3R-R",
efsctui_2 = "100002d4R-R",
efsctsi_2 = "100002d5R-R",
efsctuf_2 = "100002d6R-R",
efsctsf_2 = "100002d7R-R",
efsctuiz_2 = "100002d8R-R",
efsctsiz_2 = "100002daR-R",
efststgt_3 = "100002dcXRR",
efststgt_2 = "100002dc-RR",
efststlt_3 = "100002ddXRR",
efststlt_2 = "100002dd-RR",
efststeq_3 = "100002deXRR",
efststeq_2 = "100002de-RR",
efdadd_3 = "100002e0RRR",
efdsub_3 = "100002e1RRR",
efdcfuid_2 = "100002e2R-R",
efdcfsid_2 = "100002e3R-R",
efdabs_2 = "100002e4RR",
efdnabs_2 = "100002e5RR",
efdneg_2 = "100002e6RR",
efdmul_3 = "100002e8RRR",
efddiv_3 = "100002e9RRR",
efdctuidz_2 = "100002eaR-R",
efdctsidz_2 = "100002ebR-R",
efdcmpgt_3 = "100002ecXRR",
efdcmpgt_2 = "100002ec-RR",
efdcmplt_3 = "100002edXRR",
efdcmplt_2 = "100002ed-RR",
efdcmpeq_3 = "100002eeXRR",
efdcmpeq_2 = "100002ee-RR",
efdcfs_2 = "100002efR-R",
efdcfui_2 = "100002f0R-R",
efdcfsi_2 = "100002f1R-R",
efdcfuf_2 = "100002f2R-R",
efdcfsf_2 = "100002f3R-R",
efdctui_2 = "100002f4R-R",
efdctsi_2 = "100002f5R-R",
efdctuf_2 = "100002f6R-R",
efdctsf_2 = "100002f7R-R",
efdctuiz_2 = "100002f8R-R",
efdctsiz_2 = "100002faR-R",
efdtstgt_3 = "100002fcXRR",
efdtstgt_2 = "100002fc-RR",
efdtstlt_3 = "100002fdXRR",
efdtstlt_2 = "100002fd-RR",
efdtsteq_3 = "100002feXRR",
efdtsteq_2 = "100002fe-RR",
evlddx_3 = "10000300RR0R",
evldd_2 = "10000301R8",
evldwx_3 = "10000302RR0R",
evldw_2 = "10000303R8",
evldhx_3 = "10000304RR0R",
evldh_2 = "10000305R8",
evlwhex_3 = "10000310RR0R",
evlwhe_2 = "10000311R4",
evlwhoux_3 = "10000314RR0R",
evlwhou_2 = "10000315R4",
evlwhosx_3 = "10000316RR0R",
evlwhos_2 = "10000317R4",
evstddx_3 = "10000320RR0R",
evstdd_2 = "10000321R8",
evstdwx_3 = "10000322RR0R",
evstdw_2 = "10000323R8",
evstdhx_3 = "10000324RR0R",
evstdh_2 = "10000325R8",
evstwhex_3 = "10000330RR0R",
evstwhe_2 = "10000331R4",
evstwhox_3 = "10000334RR0R",
evstwho_2 = "10000335R4",
evstwwex_3 = "10000338RR0R",
evstwwe_2 = "10000339R4",
evstwwox_3 = "1000033cRR0R",
evstwwo_2 = "1000033dR4",
evmhessf_3 = "10000403RRR",
evmhossf_3 = "10000407RRR",
evmheumi_3 = "10000408RRR",
evmhesmi_3 = "10000409RRR",
evmhesmf_3 = "1000040bRRR",
evmhoumi_3 = "1000040cRRR",
evmhosmi_3 = "1000040dRRR",
evmhosmf_3 = "1000040fRRR",
evmhessfa_3 = "10000423RRR",
evmhossfa_3 = "10000427RRR",
evmheumia_3 = "10000428RRR",
evmhesmia_3 = "10000429RRR",
evmhesmfa_3 = "1000042bRRR",
evmhoumia_3 = "1000042cRRR",
evmhosmia_3 = "1000042dRRR",
evmhosmfa_3 = "1000042fRRR",
evmwhssf_3 = "10000447RRR",
evmwlumi_3 = "10000448RRR",
evmwhumi_3 = "1000044cRRR",
evmwhsmi_3 = "1000044dRRR",
evmwhsmf_3 = "1000044fRRR",
evmwssf_3 = "10000453RRR",
evmwumi_3 = "10000458RRR",
evmwsmi_3 = "10000459RRR",
evmwsmf_3 = "1000045bRRR",
evmwhssfa_3 = "10000467RRR",
evmwlumia_3 = "10000468RRR",
evmwhumia_3 = "1000046cRRR",
evmwhsmia_3 = "1000046dRRR",
evmwhsmfa_3 = "1000046fRRR",
evmwssfa_3 = "10000473RRR",
evmwumia_3 = "10000478RRR",
evmwsmia_3 = "10000479RRR",
evmwsmfa_3 = "1000047bRRR",
evmra_2 = "100004c4RR",
evdivws_3 = "100004c6RRR",
evdivwu_3 = "100004c7RRR",
evmwssfaa_3 = "10000553RRR",
evmwumiaa_3 = "10000558RRR",
evmwsmiaa_3 = "10000559RRR",
evmwsmfaa_3 = "1000055bRRR",
evmwssfan_3 = "100005d3RRR",
evmwumian_3 = "100005d8RRR",
evmwsmian_3 = "100005d9RRR",
evmwsmfan_3 = "100005dbRRR",
evmergehilo_3 = "1000022eRRR",
evmergelohi_3 = "1000022fRRR",
evlhhesplatx_3 = "10000308RR0R",
evlhhesplat_2 = "10000309R2",
evlhhousplatx_3 = "1000030cRR0R",
evlhhousplat_2 = "1000030dR2",
evlhhossplatx_3 = "1000030eRR0R",
evlhhossplat_2 = "1000030fR2",
evlwwsplatx_3 = "10000318RR0R",
evlwwsplat_2 = "10000319R4",
evlwhsplatx_3 = "1000031cRR0R",
evlwhsplat_2 = "1000031dR4",
evaddusiaaw_2 = "100004c0RR",
evaddssiaaw_2 = "100004c1RR",
evsubfusiaaw_2 = "100004c2RR",
evsubfssiaaw_2 = "100004c3RR",
evaddumiaaw_2 = "100004c8RR",
evaddsmiaaw_2 = "100004c9RR",
evsubfumiaaw_2 = "100004caRR",
evsubfsmiaaw_2 = "100004cbRR",
evmheusiaaw_3 = "10000500RRR",
evmhessiaaw_3 = "10000501RRR",
evmhessfaaw_3 = "10000503RRR",
evmhousiaaw_3 = "10000504RRR",
evmhossiaaw_3 = "10000505RRR",
evmhossfaaw_3 = "10000507RRR",
evmheumiaaw_3 = "10000508RRR",
evmhesmiaaw_3 = "10000509RRR",
evmhesmfaaw_3 = "1000050bRRR",
evmhoumiaaw_3 = "1000050cRRR",
evmhosmiaaw_3 = "1000050dRRR",
evmhosmfaaw_3 = "1000050fRRR",
evmhegumiaa_3 = "10000528RRR",
evmhegsmiaa_3 = "10000529RRR",
evmhegsmfaa_3 = "1000052bRRR",
evmhogumiaa_3 = "1000052cRRR",
evmhogsmiaa_3 = "1000052dRRR",
evmhogsmfaa_3 = "1000052fRRR",
evmwlusiaaw_3 = "10000540RRR",
evmwlssiaaw_3 = "10000541RRR",
evmwlumiaaw_3 = "10000548RRR",
evmwlsmiaaw_3 = "10000549RRR",
evmheusianw_3 = "10000580RRR",
evmhessianw_3 = "10000581RRR",
evmhessfanw_3 = "10000583RRR",
evmhousianw_3 = "10000584RRR",
evmhossianw_3 = "10000585RRR",
evmhossfanw_3 = "10000587RRR",
evmheumianw_3 = "10000588RRR",
evmhesmianw_3 = "10000589RRR",
evmhesmfanw_3 = "1000058bRRR",
evmhoumianw_3 = "1000058cRRR",
evmhosmianw_3 = "1000058dRRR",
evmhosmfanw_3 = "1000058fRRR",
evmhegumian_3 = "100005a8RRR",
evmhegsmian_3 = "100005a9RRR",
evmhegsmfan_3 = "100005abRRR",
evmhogumian_3 = "100005acRRR",
evmhogsmian_3 = "100005adRRR",
evmhogsmfan_3 = "100005afRRR",
evmwlusianw_3 = "100005c0RRR",
evmwlssianw_3 = "100005c1RRR",
evmwlumianw_3 = "100005c8RRR",
evmwlsmianw_3 = "100005c9RRR",
-- NYI: Book E instructions.
}
-- Add mnemonics for "." variants.
do
local t = {}
for k,v in pairs(map_op) do
if sub(v, -1) == "." then
local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2)
t[sub(k, 1, -3).."."..sub(k, -2)] = v2
end
end
for k,v in pairs(t) do
map_op[k] = v
end
end
-- Add more branch mnemonics.
for cond,c in pairs(map_cond) do
local b1 = "b"..cond
local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0)
-- bX[l]
map_op[b1.."_1"] = tohex(0x40800000 + c1).."K"
map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K"
map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K"
map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK"
map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK"
map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK"
-- bXlr[l]
map_op[b1.."lr_0"] = tohex(0x4c800020 + c1)
map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1)
map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1)
map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1)
-- bXctr[l]
map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X"
map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X"
map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X"
map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X"
end
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^r([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_fpr(expr)
local r = match(expr, "^f([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vr(expr)
local r = match(expr, "^v([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vs(expr)
local r = match(expr, "^vs([1-6]?[0-9])$")
if r then
r = tonumber(r)
if r <= 63 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_cr(expr)
local r = match(expr, "^cr([0-7])$")
if r then return tonumber(r) end
werror("bad condition register name `"..expr.."'")
end
local function parse_cond(expr)
local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$")
if r then
r = tonumber(r)
local c = map_cond[cond]
if c and c < 4 then return r*4+c end
end
werror("bad condition bit name `"..expr.."'")
end
local function parse_imm(imm, bits, shift, scale, signed)
local n = tonumber(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^[rfv]([1-3]?[0-9])$") or
match(imm, "^vs([1-6]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_shiftmask(imm, isshift)
local n = tonumber(imm)
if n then
if shr(n, 6) == 0 then
local lsb = band(imm, 31)
local msb = imm - lsb
return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb)
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^r([1-3]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
werror("NYI: parameterized 64 bit shift/mask")
end
end
local function parse_disp(disp)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 16, 0, 0, true)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_u5disp(disp, scale)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 5, 11, scale, false)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
map_op[".template__"] = function(params, template, nparams)
if not params then return sub(template, 9) end
local op = tonumber(sub(template, 1, 8), 16)
local n, rs = 1, 26
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions (rlwinm).
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
if p == "R" then
rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1
elseif p == "F" then
rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1
elseif p == "V" then
rs = rs - 5; op = op + shl(parse_vr(params[n]), rs); n = n + 1
elseif p == "Q" then
local vs = parse_vs(params[n]); n = n + 1; rs = rs - 5
local sh = rs == 6 and 2 or 3 + band(shr(rs, 1), 3)
op = op + shl(band(vs, 31), rs) + shr(band(vs, 32), sh)
elseif p == "q" then
local vs = parse_vs(params[n]); n = n + 1
op = op + shl(band(vs, 31), 21) + shr(band(vs, 32), 5)
elseif p == "A" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1
elseif p == "S" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1
elseif p == "I" then
op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1
elseif p == "U" then
op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1
elseif p == "D" then
op = op + parse_disp(params[n]); n = n + 1
elseif p == "2" then
op = op + parse_u5disp(params[n], 1); n = n + 1
elseif p == "4" then
op = op + parse_u5disp(params[n], 2); n = n + 1
elseif p == "8" then
op = op + parse_u5disp(params[n], 3); n = n + 1
elseif p == "C" then
rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1
elseif p == "X" then
rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1
elseif p == "1" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs, 0, false); n = n + 1
elseif p == "g" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs, 0, false); n = n + 1
elseif p == "3" then
rs = rs - 5; op = op + parse_imm(params[n], 3, rs, 0, false); n = n + 1
elseif p == "P" then
rs = rs - 5; op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "p" then
op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "6" then
rs = rs - 6; op = op + parse_imm(params[n], 6, rs, 0, false); n = n + 1
elseif p == "Y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+4, 0, false); n = n + 1
elseif p == "y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+3, 0, false); n = n + 1
elseif p == "Z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+3, 0, false); n = n + 1
elseif p == "z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+2, 0, false); n = n + 1
elseif p == "W" then
op = op + parse_cr(params[n]); n = n + 1
elseif p == "G" then
op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1
elseif p == "H" then
op = op + parse_shiftmask(params[n], true); n = n + 1
elseif p == "M" then
op = op + parse_shiftmask(params[n], false); n = n + 1
elseif p == "J" or p == "K" then
local mode, n, s = parse_label(params[n], false)
if p == "K" then n = n + 2048 end
waction("REL_"..mode, n, s, 1)
n = n + 1
elseif p == "0" then
if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end
elseif p == "=" or p == "%" then
local t = band(shr(op, p == "%" and rs+5 or rs), 31)
rs = rs - 5
op = op + shl(t, rs)
elseif p == "~" then
local mm = shl(31, rs)
local lo = band(op, mm)
local hi = band(op, shl(mm, 5))
op = op - lo - hi + shl(lo, 5) + shr(hi, 5)
elseif p == ":" then
if band(shr(op, rs), 1) ~= 0 then werror("register pair expected") end
elseif p == "-" then
rs = rs - 5
elseif p == "." then
-- Ignored.
else
assert(false)
end
end
wputpos(pos, op)
end
------------------------------------------------------------------------------
-- 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_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- 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])
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", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- 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
-- 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 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", 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))
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
------------------------------------------------------------------------------
| gpl-2.0 |
starlightknight/darkstar | scripts/zones/Valkurm_Dunes/IDs.lua | 8 | 4398 | -----------------------------------
-- Area: Valkurm_Dunes
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.VALKURM_DUNES] =
{
text =
{
NOTHING_HAPPENS = 141, -- Nothing happens...
ITEM_CANNOT_BE_OBTAINED = 6404, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6410, -- Obtained: <item>.
GIL_OBTAINED = 6411, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6413, -- Obtained key item: <keyitem>.
KEYITEM_LOST = 6414, -- Lost key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6424, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7071, -- Tallying conquest results...
BEASTMEN_BANNER = 7152, -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7230, -- You can't fish here.
DIG_THROW_AWAY = 7243, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7245, -- You dig and you dig, but find nothing.
SONG_RUNES_DEFAULT = 7330, -- Lyrics on the old monument sing the story of lovers torn apart.
UNLOCK_BARD = 7351, -- You can now become a bard!
SIGNPOST2 = 7359, -- Northeast: La Theine Plateau Southeast: Konschtat Highlands West: Selbina
SIGNPOST1 = 7360, -- Northeast: La Theine Plateau Southeast: Konschtat Highlands Southwest: Selbina
CONQUEST = 7370, -- You've earned conquest points!
AN_EMPTY_LIGHT_SWIRLS = 7748, -- An empty light swirls about the cave, eating away at the surroundings...
MONSTERS_KILLED_ADVENTURERS = 7824, -- Long ago, monsters killed many adventurers and merchants just off the coast here. If you find any vestige of the victims and return it to the sea, perhaps it would appease the spirits of the dead.
DYNA_NPC_DEFAULT_MESSAGE = 7850, -- You hear a mysterious, floating voice: Bring forth the <item>...
YOU_CANNOT_ENTER_DYNAMIS = 7862, -- You cannot enter Dynamis - [Dummy/San d'Oria/Bastok/Windurst/Jeuno/Beaucedine/Xarcabard/Valkurm/Buburimu/Qufim/Tavnazia] for <number> [day/days] (Vana'diel time).
PLAYERS_HAVE_NOT_REACHED_LEVEL = 7864, -- Players who have not reached level <number> are prohibited from entering Dynamis.
PLAYER_OBTAINS_ITEM = 8074, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 8075, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 8076, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 8077, -- You already possess that temporary item.
NO_COMBINATION = 8082, -- You were unable to enter a combination.
REGIME_REGISTERED = 10260, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 12314, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
VALKURM_EMPEROR_PH =
{
[17199434] = 17199438, -- -228.957 2.776 -101.226
[17199437] = 17199438, -- -264.829 -0.843 -91.306
[17199420] = 17199438, -- -95.250 -0.268 -49.386
[17199419] = 17199438, -- -144.284 -1.103 4.202
[17199435] = 17199438, -- -270.823 -2.168 -16.349
[17199436] = 17199438, -- -327.000 -1.000 -21.000
},
GOLDEN_BAT_PH =
{
[17199562] = 17199564, -- -804.502 -8.567 22.082
[17199563] = 17199564, -- -798.674 -8.672 19.204
[17199461] = 17199564, -- -296.679 -0.510 -164.298
},
MARCHELUTE = 17199566,
DOMAN = 17199567,
ONRYO = 17199568,
},
npc =
{
CASKET_BASE = 17199672,
SUNSAND_QM = 17199699,
OVERSEER_BASE = 17199709,
},
}
return zones[dsp.zone.VALKURM_DUNES] | gpl-3.0 |
starlightknight/darkstar | scripts/zones/The_Garden_of_RuHmet/mobs/Jailer_of_Faith.lua | 12 | 1159 | -----------------------------------
-- Area: The Garden of Ru'Hmet
-- NM: Jailer of Faith
-----------------------------------
local ID = require("scripts/zones/The_Garden_of_RuHmet/IDs")
mixins = {require("scripts/mixins/job_special")}
-----------------------------------
function onMobSpawn(mob)
-- Change animation to open
mob:AnimationSub(2)
end
function onMobFight(mob)
-- Forms: 0 = Closed 1 = Closed 2 = Open 3 = Closed
local randomTime = math.random(45,180)
local changeTime = mob:getLocalVar("changeTime")
if mob:getBattleTime() - changeTime > randomTime then
-- Change close to open.
if (mob:AnimationSub() == 1) then
mob:AnimationSub(2)
else -- Change from open to close
mob:AnimationSub(1)
end
mob:setLocalVar("changeTime", mob:getBattleTime())
end
end
function onMobDeath(mob)
end
function onMobDespawn(mob)
-- Move QM to random location
local pos = math.random(1, 5)
GetNPCByID(ID.npc.JAILER_OF_FAITH_QM):setPos(ID.npc.JAILER_OF_FAITH_QM_POS[pos][1], ID.npc.JAILER_OF_FAITH_QM_POS[pos][2], ID.npc.JAILER_OF_FAITH_QM_POS[pos][3])
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Pashhow_Marshlands_[S]/npcs/Cavernous_Maw.lua | 3 | 1434 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: Cavernous Maw
-- !pos 418 25 27 90
-- Teleports Players to Pashhow_Marshlands
-----------------------------------
package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/campaign");
require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (hasMawActivated(player,4) == 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: %u",csid);
-- printf("RESULT: %u",option);
if (option == 1) then
if (csid == 0x0064) then
player:addNationTeleport(MAW,16);
end
toMaw(player,16);
end
end; | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Castle_Oztroja/npcs/_475.lua | 3 | 1131 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _475 (Brass Door)
-- Involved in Mission: Magicite
-- !pos -99 24 -105 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 (npc:getAnimation() == 9) then
player:messageSpecial(ITS_LOCKED);
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 |
ironjade/DevStack | LanCom/DesignPattern/LUA/GeneralTree.lua | 1 | 2406 | #!/usr/local/bin/lua
--[[
Copyright (c) 2004 by Bruno R. Preiss, P.Eng.
$Author: brpreiss $
$Date: 2004/11/25 02:05:25 $
$RCSfile: GeneralTree.lua,v $
$Revision: 1.3 $
$Id: GeneralTree.lua,v 1.3 2004/11/25 02:05:25 brpreiss Exp $
--]]
require "Tree"
require "LinkedList"
--{
-- A general tree implemented using a linked-list of subtrees.
GeneralTree = Class.new("GeneralTree", Tree)
-- Constructs a general tree node that contains the given key.
-- @param key An object.
function GeneralTree.methods:initialize(key)
GeneralTree.super(self)
self.key = key
self.degree = 0
self.list = LinkedList.new()
end
-- Purges this general tree.
function GeneralTree.methods:purge()
self.list.purge()
self.degree = 0
end
--}>a
--{
-- The key in this general tree node.
GeneralTree:attr_reader("key")
-- Returns the specified subtree of this general tree node.
-- @param i An index.
function GeneralTree.methods:get_subtree(i)
if i < 0 or i >= self.degree then
error "IndexError"
end
ptr = self.list:get_head()
for j = 1, i do
ptr = ptr:get_succ()
end
return ptr:get_datum()
end
-- Attaches the given general tree to this general tree node.
-- @param t A general tree.
function GeneralTree.methods:attachSubtree(t)
self.list:append(t)
self.degree = self.degree + 1
end
-- Detaches and returns the specified subtree of this general tree node.
function GeneralTree.methods:detachSubtree(t)
self.list:extract(t)
self.degree = self.degree - 1
return t
end
--}>b
-- True if this general tree node is empty.
-- Alwasy returns false because general tree nodes cannot be empty.
function GeneralTree.methods:is_empty()
return false
end
-- True if this general tree node is a leaf.
function GeneralTree.methods:is_leaf()
return self.degree == 0
end
-- The degree of this general tree node.
GeneralTree:attr_reader("degree")
-- GeneralTree test program.
-- @param arg Command-line arguments.
function GeneralTree.main(arg)
print "GeneralTree test program."
print(GeneralTree)
local gt = GeneralTree.new(box'A')
gt:attachSubtree(GeneralTree.new(box'B'))
gt:attachSubtree(GeneralTree.new(box'C'))
gt:attachSubtree(GeneralTree.new(box'D'))
gt:attachSubtree(GeneralTree.new(box'E'))
Tree.test(gt)
return 0
end
if _REQUIREDNAME == nil then
os.exit( GeneralTree.main(arg) )
end
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Port_San_dOria/npcs/Portaure.lua | 17 | 1666 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Portaure
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradePortaure") == 0) then
player:messageSpecial(PORTAURE_DIALOG);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradePortaure",1);
player:messageSpecial(FLYER_ACCEPTED);
player:messageSpecial(FLYERS_HANDED,17 - player:getVar("FFR"));
player:tradeComplete();
elseif (player:getVar("tradePortaure") ==1) then
player:messageSpecial(FLYER_ALREADY);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x28b);
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 |
noname007/vanilla | vanilla/v/application.lua | 2 | 1855 | -- vanilla
local Error = require 'vanilla.v.error'
-- perf
local pairs = pairs
local pcall = pcall
local require = require
local setmetatable = setmetatable
local function buildconf(config)
local ok, sys_conf_or_error = pcall(function() return require('vanilla.sys.config') end)
if ok then
if config ~= nil then
for k,v in pairs(config) do sys_conf_or_error[k] = v end
end
else
sys_conf_or_error = config
end
ngx.app_name = sys_conf_or_error.name
ngx.app_root = sys_conf_or_error.app.root
ngx.app_version = sys_conf_or_error.version
return sys_conf_or_error
end
local Application = {}
function Application:lpcall( ... )
local ok, rs_or_error = pcall( ... )
if ok then
return rs_or_error
else
self:raise_syserror(rs_or_error)
end
end
function Application:new(config)
self.config = buildconf(config)
local instance = {
run = self.run,
bootstrap = self.bootstrap,
dispatcher = self:lpcall(function() return require('vanilla.v.dispatcher'):new(self) end)
}
setmetatable(instance, {__index = self})
return instance
end
function Application:bootstrap()
ngx.dispatcher = self.dispatcher
local lbootstrap = 'application.bootstrap'
if self.config['bootstrap'] ~= nil then
lbootstrap = self.config['bootstrap']
end
bootstrap = self:lpcall(function() return require(lbootstrap):new(self.dispatcher) end)
self:lpcall(function() bootstrap:bootstrap() end)
return self
end
function Application:run()
self:lpcall(function() return self.dispatcher:dispatch() end)
end
function Application:raise_syserror(err)
if type(err) == 'table' then
err = Error:new(err.code, err.msg)
end
ngx.say('<pre />')
ngx.say(pps(err))
ngx.eof()
end
return Application | mit |
mishin/Algorithm-Implementations | Josephus_Problem/Lua/Yonaba/josephus.lua | 26 | 1689 | -- Josephus problem implementation
-- See: http://en.wikipedia.org/wiki/Josephus_problem
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_recursive(n, k)
if n == 1 then return 1
else
return ((josephus_recursive(n-1,k)+k-1)%n)+1
end
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_loop(n, k)
local r, i = 0, 1
while i <= n do
r = (r + k) % i
i = i + 1
end
return r + 1
end
-- Private wrapper
local function j(n, k, s)
if n == 1 then return 1 end
local new_s = ((s or 1) + k - 2) % n + 1
local survivor = j(n - 1, k, new_s)
return survivor < new_s and survivor or survivor + 1
end
-- Returns the survivor
-- n : the initial number of people
-- k : the count for each step
-- returns : the survivor's number
local function josephus_elaborated(n, k)
return j(n, k, 1)
end
-- Returns the survivor (assumes the count is k = 2)
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_2(n)
return josephus_loop(n, 2)
end
-- Returns the survivor (assumes the count is k = 2)
-- Alternate implementation using logarithm.
-- n : the initial number of people
-- returns : the survivor's number
local function josephus_log_2(n)
return 2*(n - 2 ^ math.floor(math.log(n, 2)))+1
end
return {
recursive = josephus_recursive,
loop = josephus_loop,
elaborated = josephus_elaborated,
standard = josephus_2,
standard_log = josephus_log_2,
}
| mit |
starlightknight/darkstar | scripts/globals/mobskills/nerve_gas.lua | 12 | 1061 | ---------------------------------------------
-- Nerve Gas
--
-- Description: Inflicts curse and powerful poison dsp.effect.
-- Type: Magical
-- Wipes Shadows
-- Range: 10' Radial
---------------------------------------------
require("scripts/globals/monstertpmoves")
require("scripts/globals/settings")
require("scripts/globals/status")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getFamily() == 316) then -- PW
local mobSkin = mob:getModelId()
if (mobSkin == 1796) then
return 0
else
return 1
end
elseif (mob:getFamily() == 313) then -- Tinnin can use at will
return 0
else
if (mob:AnimationSub() == 0) then
return 0
else
return 1
end
end
end
function onMobWeaponSkill(target, mob, skill)
skill:setMsg(MobStatusEffectMove(mob, target, dsp.effect.CURSE_I, 50, 0, 420))
MobStatusEffectMove(mob, target, dsp.effect.POISON, 20, 3, 60)
return dsp.effect.CURSE_I
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/QuBia_Arena/mobs/Trion.lua | 10 | 1813 | -----------------------------------
-- Area: qubia arena
-- MOB: Trion
-- Ally during San d'Oria Mission 9-2
-----------------------------------
package.loaded["scripts/zones/QuBia_Arena/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/QuBia_Arena/TextIDs");
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:addMod(MOD_REGAIN, 30);
end
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:addListener("WEAPONSKILL_STATE_ENTER", "WS_START_MSG", function(mob, skillID)
-- Red Lotus Blade
if (skillID == 968) then
mob:showText(mob,RLB_PREPARE);
-- Flat Blade
elseif (skillID == 969) then
mob:showText(mob,FLAT_PREPARE);
-- Savage Blade
elseif (skillID == 970) then
mob:showText(mob,SAVAGE_PREPARE);
end
end);
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local wait = mob:getLocalVar("wait");
local ready = mob:getLocalVar("ready");
if (ready == 0 and wait > 40) then
local baseID = 17621014 + (mob:getBattlefield():getBattlefieldNumber() - 1) * 2;
mob:setLocalVar("ready", bit.band(baseID, 0xFFF));
mob:setLocalVar("wait", 0);
elseif (ready > 0) then
mob:addEnmity(GetMobByID(ready + bit.lshift(mob:getZoneID(), 12) + 0x1000000),0,1);
else
mob:setLocalVar("wait", wait+3);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
mob:getBattlefield():lose();
end;
| gpl-3.0 |
bshee/lua-interpreter | test/parser_test.lua | 1 | 4224 | require("init")
local test = require("unittest")
local parser = require("parser")
local Token = require("token")
local inspect = require("inspect")
-- Because laziness
local p = parser
test.addTest(function()
-- Test result toString
local r = parser.Result("value", 2)
test.assertEqual(tostring(r), "Result(value, 2)")
end)
test.addTest(function()
-- Test result equality
local r1 = parser.Result("value", 2)
local r2 = parser.Result("value", 2)
test.assertEqual(r1, r2)
end)
test.addTest("Reserved construction", function()
local r = parser.Reserved(1, "tag")
test.assertEqual(r.value, 1)
test.assertEqual(r.tag, "tag")
end)
test.addTest("Reserved apply", function()
local r = parser.Reserved(2, "tag2")
local tokens = {Token(2, "tag2")}
local result = r(tokens, 1)
test.assertEqual(result, parser.Result(2, 2))
end)
test.addTest("Reserved no match", function()
local r = parser.Reserved(3, "tag3")
local tokens = {Token(2, "tag2")}
local result = r(tokens, 1)
test.assertEqual(result, nil)
test.assertEqual(r({}, 1), nil)
end)
test.addTest("Tag apply", function()
local tag = parser.Tag("tag1")
local tokens = {nil, nil, Token(1, "tag1")}
test.assertEqual(tag(tokens, 3), parser.Result(1, 4))
end)
test.addTest("Concat apply", function()
local tag1 = parser.Tag("first")
local tag2 = parser.Tag("second")
local concat = parser.Concat(tag1, tag2)
local tokens = {Token(10, "first"), Token(11, "second")}
local r = concat(tokens, 1)
test.assertEqual(r, parser.Result({10, 11}, 3))
end)
test.addTest("Alternate left only", function()
local alt = parser.Alternate(parser.Tag("simple"), parser.Tag("no"))
test.assertEqual(
alt({Token("value", "simple")}, 1),
parser.Result("value", 2)
)
end)
test.addTest("Alternate right only", function()
local alt = parser.Alternate(parser.Tag("no"), parser.Tag("simple"))
test.assertEqual(
alt({Token("value2", "simple")}, 1),
parser.Result("value2", 2)
)
end)
test.addTest("Opt correct parse", function()
local opt = parser.Opt(parser.Tag("simple"))
test.assertEqual(
opt({Token("optical", "simple")}, 1),
parser.Result("optical", 2)
)
end)
test.addTest("Opt no parse", function()
local opt = parser.Opt(parser.Tag("no"))
test.assertEqual(
opt({Token("noway", "nuh")}, 1),
parser.Result(nil, 1)
)
end)
test.addTest("Rep correct parse", function()
local rep = parser.Rep(parser.Tag("simple"))
test.assertEqual(
rep({Token(1, "simple"), Token(2, "simple")}, 1),
parser.Result({1, 2}, 3)
)
end)
test.addTest("Process apply", function()
local process = p.Process(p.Tag("simple"), function(value)
return value * 2 + 1
end)
test.assertEqual(
process({Token(10, "simple")}, 1),
p.Result(21, 2)
)
end)
test.addTest("Lazy", function()
local check = 0
local lazy = p.Lazy(function()
check = check + 1
return p.Tag("simple")
end)
test.assertEqual(
lazy({Token(1, "simple")}, 1),
p.Result(1, 2)
)
lazy({Token(1, "simple")}, 1)
test.assertEqual(check, 1)
end)
test.addTest("Phrase consume all", function()
local phrase = p.Phrase(p.Rep(p.Tag("simple")))
local tokens = {Token(1, "simple"), Token(2, "simple"), Token(3, "simple")}
test.assertEqual(
phrase(tokens, 1),
p.Result({1, 2, 3}, 4)
)
end)
test.addTest("Phrase fail", function()
local phrase = p.Phrase(p.Rep(p.Tag("simple")))
local tokens = {Token(1, "simple"), Token(2, "complex"), Token(3, "simple")}
test.assertEqual(
phrase(tokens, 1),
nil
)
end)
test.addTest("Exp assign", function()
local assign = p.Reserved("x := 1", "assign")
local function processSep(parsed)
return function(left, right)
return {left, right}
end
end
local function compoundSep()
return p.Process(p.Reserved(";", "reserved"), processSep)
end
local exp = p.Exp(assign, compoundSep())
local tokens = {
Token("x := 1", "assign"),
Token(";", "reserved"),
Token("x := 1", "assign"),
Token(";", "reserved"),
Token("x := 1", "assign")
}
local result = exp(tokens, 1)
test.assertEqual(
result,
p.Result(
{{"x := 1", "x := 1"}, "x := 1"},
6
)
)
end)
test.runTests()
| mit |
starlightknight/darkstar | scripts/zones/Monastic_Cavern/npcs/Magicite.lua | 9 | 1319 | -----------------------------------
-- Area: Monastic Cavern
-- NPC: Magicite
-- Involved in Mission: Magicite
-- !pos -22 1 -66 150
-----------------------------------
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Monastic_Cavern/IDs")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
if player:getCurrentMission(player:getNation()) == 13 and not player:hasKeyItem(dsp.ki.MAGICITE_OPTISTONE) then
if player:getCharVar("Magicite") == 2 then
player:startEvent(0,1,1,1,1,1,1,1,1) -- play Lion part of the CS (this is last magicite)
else
player:startEvent(0) -- don't play Lion part of the CS
end
else
player:messageSpecial(ID.text.THE_MAGICITE_GLOWS_OMINOUSLY)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 0 then
if player:getCharVar("Magicite") == 2 then
player:setCharVar("Magicite",0)
else
player:setCharVar("Magicite",player:getCharVar("Magicite")+1)
end
player:setCharVar("MissionStatus",4)
player:addKeyItem(dsp.ki.MAGICITE_OPTISTONE)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.MAGICITE_OPTISTONE)
end
end | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Southern_San_dOria/npcs/Adaunel.lua | 9 | 1135 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Adaunel
-- General Info NPC
-- !pos 80 -7 -22 230
------------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getCharVar("tradeAdaunel") == 0) then
player:messageSpecial(ID.text.ADAUNEL_DIALOG);
player:addCharVar("FFR", -1)
player:setCharVar("tradeAdaunel",1);
player:messageSpecial(ID.text.FLYER_ACCEPTED);
player:tradeComplete();
elseif (player:getCharVar("tradeAdaunel") == 1) then
player:messageSpecial(ID.text.FLYER_ALREADY);
end
end
end;
function onTrigger(player,npc)
player:startEvent(656);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Aht_Urhgan_Whitegate/npcs/Asrahd.lua | 3 | 3066 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Asrahd
-- Type: Imperial Gate Guard
-- !pos 0.011 -1 10.587 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/besieged");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local merc_rank = getMercenaryRank(player)
if (merc_rank == 0) then
player:startEvent(0x0277,npc)
else
maps = getMapBitmask(player);
if (getAstralCandescence() == 1) then
maps = maps + 0x80000000;
end
x,y,z,w = getImperialDefenseStats();
player:startEvent(0x0276,player:getCurrency("imperial_standing"),maps,merc_rank,0,x,y,z,w);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0276 and option >= 1 and option <= 2049) then
itemid = getISPItem(option)
player:updateEvent(0,0,0,canEquip(player,itemid))
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x276) then
if (option == 0 or option == 16 or option == 32 or option == 48) then -- player chose sanction.
if (option ~= 0) then
player:delCurrency("imperial_standing", 100);
end
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
local duration = getSanctionDuration(player);
local subPower = 0; -- getImperialDefenseStats()
player:addStatusEffect(EFFECT_SANCTION,option / 16,0,duration,subPower); -- effect size 1 = regen, 2 = refresh, 3 = food.
player:messageSpecial(SANCTION);
elseif (option % 256 == 17) then -- player bought one of the maps
id = 1862 + (option - 17) / 256;
player:addKeyItem(id);
player:messageSpecial(KEYITEM_OBTAINED,id);
player:delCurrency("imperial_standing", 1000);
elseif (option <= 2049) then -- player bought item
item, price = getISPItem(option)
if (player:getFreeSlotsCount() > 0) then
player:delCurrency("imperial_standing", price);
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED,item);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item);
end
end
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/zones/Northern_San_dOria/npcs/Secodiand.lua | 11 | 1623 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Secodiand
-- Starts and Finishes Quest: Fear of the dark
-- !pos -160 -0 137 231
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
local ID = require("scripts/zones/Northern_San_dOria/IDs");
-----------------------------------
function onTrade(player,npc,trade)
--
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FEAR_OF_THE_DARK) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(922,2) and trade:getItemCount() == 2) then
player:startEvent(18);
end
end
--]]
end;
function onTrigger(player,npc)
local FearOfTheDark = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FEAR_OF_THE_DARK);
if (FearOfTheDark == QUEST_AVAILABLE) then
player:startEvent(19);
else
player:startEvent(17);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
--
if (csid == 19 and option == 1) then
player:addQuest(SANDORIA,dsp.quest.id.sandoria.FEAR_OF_THE_DARK);
elseif (csid == 18) then
player:tradeComplete();
player:addGil(GIL_RATE*200);
player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*200);
if (player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.FEAR_OF_THE_DARK) == QUEST_ACCEPTED) then
player:addFame(SANDORIA,30);
player:completeQuest(SANDORIA,dsp.quest.id.sandoria.FEAR_OF_THE_DARK);
else
player:addFame(SANDORIA,5);
end
end
--]]
end; | gpl-3.0 |
XanDDemoX/ESOFasterTravel | FasterTravel/worldmapinfocontrol.lua | 1 | 2922 | local InfoControl = {}
function InfoControl:AddCategory(control,data,categoryId,typeId,parentId)
if control == nil or data == nil or categoryId == nil then return end
ZO_ScrollList_AddCategory(control,categoryId,parentId)
typeId = data.typeId or typeId or 0
self:AddEntries(control,{data},typeId,parentId)
end
function InfoControl:GetCategoryHidden(control,categoryId)
if control == nil or categoryId == nil then return true end
return ZO_ScrollList_GetCategoryHidden(control,categoryId)
end
function InfoControl:SetCategoryHidden(control,categoryId,hidden)
if control == nil or categoryId == nil or hidden == nil then return end
if hidden == true then
ZO_ScrollList_HideCategory(control,categoryId)
else
ZO_ScrollList_ShowCategory(control,categoryId)
end
end
function InfoControl:Clear(...)
local count = select('#',...)
local control
for i=1,count do
control = select(i,...)
ZO_ScrollList_Clear(control)
end
end
function InfoControl:AddEntries(control,data,typeId,categoryId)
if control == nil or data == nil then return end
local count = #data
if count < 1 then return end
local scrollData = ZO_ScrollList_GetDataList(control)
for i,entry in ipairs(data) do
typeId = entry.typeId or typeId or 1
categoryId = entry.categoryId or categoryId
scrollData[#scrollData+1] = ZO_ScrollList_CreateDataEntry(typeId, entry,categoryId)
end
ZO_ScrollList_Commit(control)
end
function InfoControl:Refresh(...)
local count = select('#',...)
local control
for i=1,count do
control = select(i,...)
ZO_ScrollList_RefreshVisible(control)
end
end
function InfoControl:RowMouseDown(control, button)
if(button == 1) then
control.label:SetAnchor(LEFT, nil, LEFT, control.offsetX or 0, 1)
end
end
function InfoControl:RowMouseUp(control, button, upInside)
if(button == 1) then
control.label:SetAnchor(LEFT, nil, LEFT, control.offsetX or 0, 0)
end
if(upInside) then
local data = ZO_ScrollList_GetData(control)
if data.clicked then
data:clicked(control,button)
self:RowMouseClicked(control,data,button)
end
end
end
function InfoControl:RowMouseClicked(control,data,button)
end
function InfoControl:OnRefreshRow(control,data)
end
function InfoControl:RefreshRow(control,data)
if data ~= nil and data.refresh ~= nil then
data:refresh(control)
end
control.label:SetHidden(data == nil or (data.hidden ~= nil and data.hidden == true))
control.RowMouseDown = function(...) self:RowMouseDown(...) end
control.RowMouseUp = function(...) self:RowMouseUp(...) end
self:OnRefreshRow(control,data)
end
local WorldMapInfoControl = {}
FasterTravel.WorldMapInfoControl = WorldMapInfoControl
function WorldMapInfoControl.Initialise(control)
for k,v in pairs(InfoControl) do
control[k] = v
end
end
| unlicense |
starlightknight/darkstar | scripts/zones/Cloister_of_Storms/bcnms/trial_by_lightning.lua | 8 | 1535 | -----------------------------------
-- Area: Cloister of Storms
-- BCNM: Trial by Lightning
-----------------------------------
local ID = require("scripts/zones/Cloister_of_Storms/IDs")
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/quests")
require("scripts/globals/titles")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = (player:hasCompletedQuest(OTHER_AREAS_LOG, dsp.quest.id.otherAreas.TRIAL_BY_LIGHTNING)) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
player:delKeyItem(dsp.ki.TUNING_FORK_OF_LIGHTNING)
player:addKeyItem(dsp.ki.WHISPER_OF_STORMS)
player:addTitle(dsp.title.HEIR_OF_THE_GREAT_LIGHTNING)
player:messageSpecial(ID.text.KEYITEM_OBTAINED, dsp.ki.WHISPER_OF_STORMS)
end
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Northern_San_dOria/npcs/Gilipese.lua | 3 | 1039 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Gilipese
-- Type: Standard Dialogue NPC
-- @zone 231
-- !pos -155.088 0.000 120.300
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,GILIPESE_DIALOG);
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 |
starlightknight/darkstar | scripts/zones/Selbina/npcs/Elfriede.lua | 9 | 1300 | -----------------------------------
-- Area: Selbina
-- NPC: Elfriede
-- Involved In Quest: The Tenshodo Showdown
-- !pos 61 -15 10 248
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/npc_util")
-----------------------------------
function onTrade(player,npc,trade)
if npcUtil.tradeHas(trade, 4569) and player:getCharVar("theTenshodoShowdownCS") == 3 then -- Quadav Stew
player:startEvent(10004, 0, dsp.ki.TENSHODO_ENVELOPE, 4569)
end
end
function onTrigger(player,npc)
local theTenshodoShowdownCS = player:getCharVar("theTenshodoShowdownCS")
if theTenshodoShowdownCS == 2 then
player:startEvent(10002, 0, dsp.ki.TENSHODO_ENVELOPE, 4569) -- During Quest "The Tenshodo Showdown"
player:setCharVar("theTenshodoShowdownCS", 3)
elseif theTenshodoShowdownCS == 3 then
player:startEvent(10003, 0, 0, 4569)
else
player:startEvent(25) -- Standard dialog
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
if csid == 10004 then
player:setCharVar("theTenshodoShowdownCS", 4)
player:delKeyItem(dsp.ki.TENSHODO_ENVELOPE)
npcUtil.giveKeyItem(player, dsp.ki.SIGNED_ENVELOPE)
player:confirmTrade()
end
end | gpl-3.0 |
gedads/Neodynamis | scripts/zones/Aht_Urhgan_Whitegate/npcs/Kemha_Flasehp.lua | 3 | 2315 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Kemha Flasehp
-- Type: Fishing Normal/Adv. Image Support
-- !pos -28.4 -6 -98 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local guildMember = isGuildMember(player,5);
if (guildMember == 1) then
if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:tradeComplete();
player:startEvent(0x0283,8,0,0,0,188,0,6,0);
else
npc:showText(npc, IMAGE_SUPPORT_ACTIVE);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,5);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x0282,8,0,0,511,1,0,0,2184);
else
player:startEvent(0x0282,8,0,0,511,1,19267,0,2184);
end
else
player:startEvent(0x0282,0,0,0,0,0,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 == 0x0282 and option == 1) then
player:messageSpecial(IMAGE_SUPPORT,0,0,1);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600);
elseif (csid == 0x0283) then
player:messageSpecial(IMAGE_SUPPORT,0,0,0);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,2,0,7200);
end
end; | gpl-3.0 |
taschemann/kq-lives | scripts/global.lua | 2 | 10377 | -- Global functions available to all scripts
--! \name Progress indicators
-- PLEASE ADD TO THIS LIST IN ORDER!!!
P_START = 0
P_ODDWALL = 1
P_DARKIMPBOSS = 2
P_DYINGDUDE = 3
P_BUYCURE = 4
P_GETPARTNER = 5
P_PARTNER1 = 6
P_PARTNER2 = 7
P_SHOWBRIDGE = 8
P_TALKDERIG = 9
P_FIGHTONBRIDGE = 10
P_FELLINPIT = 11
P_EKLAWELCOME = 12
P_LOSERONBRIDGE = 13
P_ASLEEPONBRIDGE = 14
P_ALTARSWITCH = 15
P_KILLBLORD = 16
P_GOBLINITEM = 17
P_ORACLE = 18
P_FTOTAL = 19
P_FLOOR1 = 20
P_FLOOR2 = 21
P_FLOOR3 = 22
P_FLOOR4 = 23
--P_WSTONES = 24
--P_BSTONES = 25
P_WALL1 = 26
P_WALL2 = 27
P_WALL3 = 28
P_WALL4 = 29
P_DOOROPEN = 30
P_DOOROPEN2 = 31
P_TOWEROPEN = 32
P_DRAGONDOWN = 33
P_TREASUREROOM = 34
P_UNDEADJEWEL = 35
P_UCOIN = 36
P_CANCELROD = 37
P_PORTALGONE = 38
P_WARPEDTOT4 = 39
P_OLDPARTNER = 40
P_BOUGHTHOUSE = 41
P_TALKGELIK = 42
P_OPALHELMET = 43
P_FOUNDMAYOR = 44
P_TALK_TEMMIN = 45
P_EMBERSKEY = 46
P_FOUGHTGUILD = 47
P_GUILDSECRET = 48
P_SEECOLISEUM = 49
P_OPALSHIELD = 50
P_STONE1 = 51
P_STONE2 = 52
P_STONE3 = 53
P_STONE4 = 54
P_DENORIAN = 55
P_C4DOORSOPEN = 56
P_DEMNASDEAD = 57
P_FIRSTTIME = 58
P_ROUNDNUM = 59
P_BATTLESTATUS = 60
P_USEITEMINCOMBAT = 61
P_FINALPARTNER = 62
P_TALKGRAMPA = 63
P_SAVEBREANNE = 64
P_PASSGUARDS = 65
P_IRONKEY = 66
P_AVATARDEAD = 67
P_GIANTDEAD = 68
P_OPALBAND = 69
P_BRONZEKEY = 70
P_CAVEKEY = 71
P_TOWN6INN = 72
P_WARPSTONE = 73
P_DOINTRO = 74
P_GOTOFORT = 75
P_GOTOESTATE = 76
P_TALKBUTLER = 77
P_PASSDOOR1 = 78
P_PASSDOOR2 = 79
P_PASSDOOR3 = 80
P_BOMB1 = 81
P_BOMB2 = 82
P_BOMB3 = 83
P_BOMB4 = 84
P_BOMB5 = 85
P_DYNAMITE = 86
P_TALKRUFUS = 87
P_EARLYPROGRESS = 88
P_OPALDRAGONOUT = 89
P_OPALARMOUR = 90
-- /* These are to store who's waiting in the manor */
P_MANORPARTY = 91
P_MANORPARTY1 = 92
P_MANORPARTY2 = 93
P_MANORPARTY3 = 94
P_MANORPARTY4 = 95
P_MANORPARTY5 = 96
P_MANORPARTY6 = 97
P_MANORPARTY7 = 98
P_MANOR = 99
P_PLAYERS = 100
P_TALK_AJATHAR = 101
P_BLADE = 102
P_AYLA_QUEST = 103
P_BANGTHUMB = 104
P_WALKING = 105
P_MAYORGUARD1 = 106
P_MAYORGUARD2 = 107
P_TALK_TSORIN = 108
P_TALK_CORIN = 109
P_TALKOLDMAN = 110
P_ORACLEMONSTERS = 111
P_TRAVELPOINT = 112
-- /* side quests */
P_SIDEQUEST1 = 113
P_SIDEQUEST2 = 114
P_SIDEQUEST3 = 115
P_SIDEQUEST4 = 116
P_SIDEQUEST5 = 117
P_SIDEQUEST6 = 118
P_SIDEQUEST7 = 119
-- Item identifiers (empty for now. Defined in itemdefs.h)
-- Special Item definitions
SI_UCOIN = 0
SI_CANCELROD = 1
SI_JADEPENDANT = 2
SI_UNDEADJEWEL = 3
SI_WHITESTONE = 4
SI_BLACKSTONE = 5
SI_EMBERSKEY = 6
SI_BRONZEKEY = 7
SI_DENORIANSTATUE = 8
SI_OPALHELMET = 9
SI_OPALSHIELD = 10
SI_IRONKEY = 11
SI_OPALBAND = 12
SI_OPALARMOUR = 13
SI_CAVEKEY = 14
SI_NOTE_TSORIN = 15
SI_NOTE_DERIG = 16
SI_RUSTYKEY = 17
-- Facing directions, HERO1 and HERO2, and the Hero identifiers are all found
-- in code. These are duplicates. Avoid changing them.
-- Facing directions
FACE_DOWN = 0
FACE_UP = 1
FACE_LEFT = 2
FACE_RIGHT = 3
-- Special identifiers for bubble()
HERO1 = 200
HERO2 = 201
-- Hero identifiers
SENSAR = 0
SARINA = 1
CORIN = 2
AJATHAR = 3
CASANDRA = 4
TEMMIN = 5
AYLA = 6
NOSLOM = 7
-- gettext alias
_ = gettext
-- Add this hero to the manor if not already there
-- hero can be a single value or a table
-- returns the number of heroes that were actually added
function add_to_manor(hero)
local total, i
if (not hero) then
return 0
end
if (istable(hero)) then
total = 0
i = 1
while (hero[i]) do
total = total + add_to_manor(hero[i])
i = i + 1
end
return total
else
if (hero < 0 or hero > 7) then
return 0
end
for i = 0, 7 do
if (get_progress(i + P_MANORPARTY) == (hero + 1)) then
return 0
end
end
for i = 0, 7 do
if (get_progress(i + P_MANORPARTY) == 0) then
set_progress(i + P_MANORPARTY, hero + 1)
return 1
end
end
end
end
-- Display bubble text; just concatenate all the args and call the _ex function
-- Args ent Entity number
-- ... Variable number of arguments - text to show
function bubble(ent, ...)
s = ""
for i = 1, arg.n do
if (i ~= 1) then
s = s.."\n"
end
s = s..arg[i]
end
bubble_ex(ent, s)
end
-- See function bubble()
function thought(ent, ...)
s = ""
for i = 1, arg.n do
if (i ~= 1) then
s = s.."\n"..arg[i]
else
s = s..arg[i]
end
end
thought_ex(ent, s)
end
function get_quest_info()
if LOC_add_quest_item then
LOC_add_quest_item()
end
add_quest_item("About...", "This doesn't do much yet")
add_quest_item("Test1", "Some test info")
add_quest_item("Sensar", "He rages!")
end
-- backward compat
change_mapm = change_map
-- Checks if this ent is in the party, or in the manor,
-- or has never been recruited.
-- who: hero id
-- returns "manor" if in manor, "party" if in party, nil otherwise
function LOC_manor_or_party(who)
local a
if (get_pidx(0) == who) then
return "party"
elseif (get_numchrs() > 1 and get_pidx(1) == who) then
return "party"
end
for a = P_MANORPARTY, P_MANORPARTY7 do
if (get_progress(a) - 1 == who) then
return "manor"
end
end
return nil
end
-- Pick one of the args
-- If arg is a table it can have a pr field which gives
-- its probability of being picked
-- e.g. print(pick(1,2,3))
-- pick({pr = 5, name = "Rare"}, {pr = 95, name = "Common"}).name
function pick(...)
cumprob = 0
for i = 1, arg.n do
if (istable(arg[i]) ) then
prob = arg[i].pr or 1
else
prob = 1
end
cumprob = cumprob + prob
end
cumprob = krnd(cumprob)
for i = 1, arg.n do
if (istable(arg[i]) ) then
prob = arg[i].pr or 1
else
prob = 1
end
cumprob = cumprob - prob
if (cumprob < 0) then
return arg[i]
end
end
end
-- Select from heroes in the manor
-- The available list is stored in eight consecutive P_ constants
-- as 0 for nobody and 1..8 for characters 0..7
function select_manor()
-- Get the current list
heroes = {}
for i = 1, 8 do
v = get_progress(i + P_MANORPARTY - 1)
if (v ~= 0) then
heroes[i] = v - 1
end
end
-- Do the selecting
heroes = select_team(heroes)
-- Put back in the list
for i = 1, 8 do
if (heroes[i]) then
v = heroes[i] + 1
else
v = 0
end
set_progress(i + P_MANORPARTY - 1, v)
end
end
-- Response for reading a book.
function book_talk(ent)
if (party[0] == Sensar) then
bubble(HERO1, pick(_"Reading makes me sleepy...",
_"So many books...",
_"Reading is for wimps."))
elseif (party[0] == Temmin) then
bubble(HERO1, pick(_"If only I had more time...",
_"So many books...",
_"Some of these are pretty old."))
elseif (party[0] == Sarina) then
bubble(HERO1, pick(_"Ugh... this would take me forever to read.",
_"I never liked reading.",
_"Who wrote this trash?"))
elseif (party[0] == Noslom) then
bubble(HERO1, pick(_"Fascinating.",
_"I have this one.",
_"Romance novels... gack!"))
elseif (party[0] == Ajathar) then
bubble(HERO1, pick(_"Hmmm... I don't approve of that.",
_"I'm too busy to read now.",
_"How many books can you write that start with 'The Joy of...'?"))
elseif (party[0] == Ayla) then
bubble(HERO1, pick(_"I don't have time for this.",
_"What language is this written in?",
_"The pages are stuck together!?"))
elseif (party[0] == Casandra) then
bubble(HERO1, pick(_"Boring.",
_"Somebody should burn these.",
_"Terrible... just terrible."))
elseif (party[0] == Corin) then
bubble(HERO1, pick(_"Doesn't anybody leave spellbooks lying around?",
_"Why would I read this?",
_"Can't talk... reading."))
else
msg("Script Error. global.lua:book_talk()", 255, 0)
end
end
-- This function can be called whenever the hero touches a fire
function touch_fire(ent)
local x
if (party[0] == Sensar) then
bubble(HERO1, pick(_"What th..? Ouch! That's hot!",
_"There's no way I'm sticking my hand in that fire!",
_"This feels pretty nice."))
elseif (party[0] == Temmin) then
bubble(HERO1, pick(_"Ah, the age-old fire.",
_"This needs more coal.",
_"This would be great to read a book next to."))
elseif (party[0] == Sarina) then
bubble(HERO1, pick(_"Mmm, wood smoke.",
_"Smells like burnt hair. Hey wait... that's MY hair!",
_"Ooh, cozy."))
elseif (party[0] == Noslom) then
bubble(HERO1, pick(_"I prefer torches.",
_"I love the crackle of a good fire.",
_"I wonder if a spell would make this burn brighter?"))
elseif (party[0] == Ajathar) then
bubble(HERO1, pick(_"Hmm... I want marshmallows.",
_"You call this a fire?!",
_"Ah, relaxing."))
elseif (party[0] == Ayla) then
bubble(HERO1, pick(_"I wonder how hot this is?",
_"Someone should clean all this soot out of here.",
_"Well, my face is warm now, but my butt is still freezing!"))
elseif (party[0] == Casandra) then
bubble(HERO1, pick(_"Something's burning. I hope it's one of those stupid books!",
_"The fire is getting low.",
_"Yessir, this is a fire."))
elseif (party[0] == Corin) then
bubble(HERO1, pick(_"I sure like fire.",
_"Watching this is relaxing.",
_"This is making me sleepy."))
else
msg("Script Error. global.lua:touch_fire()", 255, 0)
end
end
| gpl-2.0 |
starlightknight/darkstar | scripts/globals/weaponskills/rampage.lua | 10 | 1509 | -----------------------------------
-- Rampage
-- Axe weapon skill
-- Skill level: 175
-- Delivers a five-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: None
-- Modifiers: STR:50%
-- 100%TP 200%TP 300%TP
-- 1 1 1
-----------------------------------
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 = 5
params.ftp100 = 0.5 params.ftp200 = 0.5 params.ftp300 = 0.5
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0
params.crit100 = 0.10 params.crit200 = 0.30 params.crit300 = 0.50
params.canCrit = true
params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1 params.ftp200 = 1 params.ftp300 = 1
params.str_wsc = 0.5
params.crit100 = 0.0 params.crit200 = 0.20 params.crit300 = 0.40
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
Craige/prosody-modules | mod_muc_limits/mod_muc_limits.lua | 10 | 3327 |
local mod_muc = module:depends"muc";
local rooms = rawget(mod_muc, "rooms"); -- Old MUC API
if not rooms then
rooms = module:shared"muc/rooms"; -- New MUC API
end
local jid_split, jid_bare = require "util.jid".split, require "util.jid".bare;
local st = require "util.stanza";
local new_throttle = require "util.throttle".create;
local t_insert, t_concat = table.insert, table.concat;
local xmlns_muc = "http://jabber.org/protocol/muc";
local period = math.max(module:get_option_number("muc_event_rate", 0.5), 0);
local burst = math.max(module:get_option_number("muc_burst_factor", 6), 1);
local max_nick_length = module:get_option_number("muc_max_nick_length", 23); -- Default chosen through scientific methods
local dropped_count = 0;
local dropped_jids;
local function log_dropped()
module:log("warn", "Dropped %d stanzas from %d JIDs: %s", dropped_count, #dropped_jids, t_concat(dropped_jids, ", "));
dropped_count = 0;
dropped_jids = nil;
end
local function handle_stanza(event)
local origin, stanza = event.origin, event.stanza;
if stanza.name == "presence" and stanza.attr.type == "unavailable" then -- Don't limit room leaving
return;
end
local dest_room, dest_host, dest_nick = jid_split(stanza.attr.to);
local room = rooms[dest_room.."@"..dest_host];
if not room then return; end
local from_jid = stanza.attr.from;
local occupant = room._occupants[room._jid_nick[from_jid]];
if (occupant and occupant.affiliation) or (not(occupant) and room._affiliations[jid_bare(from_jid)]) then
module:log("debug", "Skipping stanza from affiliated user...");
return;
elseif dest_nick and max_nick_length and stanza.name == "presence" and not room._occupants[stanza.attr.to] and #dest_nick > max_nick_length then
module:log("debug", "Forbidding long (%d bytes) nick in %s", #dest_nick, dest_room)
origin.send(st.error_reply(stanza, "modify", "policy-violation", "Your nick name is too long, please use a shorter one")
:up():tag("x", { xmlns = xmlns_muc }));
return true;
end
local throttle = room.throttle;
if not room.throttle then
throttle = new_throttle(period*burst, burst);
room.throttle = throttle;
end
if not throttle:poll(1) then
module:log("debug", "Dropping stanza for %s@%s from %s, over rate limit", dest_room, dest_host, from_jid);
if not dropped_jids then
dropped_jids = { [from_jid] = true, from_jid };
module:add_timer(5, log_dropped);
elseif not dropped_jids[from_jid] then
dropped_jids[from_jid] = true;
t_insert(dropped_jids, from_jid);
end
dropped_count = dropped_count + 1;
if stanza.attr.type == "error" then -- We don't want to bounce errors
return true;
end
local reply = st.error_reply(stanza, "wait", "policy-violation", "The room is currently overactive, please try again later");
local body = stanza:get_child_text("body");
if body then
reply:up():tag("body"):text(body):up();
end
local x = stanza:get_child("x", xmlns_muc);
if x then
reply:add_child(st.clone(x));
end
origin.send(reply);
return true;
end
end
function module.unload()
for room_jid, room in pairs(rooms) do
room.throttle = nil;
end
end
module:hook("message/bare", handle_stanza, 501);
module:hook("message/full", handle_stanza, 501);
module:hook("presence/bare", handle_stanza, 501);
module:hook("presence/full", handle_stanza, 501);
| mit |
gedads/Neodynamis | scripts/zones/West_Ronfaure/npcs/qm2.lua | 3 | 1487 | -----------------------------------
-- Area: West Ronfaure
-- NPC: qm2 (???)
-- Involved in Quest: The Dismayed Customer
-- !pos -550 -0 -542 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/West_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA, THE_DISMAYED_CUSTOMER) == QUEST_ACCEPTED and player:getVar("theDismayedCustomer") == 2) then
player:addKeyItem(GULEMONTS_DOCUMENT);
player:messageSpecial(KEYITEM_OBTAINED, GULEMONTS_DOCUMENT);
player:setVar("theDismayedCustomer", 0);
else
player:messageSpecial(DISMAYED_CUSTOMER);
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 |
soccermitchy/heroku-lapis | opt/src/openresty/bundle/LuaJIT-2.1-20150223/src/jit/p.lua | 65 | 9092 | ----------------------------------------------------------------------------
-- LuaJIT profiler.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module is a simple command line interface to the built-in
-- low-overhead profiler of LuaJIT.
--
-- The lower-level API of the profiler is accessible via the "jit.profile"
-- module or the luaJIT_profile_* C API.
--
-- Example usage:
--
-- luajit -jp myapp.lua
-- luajit -jp=s myapp.lua
-- luajit -jp=-s myapp.lua
-- luajit -jp=vl myapp.lua
-- luajit -jp=G,profile.txt myapp.lua
--
-- The following dump features are available:
--
-- f Stack dump: function name, otherwise module:line. Default mode.
-- F Stack dump: ditto, but always prepend module.
-- l Stack dump: module:line.
-- <number> stack dump depth (callee < caller). Default: 1.
-- -<number> Inverse stack dump depth (caller > callee).
-- s Split stack dump after first stack level. Implies abs(depth) >= 2.
-- p Show full path for module names.
-- v Show VM states. Can be combined with stack dumps, e.g. vf or fv.
-- z Show zones. Can be combined with stack dumps, e.g. zf or fz.
-- r Show raw sample counts. Default: show percentages.
-- a Annotate excerpts from source code files.
-- A Annotate complete source code files.
-- G Produce raw output suitable for graphical tools (e.g. flame graphs).
-- m<number> Minimum sample percentage to be shown. Default: 3.
-- i<number> Sampling interval in milliseconds. Default: 10.
--
----------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local profile = require("jit.profile")
local vmdef = require("jit.vmdef")
local math = math
local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor
local sort, format = table.sort, string.format
local stdout = io.stdout
local zone -- Load jit.zone module on demand.
-- Output file handle.
local out
------------------------------------------------------------------------------
local prof_ud
local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth
local prof_ann, prof_count1, prof_count2, prof_samples
local map_vmmode = {
N = "Compiled",
I = "Interpreted",
C = "C code",
G = "Garbage Collector",
J = "JIT Compiler",
}
-- Profiler callback.
local function prof_cb(th, samples, vmmode)
prof_samples = prof_samples + samples
local key_stack, key_stack2, key_state
-- Collect keys for sample.
if prof_states then
if prof_states == "v" then
key_state = map_vmmode[vmmode] or vmmode
else
key_state = zone:get() or "(none)"
end
end
if prof_fmt then
key_stack = profile.dumpstack(th, prof_fmt, prof_depth)
key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x)
return vmdef.ffnames[tonumber(x)]
end)
if prof_split == 2 then
local k1, k2 = key_stack:match("(.-) [<>] (.*)")
if k2 then key_stack, key_stack2 = k1, k2 end
elseif prof_split == 3 then
key_stack2 = profile.dumpstack(th, "l", 1)
end
end
-- Order keys.
local k1, k2
if prof_split == 1 then
if key_state then
k1 = key_state
if key_stack then k2 = key_stack end
end
elseif key_stack then
k1 = key_stack
if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end
end
-- Coalesce samples in one or two levels.
if k1 then
local t1 = prof_count1
t1[k1] = (t1[k1] or 0) + samples
if k2 then
local t2 = prof_count2
local t3 = t2[k1]
if not t3 then t3 = {}; t2[k1] = t3 end
t3[k2] = (t3[k2] or 0) + samples
end
end
end
------------------------------------------------------------------------------
-- Show top N list.
local function prof_top(count1, count2, samples, indent)
local t, n = {}, 0
for k, v in pairs(count1) do
n = n + 1
t[n] = k
end
sort(t, function(a, b) return count1[a] > count1[b] end)
for i=1,n do
local k = t[i]
local v = count1[k]
local pct = floor(v*100/samples + 0.5)
if pct < prof_min then break end
if not prof_raw then
out:write(format("%s%2d%% %s\n", indent, pct, k))
elseif prof_raw == "r" then
out:write(format("%s%5d %s\n", indent, v, k))
else
out:write(format("%s %d\n", k, v))
end
if count2 then
local r = count2[k]
if r then
prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or
(prof_depth < 0 and " -> " or " <- "))
end
end
end
end
-- Annotate source code
local function prof_annotate(count1, samples)
local files = {}
local ms = 0
for k, v in pairs(count1) do
local pct = floor(v*100/samples + 0.5)
ms = math.max(ms, v)
if pct >= prof_min then
local file, line = k:match("^(.*):(%d+)$")
local fl = files[file]
if not fl then fl = {}; files[file] = fl; files[#files+1] = file end
line = tonumber(line)
fl[line] = prof_raw and v or pct
end
end
sort(files)
local fmtv, fmtn = " %3d%% | %s\n", " | %s\n"
if prof_raw then
local n = math.max(5, math.ceil(math.log10(ms)))
fmtv = "%"..n.."d | %s\n"
fmtn = (" "):rep(n).." | %s\n"
end
local ann = prof_ann
for _, file in ipairs(files) do
local f0 = file:byte()
if f0 == 40 or f0 == 91 then
out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file))
break
end
local fp, err = io.open(file)
if not fp then
out:write(format("====== ERROR: %s: %s\n", file, err))
break
end
out:write(format("\n====== %s ======\n", file))
local fl = files[file]
local n, show = 1, false
if ann ~= 0 then
for i=1,ann do
if fl[i] then show = true; out:write("@@ 1 @@\n"); break end
end
end
for line in fp:lines() do
if line:byte() == 27 then
out:write("[Cannot annotate bytecode file]\n")
break
end
local v = fl[n]
if ann ~= 0 then
local v2 = fl[n+ann]
if show then
if v2 then show = n+ann elseif v then show = n
elseif show+ann < n then show = false end
elseif v2 then
show = n+ann
out:write(format("@@ %d @@\n", n))
end
if not show then goto next end
end
if v then
out:write(format(fmtv, v, line))
else
out:write(format(fmtn, line))
end
::next::
n = n + 1
end
fp:close()
end
end
------------------------------------------------------------------------------
-- Finish profiling and dump result.
local function prof_finish()
if prof_ud then
profile.stop()
local samples = prof_samples
if samples == 0 then
if prof_raw ~= true then out:write("[No samples collected]\n") end
return
end
if prof_ann then
prof_annotate(prof_count1, samples)
else
prof_top(prof_count1, prof_count2, samples, "")
end
prof_count1 = nil
prof_count2 = nil
prof_ud = nil
end
end
-- Start profiling.
local function prof_start(mode)
local interval = ""
mode = mode:gsub("i%d*", function(s) interval = s; return "" end)
prof_min = 3
mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end)
prof_depth = 1
mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end)
local m = {}
for c in mode:gmatch(".") do m[c] = c end
prof_states = m.z or m.v
if prof_states == "z" then zone = require("jit.zone") end
local scope = m.l or m.f or m.F or (prof_states and "" or "f")
local flags = (m.p or "")
prof_raw = m.r
if m.s then
prof_split = 2
if prof_depth == -1 or m["-"] then prof_depth = -2
elseif prof_depth == 1 then prof_depth = 2 end
elseif mode:find("[fF].*l") then
scope = "l"
prof_split = 3
else
prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0
end
prof_ann = m.A and 0 or (m.a and 3)
if prof_ann then
scope = "l"
prof_fmt = "pl"
prof_split = 0
prof_depth = 1
elseif m.G and scope ~= "" then
prof_fmt = flags..scope.."Z;"
prof_depth = -100
prof_raw = true
prof_min = 0
elseif scope == "" then
prof_fmt = false
else
local sc = prof_split == 3 and m.f or m.F or scope
prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ")
end
prof_count1 = {}
prof_count2 = {}
prof_samples = 0
profile.start(scope:lower()..interval, prof_cb)
prof_ud = newproxy(true)
getmetatable(prof_ud).__gc = prof_finish
end
------------------------------------------------------------------------------
local function start(mode, outfile)
if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stdout
end
prof_start(mode or "f")
end
-- Public module functions.
return {
start = start, -- For -j command line option.
stop = prof_finish
}
| gpl-2.0 |
gedads/Neodynamis | scripts/zones/Northern_San_dOria/npcs/Synergy_Engineer.lua | 3 | 1068 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Synergy Engineer
-- Type: Standard NPC
-- @zone 231
-- !pos -123.000 10.5 244.000
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2afa);
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 |
hades2013/openwrt-mtk | package/ralink/ui/luci-mtk/src/protocols/ppp/luasrc/model/cbi/admin_network/proto_pppoe.lua | 59 | 3798 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local map, section, net = ...
local username, password, ac, service
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
ac = section:taboption("general", Value, "ac",
translate("Access Concentrator"),
translate("Leave empty to autodetect"))
ac.placeholder = translate("auto")
service = section:taboption("general", Value, "service",
translate("Service Name"),
translate("Leave empty to autodetect"))
service.placeholder = translate("auto")
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
function keepalive_failure.write() end
function keepalive_failure.remove() end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| gpl-2.0 |
Lymia/MPPatch | src/patch/ui/hooks/frontend/mainmenu/mainmenu_status.lua | 3 | 1824 | -- Copyright (c) 2015-2017 Lymia Alusyia <lymia@lymiahugs.com>
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
-- THE SOFTWARE.
local success, error = pcall(function()
local versionString
if not _mpPatch then
versionString = Locale.Lookup("TXT_KEY_MPPATCH_UNKNOWN_FAILURE")
elseif not _mpPatch.loaded and _mpPatch.status.binaryLoadFailed then
versionString = Locale.Lookup("TXT_KEY_MPPATCH_BINARY_NOT_PATCHED")
elseif not _mpPatch.loaded then
versionString = Locale.Lookup("TXT_KEY_MPPATCH_UNKNOWN_FAILURE")
else
versionString = "MpPatch v".._mpPatch.versionString
end
Controls.VersionNumber:SetText(Controls.VersionNumber:GetText().." -- "..versionString)
end)
if not success then
print("Failed to add version to main menu: "..tostring(error))
end | mit |
guiquanz/Dato-Core | src/unity/python/graphlab/lua/pl/input.lua | 28 | 5192 | --- Iterators for extracting words or numbers from an input source.
--
-- require 'pl'
-- local total,n = seq.sum(input.numbers())
-- print('average',total/n)
--
-- _source_ is defined as a string or a file-like object (i.e. has a read() method which returns the next line)
--
-- See @{06-data.md.Reading_Unstructured_Text_Data|here}
--
-- Dependencies: `pl.utils`
-- @module pl.input
local strfind = string.find
local strsub = string.sub
local strmatch = string.match
local utils = require 'pl.utils'
local unpack = utils.unpack
local pairs,type,tonumber = pairs,type,tonumber
local patterns = utils.patterns
local io = io
local assert_arg = utils.assert_arg
local input = {}
--- create an iterator over all tokens.
-- based on allwords from PiL, 7.1
-- @func getter any function that returns a line of text
-- @string pattern
-- @string[opt] fn Optionally can pass a function to process each token as it's found.
-- @return an iterator
function input.alltokens (getter,pattern,fn)
local line = getter() -- current line
local pos = 1 -- current position in the line
return function () -- iterator function
while line do -- repeat while there are lines
local s, e = strfind(line, pattern, pos)
if s then -- found a word?
pos = e + 1 -- next position is after this token
local res = strsub(line, s, e) -- return the token
if fn then res = fn(res) end
return res
else
line = getter() -- token not found; try next line
pos = 1 -- restart from first position
end
end
return nil -- no more lines: end of traversal
end
end
local alltokens = input.alltokens
-- question: shd this _split_ a string containing line feeds?
--- create a function which grabs the next value from a source. If the source is a string, then the getter
-- will return the string and thereafter return nil. If not specified then the source is assumed to be stdin.
-- @param f a string or a file-like object (i.e. has a read() method which returns the next line)
-- @return a getter function
function input.create_getter(f)
if f then
if type(f) == 'string' then
local ls = utils.split(f,'\n')
local i,n = 0,#ls
return function()
i = i + 1
if i > n then return nil end
return ls[i]
end
else
-- anything that supports the read() method!
if not f.read then error('not a file-like object') end
return function() return f:read() end
end
else
return io.read -- i.e. just read from stdin
end
end
--- generate a sequence of numbers from a source.
-- @param f A source
-- @return An iterator
function input.numbers(f)
return alltokens(input.create_getter(f),
'('..patterns.FLOAT..')',tonumber)
end
--- generate a sequence of words from a source.
-- @param f A source
-- @return An iterator
function input.words(f)
return alltokens(input.create_getter(f),"%w+")
end
local function apply_tonumber (no_fail,...)
local args = {...}
for i = 1,#args do
local n = tonumber(args[i])
if n == nil then
if not no_fail then return nil,args[i] end
else
args[i] = n
end
end
return args
end
--- parse an input source into fields.
-- By default, will fail if it cannot convert a field to a number.
-- @param ids a list of field indices, or a maximum field index
-- @string delim delimiter to parse fields (default space)
-- @param f a source @see create_getter
-- @tab opts option table, `{no_fail=true}`
-- @return an iterator with the field values
-- @usage for x,y in fields {2,3} do print(x,y) end -- 2nd and 3rd fields from stdin
function input.fields (ids,delim,f,opts)
local sep
local s
local getter = input.create_getter(f)
local no_fail = opts and opts.no_fail
local no_convert = opts and opts.no_convert
if not delim or delim == ' ' then
delim = '%s'
sep = '%s+'
s = '%s*'
else
sep = delim
s = ''
end
local max_id = 0
if type(ids) == 'table' then
for i,id in pairs(ids) do
if id > max_id then max_id = id end
end
else
max_id = ids
ids = {}
for i = 1,max_id do ids[#ids+1] = i end
end
local pat = '[^'..delim..']*'
local k = 1
for i = 1,max_id do
if ids[k] == i then
k = k + 1
s = s..'('..pat..')'
else
s = s..pat
end
if i < max_id then
s = s..sep
end
end
local linecount = 1
return function()
local line,results,err
repeat
line = getter()
linecount = linecount + 1
if not line then return nil end
if no_convert then
results = {strmatch(line,s)}
else
results,err = apply_tonumber(no_fail,strmatch(line,s))
if not results then
utils.quit("line "..(linecount-1)..": cannot convert '"..err.."' to number")
end
end
until #results > 0
return unpack(results)
end
end
return input
| agpl-3.0 |
ABrandau/OpenRA | mods/ra/maps/allies-07/allies07-AI.lua | 3 | 4597 | --[[
Copyright 2007-2019 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
IdlingUnits = { }
AttackGroup = { }
AttackGroupSize = 10
BGAttackGroup = { }
BGAttackGroupSize = 8
SovietAircraftType = { "yak" }
Yaks = { }
SovietInfantry = { "e1", "e2", "e4" }
SovietVehicles =
{
hard = { "3tnk", "3tnk", "v2rl" },
normal = { "3tnk" },
easy = { "3tnk", "apc" }
}
ProductionInterval =
{
easy = DateTime.Seconds(30),
normal = DateTime.Seconds(15),
hard = DateTime.Seconds(5)
}
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
ParadropDelay = { DateTime.Seconds(30), DateTime.Minutes(1) }
ParadropWaves = 6
ParadropLZs = { ParaLZ1.CenterPosition, ParaLZ2.CenterPosition, ParaLZ3.CenterPosition, ParaLZ4.CenterPosition }
Paradropped = 0
Paradrop = function()
Trigger.AfterDelay(Utils.RandomInteger(ParadropDelay[1], ParadropDelay[2]), function()
local units = PowerProxy.SendParatroopers(Utils.Random(ParadropLZs))
Utils.Do(units, function(unit)
Trigger.OnAddedToWorld(unit, IdleHunt)
end)
Paradropped = Paradropped + 1
if Paradropped <= ParadropWaves then
Paradrop()
end
end)
end
SendBGAttackGroup = function()
if #BGAttackGroup < BGAttackGroupSize then
return
end
Utils.Do(BGAttackGroup, function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end)
BGAttackGroup = { }
end
ProduceBadGuyInfantry = function()
if BadGuyRax.IsDead or BadGuyRax.Owner ~= badguy then
return
end
badguy.Build({ Utils.Random(SovietInfantry) }, function(units)
table.insert(BGAttackGroup, units[1])
SendBGAttackGroup()
Trigger.AfterDelay(ProductionInterval[Map.LobbyOption("difficulty")], ProduceBadGuyInfantry)
end)
end
SendAttackGroup = function()
if #AttackGroup < AttackGroupSize then
return
end
Utils.Do(AttackGroup, function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end)
AttackGroup = { }
end
ProduceUSSRInfantry = function()
if USSRRax.IsDead or USSRRax.Owner ~= ussr then
return
end
ussr.Build({ Utils.Random(SovietInfantry) }, function(units)
table.insert(AttackGroup, units[1])
SendAttackGroup()
Trigger.AfterDelay(ProductionInterval[Map.LobbyOption("difficulty")], ProduceUSSRInfantry)
end)
end
ProduceVehicles = function()
if USSRWarFactory.IsDead or USSRWarFactory.Owner ~= ussr then
return
end
ussr.Build({ Utils.Random(SovietVehicles) }, function(units)
table.insert(AttackGroup, units[1])
SendAttackGroup()
Trigger.AfterDelay(ProductionInterval[Map.LobbyOption("difficulty")], ProduceVehicles)
end)
end
ProduceAircraft = function()
if (Airfield1.IsDead or Airfield1.Owner ~= ussr) and (Airfield2.IsDead or Airfield2.Owner ~= ussr) and (Airfield3.IsDead or Airfield3.Owner ~= ussr) and (Airfield4.IsDead or Airfield4.Owner ~= ussr) then
return
end
ussr.Build(SovietAircraftType, function(units)
local yak = units[1]
Yaks[#Yaks + 1] = yak
Trigger.OnKilled(yak, ProduceAircraft)
local alive = Utils.Where(Yaks, function(y) return not y.IsDead end)
if #alive < 2 then
Trigger.AfterDelay(DateTime.Seconds(ProductionInterval[Map.LobbyOption("difficulty")] / 2), ProduceAircraft)
end
TargetAndAttack(yak)
end)
end
TargetAndAttack = function(yak, target)
if not target or target.IsDead or (not target.IsInWorld) then
local enemies = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == greece and self.HasProperty("Health") and yak.CanTarget(self) end)
if #enemies > 0 then
target = Utils.Random(enemies)
end
end
if target and yak.AmmoCount() > 0 and yak.CanTarget(target) then
yak.Attack(target)
else
yak.ReturnToBase()
end
yak.CallFunc(function()
TargetAndAttack(yak, target)
end)
end
ActivateAI = function()
local difficulty = Map.LobbyOption("difficulty")
SovietVehicles = SovietVehicles[difficulty]
local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == ussr and self.HasProperty("StartBuildingRepairs") end)
Utils.Do(buildings, function(actor)
Trigger.OnDamaged(actor, function(building)
if building.Owner == ussr and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
end)
Paradrop()
ProduceBadGuyInfantry()
ProduceUSSRInfantry()
ProduceVehicles()
ProduceAircraft()
end
| gpl-3.0 |
gedads/Neodynamis | scripts/zones/Mamool_Ja_Training_Grounds/Zone.lua | 17 | 1133 | -----------------------------------
--
-- Zone: Mamool_Ja_Training_Grounds
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Mamool_Ja_Training_Grounds/TextIDs"] = nil;
require("scripts/zones/Mamool_Ja_Training_Grounds/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/items/boiled_tuna_head.lua | 12 | 1528 | -----------------------------------------
-- ID: 4540
-- Item: Boiled Tuna Head
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Magic 20
-- Dexterity 3
-- Intelligence 4
-- Mind -3
-- Magic Regen While Healing 2
-- 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,10800,4540);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_INT, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_EVA, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_INT, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_EVA, 5);
end;
| gpl-3.0 |
ironjade/DevStack | LanCom/DesignPattern/LUA/DequeAsLinkedList.lua | 1 | 1808 | #!/usr/local/bin/lua
--[[
Copyright (c) 2004 by Bruno R. Preiss, P.Eng.
$Author: brpreiss $
$Date: 2004/12/05 14:47:20 $
$RCSfile: DequeAsLinkedList.lua,v $
$Revision: 1.7 $
$Id: DequeAsLinkedList.lua,v 1.7 2004/12/05 14:47:20 brpreiss Exp $
--]]
require "Deque"
require "QueueAsLinkedList"
--{
-- Deque implemented using a linked list.
DequeAsLinkedList =
Class.new("DequeAsLinkedList", QueueAsLinkedList)
-- Constructor.
function DequeAsLinkedList.methods:initialize()
DequeAsLinkedList.super(self)
end
DequeAsLinkedList:alias_method("queueHead", "get_head")
DequeAsLinkedList:include(DequeMethods)
DequeAsLinkedList:alias_method("get_head", "queueHead")
-- Enqueues the given object at the head of this deque.
-- @param obj An object.
function DequeAsLinkedList.methods:enqueueHead(obj)
self.list:prepend(obj)
self.count = self.count + 1
end
DequeAsLinkedList:alias_method("dequeueHead", "dequeue")
--}>a
--{
-- The object at the tail of this deque.
function DequeAsLinkedList.methods:get_tail()
assert(self.count ~= 0, "ContainerEmpty")
return self.list:last()
end
DequeAsLinkedList:alias_method("enqueueTail", "enqueue")
-- Dequeues and returns the object at the tail of this deque.
function DequeAsLinkedList.methods:dequeueTail()
assert(self.count ~= 0, "ContainerEmpty")
local result = self.list:last()
self.list:extract(result)
self.count = self.count - 1
return result
end
--}>b
-- DequeAsLinkedList test program.
-- @param arg Command-line arguments.
function DequeAsLinkedList.main(arg)
print "DequeAsLinkedList test program."
local deque2 = DequeAsLinkedList.new()
Queue.test(deque2)
Deque.test(deque2)
return 0
end
if _REQUIREDNAME == nil then
os.exit( DequeAsLinkedList.main(arg) )
end
| apache-2.0 |
gedads/Neodynamis | scripts/zones/Lower_Jeuno/npcs/Zalsuhm.lua | 18 | 4645 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Zalsuhm
-- Standard Info NPC
-----------------------------------
require("scripts/globals/equipment");
require("scripts/globals/quests");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
function getQuestId(mainJobId)
return (UNLOCKING_A_MYTH_WARRIOR - 1 + mainJobId);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--printf("LowerJeuno_Zalsuhm.onTrade() - ");
if (trade:getItemCount() == 1) then
for i, wepId in pairs(BaseNyzulWeapons) do
if (trade:hasItemQty(wepId, 1)) then
local unlockingAMyth = player:getQuestStatus(JEUNO, getQuestId(i))
--printf("\tUnlockingAMyth" .. i .. " = %u", unlockingAMyth);
if (unlockingAMyth == QUEST_ACCEPTED) then
-- TODO: Logic for checking weapons current WS points
local wsPoints = 0;
--printf("\twsPoints = %u", wsPoints);
if (wsPoints >= 0 and wsPoints <= 49) then
player:startEvent(0x276B); -- Lowest Tier Dialog
elseif (wsPoints <= 200) then
player:startEvent(0x276C); -- Mid Tier Dialog
elseif (wsPoints <= 249) then
player:startEvent(0x276D); -- High Tier Dialog
elseif (wsPoints >= 250) then
player:startEvent(0x2768, i); -- Quest Complete!
end
end
return;
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--printf("LowerJeuno_Zalsuhm.onTrigger() - ");
local mainJobId = player:getMainJob();
local unlockingAMyth = player:getQuestStatus(JEUNO, getQuestId(mainJobId))
--printf("\tUnlockingAMyth" .. mainJobId .. " = %u", unlockingAMyth);
local mainWeaponId = player:getEquipID(SLOT_MAIN);
--printf("\tmainWeaponId: %u", mainWeaponId);
local nyzulWeapon = isBaseNyzulWeapon(mainWeaponId);
--printf("\tIsBaseNyzulWeapon: %s", (nyzulWeapon and "TRUE" or "FALSE"));
if (unlockingAMyth == QUEST_AVAILABLE) then
local zalsuhmUpset = player:getVar("Upset_Zalsuhm");
if (player:needToZone() and zalsuhmUpset > 0) then -- Zalsuhm is still angry
player:startEvent(0x276A);
else
if (zalsuhmUpset > 0) then
player:setVar("Upset_Zalsuhm", 0);
end
if (nyzulWeapon) then -- The player has a Nyzul weapon in the mainHand, try to initiate quest
player:startEvent(0x2766, mainJobId);
else
player:startEvent(0x2765); -- Default dialog
end
end
elseif (unlockingAMyth == QUEST_ACCEPTED) then -- Quest is active for current job
player:startEvent(0x2767); -- Zalsuhm asks for the player to show him the weapon if they sense a change
else -- Quest is complete for the current job
player:startEvent(0x2769);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("LowerJeuno_Zalsuhm.onEventUpdate() - ");
--printf("\tCSID: %u", csid);
--printf("\tRESULT: %u", option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("LowerJeuno_Zalsuhm.onEventFinish() - ");
--printf("\tCSID: %u", csid);
--printf("\tRESULT: %u", option);
-- Zalsuhm wants to research the player's Nyzul Weapon
if (csid == 0x2766) then
-- The player chose "He has shifty eyes" (turns down the quest)
if (option == 53) then
player:setVar("Upset_Zalsuhm", 1);
player:needToZone(true);
elseif (option <= JOBS["SCH"]) then -- Just to make sure we didn't get into an invalid state
-- The player chose "More power" (accepts the quest)
local questId = getQuestId(option);
player:addQuest(JEUNO, questId);
end
elseif (csid == 0x2768 and option <= JOBS["SCH"]) then -- The quest is completed
local questId = getQuestId(option);
player:completeQuest(JEUNO, questId);
end
end;
| gpl-3.0 |
starlightknight/darkstar | scripts/zones/Upper_Jeuno/npcs/Souren.lua | 9 | 1437 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Souren
-- Involved in Quests: Save the Clock Tower
-- !pos -51 0 4 244
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
local a = player:getCharVar("saveTheClockTowerNPCz1"); -- NPC Part1
if (a == 0 or (a ~= 16 and a ~= 17 and a ~= 18 and a ~= 20 and a ~= 24 and a ~= 19 and a ~= 28 and a ~= 21 and
a ~= 26 and a ~= 22 and a ~= 25 and a ~= 23 and a ~= 27 and a ~= 29 and a ~= 30 and a ~= 31)) then
player:startEvent(182,10 - player:getCharVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.SAVE_THE_CLOCK_TOWER) == QUEST_ACCEPTED) then
player:startEvent(120);
elseif (player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.SAVE_THE_CLOCK_TOWER) == QUEST_COMPLETED) then
player:startEvent(181);
else
player:startEvent(88);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 182) then
player:addCharVar("saveTheClockTowerVar", 1);
player:addCharVar("saveTheClockTowerNPCz1", 16);
end
end;
| gpl-3.0 |
gedads/Neodynamis | scripts/globals/abilities/dark_maneuver.lua | 4 | 1589 | -----------------------------------
-- Ability: Dark Maneuver
-- Enhances the effect of dark attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD) and
player:getPet()) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 10;
if (target:getMP() < target:getPet():getMP()) then
burden = 15;
end
local overload = target:addBurden(ELE_DARK-1, burden);
if (overload ~= 0 and
(player:getMod(MOD_PREVENT_OVERLOAD) > 0 or player:getPet():getMod(MOD_PREVENT_OVERLOAD) > 0) and
player:delStatusEffectSilent(EFFECT_WATER_MANEUVER)) then
overload = 0;
end
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_DARK_MANEUVER, 0, 0, 60);
end
return EFFECT_DARK_MANEUVER;
end; | gpl-3.0 |
pedro-andrade-inpe/terrame | packages/gis/tests/functional/basic/Geometry.lua | 3 | 5483 | -------------------------------------------------------------------------------------------
-- TerraME - a software platform for multiple scale spatially-explicit dynamic modeling.
-- Copyright (C) 2001-2014 INPE and TerraLAB/UFOP.
--
-- This code is part of the TerraME framework.
-- This framework is free software; you can redistribute it and/or
-- modify it under the terms of the GNU Lesser General Public
-- License as published by the Free Software Foundation; either
-- version 2.1 of the License, or (at your option) any later version.
--
-- You should have received a copy of the GNU Lesser General Public
-- License along with this library.
--
-- The authors reassure the license terms regarding the warranties.
-- They specifically disclaim any warranties, including, but not limited to,
-- the implied warranties of merchantability and fitness for a particular purpose.
-- The framework provided hereunder is on an "as is" basis, and the authors have no
-- obligation to provide maintenance, support, updates, enhancements, or modifications.
-- In no event shall INPE and TerraLAB / UFOP be held liable to any party for direct,
-- indirect, special, incidental, or consequential damages arising out of the use
-- of this library and its documentation.
--
-------------------------------------------------------------------------------------------
return {
geometry = function(unitTest)
local point = {
x = 74,
y = 23.5,
srid = 4326
}
local pt = TerraLib().geometry().Point(point.x, point.y, point.srid)
unitTest:assertEquals(point.x, pt:getX())
unitTest:assertEquals(point.y, pt:getY())
unitTest:assertEquals(0.0, pt:getDimension())
unitTest:assertEquals(2, pt:getCoordinateDimension())
unitTest:assertEquals("Point", pt:getGeometryType())
unitTest:assertEquals(point.srid, pt:getSRID())
unitTest:assertEquals(1, pt:getNPoints())
unitTest:assertEquals("point(74 23.5)", pt:asText())
unitTest:assertEquals("", pt:asBinary(0))
unitTest:assertEquals(21, pt:getWkbSize())
point.srid = 1234
pt:setSRID(point.srid)
point.x = 40
pt:setX(point.x)
point.y = 20
pt:setY(point.y)
unitTest:assertEquals(point.srid, pt:getSRID())
unitTest:assertEquals(point.x, pt:getX())
unitTest:assertEquals(point.y, pt:getY())
unitTest:assertType(pt:getBoundary(), "userdata")
unitTest:assertType(pt:getEnvelope(), "userdata")
unitTest:assertType(pt:getMBR(), "userdata")
unitTest:assert(not pt:isEmpty())
unitTest:assert(not pt:overlaps(pt))
unitTest:assert(not pt:relate(pt, "ttttttttt"))
unitTest:assert(not pt:touches(pt))
unitTest:assert(not pt:crosses(pt))
unitTest:assert(not pt:is3D())
unitTest:assert(not pt:isMeasured())
unitTest:assert(not pt:disjoint(pt))
unitTest:assert(pt:isSimple())
unitTest:assert(pt:isValid())
unitTest:assert(pt:equals(pt))
unitTest:assert(pt:intersects(pt))
unitTest:assert(pt:within(pt))
unitTest:assert(pt:contains(pt))
unitTest:assert(pt:covers(pt))
unitTest:assert(pt:coveredBy(pt))
end,
point = function(unitTest)
local cs = CellularSpace{
file = filePath("itaituba-localities.shp", "gis")
}
forEachCell(cs, function(cell)
local geometry = cell.geom:getGeometryN(0)
unitTest:assert(geometry:getX() > 0)
unitTest:assert(geometry:getY() > 0)
unitTest:assertEquals(1, cell.geom:getNPoints())
unitTest:assertEquals("MultiPoint", cell.geom:getGeometryType())
unitTest:assert(cell.geom:intersects(cell.geom))
unitTest:assert(cell.geom:within(cell.geom))
unitTest:assert(cell.geom:contains(cell.geom))
unitTest:assert(cell.geom:isValid())
end)
end,
line = function(unitTest)
local cs = CellularSpace{
file = filePath("emas-river.shp", "gis")
}
forEachCell(cs, function(cell)
local geometry = cell.geom:getGeometryN(0)
local length = geometry:getLength()
unitTest:assert(length ~= nil)
unitTest:assertEquals("number", type(length))
local nPoint = geometry:getNPoints()
for i = 0, nPoint do
unitTest:assert(geometry:getX(i) ~= nil)
unitTest:assertType(geometry:getX(i), "number")
unitTest:assert(geometry:getY(i) ~= nil)
unitTest:assertType(geometry:getX(i), "number")
end
unitTest:assertEquals("MultiLineString", cell.geom:getGeometryType())
local npoints = cell.geom:getNPoints()
unitTest:assert(npoints > 0)
unitTest:assert(cell.geom:intersects(cell.geom))
unitTest:assert(cell.geom:within(cell.geom))
unitTest:assert(cell.geom:contains(cell.geom))
unitTest:assert(cell.geom:isValid())
end)
end,
polygon = function(unitTest)
local cs = CellularSpace{
file = filePath("amazonia-limit.shp", "gis")
}
forEachCell(cs, function(cell)
local geometry = cell.geom:getGeometryN(0)
local centroid = geometry:getCentroid()
local ring = geometry:getExteriorRing()
local nPoint = ring:getNPoints()
for i = 0, nPoint do
unitTest:assertNotNil(ring:getX(i))
unitTest:assertType(ring:getX(i), "number")
unitTest:assertNotNil(ring:getY(i))
unitTest:assertType(ring:getX(i), "number")
end
unitTest:assert(centroid:getX() < 0)
unitTest:assert(centroid:getY() < 0)
unitTest:assertEquals("MultiPolygon", cell.geom:getGeometryType())
local npoints = cell.geom:getNPoints()
unitTest:assert(npoints > 0)
unitTest:assert(cell.geom:intersects(cell.geom))
unitTest:assert(cell.geom:within(cell.geom))
unitTest:assert(cell.geom:contains(cell.geom))
unitTest:assert(cell.geom:isValid())
end)
end
}
| lgpl-3.0 |
gedads/Neodynamis | scripts/zones/LaLoff_Amphitheater/npcs/qm1_2.lua | 17 | 2450 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: Shimmering Circle (BCNM Entrances)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-- Death cutscenes:
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,0,0); -- hume
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,3,0); -- elvaan
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,instance:getFastestTime(),1,instance:getTimeInside(),1,5,0); -- divine might
-- param 1: entrance #
-- param 2: fastest time
-- param 3: unknown
-- param 4: clear time
-- param 5: zoneid
-- param 6: exit cs (0-4 AA, 5 DM, 6-10 neo AA, 11 neo DM)
-- param 7: skip (0 - no skip, 1 - prompt, 2 - force)
-- param 8: 0
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option,2)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
starlightknight/darkstar | scripts/globals/items/green_quiche.lua | 11 | 1162 | -----------------------------------------
-- ID: 5170
-- Item: green_quiche
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 10
-- Agility 1
-- Vitality -1
-- Ranged ACC % 7
-- Ranged ACC Cap 15
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,5170)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.MP, 10)
target:addMod(dsp.mod.AGI, 1)
target:addMod(dsp.mod.VIT, -1)
target:addMod(dsp.mod.FOOD_RACCP, 7)
target:addMod(dsp.mod.FOOD_RACC_CAP, 15)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.MP, 10)
target:delMod(dsp.mod.AGI, 1)
target:delMod(dsp.mod.VIT, -1)
target:delMod(dsp.mod.FOOD_RACCP, 7)
target:delMod(dsp.mod.FOOD_RACC_CAP, 15)
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.