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 |
|---|---|---|---|---|---|
Enignite/darkstar | scripts/globals/items/plate_of_ikra_gunkan_+1.lua | 35 | 1733 | -----------------------------------------
-- ID: 5220
-- Item: plate_of_ikra_gunkan_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 30
-- Magic 12
-- Dexterity 3
-- Mind -1
-- Accuracy % 17
-- Accuracy Cap 30
-- Ranged ACC % 17
-- Ranged ACC Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5220);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_MP, 12);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_ACC_CAP, 30);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_FOOD_RACC_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_MP, 12);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_ACC_CAP, 30);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_FOOD_RACC_CAP, 30);
end;
| gpl-3.0 |
rodrigoftw/Estagio1 | Stay Alive/plugin/dusk/layer/imageLayer.lua | 1 | 1184 | -- ************************************************************************** --
--[[
Dusk Engine Component: Image Layer
Builds an image layer from data.
--]]
-- ************************************************************************** --
local dusk_imageLayer = {}
-- ************************************************************************** --
local dusk_settings = require("plugin.dusk.misc.settings")
local utils = require("plugin.dusk.misc.utils")
-- ************************************************************************** --
function dusk_imageLayer.createLayer(map, data, dirTree)
local props = utils.getProperties(data.properties, data.propertytypes, "image", true)
local layer = display.newGroup()
layer.props = {}
layer._layerType = "image"
local imageDir, filename = utils.getDirectory(dirTree, data.image)
layer.image = display.newImage(layer, imageDir .. filename)
layer.image.x, layer.image.y = data.x + (layer.image.width * 0.5), data.y + (layer.image.height * 0.5)
layer.destroy = utils.defaultLayerDestroy
utils.addProperties(props, "props", layer.props)
utils.addProperties(props, "layer", layer)
return layer
end
return dusk_imageLayer | apache-2.0 |
Enignite/darkstar | scripts/globals/mobskills/PL_Rock_Smash.lua | 13 | 1175 | ---------------------------------------------
-- Rock Smash
--
-- Description: Damages a single target. Additional effect: Petrification
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes:
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobSkin = mob:getModelId();
if (mobSkin == 1680) then
return 0;
else
return 1;
end
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 2;
local dmgmod = 3;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
local typeEffect = EFFECT_PETRIFICATION;
local power = math.random(25, 40) + mob:getMainLvl()/3;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, power);
target:delHP(dmg);
return dmg;
end; | gpl-3.0 |
xternalz/fb.resnet.torch | train.lua | 1 | 6680 | --
-- Copyright (c) 2016, Facebook, Inc.
-- All rights reserved.
--
-- This source code is licensed under the BSD-style license found in the
-- LICENSE file in the root directory of this source tree. An additional grant
-- of patent rights can be found in the PATENTS file in the same directory.
--
-- The training loop and learning rate schedule
--
local optim = require 'optim'
local M = {}
local Trainer = torch.class('resnet.Trainer', M)
function Trainer:__init(model, criterion, opt, optimState)
self.model = model
self.criterion = criterion
self.optimState = optimState or {
learningRate = opt.LR,
learningRateDecay = 0.0,
momentum = opt.momentum,
nesterov = true,
dampening = 0.0,
weightDecay = opt.weightDecay,
}
self.opt = opt
self.params, self.gradParams = model:getParameters()
end
function Trainer:train(epoch, dataloader)
-- Trains the model for a single epoch
self.optimState.learningRate = self:learningRate(epoch)
local timer = torch.Timer()
local dataTimer = torch.Timer()
local function feval()
return self.criterion.output, self.gradParams
end
local trainSize = dataloader:size()
local top1Sum, top5Sum, lossSum = 0.0, 0.0, 0.0
local N = 0
print('=> Training epoch # ' .. epoch)
-- set the batch norm to training mode
self.model:training()
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
local output = self.model:forward(self.input):float()
local batchSize = output:size(1)
local loss = self.criterion:forward(self.model.output, self.target)
self.model:zeroGradParameters()
self.criterion:backward(self.model.output, self.target)
self.model:backward(self.input, self.criterion.gradInput)
optim.sgd(feval, self.params, self.optimState)
local top1, top5 = self:computeScore(output, sample.target, 1)
top1Sum = top1Sum + top1*batchSize
top5Sum = top5Sum + top5*batchSize
lossSum = lossSum + loss*batchSize
N = N + batchSize
if n % 100 == 0 or n == 1 then
print((' | Epoch: [%d][%d/%d] Time %.3f Data %.3f Err %1.4f top1 %7.3f top5 %7.3f'):format(
epoch, n, trainSize, timer:time().real, dataTime, loss, top1, top5))
end
-- check that the storage didn't get changed do to an unfortunate getParameters call
assert(self.params:storage() == self.model:parameters()[1]:storage())
timer:reset()
dataTimer:reset()
end
return top1Sum / N, top5Sum / N, lossSum / N
end
function Trainer:test(epoch, dataloader)
-- Computes the top-1 and top-5 err on the validation set
local timer = torch.Timer()
local dataTimer = torch.Timer()
local size = dataloader:size()
local nCrops = self.opt.tenCrop and 10 or 1
local top1Sum, top5Sum = 0.0, 0.0
local N = 0
local top5ClassAccs = torch.zeros(365,2)
self.model:evaluate()
local softmax = cudnn.SoftMax():cuda()
-- Stochastic forward dropout during testing
if self.opt.nStocSamples > 1 then
self.model:apply(function(m)
if torch.type(m) == 'nn.Dropout' then
m.train = true
end
end)
end
for n, sample in dataloader:run() do
local dataTime = dataTimer:time().real
-- Copy input and target to the GPU
self:copyInputs(sample)
-- Stochastic inference
local output = nil
for i = 1, self.opt.nStocSamples do
if output == nil then
output = softmax:forward(self.model:forward(self.input)):clone()
else
output:add(softmax:forward(self.model:forward(self.input)))
end
end
output:div(self.opt.nStocSamples)
local batchSize = output:size(1) / nCrops
local loss = self.criterion:forward(output, self.target)
local top1, top5 = self:computeScore(output:float(), sample.target, nCrops, top5ClassAccs)
top1Sum = top1Sum + top1*batchSize
top5Sum = top5Sum + top5*batchSize
N = N + batchSize
print((' | Test: [%d][%d/%d] Time %.3f Data %.3f top1 %7.3f (%7.3f) top5 %7.3f (%7.3f)'):format(
epoch, n, size, timer:time().real, dataTime, top1, top1Sum / N, top5, top5Sum / N))
timer:reset()
dataTimer:reset()
end
self.model:training()
print((' * Finished epoch # %d top1: %7.3f top5: %7.3f class-top5-acc: %7.3f\n'):format(
epoch, top1Sum / N, top5Sum / N, torch.cdiv(top5ClassAccs:select(2,1), top5ClassAccs:select(2,2)):sum() / 365 * 100))
return top1Sum / N, top5Sum / N
end
function Trainer:computeScore(output, target, nCrops, top5ClassAccs)
if nCrops > 1 then
-- Sum over crops
output = output:view(output:size(1) / nCrops, nCrops, output:size(2))
--:exp()
:sum(2):squeeze(2)
end
-- Coputes the top1 and top5 error rate
local batchSize = output:size(1)
local _ , predictions = output:float():sort(2, true) -- descending
-- Find which predictions match the target
local correct = predictions:eq(
target:long():view(batchSize, 1):expandAs(output))
-- Top-1 score
local top1 = 1.0 - (correct:narrow(2, 1, 1):sum() / batchSize)
-- Top-5 score, if there are at least 5 classes
local len = math.min(5, correct:size(2))
local top5 = 1.0 - (correct:narrow(2, 1, len):sum() / batchSize)
-- Per-class Top-5
local correct_ = correct:narrow(2, 1, len):sum(2):squeeze()
local target_ = target:long()
for i = 1, batchSize do
top5ClassAccs[target_[i]][2] = top5ClassAccs[target_[i]][2] + 1
if correct_[i] > 0 then
top5ClassAccs[target_[i]][1] = top5ClassAccs[target_[i]][1] + 1
end
end
return top1 * 100, top5 * 100
end
function Trainer:copyInputs(sample)
-- Copies the input to a CUDA tensor, if using 1 GPU, or to pinned memory,
-- if using DataParallelTable. The target is always copied to a CUDA tensor
self.input = self.input or (self.opt.nGPU == 1
and torch.CudaTensor()
or cutorch.createCudaHostTensor())
self.target = self.target or torch.CudaTensor()
self.input:resize(sample.input:size()):copy(sample.input)
self.target:resize(sample.target:size()):copy(sample.target)
end
function Trainer:learningRate(epoch)
-- Training schedule
local decay = 0
if string.match(self.opt.dataset, 'imagenet') then
decay = math.floor((epoch - 1) / 30)
elseif string.match(self.opt.dataset, 'cifar10') then
decay = epoch >= 122 and 2 or epoch >= 81 and 1 or 0
end
return self.opt.LR * math.pow(0.1, decay)
end
return M.Trainer
| bsd-3-clause |
tks2103/angel-test | Code/Tools/BuildScripts/lua-lib/penlight-1.0.2/tests/test-config.lua | 10 | 3559 | require 'pl'
asserteq = require 'pl.test'.asserteq
function testconfig(test,tbl,cfg)
local f = stringio.open(test)
local c = config.read(f,cfg)
f:close()
if not tbl then
print(pretty.write(c))
else
asserteq(c,tbl)
end
end
testconfig ([[
; comment 2 (an ini file)
[section!]
bonzo.dog=20,30
config_parm=here we go again
depth = 2
[another]
felix="cat"
]],{
section_ = {
bonzo_dog = { -- comma-sep values get split by default
20,
30
},
depth = 2,
config_parm = "here we go again"
},
another = {
felix = "\"cat\""
}
})
testconfig ([[
# this is a more Unix-y config file
fred = 1
alice = 2
home.dog = /bonzo/dog/etc
]],{
home_dog = "/bonzo/dog/etc", -- note the default is {variablilize = true}
fred = 1,
alice = 2
})
-- backspace line continuation works, thanks to config.lines function
testconfig ([[
foo=frodo,a,c,d, \
frank, alice, boyo
]],
{
foo = {
"frodo",
"a",
"c",
"d",
"frank",
"alice",
"boyo"
}
}
)
------ options to control default behaviour -----
-- want to keep key names as is!
testconfig ([[
alpha.dog=10
# comment here
]],{
["alpha.dog"]=10
},{variabilize=false})
-- don't convert strings to numbers
testconfig ([[
alpha.dog=10
; comment here
]],{
alpha_dog="10"
},{convert_numbers=false})
-- don't split comma-lists by setting the list delimiter to something else
testconfig ([[
extra=10,'hello',42
]],{
extra="10,'hello',42"
},{list_delim='@'})
-- Unix-style password file
testconfig([[
lp:x:7:7:lp:/var/spool/lpd:/bin/sh
mail:x:8:8:mail:/var/mail:/bin/sh
news:x:9:9:news:/var/spool/news:/bin/sh
]],
{
{
"lp",
"x",
7,
7,
"lp",
"/var/spool/lpd",
"/bin/sh"
},
{
"mail",
"x",
8,
8,
"mail",
"/var/mail",
"/bin/sh"
},
{
"news",
"x",
9,
9,
"news",
"/var/spool/news",
"/bin/sh"
}
},
{list_delim=':'})
-- Unix updatedb.conf is in shell script form, but config.read
-- copes by extracting the variables as keys and the export
-- commands as the array part; there is an option to remove quotes
-- from values
testconfig([[
# Global options for invocations of find(1)
FINDOPTIONS='-ignore_readdir_race'
export FINDOPTIONS
]],{
"export FINDOPTIONS",
FINDOPTIONS = "-ignore_readdir_race"
},{trim_quotes=true})
-- Unix fstab format. No key/value assignments so use `ignore_assign`;
-- list values are separated by a number of spaces
testconfig([[
# <file system> <mount point> <type> <options> <dump> <pass>
proc /proc proc defaults 0 0
/dev/sda1 / ext3 defaults,errors=remount-ro 0 1
]],
{
{
"proc",
"/proc",
"proc",
"defaults",
0,
0
},
{
"/dev/sda1",
"/",
"ext3",
"defaults,errors=remount-ro",
0,
1
}
},
{list_delim='%s+',ignore_assign=true}
)
-- Linux procfs 'files' often use ':' as the key/pair separator;
-- a custom convert_numbers handles the units properly!
-- Here is the first two lines from /proc/meminfo
testconfig([[
MemTotal: 1024748 kB
MemFree: 220292 kB
]],
{ MemTotal = 1024748, MemFree = 220292 },
{
keysep = ':',
convert_numbers = function(s)
s = s:gsub(' kB$','')
return tonumber(s)
end
}
)
-- altho this works, rather use pl.data.read for this kind of purpose.
testconfig ([[
# this is just a set of comma-separated values
1000,444,222
44,555,224
]],{
{
1000,
444,
222
},
{
44,
555,
224
}
})
| bsd-3-clause |
vso2004/cardpeek | dot_cardpeek_dir/scripts/etc/ravkav-strings.lua | 16 | 27069 | RAVKAV_ISSUERS = {
[1] = "Service Center (Postal Bank)",
[2] = "Israel Rail",
[3] = "Egged",
[4] = "Egged Transport",
[5] = "Dan",
[6] = "NTT (Nazereth Consolidated Bus Services)",
[7] = "NTT (Nazereth Travel & Tourism)",
[8] = "JB Tours",
[9] = "Omni (Nazrin Express)",
[10] = "Ayalot Regional Council",
[11] = "Elite",
[12] = "undefined 12",
[13] = "undefined 13",
[14] = "Nativ Express",
[15] = "Metropolis",
[16] = "Superbus",
[17] = "Connex & Veolia",
[18] = "Kavim",
[19] = "Metrodan",
[20] = "Carmelit",
[21] = "CityPass",
[22] = "undefined 22",
[23] = "Galim (Narkis Gal)",
[24] = "Golan Regional Council",
[25] = "Afikim",
[26] = "undefined 26",
[27] = "undefined 27",
[28] = "undefined 28",
[29] = "undefined 29",
[30] = "Dan North",
[31] = "undefined 31",
[32] = "undefined 32",
[33] = "undefined 33",
[34] = "undefined 34",
[35] = "undefined 35",
[36] = "undefined 36",
[37] = "undefined 37",
[38] = "undefined 38",
[39] = "undefined 39",
[40] = "undefined 40",
[41] = "East Jerusalem operators"
}
RAVKAV_PROFILES = {
-- [0] = "Standard",
-- [1] = "Standard",
[2] = "2",
[3] = "Extended Student",
[4] = "Senior Citizen",
[5] = "Handicapped",
[6] = "Poor vision / blind",
[7] = "7",
[8] = "8",
[9] = "9",
[10] = "Ministry of Defence",
[11] = "11",
[12] = "12",
[13] = "Public Transport Works",
[14] = "14",
[15] = "15",
[16] = "16",
[17] = "17",
[18] = "18",
[19] = "Regular Student",
[20] = "20",
[21] = "21",
[22] = "22",
[23] = "23",
[24] = "24",
[25] = "25",
[26] = "26",
[27] = "27",
[28] = "28",
[29] = "29",
[30] = "30",
[31] = "31",
[32] = "Child aged 5-10",
[33] = "Youth",
[34] = "National Service",
[35] = "Of \"takad\" zayin",
[36] = "Israel Police",
[37] = "Prison Services",
[38] = "Member of Parliament",
[39] = "Parliament Guard",
[40] = "Eligible for Social Security",
[41] = "Victim of Hostilities",
[42] = "New Immigrant in Rural Settlement"
}
--Cluster codes
--issuerId:
--[code] = description --issuerId
RAVKAV_ROUTES = {
--18:
[1] = "Ha'Emek",
--5:
[11] = "Dan Region - Tel-Aviv",
[12] = "Dan Region - Ever Ha'Yarkon",
[13] = "Dan Region East - Bnei Brak",
[14] = "Dan Region East - Ramat Gan",
[15] = "Dan Region South - Bat Yam",
[16] = "Dan Region South - Rishon Le'Tziyon / Holon",
[17] = "Petach Tikva - Tel-Aviv",
[18] = "Students",
[19] = "Bat Yam - Ramat Gan",
--[40] = reserved ---
--2:
[50] = "Israel Rail primary",
[51] = "Israel Rail - Northern",
[52] = "Israel Rail - Central",
[53] = "Israel Rail - Southern",
--[54] = reserved ---
--[55] = reserved ---
--3:
[71] = "Holon urban + metropolis + free",
[72] = "Rishon Le'Tziyon suburban",
[73] = "Rishon Le'Tziyon urban",
[74] = "Rechovot urban",
[75] = "Rechovot suburban",
[76] = "Tel-Aviv - Ashkalon",
[77] = "Tel-Aviv - Galilee - Amekim",
[79] = "Ashdod Students",
[81] = "Haifa urban",
[83] = "Haifa suburban",
[84] = "Kiryat Shmona - Haifa",
[85] = "Matm'z Karyut",
[86] = "Hadera suburban",
[87] = "Kiryat Shmona urban",
[89] = "Carmiel urban + Carmiel, Haifa, Tiberias",
[91] = "Jerusalem urban",
[93] = "Jerusalem - Beit Shemesh",
[94] = "Jerusalem - Tel-Aviv",
[95] = "Jerusalem - Bnei Brak (402)",
[96] = "Jerusalem - Ha'Shfela",
[97] = "Jerusalem North Axis East",
[98] = "Ashdod - Ashkalon - Jerusalem",
[101] = "Eilat urban and intercity",
[102] = "Southern cluster",
[103] = "Haifa - Ha'Sharon - Jerusalem",
[104] = "Jerusalem - Be'er Sheva",
[105] = "Jerusalem - Bnei Brak (400)",
[106] = "Ashdod - Tel-Aviv (competition)",
[107] = "Nahariya - Haifa (competition)",
[108] = "Shfar'am Villages (competition)",
[109] = "Sefad (competition)",
[110] = "Tel-Aviv - Ha'Sharon - Haifa",
[111] = "Tel-Aviv - Hadera",
[112] = "Haredi sector (competition)",
[113] = "Jerusalem suburban",
[114] = "Jerusalem protected",
[115] = "Jerusalem - Haredi sector",
[116] = "Netanya - Hadera (competition)",
[118] = "Haifa - Jerusalem - Eilat",
[121] = "Nazareth lines - JB Tours", --8
[122] = "Nazareth lines - Travel and Tourism", --7
[123] = "Nazareth Lines - NTT", --6
[124] = "Nahariya - Sefad", --14
[125] = "Nazareth-Haifa shared", --7
[126] = "Nazareth-Haifa shared", --8
[127] = "Yokneam - Tivon", --9
[130] = "Golan Heights", --24
[132] = "Nazareth area - JB Tours", --8
[141] = "Ha'Negev North", --4
[142] = "Ayalot", --10
[143] = "Rahat", --23
[151] = "Elad", --4
[152] = "Beitar Illit", --18
[153] = "Beitar Illit", --11
[154] = "Modi'in", --17
[155] = "Hadera - Netanya", --14
[157] = "Modi'in Illit", --16
[158] = "Yavne - Ashdod - Tel-Aviv", --17
[160] = "Netanya - Tel-Aviv", --14
[169] = "Lod - Tel-Aviv", --17
[170] = "Peruzdor Jerusalem", --16
[171] = "Road 4 - Jerusalem - Bnei Brak", --17
[176] = "Jerusalem perimeter", --4
[180] = "East Jerusalem", --41
[190] = "Samaria", --25
[195] = "Ha'Sharon", --15
[200] = "Dan Region", --5
[201] = "Be'er Sheva urban", --19
[202] = "Tiberias regional", --17
[203] = "Ramla - Lod", --16
[204] = "Ashdod urban", --4
[205] = "Netanya urban", --4
[206] = "Fast Lane Shuttle", --5
[208] = "Ono - Petach Tikva", --18
[210] = "Jerusalem Light Rail", --21
[214] = "Carmelit", --20
[215] = "Metronit Haifa", --30
[218] = "Fast line Tel-Aviv (BRT)", --5
[220] = "Tel-Aviv Light Rail", --?
[221] = "Beer Sheva direct - Tel-Aviv", --4
[222] = "Beer Sheva - Tel-Aviv - Negev (including Arad, Yeruham, Mitzpe Ramon and Nitzana)" --15
}
-- These are the station names from the Israel Rail website.
-- However the IDs on the website do NOT match those used by RavKav and are incorrect,
-- except for the 3 that have been updated below (with original ID added as comment)
RAVKAV_LOCATIONS = {
[300] = "Modi'in - Pa'ate Modi'in",
[7049] = "Modi'in Center", --400
[700] = "Kiryat Hayyim",
[800] = "Kiryat Motzkin",
[1220] = "Lev HaMifrats",
[1300] = "Hutsot HaMifrats",
[1500] = "Akko",
[1600] = "Nahariyya",
[2100] = "Haifa Center HaShmona",
[2200] = "Haifa Bat Gallim",
[2300] = "Haifa Hof HaKarmel (Razi'el)",
[2500] = "Atlit",
[2800] = "Binyamina",
[2820] = "Ceasarea - Pardes Hanna",
[3100] = "Hadera West",
[3300] = "Natanya",
[3400] = "Bet Yehoshua",
[7002] = "Herzliya", --3500
[3600] = "Tel Aviv - University",
[3700] = "Tel Aviv Center - Savidor",
[4100] = "Bnei Brak",
[4170] = "Petah Tikva Kiryat Arye",
[4250] = "Petah Tikva Sgulla",
[7023] = "Tel Aviv HaShalom", --4600
[4640] = "Holon Junction",
[4660] = "Holon - Wolfson",
[4680] = "Bat Yam - Yoseftal",
[4690] = "Bat Yam - Komemiyyut",
[4800] = "Kfar Habbad",
[4900] = "Tel Aviv HaHagana",
[5000] = "Lod",
[5010] = "Ramla",
[5150] = "Lod Ganey Aviv",
[5200] = "Rehovot E. Hadar",
[5300] = "Be'er Ya'akov",
[5410] = "Yavne",
[5800] = "Ashdod Ad Halom (M.Bar Kochva)",
[5900] = "Ashkelon",
[6300] = "Bet Shemesh",
[6500] = "Jerusalem Biblical Zoo",
[6700] = "Jerusalem Malha",
[7000] = "Kiryat Gat",
[7300] = "Be'er Sheva North University",
[7320] = "Be'er Sheva Center",
[7500] = "Dimona",
[8550] = "Lehavim - Rahat",
[8600] = "Ben Gurion Airport",
[8700] = "Kefar Sava - Nordau (A.Kostyuk)",
[8800] = "Rosh Ha'Ayin North",
[9000] = "Yavne West",
[9100] = "Rishon LeTsiyyon HaRishonim",
[9200] = "Hod HaSharon - Sokolov",
[9800] = "Rishon LeTsiyyon - Moshe Dayan"
}
RAVKAV_EVENT_TYPES = {
[1] = "Entry -", --Used for
[2] = "Exit -",
[6] = "Transit trip",
[9] = "Cancel -",
[12] = "Loaded card and used immediately for",
[13] = "Loaded",
[14] = "Personalization"
}
RAVKAV_TICKET_TYPES = {
[1] = "Single or multiple",
[2] = "Season pass", --free period
[3] = "3",
[4] = "Free of charge",
[5] = "5",
[6] = "Aggregate value",
[7] = "Single or multiple",
[8] = "8"
}
RAVKAV_VALIDITY_TYPES = {
[0] = "Area",
[1] = "Tariff",
[2] = "2",
[3] = "3",
[4] = "4",
[7] = "Rail tariff 1",
[8] = "Rail tariff 2",
[9] = "Predefined",
[10] = "10",
[11] = "11",
[12] = "12",
[13] = "13",
[14] = "Rail area",
[15] = "End of validity locations"
}
-- ticketType, ETT
RAVKAV_CONTRACT_DESCRIPTIONS = {
[1] = { [0] = "Single ticket",
[1] = "Return",
[2] = "Tickets for 2 trips",
[3] = "Tickets for 5 trips",
[4] = "Tickets for 10 trips",
[5] = "Tickets for 12 trips",
[6] = "Tickets for 15 trips",
[7] = "Tickets for 20 trips"
},
[2] = { [0] = "Monthly free travel",
[1] = "Weekly free travel",
[2] = "Daily free travel",
[3] = "Monthly free local travel",
[4] = "Free travel for the semester",
[5] = "Annual free travel"
},
[4] = { [0] = "Reserve soldier coupon",
[1] = "Special travel"
},
[6] = { [0] = "Total value of NIS 30",
[1] = "Total value of NIS 50",
[2] = "Total value of NIS 100",
[3] = "Total value of NIS 150",
[4] = "Total value of NIS 200",
[5] = "Total value of NIS 5 + 30",
[6] = "Total value of NIS 5 + 12.80",
[7] = "Total value of NIS 5 + 20"
},
[7] = { [0] = "Tickets for 4 trips",
[1] = "Tickets for 6 trips",
[2] = "Supplementary ticket / voucher to claim",
[3] = "Special tickets"
}
}
--Predefined codes
-- 0- 999 Reserved by MOT
--1000-1999 Egged
--2000-2047 Compatibility tests
RAVKAV_CONTRACT_TYPES = {
--code = description / operators / comments
[1] = "\"Rest of the country\" entire country except for Arava (soldiers)", --wilderness?
[2] = "Arava [Eilot District, Egged] (soldiers)",
[3] = "Rest of the country - entire country except for Yozei Dofen", --certain exceptions?
[4] = "Dan Region",
[6] = "Entire country except for the Arava from price code 5 and up",
[7] = "Entire country up to price code 7 inclusive",
[8] = "Jerusalem [CityPass] (police)",
[9] = "Free travel Egged + Egged-Transport (company employees and family)",
[10] = "Free travel Dan + Kavim [Dan, Kavim] (company employees and family)",
[11] = "Free travel Dan + Kavim + Egged [Dan, Kavim, Egged] (company employees and family)",
[12] = "Free travel Dan + Egged [Dan, Egged] (company employees and family)",
[13] = "Golan Heights Student Card [Golan Heights Regional Council]",
[14] = "Netanya Municipality Youth Pass [Egged Transport]",
[15] = "Betar Illit <> Beit Shemesh [Kavim]",
[16] = "Betar Illit internal [Kavim]",
[17] = "Betar Illit youth [Kavim] (youth only, discount excepted)",
[18] = "Shoham / Modi'in Illit Student Card [Superbus] (youth only)",
[19] = "Betar Illit <> Beit Shemesh youth [Kavim] (youth only, discount excepted)",
[21] = "Beit Shemesh internal [Superbus]",
[22] = "Modi'in Illit internal [Superbus]",
[23] = "Ramla internal [Superbus]",
[24] = "Modi'in Illit <> Bnei Brak [Superbus]",
[25] = "Shoham <> Tel-Aviv [Superbus]",
[26] = "Shoham <> Ben-Gurion [Superbus]",
[27] = "Modi'in internal [Connex and Veolia]",
[28] = "Modi'in <> Ramla <> Lod [Connex and Veolia]",
[29] = "Modi'in <> Tel-Aviv [Connex and Veolia]",
[30] = "Modi'in <> Jerusalem [Connex and Veolia]",
[31] = "Ashdod zones [Connex and Veolia]",
[32] = "Yavne [Connex and Veolia]",
[33] = "Free weekly Ashdod zones [Connex and Veolia]",
[34] = "Semester Modi'in <> Jerusalem [Connex and Veolia] (students only)",
[35] = "Annual Modi'in <> Jerusalem [Connex and Veolia] (students only)",
[36] = "Free daily Ramla [Superbus]",
[37] = "Free daily Lod [Connex and Veolia]",
[39] = "Free daily Lod <> Tel-Aviv [Connex and Veolia]",
[41] = "Semester Modi'in <> Tel-Aviv [Connex and Veolia] (students only)",
[42] = "Annual Modi'in <> Tel-Aviv [Connex and Veolia] (students only)",
[45] = "Rahat urban [Narcissus-Gal]",
[46] = "Rahat surrounds [Narcissus-Gal]",
[55] = "Free daily Ashdod internal [Egged-Transport]",
[56] = "Ashdod internal [Egged-Transport]",
[57] = "Ashkalon [Egged-Transport]",
[58] = "Kiryat-Gat [Egged-Transport]",
[59] = "Ashkalon <> Kiryat-Gat [Egged-Transport]",
[60] = "Be'er Sheva urban [Metrodan]",
[61] = "Student semester [Egged-Transport] (all clusters, students only)",
[62] = "Student annual [Egged-Transport] (all clusters, students only)",
[63] = "Free weekly Nazareth <> Kfar Kana [Jaybee Tours]",
[64] = "Free weekly Nazareth <> Turan/Baina [Jaybee Tours]",
[68] = "Free weekly Turan <> Haifa [Jaybee Tours]",
[69] = "Yearly subscription for lines 28, 298, 299 [Travel and Tourism] (students only)",
[70] = "Afula [Kavim]",
[71] = "Free daily Afula [Kavim]",
[72] = "Free daily Ha'Emek surrounds [Kavim]",
[73] = "Free daily Mount Tabor [Kavim] (line 350 only)",
[74] = "Free daily Tiberias [Connex and Veolia]",
[75] = "Tiberias [Connex and Veolia]",
[76] = "Free weekly Ma'alot <> Kfar Yasif <> Nahariya [Nativ Express]",
[77] = "Nazareth [M*A*S*H]",
[78] = "Nazareth <> Kfar Kana [M*A*S*H]",
[79] = "Free weekly Peki'in <> Horfeish <> Nahariya [Nativ Express]",
[81] = "Netanya internal [Egged-Transport]",
[82] = "Free daily Netanya internal [Egged-Transport]",
[86] = "Sefad [Nativ Express]",
[87] = "Nahariya [Nativ Express]",
[88] = "Shlomi <> Nahariya [Nativ Express]",
[91] = "Free daily Sagol [Kavim] (Petach Tikva and Rosh Ha'Ayin)",
[92] = "Elad <> Petach Tikva [Egged-Transport]",
[93] = "Elad <> Bnei Brak [Egged-Transport]",
[94] = "Free daily Elad [Egged-Transport]",
[95] = "Free weekly Or Akiva <> Hadera [Nativ Express]",
[96] = "Free weekly Jat <> Charish <> Hadera [Nativ Express]",
[97] = "Kadima/Zoran <> Netanya [Nativ Express]",
[98] = "Netanya <> Tel-Aviv [Nativ Express]",
[100] = "Dan Region Free 'white' subscription [Egged, Dan, Kavim, Metropoline, Afikim] (sold through Afikim only, includes subscriptions for students)",
[105] = "Dan Region Samaria free 'brown' subscription [Egged, Dan, Kavim, Metropoline, Afikim] (sold through Afikim only, includes subscriptions for students)",
[109] = "Dan Region Sagol [Kavim] (Petach Tikva and Rosh Ha'Ayin)",
[111] = "Dan Region Free subscription zone 1 [Dan, Egged, Kavim, Metropoline] (including students)",
[112] = "Dan Region Free subscription zone 2 [Dan, Egged, Kavim, Metropoline] (including students)",
[113] = "Dan Region Free subscription surrounds [Dan, Egged, Kavim, Metropoline] (including students)",
[120] = "Dan Region - Free daily special [Dan] (in place of damaged smartcard)",
[121] = "Dan Region - cartisiya code 41 [Dan, Egged, Kavim, Metropoline] (ring 2, zone 22 + Petach Tikva only)",
[122] = "Dan Region - cartisiya code 42 [Dan, Egged, Kavim, Metropoline] (ring 1 only)",
[123] = "Dan Region - cartisiya code 43 [Dan, Egged, Kavim, Metropoline] (ring 2, zone 21 only)",
[124] = "Dan Region - cartisiya code 44 [Dan, Egged, Kavim, Metropoline] (surrounds)",
[135] = "Dan Region - Free daily zone 1 [Dan, Egged, Kavim, Metropoline] (including Petach Tikva area)",
[137] = "Dan Region - Afur, Bnei Brak [Dan]",
[200] = "Nationwide aggregate value [Egged, Dan, Kavim, Metropoline] (enabled temporarily on specific clusters)",
[210] = "Elad aggregate value [Egged-Transport] (Elad cluster only)",
[300] = "Sharing agreement lines 331, 332 [Travel and Tourism, Jaybee Tours]",
[303] = "Sharing agreement line 333 [Travel and Tourism, Jaybee Tours]",
[365] = "Free weekly Migdal Ha'Emek <> Haifa [Travel and Tourism, Jaybee Tours]",
[366] = "Free weekly Nazareth / Nazereth Illit <> Haifa [Travel and Tourism, Jaybee Tours]",
[367] = "Free weekly Nazareth <> University [Travel and Tourism, Jaybee Tours]",
[510] = "Netanya [Egged Transport, Nativ Express]",
[511] = "Netanya <> Kfar Yona [Egged Transport, Nativ Express]",
[512] = "Netanya <> Tel-Aviv [Egged Transport, Nativ Express]",
[515] = "Hadera [Egged, Nativ Express]",
[516] = "Hadera <> Or Akiva [Egged, Nativ Express]",
[517] = "Hadera <> Pardes Hanna [Egged, Nativ Express]",
[518] = "Netanya <> Hadera [Egged, Nativ Express]",
[520] = "Metropoline Haifa [Egged, Nazrin Express]",
[521] = "Single ticket code 10 [Egged, Nazrin Express]",
[522] = "Single ticket code 2 [Egged, Nazrin Express]",
[524] = "Single ticket code 4 [Egged, Nazrin Express]",
[526] = "Single ticket code 6 [Egged, Nazrin Express]",
[527] = "Single ticket code 7 [Egged, Nazrin Express]",
[528] = "Single ticket code 8 [Egged, Nazrin Express]",
[529] = "Single ticket code 9 [Egged, Nazrin Express]",
[530] = "Haifa zone [Egged, Nazrin Express]",
[532] = "Haifa surround [Egged, Nazrin Express]",
[534] = "Semester Afula <> Haifa [Egged, Nazrin Express] (students only)",
[535] = "Annual Afula <> Haifa [Egged, Nazrin Express] (students only)",
[536] = "Semester Metropoline Haifa [Egged, Nazrin Express] (students only)",
[537] = "Annual Metropoline Haifa [Egged, Nazrin Express] (students only)",
[538] = "Semester Haifa zone [Egged, Nazrin Express] (students only)",
[541] = "Cartisiya code 10 [Egged, Nazrin Express]",
[542] = "Cartisiya code 2 [Egged, Nazrin Express]",
[544] = "Cartisiya code 4 [Egged, Nazrin Express]",
[545] = "Cartisiya code 6 with hourly transition [Egged, Nazrin Express]",
[546] = "Cartisiya code 6 without hourly transition [Egged, Nazrin Express]",
[547] = "Cartisiya code 7 [Egged, Nazrin Express]",
[548] = "Cartisiya code 8 [Egged, Nazrin Express]",
[549] = "Cartisiya code 9 [Egged, Nazrin Express]",
[551] = "Nahariya <> Akko [Egged, Nativ Express]",
[552] = "Nahariya <> Kiryat Ata Junction [Egged, Nativ Express]",
[553] = "Nahariya <> Akko <> Haifa [Egged, Nativ Express]",
[554] = "Carmiel <> Akko [Egged, Nativ Express]",
[558] = "Akko <> Haifa [Egged, Nativ Express]",
[602] = "Single Jerusalem surrounds, code 2 + continuation [Egged, Superbus]",
[603] = "Shared Single Peruzdor <> Jerusalem [Egged, Superbus]",
[604] = "Jerusalem surrounds, shared, cartisiya code 2 [Egged, Superbus]",
[605] = "Peruzdor <> Jerusalem, cartisiya 5 + continuation [Egged, Superbus]",
[606] = "Peruzdor <> Jerusalem, cartisiya 6 + continuation [Egged, Superbus]",
[607] = "Beitar Illit <> Jerusalem return + continuation [Egged, Kavim]",
[608] = "Beitar Illit <> Jerusalem, cartisiya 10 + continuation [Egged, Kavim]",
[609] = "Beitar Illit <> Jerusalem, cartisiya 5 + continuation [Egged, Kavim] (entitled only (not including youth / senior citizens))",
[610] = "Beitar Illit <> Jerusalem, cartisiya 10 + continuation [Egged, Kavim]",
[611] = "Beitar Illit extended annual student [Egged, Kavim] (students only)",
[612] = "Beitar Illit extended semester A student [Egged, Kavim] (students only)",
[613] = "Beitar Illit extended semester B student [Egged, Kavim] (students only)",
[614] = "Beitar Illit standard annual student [Egged, Kavim] (students only)",
[615] = "Beitar Illit standard semester A student [Egged, Kavim] (students only)",
[616] = "Beitar Illit standard semester B student [Egged, Kavim] (students only)",
[617] = "Return Ticket + continuation [Egged, Kavim] (youth / senior citizens only)",
[620] = "Beit Shemesh <> Jerusalem, annual student [Egged, Superbus, CityPass] (students only)",
[621] = "Peruzdor <> Jerusalem, annual student [Egged, Superbus, CityPass] (students only)",
[622] = "Beit Shemesh <> Jerusalem, semester A student [Egged, Superbus, CityPass] (students only)",
[623] = "Peruzdor <> Jerusalem, semester A student [Egged, Superbus, CityPass] (students only)",
[624] = "Beit Shemesh <> Jerusalem, semester B student [Egged, Superbus, CityPass] (students only)",
[625] = "Peruzdor <> Jerusalem, semester B student [Egged, Superbus, CityPass] (students only)",
[626] = "Modi'in Illit <> Jerusalem annual student [Egged, Superbus, CityPass] (students only)",
[627] = "Modi'in Illit <> Jerusalem semester A student [Egged, Superbus, CityPass] (students only)",
[628] = "Modi'in Illit <> Jerusalem semester B student [Egged, Superbus, CityPass] (students only)",
[632] = "Beit Shemesh <> Jerusalem [Egged, Superbus, CityPass] (sold by Superbus)",
[633] = "Peruzdor <> Jerusalem [Egged, Superbus, CityPass] (sold by Superbus)",
[634] = "Modi'in Illit <> Jerusalem [Egged, Superbus, CityPass] (sold by Superbus)",
[636] = "Beitar Illit extended youth [Egged, Kavim] (sold by Kavim)",
[637] = "Extended, Beitar Illit <> Jerusalem [Egged, Kavim] (sold by Kavim)",
[638] = "Standard, Beitar Illit <> Jerusalem [Egged, Kavim] (sold by Kavim)",
[641] = "Jerusalem shared single code 2 [Egged, CityPass, Superbus]",
[642] = "Jerusalem shared single code 3 [Egged, CityPass, Superbus]",
[645] = "Jerusalem shared cartisiyot code 2 [Egged, CityPass, Superbus]",
[646] = "Jerusalem shared cartisiyot code 3 [Egged, CityPass, Superbus]",
[647] = "Jerusalem cartisiya 2 [Egged, CityPass] (Choham'f - to The Western Wall)",
[651] = "Jerusalem free surrounds semester A [Egged, CityPass, Superbus] (students only)",
[652] = "Jerusalem free surrounds annual [Egged, CityPass, Superbus] (students only)",
[653] = "Jerusalem surrounds [Egged, CityPass, Superbus] (respected by Superbus only)",
[654] = "Jerusalem free surrounds semester B [Egged, CityPass, Superbus] (students only)",
[658] = "Beit Shemesh Jerusalem semester B [Egged, CityPass] (students only)",
[659] = "Beit Shemesh Jerusalem [Egged, CityPass]",
[680] = "Lines 400-402 Bnei Brak <> Jerusalem [Egged, Dan]",
[690] = "East Jerusalem [East Jerusalem operators]",
[692] = "East Jerusalem surrounds [East Jerusalem operators]",
[701] = "Ramla <> Lod [Egged, Superbus, Connex]",
[702] = "Be'er Ya'akov <> Ben-Gurion [Egged, Superbus, Connex]",
[703] = "Ramla <> Lod <> Tel-Aviv [Egged, Superbus, Connex]",
[704] = "Rechovot <> Rishon Le'Tziyon <> Ramla <> Lod [Egged, Superbus, Connex]",
[705] = "Lod [Egged, Superbus, Connex]",
[706] = "Lod <> Petach Tikva [Egged, Connex]",
[707] = "Rechovot <> Rishon Le'Tziyon Be'er Ya'akov junction [Egged, Superbus]",
[708] = "Rechovot <> Tel-Aviv semester B [Egged, Superbus] (students only)",
[709] = "Rechovot <> Tel-Aviv [Egged, Superbus]",
[811] = "Semester South [Egged, Metrodan, Metropoline, Egged-Transport] (students only)",
[812] = "Annual South [Egged, Metrodan, Metropoline, Egged-Transport] (students only)",
[821] = "Cartisiya 2 Tel-Aviv <> Be'er Sheva [Metropoline, Egged-Transport]",
[901] = "Israel Rail free daily + Dan Region [Dan, Egged, Kavim, Metropoline] (senior citizen)",
[902] = "Israel Rail free daily + Dan Region [Dan, Egged, Kavim, Metropoline] (standard passenger)",
[903] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (senior citizen, reform)",
[904] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (senior citizen, reform)",
[905] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (standard passenger, reform)",
[906] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (standard passenger, reform)",
[907] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (senior citizen, special)",
[908] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (senior citizen, standard)",
[909] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (senior citizen, special)",
[910] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (senior citizen, standard)",
[911] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (standard passenger, special)",
[912] = "Israel Rail + Dan Region zone 1 [Dan, Egged, Kavim, Metropoline] (standard passenger, standard)",
[913] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (standard passenger, special)",
[914] = "Israel Rail + Dan Region surrounds [Dan, Egged, Kavim, Metropoline] (standard passenger, standard)",
[925] = "Israel Rail + Haifa zone [Egged] (senior citizen)",
[926] = "Israel Rail + Haifa zone [Egged] (standard passenger)",
[935] = "Israel Rail + Shoham <> Ben-Gurion [Superbus] (senior citizen)",
[936] = "Israel Rail + Shoham <> Ben-Gurion [Superbus] (standard passenger)",
[940] = "Single Ticket Israel Rail + Samaria lines [Afikim]",
[960] = "Israel Rail + Be'er Sheva [Metrodan]",
[962] = "Israel Rail + Netanya [Egged Transport]",
[964] = "Israel Rail + Rechovot [Egged]",
[966] = "Israel Rail + Lod [Superbus, Connex, Egged]",
[968] = "Israel Rail + Ashkalon [Egged Transport]",
[970] = "Israel Rail + Kiryat Gat [Egged Transport]",
[972] = "Israel Rail + Hadera (tentative)",
[974] = "Israel Rail + Beit Yehoshua [Nativ Express]",
[976] = "Israel Rail + Yavne West/East [Connex]",
[978] = "Israel Rail + Ashdod [Egged Transport]",
[980] = "Israel Rail + Kiryat Motzkin [Egged]",
[982] = "Israel Rail + Akko [Egged]"
}
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Den_of_Rancor/npcs/HomePoint#2.lua | 19 | 1194 | -----------------------------------
-- Area: Den_of_Rancor
-- NPC: HomePoint#2
-- @pos 182 34 -62 160
-----------------------------------
package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Den_of_Rancor/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 93);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
fcpxhacks/fcpxhacks | src/plugins/finalcutpro/inspector/video.lua | 1 | 47219 | --- === plugins.finalcutpro.inspector.video ===
---
--- Final Cut Pro Video Inspector Additions.
local require = require
--local log = require "hs.logger".new "videoInspector"
local deferred = require "cp.deferred"
local dialog = require "cp.dialog"
local fcp = require "cp.apple.finalcutpro"
local go = require "cp.rx.go"
local i18n = require "cp.i18n"
local If = go.If
local Do = go.Do
local WaitUntil = go.WaitUntil
local displayErrorMessage = dialog.displayErrorMessage
local displayMessage = dialog.displayMessage
-- doSpatialConformType(value) -> none
-- Function
-- Sets the Spatial Conform Type.
--
-- Parameters:
-- * value - The conform type you wish to change the clip(s) to as a Final Cut Pro string ID.
--
-- Returns:
-- * None
local function doSpatialConformType(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local libraries = fcp.browser.libraries
local spatialConformType = fcp.inspector.video:spatialConform():type()
return Do(function()
if timeline:isFocused() then
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected in the timeline:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end
else
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected in the browser:
--------------------------------------------------------------------------------
local clips = libraries:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInBrowser"))
return false
end
end
return Do(spatialConformType:doSelectValue(fcp:string(value)))
:Then(WaitUntil(spatialConformType):Is(fcp:string(value)):TimeoutAfter(5000))
:Then(true)
end)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcutpro.inspector.video.doSpatialConformType(value)")
end
-- doBlendMode(value) -> none
-- Function
-- Changes the Blend Mode.
--
-- Parameters:
-- * value - The blend mode you wish to change the clip(s) to as a Final Cut Pro string ID.
--
-- Returns:
-- * None
local function doBlendMode(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local blendMode = fcp.inspector.video:compositing():blendMode()
return Do(function()
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end
return Do(blendMode:doSelectValue(fcp:string(value)))
:Then(WaitUntil(blendMode):Is(fcp:string(value)):TimeoutAfter(2000))
:Then(true)
end)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcut.inspector.video.doBlendMode(value)")
end
-- doStabilization(value) -> none
-- Function
-- Enables or disables Stabilisation.
--
-- Parameters:
-- * value - `true` to enable, `false` to disable.
--
-- Returns:
-- * None
local function doStabilization(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local stabilization = fcp.inspector.video:stabilization().enabled
return Do(function()
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end
if value then
return Do(stabilization:doCheck())
:Then(WaitUntil(stabilization):Is(value):TimeoutAfter(2000))
:Then(true)
else
return Do(stabilization:doUncheck())
:Then(WaitUntil(stabilization):Is(value):TimeoutAfter(2000))
:Then(true)
end
end)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcut.inspector.video.doStabilization(value)")
end
-- doStabilizationMethod(value) -> none
-- Function
-- Enables or disables Stabilisation.
--
-- Parameters:
-- * value - Thestabilisation mode you wish to change the clip(s) to as a Final Cut Pro string ID.
--
-- Returns:
-- * None
local function doStabilizationMethod(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local stabilization = fcp.inspector.video:stabilization()
local method = fcp.inspector.video:stabilization():method()
return If(function()
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
else
return true
end
end):Is(true):Then(
If(stabilization:doShow())
:Then(
If(stabilization.isShowing)
:Then(
If(stabilization.enabled.checked):Is(false)
:Then(stabilization.enabled:doCheck())
:Then(WaitUntil(stabilization.enabled):Is(true):TimeoutAfter(2000))
)
:Then(
If(method.isEnabled) -- Only try and "tick" it if it's enabled. The stabilisation might still be processing.
:Then(method:doSelectValue(fcp:string(value)))
:Then(WaitUntil(method):Is(fcp:string(value)):TimeoutAfter(2000))
)
:Then(true)
:Otherwise(function()
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end)
)
:Otherwise(function()
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end)
)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcut.inspector.video.doStabilizationMethod(value)")
end
-- doRollingShutter(value) -> none
-- Function
-- Enables or disables Stabilisation.
--
-- Parameters:
-- * value - `true` to enable, `false` to disable.
--
-- Returns:
-- * None
local function doRollingShutter(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local rollingShutter = fcp.inspector.video:rollingShutter().enabled
return Do(function()
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end
if value then
return Do(rollingShutter:doCheck())
:Then(WaitUntil(rollingShutter):Is(value):TimeoutAfter(2000))
:Then(true)
else
return Do(rollingShutter:doUncheck())
:Then(WaitUntil(rollingShutter):Is(value):TimeoutAfter(2000))
:Then(true)
end
end)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcut.inspector.video.doRollingShutter(value)")
end
-- doRollingShutterAmount(value) -> none
-- Function
-- Sets the Rolling Shutter Amount.
--
-- Parameters:
-- * value - The rolling shutter amount you wish to change the clip(s) to as a Final Cut Pro string ID.
--
-- Returns:
-- * None
local function doRollingShutterAmount(value)
local timeline = fcp.timeline
local timelineContents = timeline.contents
local rollingShutter = fcp.inspector.video:rollingShutter()
local amount = rollingShutter:amount()
return If(function()
--------------------------------------------------------------------------------
-- Make sure at least one clip is selected:
--------------------------------------------------------------------------------
local clips = timelineContents:selectedClipsUI()
if clips and #clips == 0 then
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
else
return true
end
end):Is(true):Then(
If(rollingShutter:doShow())
:Then(
If(rollingShutter.isShowing)
:Then(
If(rollingShutter.enabled.checked):Is(false)
:Then(rollingShutter.enabled:doCheck())
:Then(WaitUntil(rollingShutter.enabled):Is(true):TimeoutAfter(2000))
)
:Then(
If(amount.isEnabled) -- Only try and "tick" it if it's enabled. It might still be processing.
:Then(amount:doSelectValue(fcp:string(value)))
:Then(WaitUntil(amount):Is(fcp:string(value)):TimeoutAfter(2000))
)
:Then(true)
:Otherwise(function()
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end)
)
:Otherwise(function()
displayMessage(i18n("noSelectedClipsInTimeline"))
return false
end)
)
:Catch(function(message)
displayErrorMessage(message)
return false
end)
:Label("plugins.finalcut.inspector.video.doRollingShutterAmount(value)")
end
local plugin = {
id = "finalcutpro.inspector.video",
group = "finalcutpro",
dependencies = {
["finalcutpro.commands"] = "fcpxCmds",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if FCPX is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
local SHIFT_AMOUNTS = {0.1, 1, 5, 10, 15, 20, 25, 30, 35, 40}
--------------------------------------------------------------------------------
-- Stabilization:
--------------------------------------------------------------------------------
local fcpxCmds = deps.fcpxCmds
fcpxCmds
:add("cpStabilizationEnable")
:whenActivated(function() doStabilization(true):Now() end)
fcpxCmds
:add("cpStabilizationDisable")
:whenActivated(function() doStabilization(false):Now() end)
--------------------------------------------------------------------------------
-- Stabilization Method:
--------------------------------------------------------------------------------
fcpxCmds
:add("stabilizationMethodAutomatic")
:whenActivated(function() doStabilizationMethod("FFStabilizationDynamic"):Now() end)
:titled(i18n("stabilizationMethod") .. ": " .. i18n("automatic"))
fcpxCmds
:add("stabilizationMethodInertiaCam")
:whenActivated(function() doStabilizationMethod("FFStabilizationUseInertiaCam"):Now() end)
:titled(i18n("stabilizationMethod") .. ": " .. i18n("inertiaCam"))
fcpxCmds
:add("stabilizationMethodSmoothCam")
:whenActivated(function() doStabilizationMethod("FFStabilizationUseSmoothCam"):Now() end)
:titled(i18n("stabilizationMethod") .. ": " .. i18n("smoothCam"))
--------------------------------------------------------------------------------
-- Rolling Shutter:
--------------------------------------------------------------------------------
fcpxCmds
:add("cpRollingShutterEnable")
:whenActivated(function() doRollingShutter(true):Now() end)
fcpxCmds
:add("cpRollingShutterDisable")
:whenActivated(function() doRollingShutter(false):Now() end)
--------------------------------------------------------------------------------
-- Rolling Shutter Amount:
--------------------------------------------------------------------------------
local rollingShutterAmounts = fcp.inspector.video.ROLLING_SHUTTER_AMOUNTS
local rollingShutterTitle = i18n("rollingShutter")
local rollingShutterAmount = i18n("amount")
for _, v in pairs(rollingShutterAmounts) do
fcpxCmds
:add(v.flexoID)
:whenActivated(function() doRollingShutterAmount(v.flexoID):Now() end)
:titled(rollingShutterTitle .. " " .. rollingShutterAmount .. ": " .. i18n(v.i18n))
end
--------------------------------------------------------------------------------
-- Spatial Conform:
--------------------------------------------------------------------------------
fcpxCmds
:add("cpSetSpatialConformTypeToFit")
:whenActivated(function() doSpatialConformType("FFConformTypeFit"):Now() end)
fcpxCmds
:add("cpSetSpatialConformTypeToFill")
:whenActivated(function() doSpatialConformType("FFConformTypeFill"):Now() end)
fcpxCmds
:add("cpSetSpatialConformTypeToNone")
:whenActivated(function() doSpatialConformType("FFConformTypeNone"):Now() end)
--------------------------------------------------------------------------------
-- Blend Modes:
--------------------------------------------------------------------------------
local blendModes = fcp.inspector.video.BLEND_MODES
for _, v in pairs(blendModes) do
if v.flexoID ~= nil then
fcpxCmds
:add(v.flexoID)
:whenActivated(function() doBlendMode(v.flexoID):Now() end)
:titled(i18n("blendMode") .. ": " .. i18n(v.i18n))
end
end
--------------------------------------------------------------------------------
-- Position:
--------------------------------------------------------------------------------
local posX = 0
local posY = 0
local video = fcp.inspector.video
local transform = video:transform()
local position = transform:position()
local updatePosition = deferred.new(0.01)
local posUpdating = false
updatePosition:action(function()
return If(function() return not posUpdating and (posX ~= 0 or posY ~= 0) end)
:Then(
Do(position:doShow())
:Then(function()
posUpdating = true
if posX ~= 0 then
local current = position:x()
if current then
position:x(current + posX)
end
posX = 0
end
if posY ~= 0 then
local current = position:y()
if current then
position:y(current + posY)
end
posY = 0
end
posUpdating = false
end)
)
:Label("plugins.finalcutpro.inspector.video.updatePosition")
:Now()
end)
for _, shiftAmount in pairs(SHIFT_AMOUNTS) do
fcpxCmds:add("shiftPositionLeftPixels" .. shiftAmount .. "Pixels")
:titled(i18n("shiftPositionLeftPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
posX = posX - shiftAmount
updatePosition()
end)
:whenRepeated(function()
posX = posX - shiftAmount
updatePosition()
end)
fcpxCmds:add("shiftPositionRightPixels" .. shiftAmount .. "Pixels")
:titled(i18n("shiftPositionRightPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
posX = posX + shiftAmount
updatePosition()
end)
:whenRepeated(function()
posX = posX + shiftAmount
updatePosition()
end)
fcpxCmds:add("shiftPositionUp" .. shiftAmount .. "Pixels")
:titled(i18n("shiftPositionUpPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
posY = posY + shiftAmount
updatePosition()
end)
:whenRepeated(function()
posY = posY + shiftAmount
updatePosition()
end)
fcpxCmds:add("shiftPositionDown" .. shiftAmount .. "Pixels")
:titled(i18n("shiftPositionDownPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
posY = posY - shiftAmount
updatePosition()
end)
:whenRepeated(function()
posY = posY - shiftAmount
updatePosition()
end)
end
fcpxCmds:add("resetPositionX")
:titled(i18n("reset") .. " " .. i18n("position") .. " X")
:groupedBy("timeline")
:whenPressed(function()
position:show()
position:x(0)
end)
fcpxCmds:add("resetPositionY")
:titled(i18n("reset") .. " " .. i18n("position") .. " Y")
:groupedBy("timeline")
:whenPressed(function()
position:show()
position:y(0)
end)
--------------------------------------------------------------------------------
-- Anchor:
--------------------------------------------------------------------------------
local anchorX = 0
local anchorY = 0
local anchor = transform:anchor()
local updateAnchor = deferred.new(0.01)
local anchorUpdating = false
updateAnchor:action(function()
return If(function() return not anchorUpdating and (anchorX ~= 0 or anchorY ~= 0) end)
:Then(
Do(anchor:doShow())
:Then(function()
anchorUpdating = true
if anchorX ~= 0 then
local current = anchor:x()
if current then
anchor:x(current + anchorX)
end
anchorX = 0
end
if anchorY ~= 0 then
local current = anchor:y()
if current then
anchor:y(current + anchorY)
end
anchorY = 0
end
anchorUpdating = false
end)
)
:Label("plugins.finalcutpro.inspector.video.updateAnchor")
:Now()
end)
for _, shiftAmount in pairs(SHIFT_AMOUNTS) do
fcpxCmds:add("shiftAnchorLeftPixels" .. shiftAmount .. "Pixels")
:titled(i18n("shiftAnchorLeftPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
anchorX = anchorX - shiftAmount
updateAnchor()
end)
:whenRepeated(function()
anchorX = anchorX - shiftAmount
updateAnchor()
end)
fcpxCmds:add("shiftAnchorRightPixels" .. shiftAmount .. "Pixels")
:titled(i18n("shiftAnchorRightPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
anchorX = anchorX + shiftAmount
updateAnchor()
end)
:whenRepeated(function()
anchorX = anchorX + shiftAmount
updateAnchor()
end)
fcpxCmds:add("shiftAnchorUp" .. shiftAmount .. "Pixels")
:titled(i18n("shiftAnchorUpPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
anchorY = anchorY + shiftAmount
updateAnchor()
end)
:whenRepeated(function()
anchorY = anchorY + shiftAmount
updateAnchor()
end)
fcpxCmds:add("shiftAnchorDown" .. shiftAmount .. "Pixels")
:titled(i18n("shiftAnchorDownPixels", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function()
anchorY = anchorY - shiftAmount
updateAnchor()
end)
:whenRepeated(function()
anchorY = anchorY - shiftAmount
updateAnchor()
end)
end
fcpxCmds:add("resetAnchorX")
:titled(i18n("reset") .. " " .. i18n("anchor") .. " X")
:groupedBy("timeline")
:whenPressed(function()
anchor:show()
anchor:x(0)
end)
fcpxCmds:add("resetAnchorY")
:titled(i18n("reset") .. " " .. i18n("anchor") .. " Y")
:groupedBy("timeline")
:whenPressed(function()
anchor:show()
anchor:y(0)
end)
--------------------------------------------------------------------------------
-- Scale All:
--------------------------------------------------------------------------------
local scaleAll = transform:scaleAll()
local shiftScaleUpdating = false
local shiftScaleValue = 0
local updateShiftScale = deferred.new(0.01):action(function()
return If(function() return not shiftScaleUpdating and shiftScaleValue ~= 0 end)
:Then(
Do(scaleAll:doShow())
:Then(function()
shiftScaleUpdating = true
local currentValue = scaleAll:value()
if currentValue then
scaleAll:value(currentValue + shiftScaleValue)
shiftScaleValue = 0
end
shiftScaleUpdating = false
end)
)
:Label("plugins.finalcutpro.inspector.video.updateShiftScale")
:Now()
end)
local shiftScale = function(value)
shiftScaleValue = shiftScaleValue + value
updateShiftScale()
end
for _, shiftAmount in pairs(SHIFT_AMOUNTS) do
fcpxCmds:add("shiftScaleUp" .. shiftAmount)
:titled(i18n("shiftScaleUp", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftScale(shiftAmount) end)
:whenRepeated(function() shiftScale(shiftAmount) end)
fcpxCmds:add("shiftScaleDown" .. shiftAmount)
:titled(i18n("shiftScaleDown", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftScale(shiftAmount * -1) end)
:whenRepeated(function() shiftScale(shiftAmount * -1) end)
end
fcpxCmds:add("resetScale")
:titled(i18n("reset") .. " " .. i18n("scale") .. " " .. i18n("all"))
:groupedBy("timeline")
:whenPressed(function()
scaleAll:show()
scaleAll:value(100)
end)
--------------------------------------------------------------------------------
-- Rotation:
--------------------------------------------------------------------------------
local rotation = fcp.inspector.video:transform():rotation()
local shiftRotationValue = 0
local updateShiftRotation = deferred.new(0.01):action(function()
rotation:show()
local original = rotation:value()
rotation:value(original + shiftRotationValue)
shiftRotationValue = 0
end)
local shiftRotation = function(value)
shiftRotationValue = shiftRotationValue + value
updateShiftRotation()
end
for _, shiftAmount in pairs(SHIFT_AMOUNTS) do
fcpxCmds:add("shiftRotationLeft" .. shiftAmount)
:titled(i18n("shiftRotationLeft", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftRotation(shiftAmount) end)
:whenRepeated(function() shiftRotation(shiftAmount) end)
fcpxCmds:add("shiftRotationRight" .. shiftAmount)
:titled(i18n("shiftRotationRight", {amount=shiftAmount, count=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftRotation(shiftAmount * -1) end)
:whenRepeated(function() shiftRotation(shiftAmount * -1) end)
end
fcpxCmds:add("resetRotation")
:titled(i18n("reset") .. " " .. i18n("rotation"))
:groupedBy("timeline")
:whenPressed(function()
rotation:show()
rotation:value(0)
end)
--------------------------------------------------------------------------------
-- Opacity:
--------------------------------------------------------------------------------
local opacity = fcp.inspector.video:compositing():opacity()
local shiftOpacityValue = 0
local updateShiftOpacity = deferred.new(0.01):action(function()
opacity:show()
local original = opacity:value()
opacity:value(original + shiftOpacityValue)
shiftOpacityValue = 0
end)
local shiftOpacity = function(value)
shiftOpacityValue = shiftOpacityValue + value
updateShiftOpacity()
end
for _, shiftAmount in pairs(SHIFT_AMOUNTS) do
fcpxCmds:add("shiftOpacityLeft" .. shiftAmount)
:titled(i18n("decreaseOpacity", {amount=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftOpacity(shiftAmount * -1) end)
:whenRepeated(function() shiftOpacity(shiftAmount * -1) end)
fcpxCmds:add("shiftOpacityRight" .. shiftAmount)
:titled(i18n("increaseOpacity", {amount=shiftAmount}))
:groupedBy("timeline")
:whenPressed(function() shiftOpacity(shiftAmount) end)
:whenRepeated(function() shiftOpacity(shiftAmount) end)
end
fcpxCmds:add("resetOpacity")
:titled(i18n("reset") .. " " .. i18n("opacity"))
:groupedBy("timeline")
:whenPressed(function()
opacity:show()
opacity:value(100)
end)
--------------------------------------------------------------------------------
-- Compositing Reset:
--------------------------------------------------------------------------------
fcpxCmds:add("resetCompositing")
:titled(i18n("reset") .. " " .. i18n("compositing"))
:groupedBy("timeline")
:whenPressed(function()
doBlendMode("FFHeliumBlendModeNormal"):Then(function()
opacity:show()
opacity:value(100)
end):Now()
end)
--------------------------------------------------------------------------------
-- Crop:
--------------------------------------------------------------------------------
local CROP_TYPES = fcp.inspector.video.CROP_TYPES
for _, c in pairs(CROP_TYPES) do
fcpxCmds:add("cropType" .. c.i18n)
:titled(i18n("cropType") .. ": " .. i18n(c.i18n))
:whenPressed(function()
local cropType = fcp.inspector.video:crop():type()
cropType:doShow():Then(
cropType:doSelectValue(fcp:string(c.flexoID))
):Now()
end)
end
local cropLeftValue = 0
local updateCropLeft = deferred.new(0.01):action(function()
local cropLeft = fcp.inspector.video:crop():left()
cropLeft:show()
local original = cropLeft:value()
cropLeft:value(original + cropLeftValue)
cropLeftValue = 0
end)
local cropRightValue = 0
local updateCropRight = deferred.new(0.01):action(function()
local cropRight = fcp.inspector.video:crop():right()
cropRight:show()
local original = cropRight:value()
cropRight:value(original + cropRightValue)
cropRightValue = 0
end)
local cropTopValue = 0
local updateCropTop = deferred.new(0.01):action(function()
local cropTop = fcp.inspector.video:crop():top()
cropTop:show()
local original = cropTop:value()
cropTop:value(original + cropTopValue)
cropTopValue = 0
end)
local cropBottomValue = 0
local updateCropBottom = deferred.new(0.01):action(function()
local cropBottom = fcp.inspector.video:crop():bottom()
cropBottom:show()
local original = cropBottom:value()
cropBottom:value(original + cropBottomValue)
cropBottomValue = 0
end)
local cropAmounts = {0.1, 1, 5, 10, 15, 20, 25, 30, 35, 40}
for _, c in pairs(cropAmounts) do
fcpxCmds:add("cropLeftIncrease" .. c)
:titled(i18n("crop") .. " " .. i18n("left") .. " " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
cropLeftValue = cropLeftValue + c
updateCropLeft()
end)
fcpxCmds:add("cropLeftDecrease" .. c)
:titled(i18n("crop") .. " " .. i18n("left") .. " " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
cropLeftValue = cropLeftValue - c
updateCropLeft()
end)
fcpxCmds:add("cropRightIncrease" .. c)
:titled(i18n("crop") .. " " .. i18n("right") .. " " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
cropRightValue = cropRightValue + c
updateCropRight()
end)
fcpxCmds:add("cropRightDecrease" .. c)
:titled(i18n("crop") .. " " .. i18n("right") .. " " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
cropRightValue = cropRightValue - c
updateCropRight()
end)
fcpxCmds:add("cropTopIncrease" .. c)
:titled(i18n("crop") .. " " .. i18n("top") .. " " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
cropTopValue = cropTopValue + c
updateCropTop()
end)
fcpxCmds:add("cropTopDecrease" .. c)
:titled(i18n("crop") .. " " .. i18n("top") .. " " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
cropTopValue = cropTopValue - c
updateCropTop()
end)
fcpxCmds:add("cropBottomIncrease" .. c)
:titled(i18n("crop") .. " " .. i18n("bottom") .. " " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
cropBottomValue = cropBottomValue + c
updateCropBottom()
end)
fcpxCmds:add("cropBottomDecrease" .. c)
:titled(i18n("crop") .. " " .. i18n("bottom") .. " " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
cropBottomValue = cropBottomValue - c
updateCropBottom()
end)
end
fcpxCmds:add("cropResetLeft")
:titled(i18n("crop") .. " " .. i18n("left") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:crop():left():show():value(0)
end)
fcpxCmds:add("cropResetRight")
:titled(i18n("crop") .. " " .. i18n("right") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:crop():right():show():value(0)
end)
fcpxCmds:add("cropResetTop")
:titled(i18n("crop") .. " " .. i18n("top") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:crop():top():show():value(0)
end)
fcpxCmds:add("cropResetBottom")
:titled(i18n("crop") .. " " .. i18n("bottom") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:crop():bottom():show():value(0)
end)
fcpxCmds:add("cropReset")
:titled(i18n("crop") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:crop():left():show():value(0)
fcp.inspector.video:crop():right():show():value(0)
fcp.inspector.video:crop():top():show():value(0)
fcp.inspector.video:crop():bottom():show():value(0)
end)
--------------------------------------------------------------------------------
-- Distort:
--------------------------------------------------------------------------------
local distortBottomLeftXValue = 0
local updateDistortBottomLeftX = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():bottomLeft().x
d:show()
local original = d:value()
d:value(original + distortBottomLeftXValue)
distortBottomLeftXValue = 0
end)
local distortBottomLeftYValue = 0
local updateDistortBottomLeftY = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():bottomLeft().x
d:show()
local original = d:value()
d:value(original + distortBottomLeftYValue)
distortBottomLeftYValue = 0
end)
local distortBottomRightXValue = 0
local updateDistortBottomRightX = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():bottomRight().x
d:show()
local original = d:value()
d:value(original + distortBottomRightXValue)
distortBottomRightXValue = 0
end)
local distortBottomRightYValue = 0
local updateDistortBottomRightY = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():bottomRight().x
d:show()
local original = d:value()
d:value(original + distortBottomRightYValue)
distortBottomRightYValue = 0
end)
local distortTopLeftXValue = 0
local updateDistortTopLeftX = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():topLeft().x
d:show()
local original = d:value()
d:value(original + distortTopLeftXValue)
distortTopLeftXValue = 0
end)
local distortTopLeftYValue = 0
local updateDistortTopLeftY = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():topLeft().x
d:show()
local original = d:value()
d:value(original + distortTopLeftYValue)
distortTopLeftYValue = 0
end)
local distortTopRightXValue = 0
local updateDistortTopRightX = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():topRight().x
d:show()
local original = d:value()
d:value(original + distortTopRightXValue)
distortTopRightXValue = 0
end)
local distortTopRightYValue = 0
local updateDistortTopRightY = deferred.new(0.01):action(function()
local d = fcp.inspector.video:distort():topRight().x
d:show()
local original = d:value()
d:value(original + distortTopRightYValue)
distortTopRightYValue = 0
end)
local distortAmounts = {0.1, 1, 5, 10, 15, 20, 25, 30, 35, 40}
for _, c in pairs(distortAmounts) do
--------------------------------------------------------------------------------
-- Bottom Left:
--------------------------------------------------------------------------------
fcpxCmds:add("distortBottomLeftXIncrease" .. c)
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("left") .. " X " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortBottomLeftXValue = distortBottomLeftXValue + c
updateDistortBottomLeftX()
end)
fcpxCmds:add("distortBottomLeftYIncrease" .. c)
:titled(i18n("distort") .. " " .. i18n("bottom") .. " " .. i18n("left") .. " Y " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortBottomLeftYValue = distortBottomLeftYValue + c
updateDistortBottomLeftY()
end)
fcpxCmds:add("distortBottomLeftXDecrease" .. c)
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("left") .. " X " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortBottomLeftXValue = distortBottomLeftXValue - c
updateDistortBottomLeftX()
end)
fcpxCmds:add("distortBottomLeftYDecrease" .. c)
:titled(i18n("distort") .. " " .. i18n("bottom") .. " " .. i18n("left") .. " Y " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortBottomLeftYValue = distortBottomLeftYValue - c
updateDistortBottomLeftY()
end)
--------------------------------------------------------------------------------
-- Bottom Right:
--------------------------------------------------------------------------------
fcpxCmds:add("distortBottomRightXIncrease" .. c)
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("right") .. " X " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortBottomRightXValue = distortBottomRightXValue + c
updateDistortBottomRightX()
end)
fcpxCmds:add("distortBottomRightYIncrease" .. c)
:titled(i18n("distort") .. " " .. i18n("bottom") .. " " .. i18n("right") .. " Y " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortBottomRightYValue = distortBottomRightYValue + c
updateDistortBottomRightY()
end)
fcpxCmds:add("distortBottomRightXDecrease" .. c)
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("right") .. " X " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortBottomRightXValue = distortBottomRightXValue - c
updateDistortBottomRightX()
end)
fcpxCmds:add("distortBottomRightYDecrease" .. c)
:titled(i18n("distort") .. " " .. i18n("bottom") .. " " .. i18n("right") .. " Y " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortBottomRightYValue = distortBottomRightYValue + c
updateDistortBottomRightY()
end)
--------------------------------------------------------------------------------
-- Top Left:
--------------------------------------------------------------------------------
fcpxCmds:add("distortTopLeftXIncrease" .. c)
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("left") .. " X " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortTopLeftXValue = distortTopLeftXValue + c
updateDistortTopLeftX()
end)
fcpxCmds:add("distortTopLeftYIncrease" .. c)
:titled(i18n("distort") .. " " .. i18n("top") .. " " .. i18n("left") .. " Y " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortTopLeftYValue = distortTopLeftYValue + c
updateDistortTopLeftY()
end)
fcpxCmds:add("distortTopLeftXDecrease" .. c)
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("left") .. " X " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortTopLeftXValue = distortTopLeftXValue - c
updateDistortTopLeftX()
end)
fcpxCmds:add("distortTopLeftYDecrease" .. c)
:titled(i18n("distort") .. " " .. i18n("top") .. " " .. i18n("left") .. " Y " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortTopLeftYValue = distortTopLeftYValue - c
updateDistortTopLeftY()
end)
--------------------------------------------------------------------------------
-- Top Right:
--------------------------------------------------------------------------------
fcpxCmds:add("distortTopRightXIncrease" .. c)
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("right") .. " X " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortTopRightXValue = distortTopRightXValue + c
updateDistortTopRightX()
end)
fcpxCmds:add("distortTopRightYIncrease" .. c)
:titled(i18n("distort") .. " " .. i18n("top") .. " " .. i18n("right") .. " Y " .. i18n("increase") .. " " .. c .. "px")
:whenPressed(function()
distortTopRightYValue = distortTopRightYValue + c
updateDistortTopRightY()
end)
fcpxCmds:add("distortTopRightXDecrease" .. c)
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("right") .. " X " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortTopRightXValue = distortTopRightXValue - c
updateDistortTopRightX()
end)
fcpxCmds:add("distortTopRightYDecrease" .. c)
:titled(i18n("distort") .. " " .. i18n("top") .. " " .. i18n("right") .. " Y " .. i18n("decrease") .. " " .. c .. "px")
:whenPressed(function()
distortTopRightYValue = distortTopRightYValue + c
updateDistortTopRightY()
end)
end
fcpxCmds:add("distortBottomLeftXReset")
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("left") .. " X " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():bottomLeft().x:show():value(0)
end)
fcpxCmds:add("distortBottomLeftYReset")
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("left") .. " Y " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():bottomLeft().y:show():value(0)
end)
fcpxCmds:add("distortBottomRightXReset")
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("right") .. " X " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():bottomRight().x:show():value(0)
end)
fcpxCmds:add("distortBottomRightYReset")
:titled(i18n("distort") .. " ".. i18n("bottom") .. " " .. i18n("right") .. " Y " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():bottomRight().y:show():value(0)
end)
fcpxCmds:add("distortTopLeftXReset")
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("left") .. " X " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():topLeft().x:show():value(0)
end)
fcpxCmds:add("distortTopLeftYReset")
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("left") .. " Y " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():topLeft().y:show():value(0)
end)
fcpxCmds:add("distortTopRightXReset")
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("right") .. " X " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():topRight().x:show():value(0)
end)
fcpxCmds:add("distortTopRightYReset")
:titled(i18n("distort") .. " ".. i18n("top") .. " " .. i18n("right") .. " Y " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():topRight().y:show():value(0)
end)
fcpxCmds:add("distortReset")
:titled(i18n("distort") .. " " .. i18n("reset"))
:whenPressed(function()
fcp.inspector.video:distort():bottomLeft().x:show():value(0)
fcp.inspector.video:distort():bottomLeft().y:show():value(0)
fcp.inspector.video:distort():bottomRight().x:show():value(0)
fcp.inspector.video:distort():bottomRight().y:show():value(0)
fcp.inspector.video:distort():topLeft().x:show():value(0)
fcp.inspector.video:distort():topLeft().y:show():value(0)
fcp.inspector.video:distort():topRight().x:show():value(0)
fcp.inspector.video:distort():topRight().y:show():value(0)
end)
--------------------------------------------------------------------------------
-- Effects:
--------------------------------------------------------------------------------
fcpxCmds:add("toggleSelectedEffect")
:titled(i18n("toggle") .. " " .. i18n("selected") .. " " .. i18n("effect"))
:whenPressed(function()
fcp.inspector.video:show()
local checkbox = fcp.inspector.video:selectedEffectCheckBox()
if checkbox then
checkbox:performAction("AXPress")
end
end)
for i=1, 9 do
fcpxCmds:add("toggleEffect" .. i)
:titled(i18n("toggle") .. " " .. i18n("effect") .. " " .. i)
:whenPressed(function()
fcp.inspector.video:show()
local checkboxes = fcp.inspector.video:effectCheckBoxes()
if checkboxes and checkboxes[i] then
checkboxes[i]:performAction("AXPress")
end
end)
end
--------------------------------------------------------------------------------
-- Reset Transform:
--------------------------------------------------------------------------------
fcpxCmds:add("resetTransform")
:titled(i18n("reset") .. " " .. i18n("transform"))
:groupedBy("timeline")
:whenPressed(function()
position:show()
position:x(0)
position:y(0)
rotation:show()
rotation:value(0)
local scaleX = transform:scaleX()
scaleX:show()
scaleX:value(100)
local scaleY = transform:scaleY()
scaleY:show()
scaleY:value(100)
scaleAll:show()
scaleAll:value(100)
anchor:show()
anchor:x(0)
anchor:y(0)
end)
end
return plugin
| mit |
TeleSudo/TeleRedStar | plugins/admin.lua | 1 | 11284 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, '<b>Failed, please try again!</b>', ok_cb, false)
end
end
--Function to add log supergroup
local function logadd(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = msg.to.peer_id
save_data(_config.moderation.data, data)
local text = '<b>Log_SuperGroup has has been set!</b>'
reply_msg(msg.id,text,ok_cb,false)
return
end
--Function to remove log supergroup
local function logrem(msg)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local GBan_log = 'GBan_log'
if not data[tostring(GBan_log)] then
data[tostring(GBan_log)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(GBan_log)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local text = '<b>Log_SuperGroup has has been removed!</b>'
reply_msg(msg.id,text,ok_cb,false)
return
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairsByKeys(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function reload_plugins( )
plugins = {}
return load_plugins()
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", " ")
if not is_admin1(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return reply_msg(msg.id,'<b>Please send me bot photo now</b>', ok_cb, false)
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return reply_msg(msg.id,"<b>Mark read > on</b>", ok_cb, false)
end
if matches[2] == "off" then
redis:del("bot:markread")
return reply_msg(msg.id,"<b>Mark read > off</b>", ok_cb, false)
end
return
end
if matches[1] == "pm" then
local text = "Message From "..(msg.from.username or msg.from.last_name).."\n\nMessage : "..matches[3]
send_large_msg("user#id"..matches[2],text)
return reply_msg(msg.id,"<b>Message has been sent</b>", ok_cb, false)
end
if matches[1] == "pmblock" then
if is_admin2(matches[2]) then
return reply_msg(msg.id,"<b>You can't block admins</b>", ok_cb, false)
end
block_user("user#id"..matches[2],ok_cb,false)
return "<b>User blocked</b>"
end
if matches[1] == "pmunblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return reply_msg(msg.id,"<b>User unblocked</b>", ok_cb, false)
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
if not is_sudo(msg) then-- Sudo only
return
end
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return reply_msg(msg.id,"<b>I've sent contact list with both json and text format to your private</b>", ok_cb, false)
end
if matches[1] == "delcontact" then
if not is_sudo(msg) then-- Sudo only
return
end
del_contact("user#id"..matches[2],ok_cb,false)
return reply_msg(msg.id,"<b>User </b><b>"..matches[2].." </b><b>removed from contact list</b>", ok_cb, false)
end
if matches[1] == "addcontact" and is_sudo(msg) then
phone = matches[2]
first_name = matches[3]
last_name = matches[4]
add_contact(phone, first_name, last_name, ok_cb, false)
return reply_msg(msg.id,"<b>User With Phone +</b><b>"..matches[2].."</b> <b>has been added<b>", ok_cb, false)
end
if matches[1] == "sendcontact" and is_sudo(msg) then
phone = matches[2]
first_name = matches[3]
last_name = matches[4]
send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false)
end
if matches[1] == "mycontact" and is_sudo(msg) then
if not msg.from.phone then
return reply_msg(msg.id,"<b>I must Have Your Phone Number!</b>", ok_cb, false)
end
phone = msg.from.phone
first_name = (msg.from.first_name or msg.from.phone)
last_name = (msg.from.last_name or msg.from.id)
send_contact(get_receiver(msg), phone, first_name, last_name, ok_cb, false)
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return reply_msg(msg.id,"<b>I've sent a group dialog list with both json and text format to your private messages</b>", ok_cb, false)
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
if matches[1] == "sync_gbans" then
if not is_sudo(msg) then-- Sudo only
return
end
local url = "http://seedteam.org/Teleseed/Global_bans.json"
local SEED_gbans = http.request(url)
local jdat = json:decode(SEED_gbans)
for k,v in pairs(jdat) do
redis:hset('user:'..v, 'print_name', k)
banall_user(v)
print(k, v.." Globally banned")
end
end
if matches[1] == 'reload' then
receiver = get_receiver(msg)
reload_plugins(true)
post_msg(receiver, "", ok_cb, false)
return reply_msg(msg.id,"<b>All Plugins Reloaded</b> \n<b>Order By|</b><b>"..msg.from.id.."</b><b>|</b>", ok_cb, false)
end
--[[*For Debug*
if matches[1] == "vardumpmsg" and is_admin1(msg) then
local text = serpent.block(msg, {comment=false})
send_large_msg("channel#id"..msg.to.id, text)
end]]
if matches[1] == 'updateid' then
local data = load_data(_config.moderation.data)
local long_id = data[tostring(msg.to.id)]['long_id']
if not long_id then
data[tostring(msg.to.id)]['long_id'] = msg.to.peer_id
save_data(_config.moderation.data, data)
return reply_msg(msg.id,"Updated ID", ok_cb, false)
end
end
if matches[1] == 'addlog' and not matches[2] then
if is_log_group(msg) then
return reply_msg(msg.id,"Already a Log_SuperGroup", ok_cb, false)
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") added")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logadd(msg)
end
if matches[1] == 'remlog' and not matches[2] then
if not is_log_group(msg) then
return "Not a Log_SuperGroup"
end
print("Log_SuperGroup "..msg.to.title.."("..msg.to.id..") removed")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] added Log_SuperGroup")
logrem(msg)
end
return
end
local function pre_process(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
return msg
end
return {
patterns = {
"^[#!/](pm) (%d+) (.*)$",
"^[#!/](import) (.*)$",
"^[#!/](pmunblock) (%d+)$",
"^[#!/](pmblock) (%d+)$",
"^[#!/](markread) (on)$",
"^[#!/](markread) (off)$",
"^[#!/](setbotphoto)$",
"^[#!/](contactlist)$",
"^[#!/](dialoglist)$",
"^[#!/](delcontact) (%d+)$",
"^[#!/](addcontact) (.*) (.*) (.*)$",
"^[#!/](sendcontact) (.*) (.*) (.*)$",
"^[#!/](mycontact)$",
"^[#/!](reload)$",
"^[#/!](updateid)$",
"^[#/!](sync_gbans)$",
"^[#/!](addlog)$",
"^[#/!](remlog)$",
"%[(photo)%]",
},
run = run,
pre_process = pre_process
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/test/plugins/admin.lua
---Modified by @Rondoozle for supergroups
| agpl-3.0 |
Enignite/darkstar | scripts/globals/items/bowl_of_sprightly_soup.lua | 36 | 1326 | -----------------------------------------
-- ID: 5930
-- Item: Bowl of Sprightly Soup
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- MP 30
-- Mind 4
-- HP Recovered While Healing 4
-- Enmity -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5930);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 30);
target:addMod(MOD_MND, 4);
target:addMod(MOD_HPHEAL, 4);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 30);
target:delMod(MOD_MND, 4);
target:delMod(MOD_HPHEAL, 4);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
troopizer/ot-server | data/npc/scripts/brean.lua | 1 | 3476 | local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
local talkState = {}
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
function creatureSayCallback(cid, type, msg)
if(not npcHandler:isFocused(cid)) then
return false
end
local talkUser = NPCHANDLER_CONVBEHAVIOR == CONVERSATION_DEFAULT and 0 or cid
if(msgcontains(msg, 'mission')) then
if (getPlayerStorageValue(cid,2102) < 0) then
selfSay('Soo you are looking for a job?.', cid)
selfSay('Im a leatherworker, the best one in this lands. I need some boar fur for my work.', cid)
selfSay('If you get some fur for me, I will craft armors for you, but you will have to get the materials.{ok}?', cid)
end
if (getPlayerStorageValue(cid,2102) == 0) then
if(getPlayerItemCount(cid, 5883) >= 20) then
doPlayerRemoveItem(cid, 5883, 20)
selfSay('Thanks! Now lets speak about {forge}.(You recived 50000 exp)', cid)
setPlayerStorageValue(cid,2102,1)
doPlayerAddExperience(cid,50000)
else
selfSay('I will keep waiting those furs.', cid)
end
end
if (getPlayerStorageValue(cid,2102) == 1) then
selfSay('I dont have more missions for you, but I can {forge} something for you.', cid)
end
talkState[talkUser] = 4
elseif(msgcontains(msg, 'ok') and talkState[talkUser] == 4) then
setPlayerStorageValue(cid,30010,9)
setPlayerStorageValue(cid,2102,0)
selfSay('Thanks! Get 20 boar furs.', cid)
end
if (getPlayerStorageValue(cid,2102) == 1) then
if(msgcontains(msg, 'forge')) then
talkState[talkUser] = 1
selfSay('Do you want to forge: {strong leather armor} or {hunter quilted armor}?', cid)
elseif(msgcontains(msg, 'strong leather armor') and talkState[talkUser] == 1) then
selfSay('Strong leather armor (Arm:12, Physical:2%, meele: +2), I would need {5 iron ores},{30 boar furs} and {30 leathers}, do you have they?.', cid)
talkState[talkUser] = 2
elseif(msgcontains(msg, 'yes') and talkState[talkUser] == 2) then
if(getPlayerItemCount(cid, 5883) >= 30 and getPlayerItemCount(cid, 5880) >= 5 and getPlayerItemCount(cid, 5878) >= 30) then
doPlayerRemoveItem(cid, 5883, 30)
doPlayerRemoveItem(cid, 5880, 5)
doPlayerRemoveItem(cid, 5878, 30)
doPlayerAddItem(cid,8876,1)
selfSay('Here you are.', cid)
else
selfSay('Sorry, you don\'t have enough iron, fur or leather.', cid)
end
talkState[talkUser] = 0
elseif(msgcontains(msg, 'hunter quilted armor') and talkState[talkUser] == 1) then
selfSay('Hunter quilted armor (Arm:12, Dist:+2), I would need {20 warg wolf fur},{30 boar furs} and {30 leather}, do you have they?.', cid)
talkState[talkUser] = 3
elseif(msgcontains(msg, 'yes') and talkState[talkUser] == 3) then
if(getPlayerItemCount(cid, 5883) >= 30 and getPlayerItemCount(cid, 11235) >= 20 and getPlayerItemCount(cid, 5878) >= 30) then
doPlayerRemoveItem(cid, 5883, 30)
doPlayerRemoveItem(cid, 11235, 20)
doPlayerRemoveItem(cid, 5878, 30)
doPlayerAddItem(cid,8874,1)
selfSay('Here you are.', cid)
else
selfSay('Sorry, you don\'t have enough fur or leather.', cid)
end
talkState[talkUser] = 0
end
end
end
npcHandler:setCallback(CALLBACK_MESSAGE_DEFAULT, creatureSayCallback)
npcHandler:addModule(FocusModule:new())
| gpl-2.0 |
ArmanIr/irbotttgcli | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
dcsan/telegram-bot | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
DipColor/mehrabon2 | plugins/gnuplot.lua | 622 | 1813 | --[[
* Gnuplot plugin by psykomantis
* dependencies:
* - gnuplot 5.00
* - libgd2-xpm-dev (on Debian distr) for more info visit: https://libgd.github.io/pages/faq.html
*
]]
-- Gnuplot needs absolute path for the plot, so i run some commands to find where we are
local outputFile = io.popen("pwd","r")
io.input(outputFile)
local _pwd = io.read("*line")
io.close(outputFile)
local _absolutePlotPath = _pwd .. "/data/plot.png"
local _scriptPath = "./data/gnuplotScript.gpl"
do
local function gnuplot(msg, fun)
local receiver = get_receiver(msg)
-- We generate the plot commands
local formattedString = [[
set grid
set terminal png
set output "]] .. _absolutePlotPath .. [["
plot ]] .. fun
local file = io.open(_scriptPath,"w");
file:write(formattedString)
file:close()
os.execute("gnuplot " .. _scriptPath)
os.remove (_scriptPath)
return _send_photo(receiver, _absolutePlotPath)
end
-- Check all dependencies before executing
local function checkDependencies()
local status = os.execute("gnuplot -h")
if(status==true) then
status = os.execute("gnuplot -e 'set terminal png'")
if(status == true) then
return 0 -- OK ready to go!
else
return 1 -- missing libgd2-xpm-dev
end
else
return 2 -- missing gnuplot
end
end
local function run(msg, matches)
local status = checkDependencies()
if(status == 0) then
return gnuplot(msg,matches[1])
elseif(status == 1) then
return "It seems that this bot miss a dependency :/"
else
return "It seems that this bot doesn't have gnuplot :/"
end
end
return {
description = "use gnuplot through telegram, only plot single variable function",
usage = "!gnuplot [single variable function]",
patterns = {"^!gnuplot (.+)$"},
run = run
}
end
| gpl-2.0 |
fcpxhacks/fcpxhacks | src/plugins/finalcutpro/tangent/os/display.lua | 2 | 1928 | --- === plugins.finalcutpro.tangent.os.display ===
---
--- Tangent Display Functions.
local require = require
local brightness = require "hs.brightness"
local dialog = require "cp.dialog"
local fcp = require "cp.apple.finalcutpro"
local i18n = require "cp.i18n"
local format = string.format
local mod = {}
--- plugins.finalcutpro.tangent.os.display.init() -> self
--- Function
--- Initialise the module.
---
--- Parameters:
--- * deps - Dependancies
---
--- Returns:
--- * Self
function mod.init(deps)
mod._displayGroup = deps.osGroup:group(i18n("display"))
mod._displayGroup:parameter(0x0AD00001)
:name(i18n("brightness"))
:name9(i18n("brightness9"))
:name10(i18n("brightness10"))
:minValue(0)
:maxValue(100)
:stepSize(5)
:onGet(function() return brightness.get() end)
:onChange(function(increment)
brightness.set(brightness.get() + increment)
local brightnessValue = brightness.get()
if brightnessValue and mod._lastBrightnessValue ~= brightnessValue then
dialog.displayNotification(format(i18n("brightness") .. ": %s", brightnessValue))
mod._lastBrightnessValue = brightnessValue
end
end)
:onReset(function() brightness.set(brightness.ambient()) end)
return mod
end
local plugin = {
id = "finalcutpro.tangent.os.display",
group = "finalcutpro",
dependencies = {
["finalcutpro.tangent.os"] = "osGroup",
}
}
function plugin.init(deps)
--------------------------------------------------------------------------------
-- Only load plugin if FCPX is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod.init(deps)
end
return plugin
| mit |
mt246/mt | plugins/quotes.lua | 651 | 1630 | local quotes_file = './data/quotes.lua'
local quotes_table
function read_quotes_file()
local f = io.open(quotes_file, "r+")
if f == nil then
print ('Created a new quotes file on '..quotes_file)
serialize_to_file({}, quotes_file)
else
print ('Quotes loaded: '..quotes_file)
f:close()
end
return loadfile (quotes_file)()
end
function save_quote(msg)
local to_id = tostring(msg.to.id)
if msg.text:sub(11):isempty() then
return "Usage: !addquote quote"
end
if quotes_table == nil then
quotes_table = {}
end
if quotes_table[to_id] == nil then
print ('New quote key to_id: '..to_id)
quotes_table[to_id] = {}
end
local quotes = quotes_table[to_id]
quotes[#quotes+1] = msg.text:sub(11)
serialize_to_file(quotes_table, quotes_file)
return "done!"
end
function get_quote(msg)
local to_id = tostring(msg.to.id)
local quotes_phrases
quotes_table = read_quotes_file()
quotes_phrases = quotes_table[to_id]
return quotes_phrases[math.random(1,#quotes_phrases)]
end
function run(msg, matches)
if string.match(msg.text, "!quote$") then
return get_quote(msg)
elseif string.match(msg.text, "!addquote (.+)$") then
quotes_table = read_quotes_file()
return save_quote(msg)
end
end
return {
description = "Save quote",
description = "Quote plugin, you can create and retrieve random quotes",
usage = {
"!addquote [msg]",
"!quote",
},
patterns = {
"^!addquote (.+)$",
"^!quote$",
},
run = run
}
| gpl-2.0 |
troopizer/ot-server | data/npc/lib/npcsystem/queue.lua | 4 | 1971 | -- Advanced NPC System (Created by Jiddo),
-- Modified by Talaturen.
if(Queue == nil) then
Queue = {
customers = nil,
handler = nil,
}
-- Creates a new queue, connected to the given NpcHandler handler
function Queue:new(handler)
local obj = {}
obj.handler = handler
obj.customers = {}
setmetatable(obj, self)
self.__index = self
return obj
end
-- Assigns a new handler to this queue.
function Queue:setHandler(newHandler)
self.handler = newHandler
end
-- Pushes a new cid onto the tail of this queue.
function Queue:push(cid)
if(isPlayer(cid)) then
table.insert(self.customers, cid)
end
end
-- Returns true if the given cid is already in the queue.
function Queue:isInQueue(cid)
return (isInArray(self.customers, cid))
end
-- Removes and returns the first cid from the queue
function Queue:pop()
return table.remove(self.customers, 1)
end
-- Returns the first cid in the queue, but does not remove it!
function Queue:peek()
return self.customers[1]
end
-- Returns true if htis queue is empty.
function Queue:empty()
return(self:peek() == nil)
end
-- Returns the amount of players currently in the queue.
function Queue:getSize()
return table.maxn(self.customers)
end
-- Returns true if the creature with the given cid can be greeted by this npc.
function Queue:canGreet(cid)
if(isPlayer(cid)) then
return self.handler:isInRange(cid)
else
return false
end
end
-- Greets the player with the given cid.
function Queue:greet(cid)
if(self.handler ~= nil) then
self.handler:greet(cid)
else
error('No handler assigned to queue!')
end
end
-- Makes sure the next greetable player in the queue is greeted.
function Queue:greetNext()
while (not self:empty()) do
local nextPlayer = self:pop()
if(self:canGreet(nextPlayer)) then
if(callback == nil or callback(nextPlayer)) then
self:greet(nextPlayer)
return true
end
end
end
return false
end
end | gpl-2.0 |
Tri125/MCServer | MCServer/Plugins/APIDump/Hooks/OnPlayerPlacingBlock.lua | 6 | 2109 | return
{
HOOK_PLAYER_PLACING_BLOCK =
{
CalledWhen = "Just before a player places a block. Plugin may override / refuse.",
DefaultFnName = "OnPlayerPlacingBlock", -- also used as pagename
Desc = [[
This hook is called just before a {{cPlayer|player}} places a block in the {{cWorld|world}}. The
block is not yet placed, plugins may choose to override the default behavior or refuse the placement
at all.</p>
<p>
Note that the client already expects that the block has been placed. For that reason, if a plugin
refuses the placement, MCServer sends the old block at the provided coords to the client.</p>
<p>
Use the {{cPlayer}}:GetWorld() function to get the world to which the block belongs.</p>
<p>
See also the {{OnPlayerPlacedBlock|HOOK_PLAYER_PLACED_BLOCK}} hook for a similar hook called after
the placement.</p>
<p>
If the client action results in multiple blocks being placed (such as a bed or a door), each separate
block is reported through this hook and only if all of them succeed, all the blocks are placed. If
any one of the calls are refused by the plugin, all the blocks are refused and reverted on the client.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player who is placing the block" },
{ Name = "BlockX", Type = "number", Notes = "X-coord of the block" },
{ Name = "BlockY", Type = "number", Notes = "Y-coord of the block" },
{ Name = "BlockZ", Type = "number", Notes = "Z-coord of the block" },
{ Name = "BlockType", Type = "BLOCKTYPE", Notes = "The block type of the block" },
{ Name = "BlockMeta", Type = "NIBBLETYPE", Notes = "The block meta of the block" },
},
Returns = [[
If this function returns false or no value, MCServer calls other plugins with the same event and
finally places the block and removes the corresponding item from player's inventory. If this
function returns true, no other plugin is called for this event, MCServer sends the old block at
the specified coords to the client and drops the packet.
]],
}, -- HOOK_PLAYER_PLACING_BLOCK
}
| apache-2.0 |
mogh77/ahhhh | bot/seedbot.lua | 1 | 10054 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
plugins
},
sudo_users = {143453816,166161244,0,tonumber(our_id)},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[Teleseed v2 - Open Source
An advance Administration bot based on yagop/telegram-bot
https://github.com/SEEDTEAM/TeleSeed
Our team!
Alphonse (@Iwals)
I M /-\ N (@Imandaneshi)
Siyanew (@Siyanew)
Rondoozle (@Potus)
Seyedan (@Seyedan25)
Special thanks to:
Juan Potato
Siyanew
Topkecleon
Vamptacus
Our channels:
English: @TeleSeedCH
Persian: @IranSeed
]],
help_text_realm = [[
Realm Commands:
!creategroup [name]
Create a group
!createrealm [name]
Create a realm
!setname [name]
Set realm name
!setabout [group_id] [text]
Set a group's about text
!setrules [grupo_id] [text]
Set a group's rules
!lock [grupo_id] [setting]
Lock a group's setting
!unlock [grupo_id] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [grupo_id]
Kick all memebers and delete group
!kill realm [realm_id]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
» Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
Return group id or user id
!help
Get commands list
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules [text]
Set [text] as rules
!set about [text]
Set [text] as about
!settings
Returns group settings
!newlink
Create/revoke your group link
!link
Returns group link
!owner
Returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] [text]
Save [text] as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
Returns user id
!log
Will return group logs
!banlist
Will return group ban list
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
Enignite/darkstar | scripts/zones/Port_Windurst/npcs/Panja-Nanja.lua | 53 | 1909 | -----------------------------------
-- Area: Port Windurst
-- NPC: Panja-Nanja
-- Type: Fishing Adv. Image Support
-- @pos -194.499 -3 58.692 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,8);
local SkillLevel = player:getSkillLevel(SKILL_FISHING);
local Cost = getAdvImageSupportCost(player,SKILL_FISHING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then
player:startEvent(0x271B,Cost,SkillLevel,0,239,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(0x271B,Cost,SkillLevel,0,239,player:getGil(),38586,30,0);
end
else
player:startEvent(0x271B); -- Standard Dialogue, incorrect
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local Cost = getAdvImageSupportCost(player,256);
if (csid == 0x271B and option == 1) then
player:delGil(Cost);
player:messageSpecial(FISHING_SUPPORT,0,0,0);
player:addStatusEffect(EFFECT_FISHING_IMAGERY,2,0,7200);
end
end; | gpl-3.0 |
timofonic/fpga_nes | sw/scripts/ppumc.lua | 3 | 7867 | ----------------------------------------------------------------------------------------------------
-- Script: ppumc.lua
-- Description: Tests ppumc block (read/write PPU memory)
----------------------------------------------------------------------------------------------------
dofile("../scripts/inc/nesdbg.lua")
local results = {}
local testTbl =
{
--
-- Test reading/writing 0 bytes.
--
{ wrEn=true, wrAddr=0x0000, wrBytes=0x0000, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x0000, rdBytes=0x0000 },
--
-- 1 byte write tests to various addr segments
--
{ wrEn=true, wrAddr=0x0000, wrBytes=0x0001, rdEn=true, rdAddr=0x0000, rdBytes=0x0001 },
{ wrEn=true, wrAddr=0x2000, wrBytes=0x0001, rdEn=true, rdAddr=0x2000, rdBytes=0x0001 },
--
-- 1 byte write tests to consecutive bytes then read at once for various addr segments
--
{ wrEn=true, wrAddr=0x0000, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0001, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0002, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x0000, rdBytes=0x0003 },
{ wrEn=true, wrAddr=0x0200, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0201, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0202, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0203, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x0200, rdBytes=0x0004 },
{ wrEn=true, wrAddr=0x2000, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2001, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2002, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x2000, wrBytes=0x0000, rdEn=true, rdAddr=0x2000, rdBytes=0x0003 },
{ wrEn=true, wrAddr=0x2200, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2201, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2202, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2203, wrBytes=0x0001, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x2200, rdBytes=0x0004 },
--
-- Multi-byte write tests to various addr segments, covering end of segments.
--
{ wrEn=true, wrAddr=0x0000, wrBytes=0x0002, rdEn=true, rdAddr=0x0000, rdBytes=0x0002 },
{ wrEn=true, wrAddr=0x0010, wrBytes=0x0017, rdEn=true, rdAddr=0x0010, rdBytes=0x0017 },
{ wrEn=true, wrAddr=0x0100, wrBytes=0x0700, rdEn=true, rdAddr=0x0100, rdBytes=0x0700 },
{ wrEn=true, wrAddr=0x2000, wrBytes=0x0002, rdEn=true, rdAddr=0x2000, rdBytes=0x0002 },
{ wrEn=true, wrAddr=0x2010, wrBytes=0x0017, rdEn=true, rdAddr=0x2010, rdBytes=0x0017 },
{ wrEn=true, wrAddr=0x2100, wrBytes=0x0300, rdEn=true, rdAddr=0x2100, rdBytes=0x0300 },
--
-- Overlapping multi-byte writes then read at once for various addr segments
--
{ wrEn=true, wrAddr=0x0400, wrBytes=0x0100, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0420, wrBytes=0x00C0, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x0440, wrBytes=0x0080, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x0400, rdBytes=0x0100 },
{ wrEn=true, wrAddr=0x2400, wrBytes=0x0100, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2420, wrBytes=0x00C0, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=true, wrAddr=0x2440, wrBytes=0x0080, rdEn=false, rdAddr=0x0000, rdBytes=0x0000 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x2400, rdBytes=0x0100 },
--
-- RAM mirroring tests (0x0000 - 0x1FFF)
--
{ wrEn=true, wrAddr=0x0170, wrBytes=0x0029, rdEn=true, rdAddr=0x0170, rdBytes=0x0029 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x4170, rdBytes=0x0029 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x8170, rdBytes=0x0029 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0xC170, rdBytes=0x0029 },
{ wrEn=true, wrAddr=0x2280, wrBytes=0x0100, rdEn=true, rdAddr=0x2280, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x2680, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x6280, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0x6680, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0xA280, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0xA680, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0xE280, rdBytes=0x0100 },
{ wrEn=false, wrAddr=0x0000, wrBytes=0x0000, rdEn=true, rdAddr=0xE680, rdBytes=0x0100 },
}
local shadowMem = {}
-- TranslateAddr: Handles mirroring for RAM area of shadow RAM. This will also return nil for
-- unsupported addresses, causing a lua error.
function TranslateAddr(addr)
-- 0x4000 - 0xFFFF mirors 0x0000 - 0x3FFF
local translatedAddr = addr % 0x4000
-- if translatedAddr >= 0x2000 then
-- translatedAddr = (translatedAddr - 0x2000) % 0x800
-- translatedAddr = translatedAddr + 0x2000
-- end
if translatedAddr >= 0x2000 and translatedAddr < 0x2400 then
translatedAddr = translatedAddr
elseif translatedAddr >= 0x2400 and translatedAddr < 0x2800 then
translatedAddr = translatedAddr - 0x400
elseif translatedAddr >= 0x2800 and translatedAddr < 0x2C00 then
translatedAddr = translatedAddr - 0x400
elseif translatedAddr >= 0x2C00 and translatedAddr < 0x3000 then
translatedAddr = translatedAddr - 0x800
end
return translatedAddr
end
-- ShadowMemWr: Write specified data to addr in the shadow memory.
function ShadowMemWr(addr, numBytes, data)
for i = 1,numBytes do
shadowMem[TranslateAddr(addr + i - 1)] = data[i]
end
end
-- ShadowMemRd: Read data from the shadow memory.
function ShadowMemRd(addr, numBytes)
local data = {}
for i = 1, numBytes do
data[i] = shadowMem[TranslateAddr(addr + i - 1)]
end
return data
end
-- PrintRdData: Prints data contents, useful for debugging.
function PrintRdData(data)
for i = 1, #data do
print(data[i] .. " ")
end
end
for subTestIdx = 1, #testTbl do
curTest = testTbl[subTestIdx]
if curTest.wrEn then
-- Generate random test data to be written.
wrData = {}
for i = 1, curTest.wrBytes do
wrData[i] = math.random(0, 255)
end
-- Write data for FPGA and shadow mem.
nesdbg.PpuMemWr(curTest.wrAddr, curTest.wrBytes, wrData)
ShadowMemWr(curTest.wrAddr, curTest.wrBytes, wrData)
end
if curTest.rdEn then
-- Read data from FPGA and shadow mem.
ppuRdData = nesdbg.PpuMemRd(curTest.rdAddr, curTest.rdBytes)
shadowRdData = ShadowMemRd(curTest.rdAddr, curTest.rdBytes)
if CompareArrayData(ppuRdData, shadowRdData) then
results[subTestIdx] = ScriptResult.Pass
else
results[subTestIdx] = ScriptResult.Fail
--[[
print("shadowRdData:\t")
PrintRdData(shadowRdData)
print("\n")
print("cpuRdData:\t")
PrintRdData(cpuRdData)
print("\n")
]]
end
else
-- If this subtest doesn't read, there's nothing to check, so award a free pass.
results[subTestIdx] = ScriptResult.Pass
end
ReportSubTestResult(subTestIdx, results[subTestIdx])
end
return ComputeOverallResult(results)
| bsd-2-clause |
aimingoo/ngx_4c | testcase/lib/JSON.lua | 4 | 34883 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
-- self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
return "::"..type(value).."::"
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| apache-2.0 |
Enignite/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Yang.lua | 15 | 1332 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NM: Yang
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
local YingID = 17330183;
local YingToD = mob:getLocalVar("YingToD");
-- Repop Ying every 30 seconds if Yang is up and Ying is not.
if (mob:getBattleTime() > YingToD+30 and GetMobAction(YingID) == ACTION_NONE) then
SpawnMob(YingID):updateEnmity(target);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local YingID = 17330183;
-- localVars clear on death, so setting it on its partner
GetMobByID(YingID):setLocalVar("YangToD", os.time());
-- This is not retail, this is not how you pop DynaLord:
if (GetMobAction(17330177) == ACTION_NONE and GetMobAction(YingID) == ACTION_NONE) then
-- GetMobByID(17330177):setLocalVar("timeLimit", os.time() + 1800); -- Time for the 30min limit
SpawnMob(17330177); -- Dynamis Lord
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/globals/items/bowl_of_sutlac.lua | 36 | 1315 | -----------------------------------------
-- ID: 5577
-- Item: Bowl of Sutlac
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP +8
-- MP +10
-- INT +1
-- MP Recovered while healing +2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5577);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_MP, 10);
target:addMod(MOD_INT, 1);
target:addMod(MOD_MPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_MP, 10);
target:delMod(MOD_INT, 1);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
hscells/asteroids | main.lua | 1 | 7292 | require "asteroid"
require "bullet"
local width = love.graphics.getWidth()
local height = love.graphics.getHeight() - 32
local max_asteroids = 10
local asteroids = {}
local bullets = {}
local fullscreen = false
-- add an asteroid to the game
function AddAsteroid(x,y,size,health,vx,vy)
return table.insert(asteroids,Asteroid.create(x,y,width,height,size,health,vx,vy))
end
-- add a bullet to the game
function CreateBullet(x,y)
return table.insert(bullets,Bullet.create(x,y,width,height,angle))
end
-- check the bounding box of two circles
function CheckCollisionCircle(x1,y1,radius1, x2,y2,radius2)
return math.sqrt( ( x2-x1 ) * ( x2-x1 ) + ( y2-y1 ) * ( y2-y1 ) ) < ( radius1 + radius2 )
end
-- check to see if two asteroid objects collide
function CheckAsteroidCollision(asteroid1, asteroid2)
return CheckCollisionCircle(asteroid1.x,asteroid1.y,asteroid1.size,asteroid2.x,asteroid2.y,asteroid2.size)
end
-- check to see if an asteroid collided with the ship
function CheckShipCollision(asteroid)
return CheckCollisionCircle(x,y,12,asteroid.x,asteroid.y,asteroid.size)
end
-- have some events trigger for fullscreen and to quit
function love.keypressed(key)
if key == "f" then
fullscreen = not fullscreen
love.window.setFullscreen(fullscreen,"desktop")
width = love.graphics.getWidth()
height = love.graphics.getHeight() - 32
love.window.toPixels(width,height)
elseif key == "escape" then
love.event.quit()
end
end
-- restart the whole game over
function Restart()
lives = 3
score = 0
pos = 1
for key, bullet in ipairs(bullets) do
table.remove(bullets,pos)
pos = pos + 1
end
pos = 1
for key, asteroid in ipairs(asteroids) do
table.remove(asteroids,pos)
pos = pos + 1
end
x, y = width/2, height/2
love.timer.sleep(1)
end
-- clear the board and loose a life
function LooseLife()
lives = lives - 1
x, y = width/2, height/2
pos = 1
for key, bullet in ipairs(bullets) do
table.remove(bullets,pos)
pos = pos + 1
end
pos = 1
for key, asteroid in ipairs(asteroids) do
table.remove(asteroids,pos)
pos = pos + 1
end
love.timer.sleep(1)
end
function love.load()
love.window.setTitle("Asteroids")
x, y = width/2, height/2
friction = 0.05
acceleration_rate = 0.2
speed = 0
turn_rate = 0.06
max_speed = 3
angle = 0
lives = 3
shoot = true
score = 0
font = love.graphics.newFont("VT323.ttf",30)
font:setFilter("nearest","nearest",-1)
love.graphics.setFont(font)
snd_shoot = love.audio.newSource("sounds/shoot.wav","stream")
snd_asteroid_explode = love.audio.newSource("sounds/asteroid_explode.wav","stream")
snd_ship_explode = love.audio.newSource("sounds/ship_explode.wav","stream")
end
function love.update()
-- restart the game if we loose all lives
if lives <= 0 then
Restart()
end
-- deaccelerate
speed = speed - friction
-- make sure the ship can't go negative speeds
if speed > max_speed then
speed = max_speed
elseif speed < 0 then
speed = 0
end
-- convert angular movement to (x,y)
x = x + (speed * math.cos(angle))
y = y + (speed * math.sin(angle))
-- update the asteroids and check all of their collisions with bullets and
-- the ship
pos = 1
for key, asteroid in ipairs(asteroids) do
asteroid:update()
for key, asteroid2 in ipairs(asteroids) do
if CheckAsteroidCollision(asteroid,asteroid2) then
asteroid:collide(asteroid2)
end
end
if CheckShipCollision(asteroid) then
lives = lives - 1
table.remove(asteroids,pos)
love.audio.play(snd_ship_explode)
LooseLife()
end
bpos = 1
for key, bullet in ipairs(bullets) do
if CheckAsteroidCollision(bullet,asteroid) then
love.audio.play(snd_asteroid_explode)
table.remove(asteroids,pos)
table.remove(bullets,bpos)
if asteroid.health == 3 then
score = score + 100
for i=0,1 do
AddAsteroid(asteroid.x+math.random(100)-50,asteroid.y+math.random(100)-50,math.random(5)+10,1,math.random(5.0)-2.5,math.random(5.0)-2.5)
end
else
score = score + 10
end
end
bpos = bpos + 1
end
pos = pos + 1
end
-- update all the bullet positions
pos = 1
for key, bullet in ipairs(bullets) do
if bullet.health < 0 then
table.remove(bullets,pos)
end
bullet:update()
if bullet.x > bullet.screen_width then
bullet.x = 0
elseif bullet.x < 0 then
bullet.x = width
elseif bullet.y > bullet.screen_height then
bullet.y = 0
elseif bullet.y < 0 then
bullet.y = height
end
pos = pos + 1
end
-- rotate the ship
if love.keyboard.isDown("left") then
angle = angle - turn_rate
elseif love.keyboard.isDown("right") then
angle = angle + turn_rate
end
-- accelerate the ship
if love.keyboard.isDown("up") then
speed = speed + acceleration_rate
end
-- allow the ship to shoot
if love.keyboard.isDown("z") then
if shoot == true then
CreateBullet(x,y)
love.audio.play(snd_shoot)
shoot = false
end
elseif not love.keyboard.isDown("z") then
shoot = true
end
-- loop the ship around the screen
if x > width then
x = 0
elseif x < 0 then
x = width
elseif y > height then
y = 0
elseif y < 0 then
y = height
end
-- create asteroids
if table.getn(asteroids) < max_asteroids then
if math.random(100) == 1 then
AddAsteroid(math.random(width),math.random(height),math.random(15)+25,3,math.random(3.0)-1.5,math.random(3.0)-1.5)
end
end
end
function love.draw()
-- draw the ship
love.graphics.setColor(255,255,255)
love.graphics.push()
love.graphics.translate(x,y)
love.graphics.rotate(angle)
love.graphics.translate(-x,-y)
local verticies = {x,y-10,x,y+10,x+25,y}
love.graphics.polygon("fill",verticies)
love.graphics.pop()
-- draw the asteroids
for key, asteroid in ipairs(asteroids) do
love.graphics. push()
love.graphics.translate(asteroid.x,asteroid.y)
love.graphics.rotate(asteroid.angle)
love.graphics.translate(-asteroid.x,-asteroid.y)
love.graphics.circle("fill",asteroid.x,asteroid.y,asteroid.size*1.2,5)
love.graphics.pop()
end
-- draw the bullets
for key, bullet in ipairs(bullets) do
love.graphics. push()
love.graphics.translate(bullet.x,bullet.y)
love.graphics.rotate(bullet.angle)
love.graphics.translate(-bullet.x,-bullet.y)
love.graphics.circle("fill",bullet.x,bullet.y,bullet.size,3)
love.graphics.pop()
end
-- draw the little information bar down the bottom
love.graphics.setColor(188,188,188)
love.graphics.polygon("fill",{0,height,width,height,width,height+32,0,height+32})
love.graphics.setColor(0,0,0)
love.graphics.print("SCORE: " .. score,8,height)
love.graphics.print("LIVES: " .. lives,width-108,height)
love.graphics.print("ASTEROIDS",width/2-54,height)
end
| mit |
Enignite/darkstar | scripts/zones/Bastok_Markets/npcs/Horatius.lua | 38 | 2104 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Horatius
-- Type: Quest Giver
-- Starts and Finishes: Breaking Stones
-- @pos -158.392 -5.839 -117.061 235
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(BASTOK,BREAKING_STONES) ~= QUEST_AVAILABLE) then
if (trade:hasItemQty(553,1) and trade:getItemCount() == 1) then
player:startEvent(0x0065);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,12) == false) then
player:startEvent(0x01ac);
elseif (player:getQuestStatus(BASTOK,BREAKING_STONES) == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 2) then
player:startEvent(0x0064);
else
player:startEvent(0x006e);
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 == 0x0064 and option == 0) then
player:addQuest(BASTOK,BREAKING_STONES);
elseif (csid == 0x0065) then
player:tradeComplete();
player:addGil(GIL_RATE*400);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*400);
player:completeQuest(BASTOK,BREAKING_STONES);
elseif (csid == 0x01ac) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",12,true);
end
end;
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Port_Windurst/npcs/Choyi_Totlihpa.lua | 38 | 1414 | -----------------------------------
-- Area: Port Windurst
-- NPC: Choyi Totlihpa
-- Type: Standard NPC
-- @pos -58.927 -5.732 132.819 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,17) == false) then
player:startEvent(0x026e);
else
player:startEvent(0x00d7);
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 == 0x026e) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",17,true);
end
end;
| gpl-3.0 |
brush1990/UniLua | Assets/StreamingAssets/LuaRoot/test/strings.lua | 9 | 9838 | print('testing strings and string library')
assert('alo' < 'alo1')
assert('' < 'a')
assert('alo\0alo' < 'alo\0b')
assert('alo\0alo\0\0' > 'alo\0alo\0')
assert('alo' < 'alo\0')
assert('alo\0' > 'alo')
assert('\0' < '\1')
assert('\0\0' < '\0\1')
assert('\1\0a\0a' <= '\1\0a\0a')
assert(not ('\1\0a\0b' <= '\1\0a\0a'))
assert('\0\0\0' < '\0\0\0\0')
assert(not('\0\0\0\0' < '\0\0\0'))
assert('\0\0\0' <= '\0\0\0\0')
assert(not('\0\0\0\0' <= '\0\0\0'))
assert('\0\0\0' <= '\0\0\0')
assert('\0\0\0' >= '\0\0\0')
assert(not ('\0\0b' < '\0\0a\0'))
print('+')
assert(string.sub("123456789",2,4) == "234")
assert(string.sub("123456789",7) == "789")
assert(string.sub("123456789",7,6) == "")
assert(string.sub("123456789",7,7) == "7")
assert(string.sub("123456789",0,0) == "")
assert(string.sub("123456789",-10,10) == "123456789")
assert(string.sub("123456789",1,9) == "123456789")
assert(string.sub("123456789",-10,-20) == "")
assert(string.sub("123456789",-1) == "9")
assert(string.sub("123456789",-4) == "6789")
assert(string.sub("123456789",-6, -4) == "456")
if not _no32 then
assert(string.sub("123456789",-2^31, -4) == "123456")
assert(string.sub("123456789",-2^31, 2^31 - 1) == "123456789")
assert(string.sub("123456789",-2^31, -2^31) == "")
end
assert(string.sub("\000123456789",3,5) == "234")
assert(("\000123456789"):sub(8) == "789")
print('+')
assert(string.find("123456789", "345") == 3)
a,b = string.find("123456789", "345")
assert(string.sub("123456789", a, b) == "345")
assert(string.find("1234567890123456789", "345", 3) == 3)
assert(string.find("1234567890123456789", "345", 4) == 13)
assert(string.find("1234567890123456789", "346", 4) == nil)
assert(string.find("1234567890123456789", ".45", -9) == 13)
assert(string.find("abcdefg", "\0", 5, 1) == nil)
assert(string.find("", "") == 1)
assert(string.find("", "", 1) == 1)
assert(not string.find("", "", 2))
assert(string.find('', 'aaa', 1) == nil)
assert(('alo(.)alo'):find('(.)', 1, 1) == 4)
print('+')
assert(string.len("") == 0)
assert(string.len("\0\0\0") == 3)
assert(string.len("1234567890") == 10)
assert(#"" == 0)
assert(#"\0\0\0" == 3)
assert(#"1234567890" == 10)
assert(string.byte("a") == 97)
assert(string.byte("\xe4") > 127)
assert(string.byte(string.char(255)) == 255)
assert(string.byte(string.char(0)) == 0)
assert(string.byte("\0") == 0)
assert(string.byte("\0\0alo\0x", -1) == string.byte('x'))
assert(string.byte("ba", 2) == 97)
assert(string.byte("\n\n", 2, -1) == 10)
assert(string.byte("\n\n", 2, 2) == 10)
assert(string.byte("") == nil)
assert(string.byte("hi", -3) == nil)
assert(string.byte("hi", 3) == nil)
assert(string.byte("hi", 9, 10) == nil)
assert(string.byte("hi", 2, 1) == nil)
assert(string.char() == "")
assert(string.char(0, 255, 0) == "\0\255\0")
assert(string.char(0, string.byte("\xe4"), 0) == "\0\xe4\0")
assert(string.char(string.byte("\xe4l\0óu", 1, -1)) == "\xe4l\0óu")
assert(string.char(string.byte("\xe4l\0óu", 1, 0)) == "")
assert(string.char(string.byte("\xe4l\0óu", -10, 100)) == "\xe4l\0óu")
print('+')
assert(string.upper("ab\0c") == "AB\0C")
assert(string.lower("\0ABCc%$") == "\0abcc%$")
assert(string.rep('teste', 0) == '')
assert(string.rep('tés\00tê', 2) == 'tés\0têtés\000tê')
assert(string.rep('', 10) == '')
-- repetitions with separator
assert(string.rep('teste', 0, 'xuxu') == '')
assert(string.rep('teste', 1, 'xuxu') == 'teste')
assert(string.rep('\1\0\1', 2, '\0\0') == '\1\0\1\0\0\1\0\1')
assert(string.rep('', 10, '.') == string.rep('.', 9))
if not _no32 then
assert(not pcall(string.rep, "aa", 2^30))
assert(not pcall(string.rep, "", 2^30, "aa"))
end
assert(string.reverse"" == "")
assert(string.reverse"\0\1\2\3" == "\3\2\1\0")
assert(string.reverse"\0001234" == "4321\0")
for i=0,30 do assert(string.len(string.rep('a', i)) == i) end
assert(type(tostring(nil)) == 'string')
assert(type(tostring(12)) == 'string')
assert(''..12 == '12' and type(12 .. '') == 'string')
assert(string.find(tostring{}, 'table:'))
assert(string.find(tostring(print), 'function:'))
assert(tostring(1234567890123) == '1234567890123')
assert(#tostring('\0') == 1)
assert(tostring(true) == "true")
assert(tostring(false) == "false")
print('+')
x = '"ílo"\n\\'
assert(string.format('%q%s', x, x) == '"\\"ílo\\"\\\n\\\\""ílo"\n\\')
assert(string.format('%q', "\0") == [["\0"]])
assert(load(string.format('return %q', x))() == x)
x = "\0\1\0023\5\0009"
assert(load(string.format('return %q', x))() == x)
assert(string.format("\0%c\0%c%x\0", string.byte("\xe4"), string.byte("b"), 140) ==
"\0\xe4\0b8c\0")
assert(string.format('') == "")
assert(string.format("%c",34)..string.format("%c",48)..string.format("%c",90)..string.format("%c",100) ==
string.format("%c%c%c%c", 34, 48, 90, 100))
assert(string.format("%s\0 is not \0%s", 'not be', 'be') == 'not be\0 is not \0be')
assert(string.format("%%%d %010d", 10, 23) == "%10 0000000023")
assert(tonumber(string.format("%f", 10.3)) == 10.3)
x = string.format('"%-50s"', 'a')
assert(#x == 52)
assert(string.sub(x, 1, 4) == '"a ')
assert(string.format("-%.20s.20s", string.rep("%", 2000)) ==
"-"..string.rep("%", 20)..".20s")
assert(string.format('"-%20s.20s"', string.rep("%", 2000)) ==
string.format("%q", "-"..string.rep("%", 2000)..".20s"))
-- format x tostring
assert(string.format("%s %s", nil, true) == "nil true")
assert(string.format("%s %.4s", false, true) == "false true")
assert(string.format("%.3s %.3s", false, true) == "fal tru")
local m = setmetatable({}, {__tostring = function () return "hello" end})
assert(string.format("%s %.10s", m, m) == "hello hello")
assert(string.format("%x", 0.3) == "0")
assert(string.format("%02x", 0.1) == "00")
assert(string.format("%08X", 2^32 - 1) == "FFFFFFFF")
assert(string.format("%+08d", 2^31 - 1) == "+2147483647")
assert(string.format("%+08d", -2^31) == "-2147483648")
-- longest number that can be formated
assert(string.len(string.format('%99.99f', -1e308)) >= 100)
if not _nolonglong then
print("testing large numbers for format")
assert(string.format("%8x", 2^52 - 1) == "fffffffffffff")
assert(string.format("%d", -1) == "-1")
assert(tonumber(string.format("%u", 2^62)) == 2^62)
assert(string.format("%8x", 0xffffffff) == "ffffffff")
assert(string.format("%8x", 0x7fffffff) == "7fffffff")
assert(string.format("%d", 2^53) == "9007199254740992")
assert(string.format("%d", -2^53) == "-9007199254740992")
assert(string.format("0x%8X", 0x8f000003) == "0x8F000003")
-- maximum integer that fits both in 64-int and (exact) double
local x = 2^64 - 2^(64-53)
assert(x == 0xfffffffffffff800)
assert(tonumber(string.format("%u", x)) == x)
assert(tonumber(string.format("0X%x", x)) == x)
assert(string.format("%x", x) == "fffffffffffff800")
assert(string.format("%d", x/2) == "9223372036854774784")
assert(string.format("%d", -x/2) == "-9223372036854774784")
assert(string.format("%d", -2^63) == "-9223372036854775808")
assert(string.format("%x", 2^63) == "8000000000000000")
end
if not _noformatA then
print("testing 'format %a %A'")
assert(string.format("%.2a", 0.5) == "0x1.00p-1")
assert(string.format("%A", 0x1fffffffffffff) == "0X1.FFFFFFFFFFFFFP+52")
assert(string.format("%.4a", -3) == "-0x1.8000p+1")
assert(tonumber(string.format("%a", -0.1)) == -0.1)
end
-- errors in format
local function check (fmt, msg)
local s, err = pcall(string.format, fmt, 10)
assert(not s and string.find(err, msg))
end
local aux = string.rep('0', 600)
check("%100.3d", "too long")
check("%1"..aux..".3d", "too long")
check("%1.100d", "too long")
check("%10.1"..aux.."004d", "too long")
check("%t", "invalid option")
check("%"..aux.."d", "repeated flags")
check("%d %d", "no value")
-- integers out of range
assert(not pcall(string.format, "%d", 2^63))
assert(not pcall(string.format, "%x", 2^64))
assert(not pcall(string.format, "%x", -2^64))
assert(not pcall(string.format, "%x", -1))
assert(load("return 1\n--comentário sem EOL no final")() == 1)
assert(table.concat{} == "")
assert(table.concat({}, 'x') == "")
assert(table.concat({'\0', '\0\1', '\0\1\2'}, '.\0.') == "\0.\0.\0\1.\0.\0\1\2")
local a = {}; for i=1,3000 do a[i] = "xuxu" end
assert(table.concat(a, "123").."123" == string.rep("xuxu123", 3000))
assert(table.concat(a, "b", 20, 20) == "xuxu")
assert(table.concat(a, "", 20, 21) == "xuxuxuxu")
assert(table.concat(a, "x", 22, 21) == "")
assert(table.concat(a, "3", 2999) == "xuxu3xuxu")
if not _no32 then
assert(table.concat({}, "x", 2^31-1, 2^31-2) == "")
assert(table.concat({}, "x", -2^31+1, -2^31) == "")
assert(table.concat({}, "x", 2^31-1, -2^31) == "")
assert(table.concat({[2^31-1] = "alo"}, "x", 2^31-1, 2^31-1) == "alo")
end
assert(not pcall(table.concat, {"a", "b", {}}))
a = {"a","b","c"}
assert(table.concat(a, ",", 1, 0) == "")
assert(table.concat(a, ",", 1, 1) == "a")
assert(table.concat(a, ",", 1, 2) == "a,b")
assert(table.concat(a, ",", 2) == "b,c")
assert(table.concat(a, ",", 3) == "c")
assert(table.concat(a, ",", 4) == "")
if not _port then
local locales = { "ptb", "ISO-8859-1", "pt_BR" }
local function trylocale (w)
for i = 1, #locales do
if os.setlocale(locales[i], w) then return true end
end
return false
end
if not trylocale("collate") then
print("locale not supported")
else
assert("alo" < "álo" and "álo" < "amo")
end
if not trylocale("ctype") then
print("locale not supported")
else
assert(load("a = 3.4")); -- parser should not change outside locale
assert(not load("á = 3.4")); -- even with errors
assert(string.gsub("áéíóú", "%a", "x") == "xxxxx")
assert(string.gsub("áÁéÉ", "%l", "x") == "xÁxÉ")
assert(string.gsub("áÁéÉ", "%u", "x") == "áxéx")
assert(string.upper"áÁé{xuxu}ção" == "ÁÁÉ{XUXU}ÇÃO")
end
os.setlocale("C")
assert(os.setlocale() == 'C')
assert(os.setlocale(nil, "numeric") == 'C')
end
print('OK')
| mit |
Enignite/darkstar | scripts/zones/Mhaura/npcs/Willah_Maratahya.lua | 17 | 3611 | -----------------------------------
-- Area: Mhaura
-- NPC: Willah Maratahya
-- Title Change NPC
-- @pos 23 -8 63 249
-----------------------------------
require("scripts/globals/titles");
local title2 = { PURVEYOR_IN_TRAINING , ONESTAR_PURVEYOR , TWOSTAR_PURVEYOR , THREESTAR_PURVEYOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title3 = { FOURSTAR_PURVEYOR , FIVESTAR_PURVEYOR , HEIR_OF_THE_GREAT_LIGHTNING , ORCISH_SERJEANT , BRONZE_QUADAV , YAGUDO_INITIATE ,
MOBLIN_KINSMAN , DYNAMISBUBURIMU_INTERLOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER ,
ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER ,
LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY ,
BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER ,
MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER ,
XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR ,
APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 0 , 0 , 0 , 0 , 0 }
local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 }
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x2711,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid==0x2711) then
if (option > 0 and option <29) then
if (player:delGil(200)) then
player:setTitle( title2[option] )
end
elseif (option > 256 and option <285) then
if (player:delGil(300)) then
player:setTitle( title3[option - 256] )
end
elseif (option > 512 and option < 541) then
if (player:delGil(400)) then
player:setTitle( title4[option - 512] )
end
elseif (option > 768 and option <797) then
if (player:delGil(500)) then
player:setTitle( title5[option - 768] )
end
elseif (option > 1024 and option < 1053) then
if (player:delGil(600)) then
player:setTitle( title6[option - 1024] )
end
end
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Yuhtunga_Jungle/mobs/Rose_Garden.lua | 29 | 1648 | -----------------------------------
-- Area: Yuhtunga Jungle
-- MOB: Rose Garden
-----------------------------------
-----------------------------------
function onMobSpawn(mob)
local Voluptuous_Vilma = 17281358;
GetMobByID(Voluptuous_Vilma):setLocalVar("1",os.time() + math.random((36000), (37800)));
end;
function onMobRoam(mob)
local Voluptuous_Vilma = 17281358;
local Voluptuous_Vilma_PH = 0;
local Voluptuous_Vilma_PH_Table =
{
17281357
};
local Voluptuous_Vilma_ToD = GetMobByID(Voluptuous_Vilma):getLocalVar("1");
if (Voluptuous_Vilma_ToD <= os.time()) then
Voluptuous_Vilma_PH = math.random((0), (table.getn(Voluptuous_Vilma_PH_Table)));
if (Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH] ~= nil) then
if (GetMobAction(Voluptuous_Vilma) == 0) then
SetServerVariable("Voluptuous_Vilma_PH", Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]);
DeterMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH], true);
DeterMob(Voluptuous_Vilma, false);
DespawnMob(Voluptuous_Vilma_PH_Table[Voluptuous_Vilma_PH]);
SpawnMob(Voluptuous_Vilma, "", 0);
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local Rose_Garden = 17281357;
local Rose_Garden_PH = GetServerVariable("Rose_Garden_PH");
GetMobByID(Rose_Garden):setLocalVar("1",os.time() + math.random((36000), (37800)));
SetServerVariable("Rose_Garden_PH", 0);
DeterMob(Rose_Garden, true);
DeterMob(Rose_Garden_PH, false);
SpawnMob(Rose_Garden_PH, "", GetMobRespawnTime(Rose_Garden_PH));
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Temenos/mobs/Orichalcum_Quadav.lua | 16 | 1602 | -----------------------------------
-- Area: Temenos
-- NPC:
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (IsMobDead(16929017)==true and IsMobDead(16929018)==true and IsMobDead(16929019)==true and
IsMobDead(16929020)==true and IsMobDead(16929021)==true and IsMobDead(16929022)==true
) then
mob:setMod(MOD_SLASHRES,1400);
mob:setMod(MOD_PIERCERES,1400);
mob:setMod(MOD_IMPACTRES,1400);
mob:setMod(MOD_HTHRES,1400);
else
mob:setMod(MOD_SLASHRES,300);
mob:setMod(MOD_PIERCERES,300);
mob:setMod(MOD_IMPACTRES,300);
mob:setMod(MOD_HTHRES,300);
end
GetMobByID(16929005):updateEnmity(target);
GetMobByID(16929007):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then
GetNPCByID(16928768+78):setPos(-280,-161,-440);
GetNPCByID(16928768+78):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+473):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
fcpxhacks/fcpxhacks | src/extensions/cp/websocket/http.lua | 2 | 6609 | --- === cp.websocket.http ===
---
--- Provides a full HTTP-based websocket implementation.
local require = require
local log = require "hs.logger" .new "ws_http"
local inspect = require "hs.inspect"
local hexDump = require "hs.utf8" .hexDump
local status = require "cp.websocket.status"
local event = require "cp.websocket.event"
local websocket = require "hs.websocket"
local mod = {}
mod.mt = {}
mod.mt.__index = mod.mt
--- cp.websocket.http.new(url, callback) -> object
--- Function
--- Creates a new websocket connection via a serial connection.
---
--- Parameters:
--- * url - The URL path to the websocket server.
--- * callback - A function that's triggered by websocket actions.
---
--- Returns:
--- * The `cp.websocket` object
---
--- Notes:
--- * The callback should accept two parameters.
--- * The first parameter is a `cp.websocket.event` value.
--- * The second parameter is a `string` with the received message or an error message.
--- * Given a path '/mysock' and a port of 8000, the websocket URL is as follows:
--- * `ws://localhost:8000/mysock`
--- * `wss://localhost:8000/mysock` (if SSL enabled)
function mod.new(url, callback)
local o = {
-- configuration
_url = url,
_callback = callback,
-- internal
_status = status.closed,
}
setmetatable(o, mod.mt)
return o
end
--- cp.websocket.http:status() -> cp.websocket.status
--- Method
--- Returns the current connection status.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The current `cp.websocket.status`.
function mod.mt:status()
return self._status
end
-- The websocket message handlers
mod._handler = {
open = function(self, message)
self:_update(status.open, event.opened, message)
end,
closed = function(self, message)
self:_update(status.closed, event.closed, message)
end,
fail = function(self, message)
-- Let's just ignore any errors when closing.
if self._status ~= "closing" and self._status ~= "closed" then
log.wf("Unexpected message when status is '%s':\n%s", inspect(self._status), message and hexDump(message))
self:_report(event.error, message)
end
end,
received = function(self, message)
if self._status == status.open then
self:_report(event.message, message)
else
mod._handler.fail(self, message)
end
end,
pong = function(_, message)
log.df("received an unsolicited 'pong': %s", hexDump(message))
end,
}
-- cp.websocket.http:_update(statusType[, eventType[, message]])
-- Private Method
-- Updates the status, and optionally sends an event to the callback if the status changed.
--
-- Parameters:
-- * statusType - The new `cp.websocket.status`
-- * eventType - The `cp.websocket.event` type to send if the status changed. (optional)
-- * message - The message data to send with the event type. (optional)
--
-- Returns:
-- * Nothing
function mod.mt:_update(statusType, eventType, message)
local oldStatus = self._status
self._status = statusType
if eventType and oldStatus ~= statusType then
self:_report(eventType, message)
end
end
--- cp.websocket.http:open() -> cp.websocket.status
--- Method
--- Attempts to open a websocket connection with the configured HTTP connection.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.websocket.status` after attempting to open.
function mod.mt:open()
self:_update(status.opening, event.opening)
self._connection = websocket.new(self._url, self:_createWebsocketCallback())
return self._status
end
--- cp.websocket.http:isOpen() -> boolean
--- Method
--- Gets whether or not the HTTP websocket is fully open.
---
--- Parameters:
--- * None
---
--- Returns:
--- * `true` if open, otherwise `false`.
function mod.mt:isOpen()
return self._connection and self._connection:status() == "open" and self._status == status.open
end
-- cp.websocket.http:_createSerialCallback() -> function
-- Private Method
-- Creates a callback function for the internal `hs.serial` connection.
function mod.mt:_createWebsocketCallback()
return function(eventType, message)
local handler = mod._handler[eventType]
if handler then
handler(self, message)
else
log.wf("Unsupported websocket callback type: %s; message:\n%s", inspect(eventType), hexDump(message))
end
end
end
-- cp.websocket.http:_report(eventType, message)
-- Private Method
-- Sends an event to the callback function with the specified event type and message.
--
-- Parameters:
-- * eventType - the `cp.websocket.event` type.
-- * message - The message bytes to send. May be `nil` for some event types.
--
-- Returns:
-- * Nothing
function mod.mt:_report(eventType, message)
self._callback(eventType, message)
end
--- cp.websocket.http:close() -> object
--- Method
--- Closes a websocket connection.
---
--- Parameters:
--- * None
---
--- Returns:
--- * The `cp.websocket.serial` object
---
--- Notes:
--- * The `status` may be either `closing` or `closed` after calling this method.
--- * To be notified the close has completed, listen for the `cp.websocket.event.closed` event in the callback.
function mod.mt:close()
if self._status == status.closed or self._status == status.closing then
return self
end
local conn = self._connection
self._connection = nil
if conn and conn:status() == "open" then
self:_update(status.closing, event.closing)
conn:close()
return
end
self:_update(status.closed, event.closed)
return self
end
--- cp.websocket.http:send(message[, isData]) -> object
--- Method
--- Sends a message to the websocket client.
---
--- Parameters:
--- * message - A string containing the message to send.
--- * isData - An optional boolean that sends the message as binary data (defaults to true).
---
--- Returns:
--- * The `cp.websocket.serial` object
---
--- Notes:
--- * Forcing a text representation by setting isData to `false` may alter the data if it
--- contains invalid UTF8 character sequences (the default string behavior is to make
--- sure everything is "printable" by converting invalid sequences into the Unicode
--- Invalid Character sequence).
function mod.mt:send(message, isData)
if self:isOpen() then
if type(isData) == "nil" then isData = true end
self._connection:send(message, isData)
end
return self
end
return mod
| mit |
Enignite/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Machionage.lua | 17 | 1586 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Machionage
-- @zone 80
-- @pos -255 -3 109
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(CRYSTAL_WAR,GIFTS_OF_THE_GRIFFON) == QUEST_ACCEPTED and player:getVar("GiftsOfGriffonProg") == 2) then
local mask = player:getVar("GiftsOfGriffonPlumes");
if (trade:hasItemQty(2528,1) and trade:getItemCount() == 1 and not player:getMaskBit(mask,0)) then
player:startEvent(0x01C) -- Gifts of Griffon Trade
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x026B); -- Default Dialogue
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 == 0x01C) then
player:tradeComplete()
local mask = player:getVar("GiftsOfGriffonPlumes");
player:setMaskBit(mask,"GiftsOfGriffonPlumes",0,true);
end
end; | gpl-3.0 |
RCdiy/OpenTxLua | FUNCTIONS/GoRace/GoRace.lua | 1 | 4152 | -- License https://www.gnu.org/licenses/gpl-3.0.en.html
-- OpenTX Lua script
-- FUNCTIONS
--
-- File Locations On The Transmitter's SD Card
-- This script file /SCRIPTS/FUNCTIONS/
-- Accompanying sound files /SCRIPTS/FUNCTIONS/GoRace/
-- Works On OpenTX Companion Version: 2.2
-- Author: Dean Church
-- Web: n/a
-- Thanks: Dean Church
-- Date: 2017 November 30
-- Update: 2017 December 2 RCdiy
-- Changes/Additions:
-- Removed debug code
-- Changed how switch position UP, Down, Middle is implemented
-- Removed seperate function calls; Rewrote run function.
-- To do: n/a
-- Description
--
-- A race timer suitable for quad racing.
-- An announcement to get ready to race is made. After a random delay of
-- upto 5 seconds a start buzzer sound is made.
-- Race quads starting sequence
-- Racers
-- Place their quads on the start line and check to make sure their
-- quad 'arms' ( motors spool up). They then disarm.
-- Return to their seat, put on their goggles and wait for instructions.
-- Race Starter
-- Asks for a 'thumbs up' from racers when they are ready.
-- Instructs racers to arm their quads.
-- (spool up motors but remain stationary at the start line)
-- "Pilots arm your quads, we go live on the tone is less then five."
-- After a delay of up to 5 seconds the start tone sounds.
-- Racers take off from the start line and begin to race.
-- https://youtu.be/2Y0zDKB0FaU
-- Configurations
-- For help using functions scripts
-- http://rcdiy.ca/getting-started-with-lua-function-scripts/
-- Configure this script to run as a function script.
-- Select the switch "ON" as the switch and condition in the 1st column.
-- ON Play Script GoRace
local startRaceSwitch = "sf" -- Triggers announcement
local startRaceSwitchPosition = "TOWARDS" -- Switch active position
-- "TOWARDS", "AWAY" or "MIDDLE"
local randomTimeMilliseconds = 5000 -- Maximum delay
local audioDir = "/SCRIPTS/FUNCTIONS/GoRace/" -- Location of script audio files
local raceStartPreface = audioDir.."GoRace.wav" -- Prepare to race announcement
local startTone = audioDir.."RaceTone.wav" -- Race start sound
-- AVOID EDITING BELOW HERE
local TITLE = "GoRace.lua" -- .lua to start a race.
local DEBUG = false
-- local DOWN, MIDDLE, UP = 1024, 0, -1024 --Switch position DOWN/Toward, MIDDLE, UP/Away
if startRaceSwitchPosition == "TOWARDS" then startRaceSwitchPosition = 1024 end
if startRaceSwitchPosition == "MIDDLE" then startRaceSwitchPosition = 0 end
if startRaceSwitchPosition == "AWAY" then startRaceSwitchPosition = -1024 end
local startRaceSwitchID
local startRaceSwitchVal = 0
--local startTimeMilliseconds = 0
local raceStartPrefaceLengthMilliseconds = 8000 -- Time to play raceStartPreface in milliSeconds
local startTonePlayed = false
local targetTimeMilliseconds = 0
local presentTimeMilliseconds = 0
--local waitInProgress = false
local startSequenceReset = true
local function init()
startRaceSwitchID = getFieldInfo(startRaceSwitch).id --getTelemetryId(startRaceSwitch)
end --init()
local function run()
presentTimeMilliseconds = getTime()*10
startRaceSwitchVal = getValue(startRaceSwitchID)
if presentTimeMilliseconds > targetTimeMilliseconds then
-- not in start sequence
if startRaceSwitchPosition == startRaceSwitchVal and startSequenceReset == true then
-- enter start sequence
startSequenceReset = false
startTonePlayed = false
playFile(raceStartPreface)
targetTimeMilliseconds = presentTimeMilliseconds +
raceStartPrefaceLengthMilliseconds +
math.random(100, randomTimeMilliseconds)
end
else
-- in start sequence
if startTonePlayed == false then
playFile(startTone)
startTonePlayed = true
end
end
if startRaceSwitchPosition ~= startRaceSwitchVal then
--startTonePlayed = false
startSequenceReset = true
--targetTimeMilliseconds = 0
end
end -- run()
return { init=init, run=run }
--#############################################################################
| gpl-3.0 |
zendey/Flashcard_mobile_app | scripts/classes/widget/button/StartPauseButton.lua | 1 | 3539 | -----------------------------------------------------------------------------------------
--
-- StartPauseButton.lua
-- StartPauseButton class.
--
-----------------------------------------------------------------------------------------
local StartPauseButton = {}
-- StartPauseButton class.
function StartPauseButton.new( options )
--------------------------------------------------------------
-- Inherit from parent class.
--------------------------------------------------------------
local Button = require "scripts.classes.widget.button.Button" -- Button class.
local startPauseButton = Button.new()
Button = nil
--------------------------------------------------------------
-- Include files.
--------------------------------------------------------------
local globalVariable = require "scripts.common.global-variable" -- Global variables.
local myPlayButton = {}
local myPauseButton = {}
local backgroundMusic1
--------------------------------------------------------------
-- Class methods.
--------------------------------------------------------------
function startPauseButton:createStartButton( options )
options.action = startPlaylistSound
options.defaultFile = "images/icons/ic_play_circle_fill_white_18dp.png"
options.label = "Play"
startPauseButton:createButton( options )
myPlayButton[ options.id ] = startPauseButton:get()
end
function startPauseButton:createPauseButton( options )
options.action = pausePlaylistSound
options.defaultFile = "images/icons/ic_pause_circle_fill_white_18dp.png"
options.label = "Pause"
startPauseButton:createButton( options )
myPauseButton[ options.id ] = startPauseButton:get()
myPauseButton[ options.id ].isVisible = false
end
function startPauseButton:buttonLabel( options )
options.x = options.x + 200
options.width = 300
options.fontSize = 45
local buttonLabel = display.newText( options )
end
function startPauseButton:createStartPauseButton( options )
startPauseButton:createPauseButton( options )
startPauseButton:createStartButton( options )
startPauseButton:buttonLabel( options )
backgroundMusic1 = startPauseButton:construct( "scripts.classes.audio.BackgroundMusic" )
end
function pausePlaylistSound( event )
myPauseButton[ event.target.id ].isVisible = false
myPlayButton[ event.target.id ].isVisible = true
backgroundMusic1:pauseBackgroundMusic()
end
-- Play sound.
function startPlaylistSound( event )
myPlayButton[ event.target.id ].isVisible = false
-- TODO: change all pause buttons to play except for the one playing.
--[[for k, v in pairs( myPauseButton ) do
print(k)
end ]]--
myPauseButton[ event.target.id ].isVisible = true
local options = {
filePath = event.target.id,
fileMode = "r",
systemDirectory = system.ResourceDirectory,
delimiter = "\n"
}
local audioName = startPauseButton:make( "scripts.classes.file.FileParser", options )
options = {
stringToSeparate = audioName[ 1 ],
delimiter = "\t",
}
audioName = startPauseButton:make( "scripts.classes.file.DelimiterSeparator", options )
backgroundMusic1:playBackgroundMusic( audioName[ 2 ] )
end
------------------------------------------------------------------
-- Instantiate class.
------------------------------------------------------------------
function startPauseButton:start( options )
startPauseButton:createStartPauseButton( options )
end
startPauseButton:start( options )
return startPauseButton
end
return StartPauseButton | gpl-2.0 |
apung/prosody-modules | mod_email_pass/vcard.lib.lua | 33 | 9229 | -- Copyright (C) 2011-2012 Kim Alvefur
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- TODO
-- Fix folding.
local st = require "util.stanza";
local t_insert, t_concat = table.insert, table.concat;
local type = type;
local next, pairs, ipairs = next, pairs, ipairs;
local from_text, to_text, from_xep54, to_xep54;
local line_sep = "\n";
local vCard_dtd; -- See end of file
local function fold_line()
error "Not implemented" --TODO
end
local function unfold_line()
error "Not implemented"
-- gsub("\r?\n[ \t]([^\r\n])", "%1");
end
local function vCard_esc(s)
return s:gsub("[,:;\\]", "\\%1"):gsub("\n","\\n");
end
local function vCard_unesc(s)
return s:gsub("\\?[\\nt:;,]", {
["\\\\"] = "\\",
["\\n"] = "\n",
["\\r"] = "\r",
["\\t"] = "\t",
["\\:"] = ":", -- FIXME Shouldn't need to espace : in values, just params
["\\;"] = ";",
["\\,"] = ",",
[":"] = "\29",
[";"] = "\30",
[","] = "\31",
});
end
local function item_to_xep54(item)
local t = st.stanza(item.name, { xmlns = "vcard-temp" });
local prop_def = vCard_dtd[item.name];
if prop_def == "text" then
t:text(item[1]);
elseif type(prop_def) == "table" then
if prop_def.types and item.TYPE then
if type(item.TYPE) == "table" then
for _,v in pairs(prop_def.types) do
for _,typ in pairs(item.TYPE) do
if typ:upper() == v then
t:tag(v):up();
break;
end
end
end
else
t:tag(item.TYPE:upper()):up();
end
end
if prop_def.props then
for _,v in pairs(prop_def.props) do
if item[v] then
t:tag(v):up();
end
end
end
if prop_def.value then
t:tag(prop_def.value):text(item[1]):up();
elseif prop_def.values then
local prop_def_values = prop_def.values;
local repeat_last = prop_def_values.behaviour == "repeat-last" and prop_def_values[#prop_def_values];
for i=1,#item do
t:tag(prop_def.values[i] or repeat_last):text(item[i]):up();
end
end
end
return t;
end
local function vcard_to_xep54(vCard)
local t = st.stanza("vCard", { xmlns = "vcard-temp" });
for i=1,#vCard do
t:add_child(item_to_xep54(vCard[i]));
end
return t;
end
function to_xep54(vCards)
if not vCards[1] or vCards[1].name then
return vcard_to_xep54(vCards)
else
local t = st.stanza("xCard", { xmlns = "vcard-temp" });
for i=1,#vCards do
t:add_child(vcard_to_xep54(vCards[i]));
end
return t;
end
end
function from_text(data)
data = data -- unfold and remove empty lines
:gsub("\r\n","\n")
:gsub("\n ", "")
:gsub("\n\n+","\n");
local vCards = {};
local c; -- current item
for line in data:gmatch("[^\n]+") do
local line = vCard_unesc(line);
local name, params, value = line:match("^([-%a]+)(\30?[^\29]*)\29(.*)$");
value = value:gsub("\29",":");
if #params > 0 then
local _params = {};
for k,isval,v in params:gmatch("\30([^=]+)(=?)([^\30]*)") do
k = k:upper();
local _vt = {};
for _p in v:gmatch("[^\31]+") do
_vt[#_vt+1]=_p
_vt[_p]=true;
end
if isval == "=" then
_params[k]=_vt;
else
_params[k]=true;
end
end
params = _params;
end
if name == "BEGIN" and value == "VCARD" then
c = {};
vCards[#vCards+1] = c;
elseif name == "END" and value == "VCARD" then
c = nil;
elseif vCard_dtd[name] then
local dtd = vCard_dtd[name];
local p = { name = name };
c[#c+1]=p;
--c[name]=p;
local up = c;
c = p;
if dtd.types then
for _, t in ipairs(dtd.types) do
local t = t:lower();
if ( params.TYPE and params.TYPE[t] == true)
or params[t] == true then
c.TYPE=t;
end
end
end
if dtd.props then
for _, p in ipairs(dtd.props) do
if params[p] then
if params[p] == true then
c[p]=true;
else
for _, prop in ipairs(params[p]) do
c[p]=prop;
end
end
end
end
end
if dtd == "text" or dtd.value then
t_insert(c, value);
elseif dtd.values then
local value = "\30"..value;
for p in value:gmatch("\30([^\30]*)") do
t_insert(c, p);
end
end
c = up;
end
end
return vCards;
end
local function item_to_text(item)
local value = {};
for i=1,#item do
value[i] = vCard_esc(item[i]);
end
value = t_concat(value, ";");
local params = "";
for k,v in pairs(item) do
if type(k) == "string" and k ~= "name" then
params = params .. (";%s=%s"):format(k, type(v) == "table" and t_concat(v,",") or v);
end
end
return ("%s%s:%s"):format(item.name, params, value)
end
local function vcard_to_text(vcard)
local t={};
t_insert(t, "BEGIN:VCARD")
for i=1,#vcard do
t_insert(t, item_to_text(vcard[i]));
end
t_insert(t, "END:VCARD")
return t_concat(t, line_sep);
end
function to_text(vCards)
if vCards[1] and vCards[1].name then
return vcard_to_text(vCards)
else
local t = {};
for i=1,#vCards do
t[i]=vcard_to_text(vCards[i]);
end
return t_concat(t, line_sep);
end
end
local function from_xep54_item(item)
local prop_name = item.name;
local prop_def = vCard_dtd[prop_name];
local prop = { name = prop_name };
if prop_def == "text" then
prop[1] = item:get_text();
elseif type(prop_def) == "table" then
if prop_def.value then --single item
prop[1] = item:get_child_text(prop_def.value) or "";
elseif prop_def.values then --array
local value_names = prop_def.values;
if value_names.behaviour == "repeat-last" then
for i=1,#item.tags do
t_insert(prop, item.tags[i]:get_text() or "");
end
else
for i=1,#value_names do
t_insert(prop, item:get_child_text(value_names[i]) or "");
end
end
elseif prop_def.names then
local names = prop_def.names;
for i=1,#names do
if item:get_child(names[i]) then
prop[1] = names[i];
break;
end
end
end
if prop_def.props_verbatim then
for k,v in pairs(prop_def.props_verbatim) do
prop[k] = v;
end
end
if prop_def.types then
local types = prop_def.types;
prop.TYPE = {};
for i=1,#types do
if item:get_child(types[i]) then
t_insert(prop.TYPE, types[i]:lower());
end
end
if #prop.TYPE == 0 then
prop.TYPE = nil;
end
end
-- A key-value pair, within a key-value pair?
if prop_def.props then
local params = prop_def.props;
for i=1,#params do
local name = params[i]
local data = item:get_child_text(name);
if data then
prop[name] = prop[name] or {};
t_insert(prop[name], data);
end
end
end
else
return nil
end
return prop;
end
local function from_xep54_vCard(vCard)
local tags = vCard.tags;
local t = {};
for i=1,#tags do
t_insert(t, from_xep54_item(tags[i]));
end
return t
end
function from_xep54(vCard)
if vCard.attr.xmlns ~= "vcard-temp" then
return nil, "wrong-xmlns";
end
if vCard.name == "xCard" then -- A collection of vCards
local t = {};
local vCards = vCard.tags;
for i=1,#vCards do
t[i] = from_xep54_vCard(vCards[i]);
end
return t
elseif vCard.name == "vCard" then -- A single vCard
return from_xep54_vCard(vCard)
end
end
-- This was adapted from http://xmpp.org/extensions/xep-0054.html#dtd
vCard_dtd = {
VERSION = "text", --MUST be 3.0, so parsing is redundant
FN = "text",
N = {
values = {
"FAMILY",
"GIVEN",
"MIDDLE",
"PREFIX",
"SUFFIX",
},
},
NICKNAME = "text",
PHOTO = {
props_verbatim = { ENCODING = { "b" } },
props = { "TYPE" },
value = "BINVAL", --{ "EXTVAL", },
},
BDAY = "text",
ADR = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
values = {
"POBOX",
"EXTADD",
"STREET",
"LOCALITY",
"REGION",
"PCODE",
"CTRY",
}
},
LABEL = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
value = "LINE",
},
TEL = {
types = {
"HOME",
"WORK",
"VOICE",
"FAX",
"PAGER",
"MSG",
"CELL",
"VIDEO",
"BBS",
"MODEM",
"ISDN",
"PCS",
"PREF",
},
value = "NUMBER",
},
EMAIL = {
types = {
"HOME",
"WORK",
"INTERNET",
"PREF",
"X400",
},
value = "USERID",
},
JABBERID = "text",
MAILER = "text",
TZ = "text",
GEO = {
values = {
"LAT",
"LON",
},
},
TITLE = "text",
ROLE = "text",
LOGO = "copy of PHOTO",
AGENT = "text",
ORG = {
values = {
behaviour = "repeat-last",
"ORGNAME",
"ORGUNIT",
}
},
CATEGORIES = {
values = "KEYWORD",
},
NOTE = "text",
PRODID = "text",
REV = "text",
SORTSTRING = "text",
SOUND = "copy of PHOTO",
UID = "text",
URL = "text",
CLASS = {
names = { -- The item.name is the value if it's one of these.
"PUBLIC",
"PRIVATE",
"CONFIDENTIAL",
},
},
KEY = {
props = { "TYPE" },
value = "CRED",
},
DESC = "text",
};
vCard_dtd.LOGO = vCard_dtd.PHOTO;
vCard_dtd.SOUND = vCard_dtd.PHOTO;
return {
from_text = from_text;
to_text = to_text;
from_xep54 = from_xep54;
to_xep54 = to_xep54;
-- COMPAT:
lua_to_text = to_text;
lua_to_xep54 = to_xep54;
text_to_lua = from_text;
text_to_xep54 = function (...) return to_xep54(from_text(...)); end;
xep54_to_lua = from_xep54;
xep54_to_text = function (...) return to_text(from_xep54(...)) end;
};
| mit |
Enignite/darkstar | scripts/zones/Temple_of_Uggalepih/npcs/Worn_Book.lua | 17 | 2437 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Worn Book
-- Getting "Old Rusty Key (keyitem)"
-- @pos 59 0 19 159
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ParchmentID = 17428972;
local Book1 = ParchmentID + 1;
local Book2 = ParchmentID + 2;
local Book3 = ParchmentID + 3;
local rusty = player:hasKeyItem(OLD_RUSTY_KEY);
local soul = player:hasKeyItem(PAINTBRUSH_OF_SOULS);
if (soul or rusty) then
player:messageSpecial(NO_REASON_TO_INVESTIGATE);
elseif (npc:getID() == Book1) then
player:startEvent(0x003D); -- First Book
elseif (npc:getID() == Book2) then
player:startEvent(0x003E); -- Second Book
elseif (npc:getID() == Book3) then
player:startEvent(0x003F); -- Third Book
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local book = player:getVar("paintbrushOfSouls_book");
if (csid == 0x003d and option == 1 and (book == 0 or book == 2 or book == 4 or book == 6)) then
player:setVar("paintbrushOfSouls_book",book + 1);
elseif (csid == 0x003e and option == 1 and (book == 0 or book == 1 or book == 4 or book == 5)) then
player:setVar("paintbrushOfSouls_book",book + 2);
elseif (csid == 0x003f and option == 1 and (book == 0 or book == 1 or book == 2 or book == 3)) then
player:setVar("paintbrushOfSouls_book",book + 4);
end
if (player:getVar("paintbrushOfSouls_book") == 7) then
player:messageSpecial(FALLS_FROM_THE_BOOK,OLD_RUSTY_KEY);
player:addKeyItem(OLD_RUSTY_KEY);
player:messageSpecial(KEYITEM_OBTAINED,OLD_RUSTY_KEY);
player:setVar("paintbrushOfSouls_book",0);
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Beaucedine_Glacier_[S]/npcs/Moana_CA.lua | 38 | 1064 | -----------------------------------
-- Area: Beaucedine Glacier (S)
-- NPC: Moana, C.A.
-- Type: Campaign Arbiter
-- @zone: 136
-- @pos -27.237 -60.888 -48.111
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01c5);
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 |
Enignite/darkstar | scripts/zones/North_Gustaberg_[S]/npcs/Barricade.lua | 19 | 1108 | -----------------------------------
-- Area: North Gustaberg (S) (I-6)
-- NPC: Barricade
-- Involved in Quests: The Fighting Fourth
-----------------------------------
package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil;
package.loaded["scripts/globals/quests"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/North_Gustaberg_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR,THE_FIGHTING_FOURTH) == QUEST_ACCEPTED and player:getVar("THE_FIGHTING_FOURTH") == 2) then
player:startEvent(0x006A)
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x006A) then
player:setVar("THE_FIGHTING_FOURTH",3);
end
end;
| gpl-3.0 |
doofus-01/wesnoth | data/ai/lua/ca_level_up_attack.lua | 2 | 3414 | -- An example CA that tries to level up units by attacking weakened enemies.
-- Ported from level_up_attack_eval.fai and level_up_attack_move.fai
local LS = wesnoth.require "location_set"
local F = wesnoth.require "functional"
local level_up_attack = {}
local function kill_xp(unit)
local ratio = unit.level
if ratio == 0 then ratio = 0.5 end
return wesnoth.game_config.kill_experience * ratio
end
local function get_best_defense_loc(moves, attacker, victim)
local attack_spots = F.filter(moves, function(v)
return wesnoth.map.distance_between(v, victim) == 1
end)
return F.choose(attack_spots, function(loc)
return attacker:defense_on(loc)
end)
end
local function iter_possible_targets(moves, attacker)
moves = LS.of_pairs(moves)
-- The criteria are: a) unit is reachable b) unit's health is low
local targets = wesnoth.units.find({
})
return coroutine.wrap(function()
local checked = LS.create()
moves:iter(function(to_x, to_y)
for adj_x, adj_y in wesnoth.current.map:iter_adjacent(to_x, to_y) do
if not checked:get(adj_x, adj_y) then
checked:insert(adj_x, adj_y)
local u = wesnoth.units.get(adj_x, adj_y)
if u and u.hitpoints / u.max_hitpoints < 0.2 then
coroutine.yield(u)
end
end
end
end)
end)
end
local possible_attacks
function level_up_attack:evaluation(cfg, data, filter_own)
possible_attacks = LS.create()
local moves = LS.of_raw(ai.get_src_dst())
local units = wesnoth.units.find(filter_own)
for _,me in ipairs(units) do
local save_x, save_y = me.x, me.y
if not moves[me] or #moves[me] == 0 then
goto continue
end
if kill_xp(me) <= (me.max_experience - me.experience) then
goto continue
end
for target in iter_possible_targets(moves[me], me) do
local defense_loc = get_best_defense_loc(moves[me], me, target)
me:to_map(defense_loc.x, defense_loc.y)
local attacker_outcome, defender_outcome = wesnoth.simulate_combat(me, target)
-- Only consider attacks where
-- a) there's a chance the defender dies and
-- b) there's no chance the attacker dies
if defender_outcome.hp_chance[0] == 0 or attacker_outcome.hp_chance[0] > 0 then
goto continue
end
-- If killing the defender is the most likely result, save this as a possible attack
local best = F.choose_map(defender_outcome.hp_chance, function(k, v) return v end)
if best.key == 0 then
possible_attacks:insert(defense_loc, {
chance = defender_outcome.hp_chance[0],
attacker = me, target = target
})
end
end
::continue::
me:to_map(save_x, save_y)
end
local _, best_score = F.choose_map(possible_attacks:to_map(), 'chance')
return math.max(0, best_score) * 100000
end
function level_up_attack:execution(cfg, data)
local best_attack = F.choose_map(possible_attacks:to_map(), 'chance')
ai.move(best_attack.value.attacker, best_attack.key)
ai.attack(best_attack.value.attacker, best_attack.value.target)
end
return level_up_attack
| gpl-2.0 |
SouD/LessAnimeTabbing | src/Anime.lua | 1 | 5312 | -- LessAnimeTabbing. Keep track of your anime without tabbing!
-- Copyright (C) 2014 Linus Sörensen
-- This program is free software; you can redistribute it and/or
-- modify it under the terms of the GNU General Public License
-- as published by the Free Software Foundation; either version 2
-- of the License, or (at your option) any later version.
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
-- You should have received a copy of the GNU General Public License
-- along with this program; if not, write to the Free Software
-- Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
--- Defines the Anime class.
-- @return nil.
function define_Anime()
--- Anime class.
-- Represents an anime video in the vlc playlist.
-- @class Anime
-- @field PATTERN Patterns table constant.
-- @field PATTERN.EPISODE Episode pattern constant.
-- @field PATTERN.NAME Name pattern constant.
-- @field PATTERN.SEASON Season pattern constant.
-- @field PATTERN.STRIP Strip pattern table constant.
-- @field _episode The anime episode number.
-- @field _name The parsed anime name.
-- @field _raw_name The raw anime file name.
-- @field _season The anime season number.
Anime = inherits(nil)
Anime.PATTERN = {
EPISODE = "%s*[Ee]*[pisode]*(%d+)",
NAME = "[%A]*([^%d%c%.]+)",
SEASON = "%s*[Ss][eason]*(%d+)",
STRIP = {}
}
Anime.PATTERN.STRIP["_"] = " "
Anime.PATTERN.STRIP["[~%-]"] = ""
Anime.PATTERN.STRIP["%s[Ee]p[isode]*"] = ""
Anime.PATTERN.STRIP["^%s*(.-)%s*$"] = "%1"
Anime.PATTERN.STRIP["(%s%s*)"] = " "
Anime.PATTERN.STRIP["%s[SPE]$"] = ""
Anime._episode = nil
Anime._name = nil
Anime._raw_name = nil
Anime._season = nil
Anime._new = Anime.new
--- Anime constructor.
-- Creates a new instance of @class Anime.
-- @class Anime
-- @param playlist_item A playlist item.
-- @return Instance of @class Anime.
function Anime:new(playlist_item)
local capture
local episode = -1
local name = "Unknown"
local raw_name
local season = -1
local strip
if playlist_item and type(playlist_item) == "table" and playlist_item.name then
raw_name = playlist_item.name
strip = string.gsub(string.gsub(playlist_item.name, "%b[]", ""), "%b()", "")
capture = string.match(strip, self.PATTERN.EPISODE)
if capture and tonumber(capture) ~= nil then
episode = tonumber(capture)
end
capture = string.match(strip, self.PATTERN.SEASON)
if capture and tonumber(capture) ~= nil then
season = tonumber(capture)
end
capture = string.match(strip, self.PATTERN.NAME)
if capture and string.len(capture) > 1 then
for pattern, replace in pairs(self.PATTERN.STRIP) do
capture = string.gsub(capture, pattern, replace)
end
name = capture
end
end
return self._new(self, {
_episode = episode,
_name = name,
_raw_name = raw_name,
_season = season
})
end
--- Getter/Setter for @field _episode.
-- Returns the current episode number. If @param episode is present and
-- is a number it will set it as the new episode number.
-- @class Anime
-- @param episode Episode number to set.
-- @return The current episode number.
function Anime:episode(episode)
if type(episode) == "number" then
self._episode = episode
end
return self._episode
end
--- Getter/Setter for @field _name.
-- Returns the current anime name. If @param name is present and
-- is a non-empty string it will set it as the new anime name.
-- @class Anime
-- @param name New anime name to set.
-- @return The current anime name.
function Anime:name(name)
if type(name) == "string" and string_trim(name) ~= "" then
self._name = name
end
return self._name
end
--- Getter/Setter for @field _raw_name.
-- Returns the current raw file name. If @param raw_name is present and
-- is a non-empty string it will set it as the new raw file name.
-- @class Anime
-- @param name Raw file name to set.
-- @return The current raw file name.
function Anime:raw_name(raw_name)
if type(raw_name) == "string" and string_trim(raw_name) ~= "" then
self._raw_name = raw_name
end
return self._raw_name
end
--- Getter/Setter for @field _season.
-- Returns the current season number. If @param season is present and
-- is a number it will set it as the new season number.
-- @class Anime
-- @param season Season number to set.
-- @return The current season number.
function Anime:season(season)
if type(season) == "number" then
self._season = season
end
return self._season
end
end
| gpl-2.0 |
WUTiAM/LUAnity | Source/LuaJIT-2.1.0-beta2/dynasm/dasm_ppc.lua | 33 | 57489 | ------------------------------------------------------------------------------
-- DynASM PPC/PPC64 module.
--
-- Copyright (C) 2005-2016 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.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, 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", "IMMSH"
}
-- 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,
}
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
-- Template strings for PPC instructions.
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",
subi_3 = op_alias("addi_3", function(p) p[3] = "-("..p[3]..")" end),
subis_3 = op_alias("addis_3", function(p) p[3] = "-("..p[3]..")" end),
subic_3 = op_alias("addic_3", function(p) p[3] = "-("..p[3]..")" end),
["subic._3"] = op_alias("addic._3", function(p) p[3] = "-("..p[3]..")" end),
rotlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
rotrwi_3 = op_alias("rlwinm_5", function(p)
p[3] = "32-("..p[3]..")"; p[4] = "0"; p[5] = "31"
end),
rotlw_3 = op_alias("rlwnm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
slwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[4] = "0"
end),
srwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "32-("..p[3]..")"; p[5] = "31"
end),
clrlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "0"; p[5] = "31"
end),
clrrwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[3] = "0"; p[4] = "0"
end),
-- 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.",
rotldi_3 = op_alias("rldicl_4", function(p)
p[4] = "0"
end),
rotrdi_3 = op_alias("rldicl_4", function(p)
p[3] = "64-("..p[3]..")"; p[4] = "0"
end),
rotld_3 = op_alias("rldcl_4", function(p)
p[4] = "0"
end),
sldi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"
end),
srdi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "64-("..p[3]..")"
end),
clrldi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "0"
end),
clrrdi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"; p[3] = "0"
end),
-- 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 type(v) == "string" and 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 parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
local n = parse_number(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 = parse_number(imm)
if n then
if shr(n, 6) == 0 then
local lsb = band(n, 31)
local msb = n - 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
waction("IMMSH", isshift and 1 or 0, imm)
return 0;
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.
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
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- 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
------------------------------------------------------------------------------
| mit |
Enignite/darkstar | scripts/globals/abilities/wind_shot.lua | 22 | 2984 | -----------------------------------
-- Ability: Wind Shot
-- Consumes a Wind Card to enhance wind-based debuffs. Deals wind-based magic damage
-- Choke Effect: Enhanced DoT and VIT-
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
--ranged weapon/ammo: You do not have an appropriate ranged weapon equipped.
--no card: <name> cannot perform that action.
if (player:getWeaponSkillType(SLOT_RANGED) ~= SKILL_MRK or player:getWeaponSkillType(SLOT_AMMO) ~= SKILL_MRK) then
return 216,0;
end
if (player:hasItem(2178, 0) or player:hasItem(2974, 0)) then
return 0,0;
else
return 71, 0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local params = {};
params.includemab = true;
local dmg = 2 * player:getRangedDmg() + player:getAmmoDmg() + player:getMod(MOD_QUICK_DRAW_DMG);
dmg = addBonusesAbility(player, ELE_WIND, target, dmg, params);
dmg = dmg * applyResistanceAbility(player,target,ELE_WIND,SKILL_MRK, (player:getStat(MOD_AGI)/2) + player:getMerit(MERIT_QUICK_DRAW_ACCURACY));
dmg = adjustForTarget(target,dmg,ELE_WIND);
dmg = utils.stoneskin(target, dmg);
target:delHP(dmg);
target:updateEnmityFromDamage(player,dmg);
local effects = {};
local counter = 1;
local choke = target:getStatusEffect(EFFECT_CHOKE);
if (choke ~= nil) then
effects[counter] = choke;
counter = counter + 1;
end
local threnody = target:getStatusEffect(EFFECT_THRENODY);
if (threnody ~= nil and threnody:getSubPower() == MOD_EARTHRES) then
effects[counter] = threnody;
counter = counter + 1;
end
--TODO: Frightful Roar
--[[local frightfulRoar = target:getStatusEffect(EFFECT_);
if (frightfulRoar ~= nil) then
effects[counter] = frightfulRoar;
counter = counter + 1;
end]]
if counter > 1 then
local effect = effects[math.random(1, counter-1)];
local duration = effect:getDuration();
local startTime = effect:getStartTime();
local tick = effect:getTick();
local power = effect:getPower();
local subpower = effect:getSubPower();
local tier = effect:getTier();
local effectId = effect:getType();
local subId = effect:getSubType();
power = power * 1.2;
target:delStatusEffectSilent(effectId);
target:addStatusEffect(effectId, power, tick, duration, subId, subpower, tier);
local newEffect = target:getStatusEffect(effectId);
newEffect:setStartTime(startTime);
end
return dmg;
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Lower_Jeuno/npcs/Vola.lua | 17 | 3176 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Vola
-- Starts and Finishes Quest: Fistful of Fury
-- Involved in Quests: Beat Around the Bushin (before the quest)
-- @zone 245
-- @pos 43 3 -45
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
FistfulOfFury = player:getQuestStatus(JEUNO,FISTFUL_OF_FURY);
if (FistfulOfFury == QUEST_ACCEPTED and trade:hasItemQty(1012,1) == true and trade:hasItemQty(1013,1) == true and trade:hasItemQty(1014,1) == true and trade:getItemCount() == 3) then
player:startEvent(0x00D5); -- Finish Quest "Fistful of Fury"
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
FistfulOfFury = player:getQuestStatus(JEUNO,FISTFUL_OF_FURY);
BeatAroundTheBushin = player:getQuestStatus(JEUNO,BEAT_AROUND_THE_BUSHIN);
if (player:getFameLevel(NORG) >= 3 and FistfulOfFury == QUEST_AVAILABLE and player:getQuestStatus(BASTOK,SILENCE_OF_THE_RAMS) == QUEST_COMPLETED) then
player:startEvent(0x00D8); -- Start Quest "Fistful of Fury"
elseif (FistfulOfFury == QUEST_ACCEPTED) then
player:startEvent(0x00D7); -- During Quest "Fistful of Fury"
elseif (BeatAroundTheBushin == QUEST_AVAILABLE and player:getMainJob() == 2 and player:getMainLvl() >= 71 and player:getFameLevel(NORG) >= 6) then
player:startEvent(0x00a0); -- Start Quest "Beat Around the Bushin"
elseif (BeatAroundTheBushin ~= QUEST_AVAILABLE) then
player:startEvent(0x00D6); -- During & After Quest "Beat Around the Bushin"
else
player:startEvent(0x00D4); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x00D8 and option == 1) then
player:addQuest(JEUNO,FISTFUL_OF_FURY);
elseif (csid == 0x00D5) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13202);
else
player:addTitle(BROWN_BELT);
player:addItem(13202);
player:messageSpecial(ITEM_OBTAINED,13202);
player:addFame(NORG,NORG_FAME*125);
player:tradeComplete();
player:completeQuest(JEUNO,FISTFUL_OF_FURY);
end
elseif (csid == 0x00a0 and player:getQuestStatus(JEUNO,BEAT_AROUND_THE_BUSHIN) == QUEST_AVAILABLE) then
player:setVar("BeatAroundTheBushin",1); -- For the next quest "Beat around the Bushin"
end
end;
| gpl-3.0 |
GraionDilach/OpenRA | mods/ra/maps/fort-lonestar/fort-lonestar.lua | 7 | 7769 | --[[
Copyright 2007-2017 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.
]]
SovietEntryPoints = { Entry1, Entry2, Entry3, Entry4, Entry5, Entry6, Entry7, Entry8 }
PatrolWaypoints = { Entry2, Entry4, Entry6, Entry8 }
ParadropWaypoints = { Paradrop1, Paradrop2, Paradrop3, Paradrop4 }
SpawnPoints = { Spawn1, Spawn2, Spawn3, Spawn4 }
Snipers = { Sniper1, Sniper2, Sniper3, Sniper4, Sniper5, Sniper6, Sniper7, Sniper8, Sniper9, Sniper10, Sniper11, Sniper12 }
Walls =
{
{ WallTopRight1, WallTopRight2, WallTopRight3, WallTopRight4, WallTopRight5, WallTopRight6, WallTopRight7, WallTopRight8, WallTopRight9 },
{ WallTopLeft1, WallTopLeft2, WallTopLeft3, WallTopLeft4, WallTopLeft5, WallTopLeft6, WallTopLeft7, WallTopLeft8, WallTopLeft9 },
{ WallBottomLeft1, WallBottomLeft2, WallBottomLeft3, WallBottomLeft4, WallBottomLeft5, WallBottomLeft6, WallBottomLeft7, WallBottomLeft8, WallBottomLeft9 },
{ WallBottomRight1, WallBottomRight2, WallBottomRight3, WallBottomRight4, WallBottomRight5, WallBottomRight6, WallBottomRight7, WallBottomRight8, WallBottomRight9 }
}
if Map.LobbyOption("difficulty") == "veryeasy" then
ParaChance = 20
Patrol = { "e1", "e2", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e2" }
Vehicles = { "apc" }
Tank = { "3tnk" }
LongRange = { "arty" }
Boss = { "v2rl" }
Swarm = { "shok", "shok", "shok" }
elseif Map.LobbyOption("difficulty") == "easy" then
ParaChance = 25
Patrol = { "e1", "e2", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "ftrk", "apc", "arty" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "ttnk" }
elseif Map.LobbyOption("difficulty") == "normal" then
ParaChance = 30
Patrol = { "e1", "e2", "e1", "e1" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "ftrk", "ftrk", "apc", "arty" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk" }
elseif Map.LobbyOption("difficulty") == "hard" then
ParaChance = 35
Patrol = { "e1", "e2", "e1", "e1", "e4" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1" }
Vehicles = { "arty", "ftrk", "ftrk", "apc", "apc" }
Tank = { "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk", "ttnk" }
else
ParaChance = 40
Patrol = { "e1", "e2", "e1", "e1", "e4", "e4" }
Infantry = { "e4", "e1", "e1", "e2", "e1", "e2", "e1", "e1" }
Vehicles = { "arty", "arty", "ftrk", "apc", "apc" }
Tank = { "ftrk", "3tnk" }
LongRange = { "v2rl" }
Boss = { "4tnk" }
Swarm = { "shok", "shok", "shok", "shok", "shok", "shok", "ttnk", "ttnk", "ttnk", "ttnk", "ttnk" }
end
Wave = 0
Waves =
{
{ delay = 500, units = { Infantry } },
{ delay = 500, units = { Patrol, Patrol } },
{ delay = 700, units = { Infantry, Infantry, Vehicles }, },
{ delay = 1500, units = { Infantry, Infantry, Infantry, Infantry } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Tank, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Tank, Tank, Swarm } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, LongRange } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, LongRange, Tank, LongRange } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, LongRange, LongRange, Tank, Tank, Vehicles } },
{ delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, Infantry, Boss, Swarm } }
}
-- Now do some adjustments to the waves
if Map.LobbyOption("difficulty") == "tough" or Map.LobbyOption("difficulty") == "endless" then
Waves[8] = { delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry }, ironUnits = { LongRange } }
Waves[9] = { delay = 1500, units = { Infantry, Infantry, Patrol, Infantry, Infantry, Infantry, Infantry, Infantry, LongRange, LongRange, Vehicles, Tank }, ironUnits = { Tank } }
Waves[11] = { delay = 1500, units = { Vehicles, Infantry, Patrol, Patrol, Patrol, Infantry, LongRange, Tank, Boss, Infantry, Infantry, Patrol } }
end
SendUnits = function(entryCell, unitTypes, targetCell, extraData)
Reinforcements.Reinforce(soviets, unitTypes, { entryCell }, 40, function(a)
if not a.HasProperty("AttackMove") then
Trigger.OnIdle(a, function(a)
a.Move(targetCell)
end)
return
end
a.AttackMove(targetCell)
Trigger.OnIdle(a, function(a)
a.Hunt()
end)
if extraData == "IronCurtain" then
a.GrantCondition("invulnerability", DateTime.Seconds(25))
end
end)
end
SendWave = function()
Wave = Wave + 1
local wave = Waves[Wave]
Trigger.AfterDelay(wave.delay, function()
Utils.Do(wave.units, function(units)
local entry = Utils.Random(SovietEntryPoints).Location
local target = Utils.Random(SpawnPoints).Location
SendUnits(entry, units, target)
end)
if wave.ironUnits then
Utils.Do(wave.ironUnits, function(units)
local entry = Utils.Random(SovietEntryPoints).Location
local target = Utils.Random(SpawnPoints).Location
SendUnits(entry, units, target, "IronCurtain")
end)
end
Utils.Do(players, function(player)
Media.PlaySpeechNotification(player, "EnemyUnitsApproaching")
end)
if (Wave < #Waves) then
if Utils.RandomInteger(1, 100) < ParaChance then
local units = ParaProxy.SendParatroopers(Utils.Random(ParadropWaypoints).CenterPosition)
Utils.Do(units, function(unit)
Trigger.OnIdle(unit, function(a)
if a.IsInWorld then
a.Hunt()
end
end)
end)
local delay = Utils.RandomInteger(DateTime.Seconds(20), DateTime.Seconds(45))
Trigger.AfterDelay(delay, SendWave)
else
SendWave()
end
else
if Map.LobbyOption("difficulty") == "endless" then
Wave = 0
IncreaseDifficulty()
SendWave()
return
end
Trigger.AfterDelay(DateTime.Minutes(1), SovietsRetreating)
Media.DisplayMessage("You almost survived the onslaught! No more waves incoming.")
end
end)
end
SovietsRetreating = function()
Utils.Do(Snipers, function(a)
if not a.IsDead and a.Owner == soviets then
a.Destroy()
end
end)
end
IncreaseDifficulty = function()
local additions = { Infantry, Patrol, Vehicles, Tank, LongRange, Boss, Swarm }
Utils.Do(Waves, function(wave)
wave.units[#wave.units + 1] = Utils.Random(additions)
end)
end
Tick = function()
if (Utils.RandomInteger(1, 200) == 10) then
local delay = Utils.RandomInteger(1, 10)
Lighting.Flash("LightningStrike", delay)
Trigger.AfterDelay(delay, function()
Media.PlaySound("thunder" .. Utils.RandomInteger(1,6) .. ".aud")
end)
end
if (Utils.RandomInteger(1, 200) == 10) then
Media.PlaySound("thunder-ambient.aud")
end
end
SetupWallOwners = function()
Utils.Do(players, function(player)
Utils.Do(Walls[player.Spawn], function(wall)
wall.Owner = player
end)
end)
end
WorldLoaded = function()
soviets = Player.GetPlayer("Soviets")
players = { }
for i = 0, 4 do
local player = Player.GetPlayer("Multi" ..i)
players[i] = player
if players[i] and players[i].IsBot then
ActivateAI(players[i], i)
end
end
Media.DisplayMessage("Defend Fort Lonestar at all costs!")
SetupWallOwners()
ParaProxy = Actor.Create("powerproxy.paratroopers", false, { Owner = soviets })
SendWave()
end
| gpl-3.0 |
fcpxhacks/fcpxhacks | src/extensions/cp/ui/ScrollArea.lua | 1 | 10894 | --- === cp.ui.ScrollArea ===
---
--- Scroll Area Module.
local require = require
local axutils = require("cp.ui.axutils")
local Element = require("cp.ui.Element")
local ScrollBar = require("cp.ui.ScrollBar")
local ScrollArea = Element:subclass("cp.ui.ScrollArea")
--- cp.ui.ScrollArea.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function ScrollArea.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXScrollArea"
end
--- cp.ui.ScrollArea(parent, uiFinder) -> cp.ui.ScrollArea
--- Constructor
--- Creates a new `ScrollArea`.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - A `function` or `cp.prop` which will return the `hs.axuielement` when available.
---
--- Returns:
--- * The new `ScrollArea`.
function ScrollArea:initialize(parent, uiFinder)
Element.initialize(self, parent, uiFinder)
end
--- cp.ui.ScrollArea.contentsUI <cp.prop: hs.axuielement; read-only; live?>
--- Field
--- Returns the `axuielement` representing the Scroll Area Contents, or `nil` if not available.
function ScrollArea.lazy.prop:contentsUI()
return self.UI:mutate(function(original)
local ui = original()
if ui then
local role = ui:attributeValue("AXRole")
if role and role == "AXScrollArea" then
return ui:attributeValue("AXContents")[1]
end
end
end)
end
--- cp.ui.ScrollArea.verticalScrollBar <cp.ui.ScrollBar>
--- Field
--- The vertical [ScrollBar](cp.ui.ScrollBar.md).
function ScrollArea.lazy.value:verticalScrollBar()
return ScrollBar(self, axutils.prop(self.UI, "AXVerticalScrollBar"))
end
--- cp.ui.ScrollArea.horizontalScrollBar <cp.ui.ScrollBar>
--- Field
--- The horizontal [ScrollBar](cp.ui.ScrollBar.md).
function ScrollArea.lazy.value:horizontalScrollBar()
return ScrollBar(self, axutils.prop(self.UI, "AXHorizontalScrollBar"))
end
--- cp.ui.ScrollArea.selectedChildrenUI <cp.prop: hs.axuielement; read-only; live?>
--- Field
--- Returns the `axuielement` representing the Scroll Area Selected Children, or `nil` if not available.
function ScrollArea.lazy.prop:selectedChildrenUI()
return axutils.prop(self.contentsUI, "AXSelectedChildren")
end
-----------------------------------------------------------------------
--
-- CONTENT UI:
--
-----------------------------------------------------------------------
--- cp.ui.ScrollArea:childrenUI(filterFn) -> hs.axuielement | nil
--- Method
--- Returns the `axuielement` representing the Scroll Area Contents, or `nil` if not available.
---
--- Parameters:
--- * filterFn - The function which checks if the child matches the requirements.
---
--- Return:
--- * The `axuielement` or `nil`.
function ScrollArea:childrenUI(filterFn)
local ui = self:contentsUI()
if ui then
local children
if filterFn then
children = axutils.childrenMatching(ui, filterFn)
else
children = ui:attributeValue("AXChildren")
end
if children then
table.sort(children,
function(a, b)
if a and b then -- Added in this to try and solve issue #950
local aFrame = a:attributeValue("AXFrame")
local bFrame = b:attributeValue("AXFrame")
if aFrame and bFrame then
if aFrame.y < bFrame.y then -- a is above b
return true
elseif aFrame.y == bFrame.y then
if aFrame.x < bFrame.x then -- a is left of b
return true
elseif aFrame.x == bFrame.x
and aFrame.w < bFrame.w then -- a starts with but finishes before b, so b must be multi-line
return true
end
end
end
end
return false -- b is first
end
)
return children
end
end
return nil
end
--- cp.ui.ScrollArea.viewFrame <cp.prop:hs.geometry.rect; read-only>
--- Field
--- A `cp.prop` reporting the Scroll Area frame as a hs.geometry.rect.
function ScrollArea.lazy.prop:viewFrame()
return self.UI:mutate(function(original)
local ui = original()
local hScroll = self.horizontalScrollBar:frame()
local vScroll = self.verticalScrollBar:frame()
local frame = ui:attributeValue("AXFrame")
if hScroll then
frame.h = frame.h - hScroll.h
end
if vScroll then
frame.w = frame.w - vScroll.w
end
return frame
end)
:monitor(self.horizontalScrollBar.frame)
:monitor(self.verticalScrollBar.frame)
end
--- cp.ui.ScrollArea:showChild(childUI) -> self
--- Method
--- Show's a child element in a Scroll Area.
---
--- Parameters:
--- * childUI - The `hs.axuielement` object of the child you want to show.
---
--- Return:
--- * Self
function ScrollArea:showChild(childUI)
local ui = self:UI()
if ui and childUI then
local vFrame = self:viewFrame()
local childFrame = childUI:attributeValue("AXFrame")
local top = vFrame.y
local bottom = vFrame.y + vFrame.h
local childTop = childFrame.y
local childBottom = childFrame.y + childFrame.h
if childTop < top or childBottom > bottom then
-- we need to scroll
local oFrame = self:contentsUI():attributeValue("AXFrame")
local scrollHeight = oFrame.h - vFrame.h
local vValue
if childTop < top or childFrame.h > vFrame.h then
vValue = (childTop-oFrame.y)/scrollHeight
else
vValue = 1.0 - (oFrame.y + oFrame.h - childBottom)/scrollHeight
end
self.verticalScrollBar.value:set(vValue)
end
end
return self
end
--- cp.ui.ScrollArea:showChildAt(index) -> self
--- Method
--- Show's a child element in a Scroll Area given a specific index.
---
--- Parameters:
--- * index - The index of the child you want to show.
---
--- Return:
--- * Self
function ScrollArea:showChildAt(index)
local ui = self:childrenUI()
if ui and #ui >= index then
self:showChild(ui[index])
end
return self
end
--- cp.ui.ScrollArea:selectChild(childUI) -> self
--- Method
--- Select a specific child within a Scroll Area.
---
--- Parameters:
--- * childUI - The `hs.axuielement` object of the child you want to select.
---
--- Return:
--- * Self
function ScrollArea:selectChild(childUI)
if childUI then
local parent = childUI.parent and childUI:parent()
if parent then
parent:setAttributeValue("AXSelectedChildren", { childUI } )
end
end
return self
end
--- cp.ui.ScrollArea:selectChildAt(index) -> self
--- Method
--- Select a child element in a Scroll Area given a specific index.
---
--- Parameters:
--- * index - The index of the child you want to select.
---
--- Return:
--- * Self
function ScrollArea:selectChildAt(index)
local ui = self:childrenUI()
if ui and #ui >= index then
self:selectChild(ui[index])
end
return self
end
--- cp.ui.ScrollArea:selectAll(childrenUI) -> self
--- Method
--- Select all children in a scroll area.
---
--- Parameters:
--- * childrenUI - A table of `hs.axuielement` objects.
---
--- Return:
--- * Self
function ScrollArea:selectAll(childrenUI)
childrenUI = childrenUI or self:childrenUI()
if childrenUI then
for _,clip in ipairs(childrenUI) do
self:selectChild(clip)
end
end
return self
end
--- cp.ui.ScrollArea:deselectAll() -> self
--- Method
--- Deselect all children in a scroll area.
---
--- Parameters:
--- * None
---
--- Return:
--- * Self
function ScrollArea:deselectAll()
local contents = self:contentsUI()
if contents then
contents:setAttributeValue("AXSelectedChildren", {})
end
return self
end
--- cp.ui.ScrollArea:shiftHorizontalBy(amount) -> number
--- Method
--- Attempts to shift the horizontal scroll bar by the specified amount.
---
--- Parameters:
--- * amount - The amount to shift
---
--- Returns:
--- * The actual value of the horizontal scroll bar.
function ScrollArea:shiftHorizontalBy(amount)
return self.horizontalScrollBar:shiftValueBy(amount)
end
--- cp.ui.ScrollArea:shiftHorizontalTo(value) -> number
--- Method
--- Attempts to shift the horizontal scroll bar to the specified value.
---
--- Parameters:
--- * value - The new value (typically between `0` and `1`).
---
--- Returns:
--- * The actual value of the horizontal scroll bar.
function ScrollArea:shiftHorizontalTo(value)
return self.horizontalScrollBar:value(value)
end
--- cp.ui.ScrollArea:shiftVerticalBy(amount) -> number
--- Method
--- Attempts to shift the vertical scroll bar by the specified amount.
---
--- Parameters:
--- * amount - The amount to shift
---
--- Returns:
--- * The actual value of the vertical scroll bar.
function ScrollArea:shiftVerticalBy(amount)
return self.verticalScrollBar:shiftValueBy(amount)
end
--- cp.ui.ScrollArea:shiftVerticalTo(value) -> number
--- Method
--- Attempts to shift the vertical scroll bar to the specified value.
---
--- Parameters:
--- * value - The new value (typically between `0` and `1`).
---
--- Returns:
--- * The actual value of the vertical scroll bar.
function ScrollArea:shiftVerticalTo(value)
return self.verticalScrollBar:value(value)
end
--- cp.ui.ScrollArea:saveLayout() -> table
--- Method
--- Saves the current Scroll Area layout to a table.
---
--- Parameters:
--- * None
---
--- Returns:
--- * A table containing the current Scroll Area Layout.
function ScrollArea:saveLayout()
local layout = Element.saveLayout(self)
layout.horizontalScrollBar = self.horizontalScrollBar:saveLayout()
layout.verticalScrollBar = self.verticalScrollBar:saveLayout()
layout.selectedChildren = self:selectedChildrenUI()
return layout
end
--- cp.ui.ScrollArea:loadLayout(layout) -> none
--- Method
--- Loads a Scroll Area layout.
---
--- Parameters:
--- * layout - A table containing the ScrollArea layout settings, typically created using [saveLayout](#saveLayout).
---
--- Returns:
--- * None
function ScrollArea:loadLayout(layout)
if layout then
self:selectAll(layout.selectedChildren)
self.verticalScrollBar:loadLayout(layout.verticalScrollBar)
self.horizontalScrollBar:loadLayout(layout.horizontalScrollBar)
end
end
return ScrollArea
| mit |
florian-shellfire/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
| apache-2.0 |
luanorlandi/Hex | src/game/lane.lua | 1 | 1200 | deckLane = MOAIGfxQuad2D.new()
Lane = {}
Lane.__index = Lane
function Lane:new(path)
-- "path" lane direction
local L = {}
setmetatable(L, Lane)
L.sprite = MOAIProp2D.new()
changePriority(L.sprite, "background")
L.sprite:setDeck(window.deckManager.lane)
if path == victoryPath["vertical"] then
L.sprite:setRot(123.7)
end
if path == player1.myPath then
L.color = Color:new(player1.color:getColor())
else
L.color = Color:new(player2.color:getColor())
end
L.sprite:setColor(L.color:getColor())
L.blendDuration = 0.5
L.action = nil
L.sprite:setLoc(0, 0)
window.layer:insertProp(L.sprite)
return L
end
function Lane:clear()
window.layer:removeProp(self.sprite)
end
function Lane:blendIn()
if self.action then
self.action:stop()
end
self.action = self.sprite:seekColor(
self.color.red,
self.color.green,
self.color.blue,
self.color.alpha,
self.blendDuration)
end
function Lane:blendOut()
if self.action then
self.action:stop()
end
self.action = self.sprite:seekColor(
self.color.red,
self.color.green,
self.color.blue,
0.5 * self.color.alpha,
self.blendDuration)
end | gpl-3.0 |
Enignite/darkstar | scripts/globals/items/coffeecake_muffin_+1.lua | 35 | 1377 | -----------------------------------------
-- ID: 5656
-- Item: coffeecake_muffin_+1
-- Food Effect: 1Hr, All Races
-----------------------------------------
-- Mind 2
-- Strength -1
-- MP % 10 (cap 90)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5656);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MND, 2);
target:addMod(MOD_STR, -1);
target:addMod(MOD_FOOD_MPP, 10);
target:addMod(MOD_FOOD_MP_CAP, 90);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MND, 2);
target:delMod(MOD_STR, -1);
target:delMod(MOD_FOOD_MPP, 10);
target:delMod(MOD_FOOD_MP_CAP, 90);
end; | gpl-3.0 |
TeleSudo/TeleRedStar | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| agpl-3.0 |
Enignite/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Duke_Berith.lua | 16 | 1289 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Duke Berith
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if (mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 32;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if (Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if (Animate_Trigger == 32767) then
killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Windurst_Woods/npcs/Bin_Stejihna.lua | 36 | 1886 | -----------------------------------
-- Area: Windurst_Woods
-- NPC: Bin Stejihna
-- Only sells when Windurst controlls Zulkheim Region
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ZULKHEIM);
if (RegionOwner ~= WINDURST) then
player:showText(npc,BIN_STEJIHNA_CLOSED_DIALOG);
else
player:showText(npc,BIN_STEJIHNA_OPEN_DIALOG);
rank = getNationRank(BASTOK);
if (rank ~= 3) then
table.insert(stock,0x0730); --Semolina
table.insert(stock,1840);
end
stock = {
0x0730, 1840, --Semolina
0x1114, 44, --Giant Sheep Meat
0x026E, 44, --Dried Marjoram
0x0262, 55, --San d'Orian Flour
0x0263, 36, --Rye Flour
0x110E, 22, --La Theine Cabbage
0x111A, 55 --Selbina Milk
}
showShop(player,WINDURST,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Enignite/darkstar | scripts/globals/effects/yonin.lua | 17 | 1446 | -----------------------------------
--
--
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect) --power=30 initially, subpower=20 for enmity
target:addMod(MOD_ACC,-effect:getPower());
target:addMod(MOD_EVA,effect:getPower());
target:addMod(MOD_NINJA_TOOL,effect:getPower());
target:addMod(MOD_ENMITY,effect:getSubPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
--tick down the effect and reduce the overall power
effect:setPower(effect:getPower()-1);
target:delMod(MOD_ACC,-1);
target:delMod(MOD_EVA,1);
target:delMod(MOD_NINJA_TOOL,1);
if (effect:getPower() % 2 == 0) then -- enmity+ decays from 20 to 10, so half as often as the rest.
effect:setSubPower(effect:getSubPower()-1);
target:delMod(MOD_ENMITY,1);
end;
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
--remove the remaining power
target:delMod(MOD_ACC,-effect:getPower());
target:delMod(MOD_EVA,effect:getPower());
target:delMod(MOD_NINJA_TOOL,effect:getPower());
target:delMod(MOD_ENMITY,effect:getSubPower());
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Palborough_Mines/npcs/_3z7.lua | 58 | 1142 | -----------------------------------
-- Elevator in Palborough
-- Notes: Used to operate Elevator @3z0
-----------------------------------
package.loaded["scripts/zones/Palborough_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Palborough_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RunElevator(ELEVATOR_PALBOROUGH_MINES_LIFT);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
AMIRUJK/teleujk | plugins/anti fuck.lua | 4 | 4533 | -- By Mohamed_devt { @MD_IQ19 }
-- how to use inside telegram --
-- if you want to see fuck use this command /fuck lock
-- if you want to disable the protection use this command /fuck unlock
-- if you want to check the protection use this command /link ?
-- a function that i make to cut the command and the / from the text and send me the text after the command
-- Unused but you can copy it and use it in your codes :)
-- function getText(msg)
-- TheString = msg["text"];
-- SpacePos = string.find(TheString, " ")
-- FinalString = string.sub(TheString, SpacePos + 1)
-- return FinalString;
-- end
local XCommands =
{
LockCommand = "lock", -- The command to lock the fuck see
UnlockCommand = "unlock", -- The command to unlock the fuck see
CheckCommand = "?" -- The command to check for the statue of the fuck see
}
local msgs =
{
already_locked = "تم بالفعل تفعيل مضاد الكلمات السيئة", -- the message that sent when you try to lock the fuck and it's already locked
Locked = "تم تفعيل مضاد الكلمات السيئة, يرجى من الاعضاء عدم التكلم بكلمات سيئة والفاظ مخلة بالادب", -- the message that send when you lock the fuck
already_unlocked = "تم بالفعل ايقاف تفعيل مضاد الكلمات السيئة", -- the message that sent when you try to unlock the fuck and it's already unlocked
UnLocked = "تم الغاء تفعيل مضاد الكلمات السيئة, يمكنك قول ماتشاء 😒🙌🏿", -- the message that send when you unlock the fuck
statue = { Locked2 = "The fuck see is locked here", UnLocked2 = "The fuck see is unlocked here" }
}
do
local function run(msg, matches)
-- Get the receiver
local receiver = get_receiver(msg)
local check = false;
-- use my function to get the text without the command
-- loading the data from _config.moderation.data
local data = load_data(_config.moderation.data)
if ( is_realm(msg) and is_admin(msg) or is_sudo(msg) or is_momod(msg) ) then
-- check if the command is lock and by command i mean when you write /fuck lock : lock here is the command
if ( matches[2] == XCommands.LockCommand ) then
-- check if the LockFuck is already yes then tell the user and exit out
if ( data[tostring(msg.to.id)]['settings']["Lockfuck"] == "yes" ) then
send_large_msg ( receiver , msgs.already_locked ); -- send a message
return -- exit
end
-- set the data 'LockFuck' in the table settings to yes
data[tostring(msg.to.id)]['settings']['LockFuck'] = "yes"
-- send a message
send_large_msg(receiver, msgs.Locked)
-- check if the command is unlock
elseif ( matches[2] == XCommands.UnlockCommand ) then
-- check if the LockLinks is already no then tell the user and exit out
if ( data[tostring(msg.to.id)]['settings']['LockFuck'] == "no" ) then
send_large_msg ( receiver , msgs.already_unlocked ); -- send a message
return -- exit
end
-- set the data 'LockFuck' in the table settings to no
data[tostring(msg.to.id)]['settings']['LockFuck'] = "no"
-- send a message
send_large_msg(receiver, msgs.UnLocked)
-- check if the command is ?
elseif ( matches[2] == XCommands.CheckCommand ) then
-- load the data
data = load_data(_config.moderation.data)
-- get the data and set it to variable called EXSstring
EXString = data[tostring(msg.to.id)]["settings"]["LockFuck"]
-- send the data ass a message
if ( EXString == "yes" ) then
send_large_msg(receiver, msgs.statue.Locked2 )
elseif ( EXString == "no" ) then
send_large_msg(receiver, msgs.statue.UnLocked2 )
else
print("there is an error in your code please copy it and send it to the author ")
end
end
end
-- save the data
testDataSaved = save_data(_config.moderation.data, data)
return true;
end
-- the return part
return {
-- the patterns
patterns = {
-- the command will be like /fuck <arg> { the arg can be "?" or "lock" or "unlock" }
"^(/[Ff][Uu][Cc][Kk]) (.+)"
},
run = run
}
end
| gpl-2.0 |
Enignite/darkstar | scripts/globals/weaponskills/double_thrust.lua | 30 | 1320 | -----------------------------------
-- Double Thrust
-- Polearm weapon skill
-- Skill Level: 5
-- Delivers a two-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Light Gorget.
-- Aligned with the Light Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 2.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 2;
params.str_wsc = 0.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.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.dex_wsc = 0.3;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Riverne-Site_B01/npcs/_0t3.lua | 17 | 1341 | -----------------------------------
-- Area: Riverne Site #B01
-- NPC: Unstable Displacement
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Riverne-Site_B01/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale
player:tradeComplete();
npc:openDoor(RIVERNE_PORTERS);
player:messageSpecial(SD_HAS_GROWN);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 8) then
player:startEvent(0x26);
else
player:messageSpecial(SD_VERY_SMALL);
end;
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Port_Windurst/npcs/Papo-Hopo.lua | 36 | 2900 | -----------------------------------
-- Area: Port Windurst
-- NPC: Papo-Hopo
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
if (ThePromise == QUEST_COMPLETED) then
Message = math.random(0,1)
if (Message == 1) then
player:startEvent(0x0219);
else
player:startEvent(0x020d);
end
elseif (ThePromise == QUEST_ACCEPTED) then
player:startEvent(0x0203);
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(0x01fd);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
CryingOverOnionsVar = player:getVar("CryingOverOnions");
if (CryingOverOnionsVar >= 1) then
player:startEvent(0x01fc);
else
player:startEvent(0x01f5);
end
elseif (OnionRings == QUEST_COMPLETED) then
player:startEvent(0x01b9);
elseif (OnionRings == QUEST_ACCEPTED ) then
player:startEvent(0x01b2);
elseif (InspectorsGadget == QUEST_COMPLETED) then
player:startEvent(0x01a8);
elseif (InspectorsGadget == QUEST_ACCEPTED) then
player:startEvent(0x01a0);
elseif (KnowOnesOnions == QUEST_COMPLETED) then
player:startEvent(0x0193);
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
if (KnowOnesOnionsVar == 2) then
player:startEvent(0x0192);
else
player:startEvent(0x0189);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
player:startEvent(0x017c);
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0174);
else
player:startEvent(0x016a);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
RCdiy/OpenTxLua | TELEMETRY/LapTmr/!Archive/LapTmr-2018-01-01.lua | 1 | 6798 | -- License https://www.gnu.org/licenses/gpl-3.0.en.html
-- OpenTX Lua script
-- TELEMETRY
-- Place this file in the SD Card folder on your computer and Tx
-- SD Card /SCRIPTS/TELEMETRY/
-- Place the accompanying sound files in /SCRIPTS/SOUNDS/LapTmr/
-- Further instructions http://rcdiy.ca/telemetry-scripts-getting-started/
-- Works On OpenTX Version: 2.1.8 to 2.1.9
-- Works With Sensor: none
-- Author: RCdiy
-- Web: http://RCdiy.ca
-- Thanks: none
-- Date: 2017 January 7
-- Update: none
-- Description
-- Displays time elapsed in minutes, seconds an miliseconds.
-- Timer activated by a physical or logical switch.
-- Lap recorded by a second physical or logical switch.
-- Reset to zero by Timer switch being set to off and Lap switch set on.
-- Default Timer switch is "ls1" (logical switch one).
-- OpenTX "ls1" set to a>x, THR, -100
-- Default Lap switch is "sh", a momentary switch.
-- Change as desired
-- sa to sh, ls1 to ls32
-- If you want the timer to start and stop when the throttle is up and down
-- create a logical switch that changes state based on throttle position.
local TimerSwitch = "ls1"
-- Position U (up/away from you), D (down/towards), M (middle)
-- When using logical switches use "U" for true, "D" for false
local TimerSwitchOnPosition = "U"
local LapSwitch = "sh"
local LapSwitchRecordPosition = "U"
-- Audio
local SpeakLapNumber = true
local SpeakLapTime = true
local SpeakLapNumber = true
local SpeakLapTimeHours = 0 -- 1 hours, minutes, seconds else minutes, seconds
local BeepOnLap = true
local BeepFrequency = 200 -- Hz
local BeemLengthMiliseconds = 200
-- File Paths
-- location you placed the accompanying sound files
local SoundFilesPath = "/SCRIPTS/TELEMETRY/LapTmr/"
-- ----------------------------------------------------------------------------------------
-- ----------------------------------------------------------------------------------------
-- AVOID EDITING BELOW HERE
-- Global Lua environment variables used (Global between scripts)
-- None
-- Variables local to this script
-- must use the word "local" before the variable
-- Time Tracking
local StartTimeMiliseconds = -1
local ElapsedTimeMiliseconds = 0
local PreviousElapsedTimeMiliseconds = 0
local LapTime = 0
local LapTimeList = {ElapsedTimeMiliseconds}
local LapTimeRecorded = false
-- Display
local TextHeader = "Lap Timer"
local TextSize = 0
local Debuging = false
local function getTimeMiliSeconds()
-- Returns the number of miliseconds elapsed since the Tx was turned on
-- Increments in 10 milisecond intervals
-- getTime()
-- Return the time since the radio was started in multiple of 10ms
-- Number of 10ms ticks since the radio was started Example: run time: 12.54 seconds, return value: 1254
now = getTime() * 10
return now
end
local function getMinutesSecondsHundrethsAsString(miliseconds)
-- Returns MM:SS.hh as a string
seconds = miliseconds/1000
minutes = math.floor(seconds/60) -- seconds/60 gives minutes
seconds = seconds % 60 -- seconds % 60 gives seconds
return string.format("%02d:%05.2f", minutes, seconds)
end
local function getSwitchPosition( switchID )
-- Returns switch position as one of U,D,M
-- Passed a switch identifier sa to sf, ls1 to ls32
switchValue = getValue(switchID)
if Debuging == true then
print(switchValue)
end
-- typical Tx switch middle value is
if switchValue < -100 then
return "D"
elseif switchValue < 100 then
return "M"
else
return "U"
end
end
local function myTableInsert(t,v)
-- Adds values to the end of the passed table
end
local function init_func()
-- Called once when model is loaded or telemetry reset.
StartTimeMiliseconds = -1
ElapsedTimeMiliseconds = 0
-- XXLSIZE, MIDSIZE, SMLSIZE, INVERS, BLINK
if LCD_W > 128 then
TextSize = MIDSIZE
else
TextSize = 0
end
end
local function bg_func()
-- Called periodically when screen is not visible
-- This could be empty
-- Place code here that would be executed even when the telemetry
-- screen is not being displayed on the Tx
--print(#LapTimeList)
-- Start recording time
if getSwitchPosition(TimerSwitch) == TimerSwitchOnPosition then
-- Start reference time
if StartTimeMiliseconds == -1 then
StartTimeMiliseconds = getTimeMiliSeconds()
end
-- Time difference
ElapsedTimeMiliseconds = getTimeMiliSeconds() - StartTimeMiliseconds
-- TimerSwitch and LapSwitch On so record the lap time
if getSwitchPosition(LapSwitch) == LapSwitchRecordPosition then
if LapTimeRecorded == false then
LapTime = ElapsedTimeMiliseconds - PreviousElapsedTimeMiliseconds
PreviousElapsedTimeMiliseconds = ElapsedTimeMiliseconds
LapTimeList[#LapTimeList+1] = LapTime
LapTimeRecorded = true
playTone(BeepFrequency,BeemLengthMiliseconds,0)
if (#LapTimeList-1) <= 16 then
filePathName = SoundFilesPath..tostring(#LapTimeList-1)..".wav"
playFile(filePathName)
end
-- playNumber(#LapTimeList-1,0)
--if (#LapTimeList-1) == 1 then
--playFile(SoundFilesPath.."laps.wav")
---else
--playFile(SoundFilesPath.."lap.wav")
--end
local LapTimeInt = math.floor((LapTime/1000)+0.5)
playDuration(LapTimeInt, SpeakLapTimeHours)
end
else
LapTimeRecorded = false
end
else
--TimerSwitch Off and LapSwitch On so reset time
if getSwitchPosition(LapSwitch) == LapSwitchRecordPosition then
StartTimeMiliseconds = -1
ElapsedTimeMiliseconds = 0
PreviousElapsedTimeMiliseconds = 0
LapTime = 0
LapTimeList = {0}
end
end
end
local function run_func(event)
-- Called periodically when screen is visible
bg_func() -- a good way to reduce repitition
-- LCD / Display code
lcd.clear()
-- lcd.drawText(x, y, text [, flags])
-- Displays text
-- text is the text to display
-- flags are optional
-- XXLSIZE, MIDSIZE, SMLSIZE, INVERS, BLINK
lcd.drawText( 0, 0, TextHeader, TextSize + INVERS)
-- lcd.drawText( lcd.getLastPos(), 15, "s", SMLSIZE)
x = lcd.getLastPos() + 2
lcd.drawText( x, 0, getMinutesSecondsHundrethsAsString(ElapsedTimeMiliseconds).."s", TextSize)
x = lcd.getLastPos() + 2
lcd.drawText( x, 0, "Laps", TextSize + INVERS)
x = lcd.getLastPos() + 2
lcd.drawText( x, 0, #LapTimeList-1, TextSize)
rowHeight = 12
x = 0
y = rowHeight
-- i = 2 first entry is always 0:00.00 so skippind it
for i = #LapTimeList, 2, -1 do
if y % 60 == 0 then
-- next column
x = lcd.getLastPos() + 3
y = rowHeight
end
lcd.drawText( x, y, getMinutesSecondsHundrethsAsString(LapTimeList[i]),TextSize)
y = y + rowHeight
end
end
return { run=run_func, background=bg_func, init=init_func }
| gpl-3.0 |
noblepepper/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/nat_traffic.lua | 79 | 1251 | local function scrape()
-- documetation about nf_conntrack:
-- https://www.frozentux.net/iptables-tutorial/chunkyhtml/x1309.html
nat_metric = metric("node_nat_traffic", "gauge" )
for e in io.lines("/proc/net/nf_conntrack") do
-- output(string.format("%s\n",e ))
local fields = space_split(e)
local src, dest, bytes;
bytes = 0;
for _, field in ipairs(fields) do
if src == nil and string.match(field, '^src') then
src = string.match(field,"src=([^ ]+)");
elseif dest == nil and string.match(field, '^dst') then
dest = string.match(field,"dst=([^ ]+)");
elseif string.match(field, '^bytes') then
local b = string.match(field, "bytes=([^ ]+)");
bytes = bytes + b;
-- output(string.format("\t%d %s",ii,field ));
end
end
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) .- bytes=([^ ]+)");
-- local src, dest, bytes = string.match(natstat[i], "src=([^ ]+) dst=([^ ]+) sport=[^ ]+ dport=[^ ]+ packets=[^ ]+ bytes=([^ ]+)")
local labels = { src = src, dest = dest }
-- output(string.format("src=|%s| dest=|%s| bytes=|%s|", src, dest, bytes ))
nat_metric(labels, bytes )
end
end
return { scrape = scrape }
| gpl-2.0 |
fcpxhacks/fcpxhacks | src/plugins/finalcutpro/timeline/videoeffects.lua | 2 | 5765 | --- === plugins.finalcutpro.timeline.videoeffects ===
---
--- Controls Final Cut Pro's Video Effects.
local require = require
local timer = require("hs.timer")
local dialog = require("cp.dialog")
local fcp = require("cp.apple.finalcutpro")
local i18n = require("cp.i18n")
local doAfter = timer.doAfter
local mod = {}
--- plugins.finalcutpro.timeline.videoeffects(action) -> boolean
--- Function
--- Applies the specified action as a video effect. Expects action to be a table with the following structure:
---
--- ```lua
--- { name = "XXX", category = "YYY", theme = "ZZZ" }
--- ```
---
--- ...where `"XXX"`, `"YYY"` and `"ZZZ"` are in the current FCPX language. The `category` and `theme` are optional,
--- but if they are known it's recommended to use them, or it will simply execute the first matching video effect with that name.
---
--- Alternatively, you can also supply a string with just the name.
---
--- Parameters:
--- * `action` - A table with the name/category/theme for the video effect to apply, or a string with just the name.
---
--- Returns:
--- * `true` if a matching video effect was found and applied to the timeline.
function mod.apply(action)
--------------------------------------------------------------------------------
-- Get settings:
--------------------------------------------------------------------------------
if type(action) == "string" then
action = { name = action }
end
local name, category = action.name, action.category
if name == nil then
dialog.displayMessage(i18n("noEffectShortcut"))
return false
end
--------------------------------------------------------------------------------
-- Save the Transitions Browser layout:
--------------------------------------------------------------------------------
local transitions = fcp.transitions
local transitionsLayout = transitions:saveLayout()
--------------------------------------------------------------------------------
-- Get Effects Browser:
--------------------------------------------------------------------------------
local effects = fcp.effects
local effectsShowing = effects:isShowing()
local effectsLayout = effects:saveLayout()
--------------------------------------------------------------------------------
-- Make sure FCPX is at the front.
--------------------------------------------------------------------------------
fcp:launch()
--------------------------------------------------------------------------------
-- Make sure panel is open:
--------------------------------------------------------------------------------
effects:show()
--------------------------------------------------------------------------------
-- Make sure "Installed Effects" is selected:
--------------------------------------------------------------------------------
local group = effects.group:UI()
local groupValue = group:attributeValue("AXValue")
if groupValue ~= fcp:string("PEMediaBrowserInstalledEffectsMenuItem") then
effects:showInstalledEffects()
end
--------------------------------------------------------------------------------
-- Get original search value:
--------------------------------------------------------------------------------
local originalSearch = effects.search:value()
--------------------------------------------------------------------------------
-- Make sure there's nothing in the search box:
--------------------------------------------------------------------------------
effects.search:clear()
--------------------------------------------------------------------------------
-- Click 'All':
--------------------------------------------------------------------------------
if category then
effects:showVideoCategory(category)
else
effects:showAllVideoEffects()
end
--------------------------------------------------------------------------------
-- Perform Search:
--------------------------------------------------------------------------------
effects.search:setValue(name)
--------------------------------------------------------------------------------
-- Get the list of matching effects
--------------------------------------------------------------------------------
local matches = effects:currentItemsUI()
if not matches or #matches == 0 then
dialog.displayErrorMessage("Unable to find a video effect called '"..name.."'.")
return false
end
local effect = matches[1]
--------------------------------------------------------------------------------
-- Apply the selected Transition:
--------------------------------------------------------------------------------
effects:applyItem(effect)
-- TODO: HACK: This timer exists to work around a mouse bug in Hammerspoon Sierra
doAfter(0.1, function()
effects.search:setValue(originalSearch)
effects:loadLayout(effectsLayout)
if transitionsLayout then transitions:loadLayout(transitionsLayout) end
if not effectsShowing then effects:hide() end
end)
-- Success!
return true
end
local plugin = {
id = "finalcutpro.timeline.videoeffects",
group = "finalcutpro",
dependencies = {
}
}
function plugin.init()
--------------------------------------------------------------------------------
-- Only load plugin if Final Cut Pro is supported:
--------------------------------------------------------------------------------
if not fcp:isSupported() then return end
return mod
end
return plugin
| mit |
Enignite/darkstar | scripts/zones/Phanauet_Channel/Zone.lua | 32 | 1482 | -----------------------------------
--
-- Zone: Phanauet_Channel
--
-----------------------------------
package.loaded["scripts/zones/Phanauet_Channel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Phanauet_Channel/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm4.lua | 16 | 1197 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Wulgaru(ZNM T2))
-- @pos -22 -4 204 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:hasItemQty(2597,1) and trade:getItemCount() == 1) then -- Trade Opalus Gem
player:tradeComplete();
SpawnMob(17072179,180):updateClaim(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
dwdm/snabbswitch | src/apps/intel/intel10g.lua | 7 | 54048 | --- Device driver for the Intel 82599 10-Gigabit Ethernet controller.
--- This is one of the most popular production 10G Ethernet
--- controllers on the market and it is readily available in
--- affordable (~$400) network cards made by Intel and others.
---
--- You will need to familiarize yourself with the excellent [data
--- sheet]() to understand this module.
module(...,package.seeall)
local ffi = require "ffi"
local C = ffi.C
local lib = require("core.lib")
local pci = require("lib.hardware.pci")
local register = require("lib.hardware.register")
local index_set = require("lib.index_set")
local macaddress = require("lib.macaddress")
local mib = require("lib.ipc.shmem.mib")
local timer = require("core.timer")
local bits, bitset = lib.bits, lib.bitset
local band, bor, lshift = bit.band, bit.bor, bit.lshift
num_descriptors = 512
--num_descriptors = 32
-- Defaults for configurable items
local default = {
-- The MTU configured through the MAXFRS.MFS register includes the
-- Ethernet header and CRC. It is limited to 65535 bytes. We use
-- the convention that the configurable MTU includes the Ethernet
-- header but not the CRC. This is "natural" in the sense that the
-- unit of data handed to the driver contains a complete Ethernet
-- packet.
--
-- For untagged packets, the Ethernet overhead is 14 bytes. If
-- 802.1q tagging is used, the Ethernet overhead is increased by 4
-- bytes per tag. This overhead must be included in the MTU if
-- tags are handled by the software. However, the NIC always
-- accepts packets of size MAXFRS.MFS+4 and MAXFRS.MFS+8 if single-
-- or double tagged packets are received (see section 8.2.3.22.13).
-- In this case, we will actually accept packets which exceed the
-- MTU.
--
-- XXX If hardware support for VLAN tag adding or stripping is
-- enabled, one should probably not include the tags in the MTU.
--
-- The default MTU allows for an IP packet of a total size of 9000
-- bytes without VLAN tagging.
mtu = 9014,
snmp = {
status_timer = 5, -- Interval for IF status check and MIB update
}
}
local function pass (...) return ... end
--- ### SF: single function: non-virtualized device
local M_sf = {}; M_sf.__index = M_sf
function new_sf (conf)
local dev = { pciaddress = conf.pciaddr, -- PCI device address
mtu = (conf.mtu or default.mtu),
fd = false, -- File descriptor for PCI memory
r = {}, -- Configuration registers
s = {}, -- Statistics registers
qs = {}, -- queue statistic registers
txdesc = 0, -- Transmit descriptors (pointer)
txdesc_phy = 0, -- Transmit descriptors (physical address)
txpackets = {}, -- Tx descriptor index -> packet mapping
tdh = 0, -- Cache of transmit head (TDH) register
tdt = 0, -- Cache of transmit tail (TDT) register
rxdesc = 0, -- Receive descriptors (pointer)
rxdesc_phy = 0, -- Receive descriptors (physical address)
rxpackets = {}, -- Rx descriptor index -> packet mapping
rdh = 0, -- Cache of receive head (RDH) register
rdt = 0, -- Cache of receive tail (RDT) register
rxnext = 0, -- Index of next buffer to receive
snmp = conf.snmp,
}
return setmetatable(dev, M_sf)
end
function M_sf:open ()
pci.unbind_device_from_linux(self.pciaddress)
pci.set_bus_master(self.pciaddress, true)
self.base, self.fd = pci.map_pci_memory(self.pciaddress, 0)
register.define(config_registers_desc, self.r, self.base)
register.define(transmit_registers_desc, self.r, self.base)
register.define(receive_registers_desc, self.r, self.base)
register.define_array(packet_filter_desc, self.r, self.base)
register.define(statistics_registers_desc, self.s, self.base)
register.define_array(queue_statistics_registers_desc, self.qs, self.base)
self.txpackets = ffi.new("struct packet *[?]", num_descriptors)
self.rxpackets = ffi.new("struct packet *[?]", num_descriptors)
return self:init()
end
function M_sf:close()
pci.set_bus_master(self.pciaddress, false)
if self.free_receive_buffers then
self:free_receive_buffers()
end
if self.discard_unsent_packets then
self:discard_unsent_packets()
C.usleep(1000)
end
if self.fd then
pci.close_pci_resource(self.fd, self.base)
self.fd = false
end
self:free_dma_memory()
end
--- See data sheet section 4.6.3 "Initialization Sequence."
function M_sf:init ()
if self.snmp then
self:init_snmp()
end
self:init_dma_memory()
self.redos = 0
local mask = bits{Link_up=30}
for i = 1, 100 do
self
:disable_interrupts()
:global_reset()
if i%5 == 0 then self:autonegotiate_sfi() end
self
:wait_eeprom_autoread()
:wait_dma()
:init_statistics()
:init_receive()
:init_transmit()
:wait_enable()
:wait_linkup()
if band(self.r.LINKS(), mask) == mask then
self.redos = i
return self
end
end
io.write ('never got link up: ', self.pciaddress, '\n')
os.exit(2)
return self
end
do
local _rx_pool = {}
local _tx_pool = {}
local function get_ring(ct, pool)
local spot, v = next(pool)
if spot and v then
pool[spot] = nil
return v.ptr, v.phy
end
local ptr, phy =
memory.dma_alloc(num_descriptors * ffi.sizeof(ct))
-- Initialize unused DMA memory with -1. This is so that
-- accidental premature use of DMA memory will cause a DMA error
-- (write to illegal address) instead of overwriting physical
-- memory near address 0.
ffi.fill(ptr, 0xff, num_descriptors * ffi.sizeof(ct))
ptr = lib.bounds_checked(ct, ptr, 0, num_descriptors)
return ptr, phy
end
function M_sf:init_dma_memory ()
self.rxdesc, self.rxdesc_phy = get_ring(rxdesc_t, _rx_pool)
self.txdesc, self.txdesc_phy = get_ring(txdesc_t, _tx_pool)
return self
end
function M_sf:free_dma_memory()
_rx_pool[#_rx_pool+1] = {ptr = self.rxdesc, phy = self.rxdesc_phy}
_tx_pool[#_tx_pool+1] = {ptr = self.txdesc, phy = self.txdesc_phy}
return self
end
end
function M_sf:init_snmp ()
-- Rudimentary population of a row in the ifTable MIB. Allocation
-- of the ifIndex is delegated to the SNMP agent via the name of
-- the interface in ifDescr (currently the PCI address).
local ifTable = mib:new({ directory = self.snmp.directory or nil,
filename = self.pciaddress })
self.snmp.ifTable = ifTable
-- ifTable
ifTable:register('ifDescr', 'OctetStr', self.pciaddress)
ifTable:register('ifType', 'Integer32', 6) -- ethernetCsmacd
ifTable:register('ifMtu', 'Integer32', self.mtu)
ifTable:register('ifSpeed', 'Gauge32', 10000000)
-- After a reset of the NIC, the "native" MAC address is copied to
-- the receive address register #0 from the EEPROM
local ral, rah = self.r.RAL[0](), self.r.RAH[0]()
assert(bit.band(rah, bits({ AV = 31 })) == bits({ AV = 31 }),
"MAC address on "..self.pciaddress.." is not valid ")
local mac = ffi.new("struct { uint32_t lo; uint16_t hi; }")
mac.lo = ral
mac.hi = bit.band(rah, 0xFFFF)
ifTable:register('ifPhysAddress', { type = 'OctetStr', length = 6 },
ffi.string(mac, 6))
ifTable:register('ifAdminStatus', 'Integer32', 1) -- up
ifTable:register('ifOperStatus', 'Integer32', 2) -- down
ifTable:register('ifLastChange', 'TimeTicks', 0)
ifTable:register('_X_ifLastChange_TicksBase', 'Counter64', C.get_unix_time())
ifTable:register('ifInOctets', 'Counter32', 0)
ifTable:register('ifInUcastPkts', 'Counter32', 0)
ifTable:register('ifInDiscards', 'Counter32', 0)
ifTable:register('ifInErrors', 'Counter32', 0) -- TBD
ifTable:register('ifInUnknownProtos', 'Counter32', 0) -- TBD
ifTable:register('ifOutOctets', 'Counter32', 0)
ifTable:register('ifOutUcastPkts', 'Counter32', 0)
ifTable:register('ifOutDiscards', 'Counter32', 0)
ifTable:register('ifOutErrors', 'Counter32', 0) -- TBD
-- ifXTable
ifTable:register('ifName', { type = 'OctetStr', length = 255 },
self.pciaddress)
ifTable:register('ifInMulticastPkts', 'Counter32', 0)
ifTable:register('ifInBroadcastPkts', 'Counter32', 0)
ifTable:register('ifOutMulticastPkts', 'Counter32', 0)
ifTable:register('ifOutBroadcastPkts', 'Counter32', 0)
ifTable:register('ifHCInOctets', 'Counter64', 0)
ifTable:register('ifHCInUcastPkts', 'Counter64', 0)
ifTable:register('ifHCInMulticastPkts', 'Counter64', 0)
ifTable:register('ifHCInBroadcastPkts', 'Counter64', 0)
ifTable:register('ifHCOutOctets', 'Counter64', 0)
ifTable:register('ifHCOutUcastPkts', 'Counter64', 0)
ifTable:register('ifHCOutMulticastPkts', 'Counter64', 0)
ifTable:register('ifHCOutBroadcastPkts', 'Counter64', 0)
ifTable:register('ifLinkUpDownTrapEnable', 'Integer32', 2) -- disabled
ifTable:register('ifHighSpeed', 'Gauge32', 10000)
ifTable:register('ifPromiscuousMode', 'Integer32', 2) -- false
ifTable:register('ifConnectorPresent', 'Integer32', 1) -- true
ifTable:register('ifAlias', { type = 'OctetStr', length = 64 },
self.pciaddress) -- TBD add description
ifTable:register('ifCounterDiscontinuityTime', 'TimeTicks', 0) -- TBD
ifTable:register('_X_ifCounterDiscontinuityTime', 'Counter64', 0) -- TBD
--- Create a timer to periodically check the interface status.
--- Static variables are used in the timer function to avoid
--- garbage.
local status = { [1] = 'up', [2] = 'down' }
local mask = bits{Link_up=30}
local promisc = bits({UPE = 9})
-- Pre-allocate storage for the results of register-reads
local r = {
in_mcast_pkts = { r = self.s.MPRC },
in_bcast_pkts = { r = self.s.BPRC },
in_pkts = { r = self.s.GPRC },
in_octets64 = { r = self.s.GORC64 },
out_mcast_pkts = { r = self.s.MPTC },
out_bcast_pkts = { r = self.s.BPTC },
out_pkts = { r = self.s.GPTC },
out_octets64 = { r = self.s.GOTC64 },
}
local r_keys = {}
for k, _ in pairs(r) do
table.insert(r_keys, k)
r[k].v = ffi.new("uint64_t [1]")
end
local function read_registers()
for _, k in ipairs(r_keys) do
r[k].v[0] = r[k].r()
end
end
local t = timer.new("Interface "..self.pciaddress.." status checker",
function(t)
local old = ifTable:get('ifOperStatus')
local new = 1
if band(self.r.LINKS(), mask) ~= mask then
new = 2
end
if old ~= new then
print("Interface "..self.pciaddress..
" status change: "..status[old]..
" => "..status[new])
ifTable:set('ifOperStatus', new)
ifTable:set('ifLastChange', 0)
ifTable:set('_X_ifLastChange_TicksBase',
C.get_unix_time())
end
ifTable:set('ifPromiscuousMode',
(bit.band(self.r.FCTRL(), promisc) ~= 0ULL
and 1) or 2)
-- Update counters
read_registers()
ifTable:set('ifHCInMulticastPkts', r.in_mcast_pkts.v[0])
ifTable:set('ifInMulticastPkts', r.in_mcast_pkts.v[0])
ifTable:set('ifHCInBroadcastPkts', r.in_bcast_pkts.v[0])
ifTable:set('ifInBroadcastPkts', r.in_bcast_pkts.v[0])
local in_ucast_pkts = r.in_pkts.v[0] - r.in_bcast_pkts.v[0]
- r.in_mcast_pkts.v[0]
ifTable:set('ifHCInUcastPkts', in_ucast_pkts)
ifTable:set('ifInUcastPkts', in_ucast_pkts)
ifTable:set('ifHCInOctets', r.in_octets64.v[0])
ifTable:set('ifInOctets', r.in_octets64.v[0])
ifTable:set('ifHCOutMulticastPkts', r.out_mcast_pkts.v[0])
ifTable:set('ifOutMulticastPkts', r.out_mcast_pkts.v[0])
ifTable:set('ifHCOutBroadcastPkts', r.out_bcast_pkts.v[0])
ifTable:set('ifOutBroadcastPkts', r.out_bcast_pkts.v[0])
local out_ucast_pkts = r.out_pkts.v[0] - r.out_bcast_pkts.v[0]
- r.out_mcast_pkts.v[0]
ifTable:set('ifHCOutUcastPkts', out_ucast_pkts)
ifTable:set('ifOutUcastPkts', out_ucast_pkts)
ifTable:set('ifHCOutOctets', r.out_octets64.v[0])
ifTable:set('ifOutOctets', r.out_octets64.v[0])
-- The RX receive drop counts are only
-- available through the RX stats register.
-- We only read stats register #0 here. See comment
-- in init_statistics()
ifTable:set('ifInDiscards', self.qs.QPRDC[0]())
ifTable:set('ifInErrors', self.s.CRCERRS() +
self.s.ILLERRC() + self.s.ERRBC() +
self.s.RUC() + self.s.RFC() +
self.s.ROC() + self.s.RJC())
end,
1e9 * (self.snmp.status_timer or
default.snmp.status_timer), 'repeating')
timer.activate(t)
return self
end
function M_sf:global_reset ()
local reset = bits{LinkReset=3, DeviceReset=26}
self.r.CTRL(reset)
C.usleep(1000)
self.r.CTRL:wait(reset, 0)
return self
end
function M_sf:disable_interrupts () return self end --- XXX do this
function M_sf:wait_eeprom_autoread ()
self.r.EEC:wait(bits{AutoreadDone=9})
return self
end
function M_sf:wait_dma ()
self.r.RDRXCTL:wait(bits{DMAInitDone=3})
return self
end
function M_sf:init_statistics ()
-- Read and then zero each statistic register
for _,reg in pairs(self.s) do reg:read() reg:reset() end
-- Make sure RX Queue #0 is mapped to the stats register #0. In
-- the default configuration, all 128 RX queues are mapped to this
-- stats register. In non-virtualized mode, only queue #0 is
-- actually used.
self.qs.RQSMR[0]:set(0)
return self
end
function M_sf:init_receive ()
self.r.RXCTRL:clr(bits{RXEN=0})
self:set_promiscuous_mode() -- NB: don't need to program MAC address filter
self.r.HLREG0(bits{
TXCRCEN=0, RXCRCSTRP=1, rsv2=3, TXPADEN=10,
rsvd3=11, rsvd4=13, MDCSPD=16
})
if self.mtu > 1514 then
self.r.HLREG0:set(bits{ JUMBOEN=2 })
-- MAXFRS is set to a hard-wired default of 1518 if JUMBOEN is
-- not set. The MTU does *not* include the 4-byte CRC, but
-- MAXFRS does.
self.r.MAXFRS(lshift(self.mtu+4, 16))
end
self:set_receive_descriptors()
self.r.RXCTRL:set(bits{RXEN=0})
if self.r.DCA_RXCTRL then -- Register may be undefined in subclass (PF)
-- Datasheet 4.6.7 says to clear this bit.
-- Have observed payload corruption when this is not done.
self.r.DCA_RXCTRL:clr(bits{RxCTRL=12})
end
return self
end
function M_sf:set_rx_buffersize(rx_buffersize)
rx_buffersize = math.min(16, math.floor((rx_buffersize or 16384) / 1024)) -- size in KB, max 16KB
assert (rx_buffersize > 0, "rx_buffersize must be more than 1024")
assert(rx_buffersize*1024 >= self.mtu, "rx_buffersize is too small for the MTU")
self.rx_buffersize = rx_buffersize * 1024
self.r.SRRCTL(bits({DesctypeLSB=25}, rx_buffersize))
self.r.SRRCTL:set(bits({Drop_En=28})) -- Enable RX queue drop counter
return self
end
function M_sf:set_receive_descriptors ()
self:set_rx_buffersize(16384) -- start at max
self.r.RDBAL(self.rxdesc_phy % 2^32)
self.r.RDBAH(self.rxdesc_phy / 2^32)
self.r.RDLEN(num_descriptors * ffi.sizeof(rxdesc_t))
return self
end
function M_sf:wait_enable ()
self.r.RXDCTL(bits{Enable=25})
self.r.RXDCTL:wait(bits{enable=25})
self.r.TXDCTL:wait(bits{Enable=25})
return self
end
function M_sf:set_promiscuous_mode ()
self.r.FCTRL(bits({MPE=8, UPE=9, BAM=10}))
return self
end
function M_sf:init_transmit ()
self.r.HLREG0:set(bits{TXCRCEN=0})
self:set_transmit_descriptors()
self.r.DMATXCTL:set(bits{TE=0})
return self
end
function M_sf:set_transmit_descriptors ()
self.r.TDBAL(self.txdesc_phy % 2^32)
self.r.TDBAH(self.txdesc_phy / 2^32)
self.r.TDLEN(num_descriptors * ffi.sizeof(txdesc_t))
return self
end
--- ### Transmit
--- See datasheet section 7.1 "Inline Functions -- Transmit Functionality."
local txdesc_flags = bits{ifcs=25, dext=29, dtyp0=20, dtyp1=21, eop=24}
function M_sf:transmit (p)
-- We must not send packets that are bigger than the MTU. This
-- check is currently disabled to satisfy some selftests until
-- agreement on this strategy is reached.
-- if p.length > self.mtu then
-- if self.snmp then
-- local errors = self.snmp.ifTable:ptr('ifOutDiscards')
-- errors[0] = errors[0] + 1
-- end
-- packet.free(p)
-- else
do
self.txdesc[self.tdt].address = memory.virtual_to_physical(p.data)
self.txdesc[self.tdt].options = bor(p.length, txdesc_flags, lshift(p.length+0ULL, 46))
self.txpackets[self.tdt] = p
self.tdt = band(self.tdt + 1, num_descriptors - 1)
end
end
function M_sf:sync_transmit ()
local old_tdh = self.tdh
self.tdh = self.r.TDH()
C.full_memory_barrier()
-- Release processed buffers
if old_tdh ~= self.tdh then
while old_tdh ~= self.tdh do
packet.free(self.txpackets[old_tdh])
self.txpackets[old_tdh] = nil
old_tdh = band(old_tdh + 1, num_descriptors - 1)
end
end
self.r.TDT(self.tdt)
end
function M_sf:can_transmit ()
return band(self.tdt + 1, num_descriptors - 1) ~= self.tdh
end
function M_sf:discard_unsent_packets()
local old_tdt = self.tdt
self.tdt = self.r.TDT()
self.tdh = self.r.TDH()
self.r.TDT(self.tdh)
while old_tdt ~= self.tdh do
old_tdt = band(old_tdt - 1, num_descriptors - 1)
packet.free(self.txpackets[old_tdt])
self.txdesc[old_tdt].address = -1
self.txdesc[old_tdt].options = 0
end
self.tdt = self.tdh
end
--- See datasheet section 7.1 "Inline Functions -- Receive Functionality."
function M_sf:receive ()
assert(self:can_receive())
local wb = self.rxdesc[self.rxnext].wb
local p = self.rxpackets[self.rxnext]
p.length = wb.pkt_len
self.rxpackets[self.rxnext] = nil
self.rxnext = band(self.rxnext + 1, num_descriptors - 1)
return p
end
function M_sf:can_receive ()
return self.rxnext ~= self.rdh and band(self.rxdesc[self.rxnext].wb.xstatus_xerror, 1) == 1
end
function M_sf:can_add_receive_buffer ()
return band(self.rdt + 1, num_descriptors - 1) ~= self.rxnext
end
function M_sf:add_receive_buffer (p)
assert(self:can_add_receive_buffer())
local desc = self.rxdesc[self.rdt].data
desc.address, desc.dd = memory.virtual_to_physical(p.data), 0
self.rxpackets[self.rdt] = p
self.rdt = band(self.rdt + 1, num_descriptors - 1)
end
function M_sf:free_receive_buffers ()
while self.rdt ~= self.rdh do
self.rdt = band(self.rdt - 1, num_descriptors - 1)
local desc = self.rxdesc[self.rdt].data
desc.address, desc.dd = -1, 0
packet.free(self.rxpackets[self.rdt])
self.rxpackets[self.rdt] = nil
end
end
function M_sf:sync_receive ()
-- XXX I have been surprised to see RDH = num_descriptors,
-- must check what that means. -luke
self.rdh = math.min(self.r.RDH(), num_descriptors-1)
assert(self.rdh < num_descriptors)
C.full_memory_barrier()
self.r.RDT(self.rdt)
end
function M_sf:wait_linkup ()
self.waitlu_ms = 0
local mask = bits{Link_up=30}
for count = 1, 250 do
if band(self.r.LINKS(), mask) == mask then
self.waitlu_ms = count
return self
end
C.usleep(1000)
end
self.waitlu_ms = 250
return self
end
--- ### Status and diagnostics
-- negotiate access to software/firmware shared resource
-- section 10.5.4
function negotiated_autoc (dev, f)
local function waitfor (test, attempts, interval)
interval = interval or 100
for count = 1,attempts do
if test() then return true end
C.usleep(interval)
io.flush()
end
return false
end
local function tb (reg, mask, val)
return function() return bit.band(reg(), mask) == (val or mask) end
end
local gotresource = waitfor(function()
local accessible = false
local softOK = waitfor (tb(dev.r.SWSM, bits{SMBI=0},0), 30100)
dev.r.SWSM:set(bits{SWESMBI=1})
local firmOK = waitfor (tb(dev.r.SWSM, bits{SWESMBI=1}), 30000)
accessible = bit.band(dev.r.SW_FW_SYNC(), 0x108) == 0
if not firmOK then
dev.r.SW_FW_SYNC:clr(0x03E0) -- clear all firmware bits
accessible = true
end
if not softOK then
dev.r.SW_FW_SYNC:clr(0x1F) -- clear all software bits
accessible = true
end
if accessible then
dev.r.SW_FW_SYNC:set(0x8)
end
dev.r.SWSM:clr(bits{SMBI=0, SWESMBI=1})
if not accessible then C.usleep(100) end
return accessible
end, 10000) -- TODO: only twice
if not gotresource then error("Can't acquire shared resource") end
local r = f(dev)
waitfor (tb(dev.r.SWSM, bits{SMBI=0},0), 30100)
dev.r.SWSM:set(bits{SWESMBI=1})
waitfor (tb(dev.r.SWSM, bits{SWESMBI=1}), 30000)
dev.r.SW_FW_SYNC:clr(0x108)
dev.r.SWSM:clr(bits{SMBI=0, SWESMBI=1})
return r
end
function set_SFI (dev, lms)
lms = lms or bit.lshift(0x3, 13) -- 10G SFI
local autoc = dev.r.AUTOC()
if bit.band(autoc, bit.lshift(0x7, 13)) == lms then
dev.r.AUTOC(bits({restart_AN=12}, bit.bxor(autoc, 0x8000))) -- flip LMS[2] (15)
lib.waitfor(function ()
return bit.band(dev.r.ANLP1(), 0xF0000) ~= 0
end)
end
dev.r.AUTOC(bit.bor(bit.band(autoc, 0xFFFF1FFF), lms))
return dev
end
function M_sf:autonegotiate_sfi ()
return negotiated_autoc(self, function()
set_SFI(self)
self.r.AUTOC:set(bits{restart_AN=12})
self.r.AUTOC2(0x00020000)
return self
end)
end
--- ### PF: the physiscal device in a virtualized setup
local M_pf = {}; M_pf.__index = M_pf
function new_pf (conf)
local dev = { pciaddress = conf.pciaddr, -- PCI device address
mtu = (conf.mtu or default.mtu),
r = {}, -- Configuration registers
s = {}, -- Statistics registers
qs = {}, -- queue statistic registers
mac_set = index_set:new(127, "MAC address table"),
vlan_set = index_set:new(64, "VLAN Filter table"),
mirror_set = index_set:new(4, "Mirror pool table"),
snmp = conf.snmp,
}
return setmetatable(dev, M_pf)
end
function M_pf:open ()
pci.unbind_device_from_linux(self.pciaddress)
pci.set_bus_master(self.pciaddress, true)
self.base, self.fd = pci.map_pci_memory(self.pciaddress, 0)
register.define(config_registers_desc, self.r, self.base)
register.define_array(switch_config_registers_desc, self.r, self.base)
register.define_array(packet_filter_desc, self.r, self.base)
register.define(statistics_registers_desc, self.s, self.base)
register.define_array(queue_statistics_registers_desc, self.qs, self.base)
return self:init()
end
function M_pf:close()
pci.set_bus_master(self.pciaddress, false)
if self.fd then
pci.close_pci_resource(self.fd, self.base)
self.fd = false
end
end
function M_pf:init ()
if self.snmp then
self:init_snmp()
end
self.redos = 0
local mask = bits{Link_up=30}
for i = 1, 100 do
self
:disable_interrupts()
:global_reset()
if i%5 == 0 then self:autonegotiate_sfi() end
self
:wait_eeprom_autoread()
:wait_dma()
:set_vmdq_mode()
:init_statistics()
:init_receive()
:init_transmit()
:wait_linkup()
if band(self.r.LINKS(), mask) == mask then
return self
end
self.redos = i
end
io.write ('never got link up: ', self.pciaddress, '\n')
os.exit(2)
return self
end
M_pf.init_snmp = M_sf.init_snmp
M_pf.global_reset = M_sf.global_reset
M_pf.disable_interrupts = M_sf.disable_interrupts
M_pf.set_receive_descriptors = pass
M_pf.set_transmit_descriptors = pass
M_pf.autonegotiate_sfi = M_sf.autonegotiate_sfi
M_pf.wait_eeprom_autoread = M_sf.wait_eeprom_autoread
M_pf.wait_dma = M_sf.wait_dma
M_pf.init_statistics = M_sf.init_statistics
M_pf.set_promiscuous_mode = M_sf.set_promiscuous_mode
M_pf.init_receive = M_sf.init_receive
M_pf.init_transmit = M_sf.init_transmit
M_pf.wait_linkup = M_sf.wait_linkup
function M_pf:set_vmdq_mode ()
self.r.RTTDCS(bits{VMPAC=1,ARBDIS=6,BDPM=22}) -- clear TDPAC,TDRM=4, BPBFSM
self.r.RFCTL:set(bits{RSC_Dis=5}) -- no RSC
self.r.MRQC(0x08) -- 1000b -> 64 pools, x2queues, no RSS, no IOV
self.r.MTQC(bits{VT_Ena=1, Num_TC_OR_Q=2}) -- 128 Tx Queues, 64 VMs (4.6.11.3.3)
self.r.PFVTCTL(bits{VT_Ena=0, Rpl_En=30, DisDefPool=29}) -- enable virtualization, replication enabled
self.r.PFDTXGSWC:set(bits{LBE=0}) -- enable Tx to Rx loopback
self.r.RXPBSIZE[0](0x80000) -- no DCB: all queues to PB0 (0x200<<10)
self.r.TXPBSIZE[0](0x28000) -- (0xA0<<10)
self.r.TXPBTHRESH[0](0xA0)
self.r.FCRTH[0](0x10000)
self.r.RXDSTATCTRL(0x10) -- Rx DMA Statistic for all queues
self.r.VLNCTRL:set(bits{VFE=30}) -- Vlan filter enable
for i = 1, 7 do
self.r.RXPBSIZE[i](0x00)
self.r.TXPBSIZE[i](0x00)
self.r.TXPBTHRESH[i](0x00)
end
for i = 0, 7 do
self.r.RTTDT2C[i](0x00)
self.r.RTTPT2C[i](0x00)
self.r.ETQF[i](0x00) -- disable ethertype filter
self.r.ETQS[0](0x00)
end
-- clear PFQDE.QDE (queue drop enable) for each queue
for i = 0, 127 do
self.r.PFQDE(bor(lshift(1,16), lshift(i,8)))
self.r.FTQF[i](0x00) -- disable L3/4 filter
self.r.RAH[i](0)
self.r.RAL[i](0)
self.r.VFTA[i](0)
self.r.PFVLVFB[i](0)
end
for i = 0, 63 do
self.r.RTTDQSEL(i)
self.r.RTTDT1C(0x00)
self.r.PFVLVF[i](0)
end
for i = 0, 31 do
self.r.RETA[i](0x00) -- clear redirection table
end
self.r.RTRUP2TC(0x00) -- Rx UPnMAP = 0
self.r.RTTUP2TC(0x00) -- Tx UPnMAP = 0
-- move to vf initialization
-- set_pool_transmit_weight(dev, 0, 0x1000) -- pool 0 must be initialized, set at range midpoint
self.r.DTXMXSZRQ(0xFFF)
self.r.MFLCN(bits{RFCE=3}) -- optional? enable legacy flow control
self.r.FCCFG(bits{TFCE=3})
self.r.RTTDCS:clr(bits{ARBDIS=6})
return self
end
--- ### VF: virtualized device
local M_vf = {}; M_vf.__index = M_vf
-- it's the PF who creates a VF
function M_pf:new_vf (poolnum)
assert(poolnum < 64, "Pool overflow: Intel 82599 can only have up to 64 virtualized devices.")
local txqn = poolnum*2
local rxqn = poolnum*2
local vf = {
pf = self,
-- some things are shared with the main device...
base = self.base, -- mmap()ed register file
s = self.s, -- Statistics registers
mtu = self.mtu,
snmp = self.snmp,
-- and others are our own
r = {}, -- Configuration registers
poolnum = poolnum,
txqn = txqn, -- Transmit queue number
txdesc = 0, -- Transmit descriptors (pointer)
txdesc_phy = 0, -- Transmit descriptors (io address)
txpackets = {}, -- Tx descriptor index -> packet mapping
tdh = 0, -- Cache of transmit head (TDH) register
tdt = 0, -- Cache of transmit tail (TDT) register
rxqn = rxqn, -- receive queue number
rxdesc = 0, -- Receive descriptors (pointer)
rxdesc_phy = 0, -- Receive descriptors (physical address)
rxpackets = {}, -- Rx descriptor index -> packet mapping
rdh = 0, -- Cache of receive head (RDH) register
rdt = 0, -- Cache of receive tail (RDT) register
rxnext = 0, -- Index of next buffer to receive
}
return setmetatable(vf, M_vf)
end
function M_vf:open (opts)
register.define(transmit_registers_desc, self.r, self.base, self.txqn)
register.define(receive_registers_desc, self.r, self.base, self.rxqn)
self.txpackets = ffi.new("struct packet *[?]", num_descriptors)
self.rxpackets = ffi.new("struct packet *[?]", num_descriptors)
return self:init(opts)
end
function M_vf:close()
local poolnum = self.poolnum or 0
local pf = self.pf
if self.free_receive_buffers then
self:free_receive_buffers()
end
if self.discard_unsent_packets then
self:discard_unsent_packets()
C.usleep(1000)
end
-- unset_tx_rate
self:set_tx_rate(0, 0)
self
:unset_mirror()
:unset_VLAN()
-- unset MAC
do
local msk = bits{Ena=self.poolnum%32}
for mac_index = 0, 127 do
pf.r.MPSAR[2*mac_index + math.floor(poolnum/32)]:clr(msk)
end
end
self:disable_transmit()
:disable_receive()
:free_dma_memory()
return self
end
function M_vf:reconfig(opts)
local poolnum = self.poolnum or 0
local pf = self.pf
self
:unset_mirror()
:unset_VLAN()
:unset_MAC()
do
local msk = bits{Ena=self.poolnum%32}
for mac_index = 0, 127 do
pf.r.MPSAR[2*mac_index + math.floor(poolnum/32)]:clr(msk)
end
end
return self
:set_MAC(opts.macaddr)
:set_mirror(opts.mirror)
:set_VLAN(opts.vlan)
:set_rx_stats(opts.rxcounter)
:set_tx_stats(opts.txcounter)
:set_tx_rate(opts.rate_limit, opts.priority)
:enable_receive()
:enable_transmit()
end
function M_vf:init (opts)
return self
:init_dma_memory()
:init_receive()
:init_transmit()
:set_MAC(opts.macaddr)
:set_mirror(opts.mirror)
:set_VLAN(opts.vlan)
:set_rx_stats(opts.rxcounter)
:set_tx_stats(opts.txcounter)
:set_tx_rate(opts.rate_limit, opts.priority)
:enable_receive()
:enable_transmit()
end
M_vf.init_dma_memory = M_sf.init_dma_memory
M_vf.free_dma_memory = M_sf.free_dma_memory
M_vf.set_receive_descriptors = M_sf.set_receive_descriptors
M_vf.set_transmit_descriptors = M_sf.set_transmit_descriptors
M_vf.can_transmit = M_sf.can_transmit
M_vf.transmit = M_sf.transmit
M_vf.sync_transmit = M_sf.sync_transmit
M_vf.discard_unsent_packets = M_sf.discard_unsent_packets
M_vf.can_receive = M_sf.can_receive
M_vf.receive = M_sf.receive
M_vf.can_add_receive_buffer = M_sf.can_add_receive_buffer
M_vf.set_rx_buffersize = M_sf.set_rx_buffersize
M_vf.add_receive_buffer = M_sf.add_receive_buffer
M_vf.free_receive_buffers = M_sf.free_receive_buffers
M_vf.sync_receive = M_sf.sync_receive
function M_vf:init_receive ()
local poolnum = self.poolnum or 0
self.pf.r.PSRTYPE[poolnum](0) -- no splitting, use pool's first queue
self.r.RSCCTL(0x0) -- no RSC
self:set_receive_descriptors()
self.pf.r.PFVML2FLT[poolnum]:set(bits{MPE=28, BAM=27, AUPE=24})
return self
end
function M_vf:enable_receive()
self.r.RXDCTL(bits{Enable=25, VME=30})
self.r.RXDCTL:wait(bits{enable=25})
self.r.DCA_RXCTRL:clr(bits{RxCTRL=12})
self.pf.r.PFVFRE[math.floor(self.poolnum/32)]:set(bits{VFRE=self.poolnum%32})
return self
end
function M_vf:disable_receive(reenable)
self.r.RXDCTL:clr(bits{Enable=25})
self.r.RXDCTL:wait(bits{Enable=25}, 0)
C.usleep(100)
-- TODO free packet buffers
self.pf.r.PFVFRE[math.floor(self.poolnum/32)]:clr(bits{VFRE=self.poolnum%32})
if reenable then
self.r.RXDCTL(bits{Enable=25, VME=30})
-- self.r.RXDCTL:wait(bits{enable=25})
end
return self
end
function M_vf:init_transmit ()
local poolnum = self.poolnum or 0
self.r.TXDCTL:clr(bits{Enable=25})
self:set_transmit_descriptors()
self.pf.r.PFVMTXSW[math.floor(poolnum/32)]:clr(bits{LLE=poolnum%32})
self.pf.r.PFVFTE[math.floor(poolnum/32)]:set(bits{VFTE=poolnum%32})
self.pf.r.RTTDQSEL(poolnum)
self.pf.r.RTTDT1C(0x80)
self.pf.r.RTTBCNRC(0x00) -- no rate limiting
return self
end
function M_vf:enable_transmit()
self.pf.r.DMATXCTL:set(bits{TE=0})
self.r.TXDCTL:set(bits{Enable=25, SWFLSH=26})
self.r.TXDCTL:wait(bits{Enable=25})
return self
end
function M_vf:disable_transmit(reenable)
-- TODO: wait TDH==TDT
-- TODO: wait all is written back: DD bit or Head_WB
self.r.TXDCTL:clr(bits{Enable=25})
self.r.TXDCTL:set(bits{SWFLSH=26})
self.r.TXDCTL:wait(bits{Enable=25}, 0)
self.pf.r.PFVFTE[math.floor(self.poolnum/32)]:clr(bits{VFTE=self.poolnum%32})
if reenable then
self.r.TXDCTL:set(bits{Enable=25, SWFLSH=26})
-- self.r.TXDCTL:wait(bits{Enable=25})
end
return self
end
function M_vf:set_MAC (mac)
if not mac then return self end
mac = macaddress:new(mac)
return self
:add_receive_MAC(mac)
:set_transmit_MAC(mac)
end
function M_vf:unset_MAC()
end
function M_vf:add_receive_MAC (mac)
mac = macaddress:new(mac)
local pf = self.pf
local mac_index, is_new = pf.mac_set:add(tostring(mac))
if is_new then
pf.r.RAL[mac_index](mac:subbits(0,32))
pf.r.RAH[mac_index](bits({AV=31},mac:subbits(32,48)))
end
pf.r.MPSAR[2*mac_index + math.floor(self.poolnum/32)]
:set(bits{Ena=self.poolnum%32})
return self
end
function M_vf:set_transmit_MAC (mac)
local poolnum = self.poolnum or 0
self.pf.r.PFVFSPOOF[math.floor(poolnum/8)]:set(bits{MACAS=poolnum%8})
return self
end
function M_vf:set_mirror (want_mirror)
if want_mirror then
-- set MAC promiscuous
self.pf.r.PFVML2FLT[self.poolnum]:set(bits{
AUPE=24, ROMPE=25, ROPE=26, BAM=27, MPE=28})
-- pick one of a limited (4) number of mirroring rules
local mirror_ndx, is_new = self.pf.mirror_set:add(self.poolnum)
local mirror_rule = 0ULL
-- mirror some or all pools
if want_mirror.pool then
mirror_rule = bor(bits{VPME=0}, mirror_rule)
if want_mirror.pool == true then -- mirror all pools
self.pf.r.PFMRVM[mirror_ndx](0xFFFFFFFF)
self.pf.r.PFMRVM[mirror_ndx+4](0xFFFFFFFF)
elseif type(want_mirror.pool) == 'table' then
local bm0 = self.pf.r.PFMRVM[mirror_ndx]
local bm1 = self.pf.r.PFMRVM[mirror_ndx+4]
for _, pool in ipairs(want_mirror.pool) do
if pool <= 32 then
bm0 = bor(lshift(1, pool), bm0)
else
bm1 = bor(lshift(1, pool-32), bm1)
end
end
self.pf.r.PFMRVM[mirror_ndx](bm0)
self.pf.r.PFMRVM[mirror_ndx+4](bm1)
end
end
-- mirror hardware port
if want_mirror.port then
if want_mirror.port == true or want_mirror.port == 'in' or want_mirror.port == 'inout' then
mirror_rule = bor(bits{UPME=1}, mirror_rule)
end
if want_mirror.port == true or want_mirror.port == 'out' or want_mirror.port == 'inout' then
mirror_rule = bor(bits{DPME=2}, mirror_rule)
end
end
-- mirror some or all vlans
if want_mirror.vlan then
mirror_rule = bor(bits{VLME=3}, mirror_rule)
-- TODO: set which vlan's want to mirror
end
if mirror_rule ~= 0 then
mirror_rule = bor(mirror_rule, lshift(self.poolnum, 8))
self.pf.r.PFMRCTL[mirror_ndx]:set(mirror_rule)
end
end
return self
end
function M_vf:unset_mirror()
for rule_i = 0, 3 do
-- check if any mirror rule points here
local rule_dest = band(bit.rshift(self.pf.r.PFMRCTL[rule_i](), 8), 63)
local bits = band(self.pf.r.PFMRCTL[rule_i](), 0x07)
if bits ~= 0 and rule_dest == self.poolnum then
self.pf.r.PFMRCTL[rule_i](0x0) -- clear rule
self.pf.r.PFMRVLAN[rule_i](0x0) -- clear VLANs mirrored
self.pf.r.PFMRVLAN[rule_i+4](0x0)
self.pf.r.PFMRVM[rule_i](0x0) -- clear pools mirrored
self.pf.r.PFMRVM[rule_i+4](0x0)
end
end
self.pf.mirror_set:pop(self.poolnum)
return self
end
function M_vf:set_VLAN (vlan)
if not vlan then return self end
assert(vlan>=0 and vlan<4096, "bad VLAN number")
return self
:add_receive_VLAN(vlan)
:set_tag_VLAN(vlan)
end
function M_vf:add_receive_VLAN (vlan)
assert(vlan>=0 and vlan<4096, "bad VLAN number")
local pf = self.pf
local vlan_index, is_new = pf.vlan_set:add(vlan)
if is_new then
pf.r.VFTA[math.floor(vlan/32)]:set(bits{Ena=vlan%32})
pf.r.PFVLVF[vlan_index](bits({Vl_En=31},vlan))
end
pf.r.PFVLVFB[2*vlan_index + math.floor(self.poolnum/32)]
:set(bits{PoolEna=self.poolnum%32})
return self
end
function M_vf:set_tag_VLAN(vlan)
local poolnum = self.poolnum or 0
self.pf.r.PFVFSPOOF[math.floor(poolnum/8)]:set(bits{VLANAS=poolnum%8+8})
self.pf.r.PFVMVIR[poolnum](bits({VLANA=30}, vlan)) -- always add VLAN tag
return self
end
function M_vf:unset_VLAN()
local r = self.pf.r
local offs, mask = math.floor(self.poolnum/32), bits{PoolEna=self.poolnum%32}
for vln_ndx = 0, 63 do
if band(r.PFVLVFB[2*vln_ndx+offs](), mask) ~= 0 then
-- found a vlan this pool belongs to
r.PFVLVFB[2*vln_ndx+offs]:clr(mask)
if r.PFVLVFB[2*vln_ndx+offs]() == 0 then
-- it was the last pool of the vlan
local vlan = tonumber(band(r.PFVLVF[vln_ndx](), 0xFFF))
r.PFVLVF[vln_ndx](0x0)
r.VFTA[math.floor(vlan/32)]:clr(bits{Ena=vlan%32})
self.pf.vlan_set:pop(vlan)
end
end
end
return self
end
function M_vf:set_rx_stats (counter)
if not counter then return self end
assert(counter>=0 and counter<16, "bad Rx counter")
self.rxstats = counter
self.pf.qs.RQSMR[math.floor(self.rxqn/4)]:set(lshift(counter,8*(self.rxqn%4)))
return self
end
function M_vf:set_tx_stats (counter)
if not counter then return self end
assert(counter>=0 and counter<16, "bad Tx counter")
self.txstats = counter
self.pf.qs.TQSM[math.floor(self.txqn/4)]:set(lshift(counter,8*(self.txqn%4)))
return self
end
function M_vf:get_rxstats ()
if not self.rxstats then return nil end
return {
counter_id = self.rxstats,
packets = tonumber(self.pf.qs.QPRC[self.rxstats]()),
dropped = tonumber(self.pf.qs.QPRDC[self.rxstats]()),
bytes = tonumber(lshift(self.pf.qs.QBRC_H[self.rxstats]()+0LL, 32)
+ self.pf.qs.QBRC_L[self.rxstats]())
}
end
function M_vf:get_txstats ()
if not self.txstats then return nil end
return {
counter_id = self.txstats,
packets = tonumber(self.pf.qs.QPTC[self.txstats]()),
bytes = tonumber(lshift(self.pf.qs.QBTC_H[self.txstats]()+0LL, 32)
+ self.pf.qs.QBTC_L[self.txstats]())
}
end
function M_vf:set_tx_rate (limit, priority)
limit = tonumber(limit) or 0
self.pf.r.RTTDQSEL(self.poolnum)
if limit >= 10 then
local factor = 10000 / tonumber(limit) -- line rate = 10,000 Mb/s
factor = bit.band(math.floor(factor*2^14+0.5), 2^24-1) -- 10.14 bits
self.pf.r.RTTBCNRC(bits({RS_ENA=31}, factor))
else
self.pf.r.RTTBCNRC(0x00)
end
priority = tonumber(priority) or 1.0
self.pf.r.RTTDT1C(bit.band(math.floor(priority * 0x80), 0x3FF))
return self
end
rxdesc_t = ffi.typeof [[
union {
struct {
uint64_t address;
uint64_t dd;
} __attribute__((packed)) data;
struct {
uint16_t rsstype_packet_type;
uint16_t rsccnt_hdrlen_sph;
uint32_t xargs;
uint32_t xstatus_xerror;
uint16_t pkt_len;
uint16_t vlan;
} __attribute__((packed)) wb;
}
]]
txdesc_t = ffi.typeof [[
struct {
uint64_t address, options;
}
]]
--- ### Configuration register description.
config_registers_desc = [[
ANLP1 0x042B0 - RO Auto Negotiation Link Partner
ANLP2 0x042B4 - RO Auto Negotiation Link Partner 2
AUTOC 0x042A0 - RW Auto Negotiation Control
AUTOC2 0x042A8 - RW Auto Negotiation Control 2
CTRL 0x00000 - RW Device Control
CTRL_EX 0x00018 - RW Extended Device Control
DCA_ID 0x11070 - RW DCA Requester ID Information
DCA_CTRL 0x11074 - RW DCA Control Register
DMATXCTL 0x04A80 - RW DMA Tx Control
DTXMXSZRQ 0x08100 - RW DMA Tx Map Allow Size Requests
DTXTCPFLGL 0x04A88 - RW DMA Tx TCP Flags Control Low
DTXTCPFLGH 0x04A88 - RW DMA Tx TCP Flags Control High
EEC 0x10010 - RW EEPROM/Flash Control
FCTRL 0x05080 - RW Filter Control
FCCFG 0x03D00 - RW Flow Control Configuration
HLREG0 0x04240 - RW MAC Core Control 0
LINKS 0x042A4 - RO Link Status Register
LINKS2 0x04324 - RO Second status link register
MANC 0x05820 - RW Management Control Register
MAXFRS 0x04268 - RW Max Frame Size
MNGTXMAP 0x0CD10 - RW Mangeability Tranxmit TC Mapping
MFLCN 0x04294 - RW MAC Flow Control Register
MTQC 0x08120 - RW Multiple Transmit Queues Command Register
MRQC 0x0EC80 - RW Multiple Receive Queues Command Register
PFQDE 0x02F04 - RW PF Queue Drop Enable Register
PFVTCTL 0x051B0 - RW PF Virtual Control Register
RDRXCTL 0x02F00 - RW Receive DMA Control
RTRUP2TC 0x03020 - RW DCB Receive Use rPriority to Traffic Class
RTTBCNRC 0x04984 - RW DCB Transmit Rate-Scheduler Config
RTTDCS 0x04900 - RW DCB Transmit Descriptor Plane Control
RTTDQSEL 0x04904 - RW DCB Transmit Descriptor Plane Queue Select
RTTDT1C 0x04908 - RW DCB Transmit Descriptor Plane T1 Config
RTTUP2TC 0x0C800 - RW DCB Transmit User Priority to Traffic Class
RXCTRL 0x03000 - RW Receive Control
RXDSTATCTRL 0x02F40 - RW Rx DMA Statistic Counter Control
SECRXCTRL 0x08D00 - RW Security RX Control
SECRXSTAT 0x08D04 - RO Security Rx Status
SECTXCTRL 0x08800 - RW Security Tx Control
SECTXSTAT 0x08804 - RO Security Tx Status
STATUS 0x00008 - RO Device Status
SWSM 0x10140 - RW Software Semaphore Register
SW_FW_SYNC 0x10160 - RW Software–Firmware Synchronization
]]
switch_config_registers_desc = [[
PFMRCTL 0x0F600 +0x04*0..3 RW PF Mirror Rule Control
PFMRVLAN 0x0F610 +0x04*0..7 RW PF mirror Rule VLAN
PFMRVM 0x0F630 +0x04*0..7 RW PF Mirror Rule Pool
PFVFRE 0x051E0 +0x04*0..1 RW PF VF Receive Enable
PFVFTE 0x08110 +0x04*0..1 RW PF VF Transmit Enable
PFVMTXSW 0x05180 +0x04*0..1 RW PF VM Tx Switch Loopback Enable
PFVMVIR 0x08000 +0x04*0..63 RW PF VM VLAN Insert Register
PFVFSPOOF 0x08200 +0x04*0..7 RW PF VF Anti Spoof control
PFDTXGSWC 0x08220 - RW PFDMA Tx General Switch Control
RTTDT2C 0x04910 +0x04*0..7 RW DCB Transmit Descriptor Plane T2 Config
RTTPT2C 0x0CD20 +0x04*0..7 RW DCB Transmit Packet Plane T2 Config
RXPBSIZE 0x03C00 +0x04*0..7 RW Receive Packet Buffer Size
TXPBSIZE 0x0CC00 +0x04*0..7 RW Transmit Packet Buffer Size
TXPBTHRESH 0x04950 +0x04*0..7 RW Tx Packet Buffer Threshold
]]
receive_registers_desc = [[
DCA_RXCTRL 0x0100C +0x40*0..63 RW Rx DCA Control Register
DCA_RXCTRL 0x0D00C +0x40*64..127 RW Rx DCA Control Register
RDBAL 0x01000 +0x40*0..63 RW Receive Descriptor Base Address Low
RDBAL 0x0D000 +0x40*64..127 RW Receive Descriptor Base Address Low
RDBAH 0x01004 +0x40*0..63 RW Receive Descriptor Base Address High
RDBAH 0x0D004 +0x40*64..127 RW Receive Descriptor Base Address High
RDLEN 0x01008 +0x40*0..63 RW Receive Descriptor Length
RDLEN 0x0D008 +0x40*64..127 RW Receive Descriptor Length
RDH 0x01010 +0x40*0..63 RO Receive Descriptor Head
RDH 0x0D010 +0x40*64..127 RO Receive Descriptor Head
RDT 0x01018 +0x40*0..63 RW Receive Descriptor Tail
RDT 0x0D018 +0x40*64..127 RW Receive Descriptor Tail
RXDCTL 0x01028 +0x40*0..63 RW Receive Descriptor Control
RXDCTL 0x0D028 +0x40*64..127 RW Receive Descriptor Control
SRRCTL 0x01014 +0x40*0..63 RW Split Receive Control Registers
SRRCTL 0x0D014 +0x40*64..127 RW Split Receive Control Registers
RSCCTL 0x0102C +0x40*0..63 RW RSC Control
RSCCTL 0x0D02C +0x40*64..127 RW RSC Control
]]
transmit_registers_desc = [[
DCA_TXCTRL 0x0600C +0x40*0..127 RW Tx DCA Control Register
TDBAL 0x06000 +0x40*0..127 RW Transmit Descriptor Base Address Low
TDBAH 0x06004 +0x40*0..127 RW Transmit Descriptor Base Address High
TDH 0x06010 +0x40*0..127 RW Transmit Descriptor Head
TDT 0x06018 +0x40*0..127 RW Transmit Descriptor Tail
TDLEN 0x06008 +0x40*0..127 RW Transmit Descriptor Length
TDWBAL 0x06038 +0x40*0..127 RW Tx Desc Completion Write Back Address Low
TDWBAH 0x0603C +0x40*0..127 RW Tx Desc Completion Write Back Address High
TXDCTL 0x06028 +0x40*0..127 RW Transmit Descriptor Control
]]
packet_filter_desc = [[
FCTRL 0x05080 - RW Filter Control Register
FCRTL 0x03220 +0x04*0..7 RW Flow Control Receive Threshold Low
FCRTH 0x03260 +0x04*0..7 RW Flow Control Receive Threshold High
VLNCTRL 0x05088 - RW VLAN Control Register
MCSTCTRL 0x05090 - RW Multicast Control Register
PSRTYPE 0x0EA00 +0x04*0..63 RW Packet Split Receive Type Register
RXCSUM 0x05000 - RW Receive Checksum Control
RFCTL 0x05008 - RW Receive Filter Control Register
PFVFRE 0x051E0 +0x04*0..1 RW PF VF Receive Enable
PFVFTE 0x08110 +0x04*0..1 RW PF VF Transmit Enable
MTA 0x05200 +0x04*0..127 RW Multicast Table Array
RAL 0x0A200 +0x08*0..127 RW Receive Address Low
RAH 0x0A204 +0x08*0..127 RW Receive Address High
MPSAR 0x0A600 +0x04*0..255 RW MAC Pool Select Array
VFTA 0x0A000 +0x04*0..127 RW VLAN Filter Table Array
RQTC 0x0EC70 - RW RSS Queues Per Traffic Class Register
RSSRK 0x0EB80 +0x04*0..9 RW RSS Random Key Register
RETA 0x0EB00 +0x04*0..31 RW Redirection Rable
SAQF 0x0E000 +0x04*0..127 RW Source Address Queue Filter
DAQF 0x0E200 +0x04*0..127 RW Destination Address Queue Filter
SDPQF 0x0E400 +0x04*0..127 RW Source Destination Port Queue Filter
FTQF 0x0E600 +0x04*0..127 RW Five Tuple Queue Filter
SYNQF 0x0EC30 - RW SYN Packet Queue Filter
ETQF 0x05128 +0x04*0..7 RW EType Queue Filter
ETQS 0x0EC00 +0x04*0..7 RW EType Queue Select
PFVML2FLT 0x0F000 +0x04*0..63 RW PF VM L2 Control Register
PFVLVF 0x0F100 +0x04*0..63 RW PF VM VLAN Pool Filter
PFVLVFB 0x0F200 +0x04*0..127 RW PF VM VLAN Pool Filter Bitmap
PFUTA 0X0F400 +0x04*0..127 RW PF Unicast Table Array
]]
--- ### Statistics register description.
statistics_registers_desc = [[
CRCERRS 0x04000 - RC CRC Error Count
ILLERRC 0x04004 - RC Illegal Byte Error Count
ERRBC 0x04008 - RC Error Byte Count
MLFC 0x04034 - RC MAC Local Fault Count
MRFC 0x04038 - RC MAC Remote Fault Count
RLEC 0x04040 - RC Receive Length Error Count
SSVPC 0x08780 - RC Switch Security Violation Packet Count
LXONRXCNT 0x041A4 - RC Link XON Received Count
LXOFFRXCNT 0x041A8 - RC Link XOFF Received Count
PXONRXCNT 0x04140 +4*0..7 RC Priority XON Received Count
PXOFFRXCNT 0x04160 +4*0..7 RC Priority XOFF Received Count
PRC64 0x0405C - RC Packets Received [64 Bytes] Count
PRC127 0x04060 - RC Packets Received [65-127 Bytes] Count
PRC255 0x04064 - RC Packets Received [128-255 Bytes] Count
PRC511 0x04068 - RC Packets Received [256-511 Bytes] Count
PRC1023 0x0406C - RC Packets Received [512-1023 Bytes] Count
PRC1522 0x04070 - RC Packets Received [1024 to Max Bytes] Count
BPRC 0x04078 - RC Broadcast Packets Received Count
MPRC 0x0407C - RC Multicast Packets Received Count
GPRC 0x04074 - RC Good Packets Received Count
GORC64 0x04088 - RC64 Good Octets Received Count 64-bit
GORCL 0x04088 - RC Good Octets Received Count Low
GORCH 0x0408C - RC Good Octets Received Count High
RXNFGPC 0x041B0 - RC Good Rx Non-Filtered Packet Counter
RXNFGBCL 0x041B4 - RC Good Rx Non-Filter Byte Counter Low
RXNFGBCH 0x041B8 - RC Good Rx Non-Filter Byte Counter High
RXDGPC 0x02F50 - RC DMA Good Rx Packet Counter
RXDGBCL 0x02F54 - RC DMA Good Rx Byte Counter Low
RXDGBCH 0x02F58 - RC DMA Good Rx Byte Counter High
RXDDPC 0x02F5C - RC DMA Duplicated Good Rx Packet Counter
RXDDBCL 0x02F60 - RC DMA Duplicated Good Rx Byte Counter Low
RXDDBCH 0x02F64 - RC DMA Duplicated Good Rx Byte Counter High
RXLPBKPC 0x02F68 - RC DMA Good Rx LPBK Packet Counter
RXLPBKBCL 0x02F6C - RC DMA Good Rx LPBK Byte Counter Low
RXLPBKBCH 0x02F70 - RC DMA Good Rx LPBK Byte Counter High
RXDLPBKPC 0x02F74 - RC DMA Duplicated Good Rx LPBK Packet Counter
RXDLPBKBCL 0x02F78 - RC DMA Duplicated Good Rx LPBK Byte Counter Low
RXDLPBKBCH 0x02F7C - RC DMA Duplicated Good Rx LPBK Byte Counter High
GPTC 0x04080 - RC Good Packets Transmitted Count
GOTC64 0x04090 - RC64 Good Octets Transmitted Count 64-bit
GOTCL 0x04090 - RC Good Octets Transmitted Count Low
GOTCH 0x04094 - RC Good Octets Transmitted Count High
TXDGPC 0x087A0 - RC DMA Good Tx Packet Counter
TXDGBCL 0x087A4 - RC DMA Good Tx Byte Counter Low
TXDGBCH 0x087A8 - RC DMA Good Tx Byte Counter High
RUC 0x040A4 - RC Receive Undersize Count
RFC 0x040A8 - RC Receive Fragment Count
ROC 0x040AC - RC Receive Oversize Count
RJC 0x040B0 - RC Receive Jabber Count
MNGPRC 0x040B4 - RC Management Packets Received Count
MNGPDC 0x040B8 - RC Management Packets Dropped Count
TORL 0x040C0 - RC Total Octets Received
TORH 0x040C4 - RC Total Octets Received
TPR 0x040D0 - RC Total Packets Received
TPT 0x040D4 - RC Total Packets Transmitted
PTC64 0x040D8 - RC Packets Transmitted [64 Bytes] Count
PTC127 0x040DC - RC Packets Transmitted [65-127 Bytes] Count
PTC255 0x040E0 - RC Packets Transmitted [128-255 Bytes] Count
PTC511 0x040E4 - RC Packets Transmitted [256-511 Bytes] Count
PTC1023 0x040E8 - RC Packets Transmitted [512-1023 Bytes] Count
PTC1522 0x040EC - RC Packets Transmitted [Greater than 1024 Bytes] Count
MPTC 0x040F0 - RC Multicast Packets Transmitted Count
BPTC 0x040F4 - RC Broadcast Packets Transmitted Count
MSPDC 0x04010 - RC MAC short Packet Discard Count
XEC 0x04120 - RC XSUM Error Count
FCCRC 0x05118 - RC FC CRC Error Count
FCOERPDC 0x0241C - RC FCoE Rx Packets Dropped Count
FCLAST 0x02424 - RC FC Last Error Count
FCOEPRC 0x02428 - RC FCoE Packets Received Count
FCOEDWRC 0x0242C - RC FCOE DWord Received Count
FCOEPTC 0x08784 - RC FCoE Packets Transmitted Count
FCOEDWTC 0x08788 - RC FCoE DWord Transmitted Count
]]
queue_statistics_registers_desc = [[
RQSMR 0x02300 +0x4*0..31 RW Receive Queue Statistic Mapping Registers
TQSM 0x08600 +0x4*0..31 RW Transmit Queue Statistic Mapping Registers
QPRC 0x01030 +0x40*0..15 RC Queue Packets Received Count
QPRDC 0x01430 +0x40*0..15 RC Queue Packets Received Drop Count
QBRC_L 0x01034 +0x40*0..15 RC Queue Bytes Received Count Low
QBRC_H 0x01038 +0x40*0..15 RC Queue Bytes Received Count High
QPTC 0x08680 +0x4*0..15 RC Queue Packets Transmitted Count
QBTC_L 0x08700 +0x8*0..15 RC Queue Bytes Transmitted Count Low
QBTC_H 0x08704 +0x8*0..15 RC Queue Bytes Transmitted Count High
]]
| apache-2.0 |
Enignite/darkstar | scripts/globals/items/plate_of_flapanos_paella.lua | 36 | 1435 | -----------------------------------------
-- ID: 5975
-- Item: Plate of Flapano's Paella
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- HP 45
-- Vitality 6
-- Defense % 26 Cap 155
-- Undead Killer 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5975);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 45);
target:addMod(MOD_VIT, 6);
target:addMod(MOD_FOOD_DEFP, 26);
target:addMod(MOD_FOOD_DEF_CAP, 155);
target:addMod(MOD_UNDEAD_KILLER, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 45);
target:delMod(MOD_VIT, 6);
target:delMod(MOD_FOOD_DEFP, 26);
target:delMod(MOD_FOOD_DEF_CAP, 155);
target:delMod(MOD_UNDEAD_KILLER, 6);
end;
| gpl-3.0 |
Enignite/darkstar | scripts/globals/items/lizard_egg.lua | 35 | 1182 | -----------------------------------------
-- ID: 4362
-- Item: lizard_egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 5
-- Magic 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,300,4362);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 5);
target:addMod(MOD_MP, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 5);
target:delMod(MOD_MP, 5);
end;
| gpl-3.0 |
fcpxhacks/fcpxhacks | src/extensions/cp/ui/SplitGroup.lua | 1 | 1035 | --- === cp.ui.SplitGroup ===
---
--- Split Group UI.
local require = require
local Element = require "cp.ui.Element"
local SplitGroup = Element:subclass("cp.ui.SplitGroup")
--- cp.ui.SplitGroup.matches(element) -> boolean
--- Function
--- Checks to see if an element matches what we think it should be.
---
--- Parameters:
--- * element - An `axuielementObject` to check.
---
--- Returns:
--- * `true` if matches otherwise `false`
function SplitGroup.static.matches(element)
return Element.matches(element) and element:attributeValue("AXRole") == "AXSplitGroup"
end
--- cp.ui.SplitGroup(parent, uiFinder) -> cp.ui.SplitGroup
--- Constructor
--- Creates a new Split Group.
---
--- Parameters:
--- * parent - The parent object.
--- * uiFinder - The `function` or `cp.prop` which returns an `hs.axuielement` for the Split Group, or `nil`.
---
--- Returns:
--- * A new `SplitGroup` instance.
function SplitGroup:initialize(parent, uiFinder)
Element.initialize(self, parent, uiFinder)
end
return SplitGroup
| mit |
Enignite/darkstar | scripts/zones/Northern_San_dOria/npcs/Shakir.lua | 38 | 1046 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Shakir
-- Type: Standard NPC
-- @zone: 231
-- @pos 48.952 -2.999 -16.687
--
-- 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(0x021a);
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 |
Enignite/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Yahsra.lua | 30 | 3592 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Yahsra
-- Type: Assault Mission Giver
-- @pos 120.967 0.161 -44.002 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/besieged");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local rank = getMercenaryRank(player);
local haveimperialIDtag;
local assaultPoints = player:getAssaultPoint(LEUJAOAM_ASSAULT_POINT);
if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then
haveimperialIDtag = 1;
else
haveimperialIDtag = 0;
end
if (rank > 0) then
player:startEvent(273,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault());
else
player:startEvent(279); -- no rank
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 == 273) then
local selectiontype = bit.band(option, 0xF);
if (selectiontype == 1) then
-- taken assault mission
player:addAssault(bit.rshift(option,4));
player:delKeyItem(IMPERIAL_ARMY_ID_TAG);
player:addKeyItem(LEUJAOAM_ASSAULT_ORDERS);
player:messageSpecial(KEYITEM_OBTAINED,LEUJAOAM_ASSAULT_ORDERS);
elseif (selectiontype == 2) then
-- purchased an item
local item = bit.rshift(option,14);
local itemID = 0;
local price = 0;
-- Copy/pasted from Famad, TODO: fill in the actual IDs/prices for Yahsra
--[[if (item == 1) then
itemID = 15972;
price = 3000;
elseif (item == 2) then
itemID = 15777;
price = 5000;
elseif (item == 3) then
itemID = 15523;
price = 8000;
elseif (item == 4) then
itemID = 15886;
price = 10000;
elseif (item == 5) then
itemID = 15492;
price = 10000;
elseif (item == 6) then
itemID = 18583;
price = 10000;
elseif (item == 7) then
itemID = 18388;
price = 15000;
elseif (item == 8) then
itemID = 18417;
price = 15000;
elseif (item == 9) then
itemID = 14940;
price = 15000;
elseif (item == 10) then
itemID = 15690;
price = 20000;
elseif (item == 11) then
itemID = 14525;
price = 20000;
else
return;
end
player:addItem(itemID);
player:messageSpecial(ITEM_OBTAINED,itemID);
player:delAssaultPoint(LEBROS_ASSAULT_POINT,price);]]
end
end
end;
| gpl-3.0 |
Enignite/darkstar | scripts/globals/weaponskills/glory_slash.lua | 18 | 1563 | -----------------------------------
-- Glory Slash
-- Sword weapon skill
-- Skill Level: NA
-- Only avaliable during Campaign Battle while weilding Lex Talionis.
-- Delivers and area attack that deals triple damage. Damage varies with TP. Additional effect Stun.
-- Will stack with Sneak Attack.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: Light
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 3.00 3.50 4.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3.5; params.ftp300 = 4;
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.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if damage > 0 then
local tp = player:getTP();
local duration = (tp/50);
if (target:hasStatusEffect(EFFECT_STUN) == false) then
target:addStatusEffect(EFFECT_STUN, 1, 0, duration);
end
end
local damage, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, damage;
end
| gpl-3.0 |
clevermm/clever-bot | 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 |
Enignite/darkstar | scripts/commands/jail.lua | 26 | 2109 | ---------------------------------------------------------------------------------------------------
-- func: jail
-- desc: Sends the target player to jail. (Mordion Gaol)
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "sis"
};
function onTrigger(player, target, cellId, reason)
local jailCells =
{
-- Floor 1 (Bottom)
{-620, 11, 660, 0}, {-180, 11, 660, 0}, {-260, 11, 660, 0}, {-700, 11, 660, 0},
{-620, 11, 220, 0}, {-180, 11, 220, 0}, {-260, 11, 220, 0}, {-700, 11, 220, 0},
{-620, 11, -220, 0}, {-180, 11, -220, 0}, {-260, 11, -220, 0}, {-700, 11, -220, 0},
{-620, 11, -660, 0}, {-180, 11, -660, 0}, {-260, 11, -660, 0}, {-700, 11, -660, 0},
-- Floor 2 (Top)
{-620, -440, 660, 0}, {-180, -440, 660, 0}, {-260, -440, 660, 0}, {-700, -440, 660, 0},
{-620, -440, 220, 0}, {-180, -440, 220, 0}, {-260, -440, 220, 0}, {-700, -440, 220, 0},
{-620, -440, -220, 0}, {-180, -440, -220, 0}, {-260, -440, -220, 0}, {-700, -440, -220, 0},
{-620, -440, -660, 0}, {-180, -440, -660, 0}, {-260, -440, -660, 0}, {-700, -440, -660, 0},
};
-- Validate the target..
local targ = GetPlayerByName( target );
if (targ == nil) then
player:PrintToPlayer( string.format( "Invalid player '%s' given.", target ) );
return;
end
-- Validate the cell id..
if (cellId == nil or cellId == 0 or cellId > 32) then
cellId = 1;
end
-- Validate the reason..
if (reason == nil) then
reason = "Unspecified.";
end
-- Print that we have jailed someone..
local message = string.format( '%s jailed %s(%d) into cell %d. Reason: %s', player:getName(), target, targ:getID(), cellId, reason );
printf( message );
-- Send the target to jail..
local dest = jailCells[ cellId ];
targ:setVar( "inJail", cellId );
targ:setPos( dest[1], dest[2], dest[3], dest[4], 131 );
end | gpl-3.0 |
GraionDilach/OpenRA | lua/sandbox.lua | 84 | 5098 | local sandbox = {
_VERSION = "sandbox 0.5",
_DESCRIPTION = "A pure-lua solution for running untrusted Lua code.",
_URL = "https://github.com/kikito/sandbox.lua",
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
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.
]]
}
-- The base environment is merged with the given env option (or an empty table, if no env provided)
--
local BASE_ENV = {}
-- List of non-safe packages/functions:
--
-- * string.rep: can be used to allocate millions of bytes in 1 operation
-- * {set|get}metatable: can be used to modify the metatable of global objects (strings, integers)
-- * collectgarbage: can affect performance of other systems
-- * dofile: can access the server filesystem
-- * _G: It has access to everything. It can be mocked to other things though.
-- * load{file|string}: All unsafe because they can grant acces to global env
-- * raw{get|set|equal}: Potentially unsafe
-- * module|require|module: Can modify the host settings
-- * string.dump: Can display confidential server info (implementation of functions)
-- * string.rep: Can allocate millions of bytes in one go
-- * math.randomseed: Can affect the host sytem
-- * io.*, os.*: Most stuff there is non-save
-- Safe packages/functions below
([[
_VERSION assert error ipairs next pairs
pcall select tonumber tostring type unpack xpcall
coroutine.create coroutine.resume coroutine.running coroutine.status
coroutine.wrap coroutine.yield
math.abs math.acos math.asin math.atan math.atan2 math.ceil
math.cos math.cosh math.deg math.exp math.fmod math.floor
math.frexp math.huge math.ldexp math.log math.log10 math.max
math.min math.modf math.pi math.pow math.rad
math.sin math.sinh math.sqrt math.tan math.tanh
os.clock os.difftime os.time
string.byte string.char string.find string.format string.gmatch
string.gsub string.len string.lower string.match string.reverse
string.sub string.upper
table.insert table.maxn table.remove table.sort
]]):gsub('%S+', function(id)
local module, method = id:match('([^%.]+)%.([^%.]+)')
if module then
BASE_ENV[module] = BASE_ENV[module] or {}
BASE_ENV[module][method] = _G[module][method]
else
BASE_ENV[id] = _G[id]
end
end)
local function protect_module(module, module_name)
return setmetatable({}, {
__index = module,
__newindex = function(_, attr_name, _)
error('Can not modify ' .. module_name .. '.' .. attr_name .. '. Protected by the sandbox.')
end
})
end
('coroutine math os string table'):gsub('%S+', function(module_name)
BASE_ENV[module_name] = protect_module(BASE_ENV[module_name], module_name)
end)
-- auxiliary functions/variables
local string_rep = string.rep
local function merge(dest, source)
for k,v in pairs(source) do
dest[k] = dest[k] or v
end
return dest
end
local function sethook(f, key, quota)
if type(debug) ~= 'table' or type(debug.sethook) ~= 'function' then return end
debug.sethook(f, key, quota)
end
local function cleanup()
sethook()
string.rep = string_rep
end
-- Public interface: sandbox.protect
function sandbox.protect(f, options)
if type(f) == 'string' then f = assert(loadstring(f)) end
options = options or {}
local quota = false
if options.quota ~= false then
quota = options.quota or 500000
end
local env = merge(options.env or {}, BASE_ENV)
env._G = env._G or env
setfenv(f, env)
return function(...)
if quota then
local timeout = function()
cleanup()
error('Quota exceeded: ' .. tostring(quota))
end
sethook(timeout, "", quota)
end
string.rep = nil
local ok, result = pcall(f, ...)
cleanup()
if not ok then error(result) end
return result
end
end
-- Public interface: sandbox.run
function sandbox.run(f, options, ...)
return sandbox.protect(f, options)(...)
end
-- make sandbox(f) == sandbox.protect(f)
setmetatable(sandbox, {__call = function(_,f,o) return sandbox.protect(f,o) end})
return sandbox
| gpl-3.0 |
dr-slump/bajawa | conf/desktop-manager/awesome/blingbling/udisks_glue.lua | 5 | 10051 | --@author cedlemo
local helpers = require("blingbling.helpers")
local awful = require("awful")
local naughty = require("naughty")
local string = string
local math = math
local ipairs = ipairs
local next = next
local pairs = pairs
local type = type
local setmetatable = setmetatable
local table = table
local wibox = require("wibox")
local debug = debug
---A menu for udisks-glue informations and actions
--@module blingbling.udisks_glue
local udisks_glue = { mt = {} }
local data = setmetatable( {}, { __mode = "k"})
local function udisks_send(ud_menu,command,a_device)
local s=""
data[ud_menu].menu_visible = "false"
data[ud_menu].menu:hide()
s=s .. "udisks --"..command.." "..a_device
return s
end
local function mounted_submenu(ud_menu, a_device)
local my_submenu= {
{ "umount",udisks_send(ud_menu,"unmount", a_device),data[ud_menu].umount_icon}--,
}
return my_submenu
end
local function unmounted_submenu(ud_menu,a_device)
local my_submenu= {
{ "mount",udisks_send(ud_menu,"mount", a_device),data[ud_menu].mount_icon}--,
}
return my_submenu
end
local function unmount_multiple_partitions(ud_menu, a_device, mount_points)
local command = "bash -c \""
for _,m in ipairs(mount_points) do
command = command .. udisks_send(ud_menu, "unmount", m)..";"
end
command = command .. udisks_send(ud_menu, "detach", a_device) .. "\""
return command
end
local function generate_menu(ud_menu)
--all_devices={device_name={partition_1,partition_2}
--devices_type={device_name=Usb or Cdrom}
--partition_state={partition_name = mounted or unmounted}
local my_menu={}
if next(data[ud_menu].all_devices) ~= nil then
for k,v in pairs(data[ud_menu].all_devices) do
local device_type=data[ud_menu].devices_type[k]
local action=""
if device_type == "Usb" then
action="detach"
else
action="eject"
end
local check_remain_mounted_partition =0
my_submenu={}
local mounted_partitions = {}
for j,x in ipairs(v) do
if data[ud_menu].partition_state[x] == "mounted" then
check_remain_mounted_partition = 1
table.insert(my_submenu,{x, mounted_submenu(ud_menu, x), data[ud_menu][device_type.."_icon"]})
table.insert(mounted_partitions,x)
else
table.insert(my_submenu,{x, unmounted_submenu(ud_menu, x), data[ud_menu][device_type.."_icon"]})
end
end
if check_remain_mounted_partition == 1 then
table.insert(my_submenu,{"unmount all", unmount_multiple_partitions(ud_menu, k, mounted_partitions ), data[ud_menu]["umount_icon"]})
--table.insert(my_submenu,{"Can\'t "..action, {{k .." busy"}}, data[ud_menu][action.."_icon"]})
else
table.insert(my_submenu,{action, udisks_send(ud_menu, action, k), data[ud_menu][action.."_icon"]})
end
table.insert(my_menu, {k, my_submenu, data[ud_menu][device_type.."_icon"]})
end
else
my_menu={{"No media",""}}
end
data[ud_menu].menu= awful.menu({ items = my_menu,
})
return ud_menu
end
local function display_menu(ud_menu)
ud_menu:buttons(awful.util.table.join(
awful.button({ }, 1, function()
if data[ud_menu].menu_visible == "false" then
data[ud_menu].menu_visible = "true"
generate_menu(ud_menu )
data[ud_menu].menu:show()
else
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
end
end),
awful.button({ }, 3, function()
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
end)
))
end
function udisks_glue.insert_device(ud_menu,device, mount_point, device_type)
-- generate the device_name
if device_type == "Usb" then
device_name = string.gsub(device,"%d*","")
else
device_name=device
end
-- add all_devices entry:
-- check if device is already registred
if data[ud_menu].all_devices[device_name] == nil then
data[ud_menu].all_devices[device_name]={device}
data[ud_menu].devices_type[device_name] = device_type
else
partition_already_registred = 0
for i, v in ipairs(data[ud_menu].all_devices[device_name]) do
if v == device then
partition_already_registred = 1
end
end
if partition_already_registred == 0 then
table.insert(data[ud_menu].all_devices[device_name],device)
end
end
data[ud_menu].partition_state[device]="unmounted"
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
naughty.notify({title = device_type..":", text = device .." inserted", timeout = 10})
end
function udisks_glue.mount_device(ud_menu,device, mount_point, device_type)
-- generate the device_name
if device_type == "Usb" then
device_name = string.gsub(device,"%d*","")
else
device_name=device
end
-- add all_devices entry:
-- check if device is already registred
if data[ud_menu].all_devices[device_name] == nil then
data[ud_menu].all_devices[device_name]={device}
data[ud_menu].devices_type[device_name] = device_type
else
partition_already_registred = 0
for i, v in ipairs(data[ud_menu].all_devices[device_name]) do
if v == device then
partition_already_registred = 1
end
end
if partition_already_registred == 0 then
table.insert(data[ud_menu].all_devices[device_name],device)
end
end
data[ud_menu].partition_state[device]="mounted"
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
naughty.notify({title = device_type..":", text =device .. " mounted on" .. mount_point, timeout = 10})
return ud_menu
end
function unmount_device(ud_menu, device, mount_point, device_type)
data[ud_menu].partition_state[device]="unmounted"
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
naughty.notify({title = device_type..":", text = device .." unmounted", timeout = 10})
end
function remove_device(ud_menu, device, mount_point, device_type )
local device_name=""
if device_type == "Usb" then
device_name=string.gsub(device,"%d*","")
else
device_name = device
end
--Remove the partitions
if data[ud_menu].all_devices[device_name] ~= nil then
for i,v in ipairs(data[ud_menu].all_devices[device_name]) do
if v == device then
table.remove(data[ud_menu].all_devices[device_name],i)
helpers.hash_remove(data[ud_menu].partition_state, device)
end
end
end
--Remove the device if no remaining partition
if data[ud_menu].all_devices[device_name] ~= nil and #data[ud_menu].all_devices[device_name] == 0 then
helpers.hash_remove(data[ud_menu].all_devices, device_name)
helpers.hash_remove(data[ud_menu].devices_type, device_name)
end
data[ud_menu].menu:hide()
data[ud_menu].menu_visible = "false"
naughty.notify({title = device_type ..":", text = device .." removed", timeout = 10})
end
---Define the icon for the mount action in the menu.
--@usage ud_widget:set_mount_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_mount_icon
--@param an_image an image file name
function set_mount_icon(ud_menu,an_image)
data[ud_menu].mount_icon=an_image
return ud_menu
end
---Define the icon for the umount action in the menu.
--@usage ud_widget:set_umount_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_umount_icon
--@param an_image an image file name
function set_umount_icon(ud_menu,an_image)
data[ud_menu].umount_icon=an_image
return ud_menu
end
---Define the icon for the detach action in the menu.
--@usage ud_widget:set_detach_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_detach_icon
--@param an_image an image file name
function set_detach_icon(ud_menu,an_image)
data[ud_menu].detach_icon=an_image
return ud_menu
end
---Define the icon for eject action in the menu.
--@usage ud_widget:set_eject_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_eject_icon
--@param an_image an image file name
function set_eject_icon(ud_menu,an_image)
data[ud_menu].eject_icon=an_image
return ud_menu
end
---Define the icon for usb devices in the menu.
--@usage ud_widget:set_Usb_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_Usb_icon
--@param an_image an image file name
function set_Usb_icon(ud_menu,an_image)
data[ud_menu].Usb_icon=an_image
return ud_menu
end
---Define the icon for Cdrom devices in the menu.
--@usage ud_widget:set_Cdrom_icon(icon)
--@param ud_menu the udisk-glue menu widget or nothing if you use widget:set_Cdrom_icon
--@param an_image an image file name
function set_Cdrom_icon(ud_menu,an_image)
data[ud_menu].Cdrom_icon=an_image
return ud_menu
end
function udisks_glue.new(args)
local args = args or {}
local ud_menu
ud_menu = wibox.widget.imagebox()
ud_menu:set_image(args.menu_icon)
data[ud_menu]={ image = menu_icon,
all_devices= {},
devices_type={},
partition_state={},
menu_visible = "false",
menu={},
Cdrom_icon=args.Cdrom_icon,
Usb_icon=args.Usb_icon,
mount_icon=args.mount_icon,
umount_icon=args.umount_icon,
detach_icon=args.detach_icon,
eject_icon=args.eject_icon,
}
ud_menu.insert_device = udisks_glue.insert_device
ud_menu.mount_device = udisks_glue.mount_device
ud_menu.unmount_device = unmount_device
ud_menu.remove_device = remove_device
ud_menu.set_mount_icon = set_mount_icon
ud_menu.set_umount_icon = set_umount_icon
ud_menu.set_detach_icon = set_detach_icon
ud_menu.set_eject_icon = set_eject_icon
ud_menu.set_Usb_icon = set_Usb_icon
ud_menu.set_Cdrom_icon = set_Cdrom_icon
generate_menu(ud_menu)
display_menu(ud_menu)
return ud_menu
end
function udisks_glue.mt:__call(...)
return udisks_glue.new(...)
end
return setmetatable(udisks_glue, udisks_glue.mt)
| mit |
amindark1/bot-amin | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
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.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function 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(target, receiver)
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
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
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 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
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(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)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
sik3/singnal | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
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.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function 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(target, receiver)
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
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
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 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
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(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)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
fegimanam/seed | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
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.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function 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(target, receiver)
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
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
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 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
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(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)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Enignite/darkstar | scripts/zones/Beaucedine_Glacier/npcs/Akane_IM.lua | 28 | 3168 | -----------------------------------
-- Area: Beaucedine Glacier
-- NPC: Akane, I.M.
-- Type: Outpost Conquest Guards
-- @pos -24.351 -60.421 -114.215 111
-------------------------------------
package.loaded["scripts/zones/Beaucedine_Glacier/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Beaucedine_Glacier/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = FAUREGANDI;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/Kazham/npcs/Toji_Mumosulah.lua | 37 | 1558 | -----------------------------------
-- Area: Kazham
-- NPC: Toji Mumosulah
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TOJIMUMOSULAH_SHOP_DIALOG);
stock = {0x0070,456, -- Yellow Jar
0x338F,95, -- Blood Stone
0x3314,3510, -- Fang Necklace
0x3409,1667, -- Bone Earring
0x43C7,4747, -- Gemshorn
0x4261,69, -- Peeled Crayfish
0x4266,36, -- Insect Paste
0x45D4,165, -- Fish Broth
0x45D8,695, -- Seedbed Soil
0x03FD,450, -- Hatchet
0x137B,328, -- Scroll of Army's Paeon II
0x13d7,64528, -- Scroll of Foe Lullaby II
0x137C,3312, -- Scroll of Army's Paeon III
0x1364,8726} -- Scroll of Monomi: Ichi
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Al_Zahbi/npcs/Shayadar.lua | 38 | 1034 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Shayadar
-- Type: Gadalar's Attendant
-- @zone: 48
-- @pos -107.177 -6.999 33.463
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00fc);
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 |
Enignite/darkstar | scripts/zones/Behemoths_Dominion/npcs/Cermet_Headstone.lua | 17 | 2940 | -----------------------------------
-- Area: Behemoth's Dominion
-- NPC: Cermet Headstone
-- Involved in Mission: ZM5 Headstone Pilgrimage (Lightning Headstone)
-- @pos -74 -4 -87 127
-----------------------------------
package.loaded["scripts/zones/Behemoths_Dominion/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/missions");
require("scripts/zones/Behemoths_Dominion/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then
-- if requirements are met and 15 mins have passed since mobs were last defeated, spawn them
if (player:hasKeyItem(LIGHTNING_FRAGMENT) == false and GetServerVariable("[ZM4]Lightning_Headstone_Active") < os.time()) then
player:startEvent(0x00C8,LIGHTNING_FRAGMENT);
-- if 15 min window is open and requirements are met, recieve key item
elseif (player:hasKeyItem(LIGHTNING_FRAGMENT) == false and GetServerVariable("[ZM4]Lightning_Headstone_Active") > os.time()) then
player:addKeyItem(LIGHTNING_FRAGMENT);
-- Check and see if all fragments have been found (no need to check wind and dark frag)
if (player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and
player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) and player:hasKeyItem(LIGHT_FRAGMENT)) then
player:messageSpecial(FOUND_ALL_FRAGS,LIGHTNING_FRAGMENT);
player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS);
player:completeMission(ZILART,HEADSTONE_PILGRIMAGE);
player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
else
player:messageSpecial(KEYITEM_OBTAINED,LIGHTNING_FRAGMENT);
end
else
player:messageSpecial(ALREADY_OBTAINED_FRAG,LIGHTNING_FRAGMENT);
end
elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then
player:messageSpecial(ZILART_MONUMENT);
else
player:messageSpecial(CANNOT_REMOVE_FRAG);
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 == 0x00C8 and option == 1) then
SpawnMob(17297450,300):updateClaim(player); -- Legendary Weapon
SpawnMob(17297449,300):updateClaim(player); -- Ancient Weapon
SetServerVariable("[ZM4]Lightning_Headstone_Active",0);
end
end; | gpl-3.0 |
Enignite/darkstar | scripts/zones/The_Shrine_of_RuAvitau/mobs/Kirin.lua | 23 | 3674 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: Kirin
-----------------------------------
package.loaded[ "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" ] = nil;
-----------------------------------
require( "scripts/zones/The_Shrine_of_RuAvitau/TextIDs" );
require( "scripts/globals/titles" );
require( "scripts/globals/ability" );
require( "scripts/globals/pets" );
require( "scripts/globals/status" );
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize( mob )
end
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMod(MOD_WINDRES, -64);
end
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight( mob, target )
if (mob:getHPP() < math.random(50,60) and mob:getLocalVar("astralFlow") == 0) then
mob:useMobAbility(478);
-- Spawn Avatar
mob:spawnPet();
mob:setLocalVar("astralFlow", 1);
end
if (mob:getBattleTime() ~= 0 and mob:getBattleTime() % 180 == 0) then
-- Ensure we have not spawned all pets yet..
local genbu = mob:getLocalVar("genbu");
local seiryu = mob:getLocalVar("seiryu");
local byakko = mob:getLocalVar("byakko");
local suzaku = mob:getLocalVar("suzaku");
if (genbu == 1 and seiryu == 1 and byakko == 1 and suzaku == 1) then
return;
end
-- Pick a pet to spawn at random..
local ChosenPet = nil;
local newVar = nil;
repeat
local rand = math.random( 0, 3 );
ChosenPet = 17506671 + rand;
switch (ChosenPet): caseof {
[17506671] = function (x) if ( genbu == 1) then ChosenPet = 0; else newVar = "genbu"; end end, -- Genbu
[17506672] = function (x) if (seiryu == 1) then ChosenPet = 0; else newVar = "seiryu"; end end, -- Seiryu
[17506673] = function (x) if (byakko == 1) then ChosenPet = 0; else newVar = "byakko"; end end, -- Byakko
[17506674] = function (x) if (suzaku == 1) then ChosenPet = 0; else newVar = "suzaku"; end end, -- Suzaku
}
until (ChosenPet ~= 0 and ChosenPet ~= nil)
-- Spawn the pet..
local pet = SpawnMob( ChosenPet );
pet:updateEnmity( target );
pet:setPos( mob:getXPos(), mob:getYPos(), mob:getZPos() );
-- Update Kirins extra vars..
mob:setLocalVar(newVar, 1);
end
-- Ensure all spawned pets are doing stuff..
for pets = 17506671, 17506674 do
if (GetMobAction( pets ) == 16) then
-- Send pet after current target..
GetMobByID( pets ):updateEnmity( target );
end
end
end
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath( mob, killer )
-- Award title and cleanup..
killer:addTitle( KIRIN_CAPTIVATOR );
killer:showText( mob, KIRIN_OFFSET + 1 );
GetNPCByID( 17506693 ):hideNPC( 900 );
-- Despawn pets..
DespawnMob( 17506671 );
DespawnMob( 17506672 );
DespawnMob( 17506673 );
DespawnMob( 17506674 );
end
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn( mob )
-- Despawn pets..
DespawnMob( 17506671 );
DespawnMob( 17506672 );
DespawnMob( 17506673 );
DespawnMob( 17506674 );
end
| gpl-3.0 |
Enignite/darkstar | scripts/globals/weaponskills/omniscience.lua | 18 | 4697 | -----------------------------------
-- Omniscience
-- Staff weapon skill
-- Skill Level: N/A
-- Lowers target's magic attack. Duration of effect varies with TP. Tupsimati: Aftermath effect varies with TP.
-- Reduces enemy's magic attack by -10.
-- Available only after completing the Unlocking a Myth (Scholar) quest.
-- Aligned with the Shadow Gorget, Soil Gorget & Light Gorget.
-- Aligned with the Shadow Belt, Soil Belt & Light Belt.
-- Element: Dark
-- Modifiers: MND:80%
-- 100%TP 200%TP 300%TP
-- 2.00 2.00 2.00
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 2; params.ftp200 = 2; params.ftp300 = 2;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.3; params.chr_wsc = 0.0;
params.ele = ELE_DARK;
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.mnd_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
if damage > 0 then
local tp = player:getTP();
local duration = (tp/100 * 60);
if (target:hasStatusEffect(EFFECT_MAGIC_ATK_DOWN) == false) then
target:addStatusEffect(EFFECT_MAGIC_ATK_DOWN, 10, 0, duration);
end
end
if ((player:getEquipID(SLOT_MAIN) == 18990) and (player:getMainJob() == JOB_SCH)) then
if (damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 2);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 2);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 2);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 2);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 2);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 2);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 2);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 2);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 2);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 2);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 3);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 3);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 3);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 3);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 3);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 3);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 3);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 3);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 3);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 3);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Enignite/darkstar | scripts/globals/items/serving_of_salmon_roe.lua | 35 | 1341 | -----------------------------------------
-- ID: 5218
-- Item: serving_of_salmon_roe
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 8
-- Magic 8
-- Dexterity 2
-- Mind -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5218);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 8);
target:addMod(MOD_MP, 8);
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 8);
target:delMod(MOD_MP, 8);
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -1);
end;
| gpl-3.0 |
Enignite/darkstar | scripts/zones/FeiYin/npcs/qm1.lua | 17 | 1507 | -----------------------------------
-- Area: FeiYin
-- NPC: qm1 (???)
-- Involved In Quest: Pieuje's Decision
-- @pos -55 -16 69 204
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,PIEUJE_S_DECISION) == QUEST_ACCEPTED and player:hasItem(13842) == false) then
if (trade:hasItemQty(1098,1) and trade:getItemCount() == 1) then -- Trade Tavnazia Bell
player:tradeComplete();
player:messageSpecial(SENSE_OF_FOREBODING);
SpawnMob(17612836,180):updateClaim(player);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
QUSpilPrgm/cuberite | Server/Plugins/APIDump/Hooks/OnKilled.lua | 38 | 1204 | return
{
HOOK_KILLED =
{
CalledWhen = "A player or a mob died.",
DefaultFnName = "OnKilled",
Desc = [[
This hook is called whenever player or a mob dies. It can be used to change the death message.
]],
Params =
{
{ Name = "Victim", Type = "{{cEntity}}", Notes = "The player or mob that died" },
{ Name = "TDI", Type = "{{TakeDamageInfo}}", Notes = "Informations about the death" },
{ Name = "DeathMessage", Type = "string", Notes = "The default death message. An empty string if the victim is not a player" },
},
Returns = [[
The function may return two values. The first value is a boolean specifying whether other plugins should be called. If it is true, the other plugins won't get notified of the death. If it is false, the other plugins will get notified.</p>
<p>The second value is a string containing the death message. If the victim is a player, this death message is broadcasted instead of the default death message. If it is empty, no death message is broadcasted. If it is nil, the message is left unchanged. If the victim is not a player, the death message is never broadcasted.</p>
<p>In either case, the victim is dead.
]],
}, -- HOOK_KILLED
}
| apache-2.0 |
fcpxhacks/fcpxhacks | src/extensions/cp/apple/finalcutpro/inspector/audio/AudioInspector.lua | 1 | 11037 | --- === cp.apple.finalcutpro.inspector.audio.AudioInspector ===
---
--- Audio Inspector Module.
---
--- Header Rows (`compositing`, `transform`, etc.) have the following properties:
--- * enabled - (cp.ui.CheckBox) Indicates if the section is enabled.
--- * toggle - (cp.ui.Button) Will toggle the Hide/Show button.
--- * reset - (cp.ui.Button) Will reset the contents of the section.
--- * expanded - (cp.prop <boolean>) Get/sets whether the section is expanded.
---
--- Property Rows depend on the type of property:
---
--- Menu Property:
--- * value - (cp.ui.PopUpButton) The current value of the property.
---
--- Slider Property:
--- * value - (cp.ui.Slider) The current value of the property.
---
--- XY Property:
--- * x - (cp.ui.TextField) The current 'X' value.
--- * y - (cp.ui.TextField) The current 'Y' value.
---
--- CheckBox Property:
--- * value - (cp.ui.CheckBox) The currently value.
---
--- For example:
--- ```lua
--- local audio = fcp.inspector.audio
--- -- Menu Property:
--- audio:compositing():blendMode():value("Subtract")
--- -- Slider Property:
--- audio:compositing():opacity():value(50.0)
--- -- XY Property:
--- audio:transform():position():x(-10.0)
--- -- CheckBox property:
--- audio:stabilization():tripodMode():value(true)
--- ```
---
--- You should also be able to show a specific property and it will be revealed:
--- ```lua
--- audio:stabilization():smoothing():show():value(1.5)
--- ```
local require = require
-- local log = require("hs.logger").new("AudioInspector")
local axutils = require("cp.ui.axutils")
local prop = require("cp.prop")
local Button = require("cp.ui.Button")
local Group = require("cp.ui.Group")
local PopUpButton = require("cp.ui.PopUpButton")
local RadioButton = require("cp.ui.RadioButton")
local SplitGroup = require("cp.ui.SplitGroup")
local BasePanel = require("cp.apple.finalcutpro.inspector.BasePanel")
local IP = require("cp.apple.finalcutpro.inspector.InspectorProperty")
local AudioConfiguration = require("cp.apple.finalcutpro.inspector.audio.AudioConfiguration")
local childFromLeft, childFromRight = axutils.childFromLeft, axutils.childFromRight
local withRole, childWithRole = axutils.withRole, axutils.childWithRole
local hasProperties, simple = IP.hasProperties, IP.simple
local section, slider, numberField, popUpButton = IP.section, IP.slider, IP.numberField, IP.popUpButton
local AudioInspector = BasePanel:subclass("cp.apple.finalcutpro.inspector.audio.AudioInspector")
--- cp.apple.finalcutpro.inspector.audio.AudioInspector.matches(element)
--- Function
--- Checks if the provided element could be a AudioInspector.
---
--- Parameters:
--- * element - The element to check
---
--- Returns:
--- * `true` if it matches, `false` if not.
function AudioInspector.static.matches(element)
local root = BasePanel.matches(element) and withRole(element, "AXGroup")
local split = root and #root == 1 and childWithRole(root, "AXSplitGroup")
return split and #split > 5 or false
end
--- cp.apple.finalcutpro.inspector.audio.AudioInspector(parent) -> cp.apple.finalcutpro.audio.AudioInspector
--- Constructor
--- Creates a new `AudioInspector` object
---
--- Parameters:
--- * `parent` - The parent
---
--- Returns:
--- * A `AudioInspector` object
function AudioInspector:initialize(parent)
BasePanel.initialize(self, parent, "Audio")
end
function AudioInspector.lazy.value:content()
return SplitGroup(self, self.UI:mutate(function(original)
return axutils.cache(self, "_ui", function()
local ui = original()
if ui then
local splitGroup = ui[1]
return SplitGroup.matches(splitGroup) and splitGroup or nil
end
return nil
end, SplitGroup.matches)
end))
end
function AudioInspector.lazy.value:topProperties()
local topProps = Group(self, function()
return axutils.childFromTop(self.content:UI(), 1)
end)
prop.bind(topProps) {
contentUI = topProps.UI:mutate(function(original)
local ui = original()
if ui and ui[1] then
return ui[1]
end
end)
}
hasProperties(topProps, topProps.contentUI) {
volume = slider "FFAudioVolumeToolName",
}
return topProps
end
function AudioInspector.lazy.value:mainProperties()
local mainProps = Group(self, function()
return axutils.childFromTop(self.content:UI(), 2)
end)
prop.bind(mainProps) {
contentUI = mainProps.UI:mutate(function(original)
local ui = original()
if ui and ui[1] and ui[1][1] then
return ui[1][1]
end
end)
}
hasProperties(mainProps, mainProps.contentUI) {
audioEnhancements = section "FFAudioAnalysisLabel_EnhancementsBrick" {
equalization = section "FFAudioAnalysisLabel_Equalization" {}
:extend(function(row)
row.mode = PopUpButton(row, function() return childFromLeft(row:children(), 1, PopUpButton.matches) end)
row.enhanced = Button(row, function() return childFromLeft(row:children(), 1, Button.matches) end)
end),
audioAnalysis = section "FFAudioAnalysisLabel_AnalysisBrick" {
loudness = section "FFAudioAnalysisLabel_Loudness" {
amount = numberField "FFAudioAnalysisLabel_LoudnessAmount",
uniformity = numberField "FFAudioAnalysisLabel_LoudnessUniformity",
},
noiseRemoval = section "FFAudioAnalysisLabel_NoiseRemoval" {
amount = numberField "FFAudioAnalysisLabel_NoiseRemovalAmount",
},
humRemoval = section "FFAudioAnalysisLabel_HumRemoval" {
frequency = simple("FFAudioAnalysisLabel_HumRemovalFrequency", function(row)
row.fiftyHz = RadioButton(row, function()
return childFromLeft(row:children(), 1, RadioButton.matches)
end)
row.sixtyHz = RadioButton(row, function()
return childFromRight(row:children(), 1, RadioButton.matches)
end)
end),
}
}
:extend(function(row)
row.magic = Button(row, function() return childFromLeft(row:children(), 1, Button.matches) end)
end),
},
pan = section "FFAudioIntrinsicChannels_Pan" {
mode = popUpButton "FFAudioIntrinsicChannels_PanMode",
amount = slider "FFAudioIntrinsicChannels_PanAmount",
surroundPanner = section "FFAudioIntrinsicChannels_PanSettings" {
--------------------------------------------------------------------------------
-- TODO: Add Surround Panner.
--
--/Applications/Final Cut Pro.app/Contents/Frameworks/Flexo.framework/Versions/A/Resources/en.lproj/FFAudioSurroundPannerHUD.nib
--------------------------------------------------------------------------------
}
},
effects = section "FFInspectorBrickEffects" {},
}
return mainProps
end
--- cp.apple.finalcutpro.inspector.color.VideoInspector.volume <cp.prop: PropertyRow>
--- Field
--- Volume
function AudioInspector.lazy.prop:volume()
return self.topProperties.volume
end
--- cp.apple.finalcutpro.inspector.color.VideoInspector.audioEnhancements <cp.prop: PropertyRow>
--- Field
--- Audio Enhancements
function AudioInspector.lazy.prop:audioEnhancements()
return self.mainProperties.audioEnhancements
end
--- cp.apple.finalcutpro.inspector.color.VideoInspector.pan <cp.prop: PropertyRow>
--- Field
--- Pan
function AudioInspector.lazy.prop:pan()
return self.mainProperties.pan
end
--- cp.apple.finalcutpro.inspector.color.VideoInspector.effects <cp.prop: PropertyRow>
--- Field
--- Effects
function AudioInspector.lazy.prop:effects()
return self.mainProperties.effects
end
--- cp.apple.finalcutpro.inspector.audio.AudioInspector.audioConfiguration <AudioConfiguration>
--- Field
--- The `AudioConfiguration` instance.
function AudioInspector.lazy.value:audioConfiguration()
return AudioConfiguration(self)
end
--- cp.apple.finalcutpro.inspector.audio.AudioInspector.PAN_MODES -> table
--- Constant
--- Pan Modes
AudioInspector.PAN_MODES = {
[1] = {flexoID = "None", i18n="none"},
[2] = {flexoID = "Stereo Left/Right", i18n="stereoLeftRight"},
[3] = {}, -- Separator
[4] = {}, -- SURROUND Label
[5] = {flexoID = "Basic Surround", i18n="basicSurround"},
[6] = {flexoID = "Create Space", i18n="createSpace"},
[7] = {flexoID = "Dialogue", i18n="dialogue"},
[8] = {flexoID = "Music", i18n="music"},
[9] = {flexoID = "Ambience", i18n="ambience"},
[10] = {flexoID = "Circle", i18n="circle"},
[11] = {flexoID = "Rotate", i18n="rotate"},
[12] = {flexoID = "Back to Front", i18n="backToFront"},
[13] = {flexoID = "Left Surround to Right Front", i18n="leftSurroundToRightFront"},
[14] = {flexoID = "Right Surround to Left Front", i18n="rightSurroundToLeftFront"},
}
--- cp.apple.finalcutpro.inspector.audio.AudioInspector.EQ_MODES -> table
--- Constant
--- EQ Modes
AudioInspector.EQ_MODES = {
[1] = {flexoID = "Flat", i18n="flat"},
[2] = {flexoID = "Voice Enhance", i18n="voiceEnhance"},
[3] = {flexoID = "Music Enhance", i18n="musicEnhance"},
[4] = {flexoID = "Loudness", i18n="loudness"},
[5] = {flexoID = "Hum Reduction", i18n="humReduction"},
[6] = {flexoID = "Bass Boost", i18n="bassBoost"},
[7] = {flexoID = "Bass Reduce", i18n="bassReduce"},
[8] = {flexoID = "Treble Boost", i18n="trebleBoost"},
[9] = {flexoID = "Treble Reduce", i18n="trebleReduce"},
[10] = {}, -- Separator
[11] = {flexoID = "FFAudioAnalysisMatchAudioEqualizationMenuName", i18n="match"},
}
return AudioInspector
| mit |
dr-slump/bajawa | conf/desktop-manager/awesome/tyrannical/extra/request.lua | 1 | 1335 | local capi = {client=client,awesome=awesome}
local ewmh = require("awful.ewmh")
local tyrannical = nil
-- Use Tyrannical policies instead of the default ones
capi.client.disconnect_signal("request::activate",ewmh.activate)
capi.client.connect_signal("request::activate",function(c,reason)
if not tyrannical then
tyrannical = require("tyrannical")
end
-- Always grant those request as it probably mean that it is a modal dialog
if c.transient_for and capi.client.focus == c.transient_for then
capi.client.focus = c
c:raise()
-- If it is not modal, then use the normal code path
elseif reason == "rule" or reason == "ewmh" then
tyrannical.focus_client(c)
-- Tyrannical doesn't have enough information, grant the request
else
capi.client.focus = c
c:raise()
end
end)
capi.client.disconnect_signal("request::tag", ewmh.tag)
capi.client.connect_signal("request::tag", function(c)
-- if capi.awesome.startup then
-- --TODO create a tag on that screen
-- else
-- --TODO block invalid requests, let Tyrannical do its job
-- local tags = c:tags()
-- if #tags == 0 then
-- --TODO cannot happen
-- end
-- end
end)
--lib/awful/tag.lua.in:capi.tag.connect_signal("request::select", tag.viewonly) | mit |
Enignite/darkstar | scripts/zones/Mhaura/npcs/Porter_Moogle.lua | 41 | 1512 | -----------------------------------
-- Area: Mhaura
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 249
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 336,
STORE_EVENT_ID = 337,
RETRIEVE_EVENT_ID = 338,
ALREADY_STORED_ID = 339,
MAGIAN_TRIAL_ID = 340
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
doofus-01/wesnoth | data/campaigns/tutorial/lua/character_selection.lua | 3 | 1070 | -- #textdomain wesnoth-tutorial
-- Allows the player to choose whether they want to play Konrad or Li’sar
-- for the tutorial
local T = wml.tag
local wml_actions = wesnoth.wml_actions
local _ = wesnoth.textdomain "wesnoth-tutorial"
function wml_actions.select_character()
local character_selection_dialog = wml.load "campaigns/tutorial/gui/character_selection.cfg"
local dialog_wml = wml.get_child(character_selection_dialog, 'resolution')
local result = wesnoth.sync.evaluate_single(function()
return { value = gui.show_dialog(dialog_wml) }
end)
local character = result.value
local unit = wml.variables.student_store
if character == 2 then
wesnoth.units.to_map({
type = "Fighteress",
id = unit.id,
name = _"Li’sar",
unrenamable = true,
profile = "portraits/lisar.png",
canrecruit = true,
facing = unit.facing,
}, unit.x, unit.y )
wesnoth.sides[1].side_name = _"Li’sar"
-- enable the help to display this unit's page
wesnoth.add_known_unit("Fighteress")
else
wesnoth.units.to_map(unit)
end
wesnoth.redraw {}
end
| gpl-2.0 |
rohmad-st/waifu2x | lib/image_loader.lua | 32 | 2887 | local gm = require 'graphicsmagick'
local ffi = require 'ffi'
require 'pl'
local image_loader = {}
function image_loader.decode_float(blob)
local im, alpha = image_loader.decode_byte(blob)
if im then
im = im:float():div(255)
end
return im, alpha
end
function image_loader.encode_png(rgb, alpha)
if rgb:type() == "torch.ByteTensor" then
error("expect FloatTensor")
end
if alpha then
if not (alpha:size(2) == rgb:size(2) and alpha:size(3) == rgb:size(3)) then
alpha = gm.Image(alpha, "I", "DHW"):size(rgb:size(3), rgb:size(2), "Sinc"):toTensor("float", "I", "DHW")
end
local rgba = torch.Tensor(4, rgb:size(2), rgb:size(3))
rgba[1]:copy(rgb[1])
rgba[2]:copy(rgb[2])
rgba[3]:copy(rgb[3])
rgba[4]:copy(alpha)
local im = gm.Image():fromTensor(rgba, "RGBA", "DHW")
im:format("png")
return im:toBlob(9)
else
local im = gm.Image(rgb, "RGB", "DHW")
im:format("png")
return im:toBlob(9)
end
end
function image_loader.save_png(filename, rgb, alpha)
local blob, len = image_loader.encode_png(rgb, alpha)
local fp = io.open(filename, "wb")
fp:write(ffi.string(blob, len))
fp:close()
return true
end
function image_loader.decode_byte(blob)
local load_image = function()
local im = gm.Image()
local alpha = nil
im:fromBlob(blob, #blob)
-- FIXME: How to detect that a image has an alpha channel?
if blob:sub(1, 4) == "\x89PNG" or blob:sub(1, 3) == "GIF" then
-- split alpha channel
im = im:toTensor('float', 'RGBA', 'DHW')
local sum_alpha = (im[4] - 1):sum()
if sum_alpha > 0 or sum_alpha < 0 then
alpha = im[4]:reshape(1, im:size(2), im:size(3))
end
local new_im = torch.FloatTensor(3, im:size(2), im:size(3))
new_im[1]:copy(im[1])
new_im[2]:copy(im[2])
new_im[3]:copy(im[3])
im = new_im:mul(255):byte()
else
im = im:toTensor('byte', 'RGB', 'DHW')
end
return {im, alpha}
end
local state, ret = pcall(load_image)
if state then
return ret[1], ret[2]
else
return nil
end
end
function image_loader.load_float(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_float(buff)
end
function image_loader.load_byte(file)
local fp = io.open(file, "rb")
if not fp then
error(file .. ": failed to load image")
end
local buff = fp:read("*a")
fp:close()
return image_loader.decode_byte(buff)
end
local function test()
require 'image'
local img
img = image_loader.load_float("./a.jpg")
if img then
print(img:min())
print(img:max())
image.display(img)
end
img = image_loader.load_float("./b.png")
if img then
image.display(img)
end
end
--test()
return image_loader
| mit |
Enignite/darkstar | scripts/zones/Castle_Zvahl_Keep_[S]/Zone.lua | 28 | 1341 | -----------------------------------
--
-- Zone: Castle_Zvahl_Keep_[S] (155)
--
-----------------------------------
package.loaded["scripts/zones/Castle_Zvahl_Keep_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Castle_Zvahl_Keep_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-555.996,-71.691,60,255);
end
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 |
tks2103/angel-test | Code/Tools/BuildScripts/lua-lib/penlight-1.0.2/lua/pl/func.lua | 13 | 10456 | --- Functional helpers like composition, binding and placeholder expressions.
-- Placeholder expressions are useful for short anonymous functions, and were
-- inspired by the Boost Lambda library.
--
-- > utils.import 'pl.func'
-- > ls = List{10,20,30}
-- > = ls:map(_1+1)
-- {11,21,31}
--
-- They can also be used to _bind_ particular arguments of a function.
--
-- > p = bind(print,'start>',_0)
-- > p(10,20,30)
-- > start> 10 20 30
--
-- See @{07-functional.md.Creating_Functions_from_Functions|the Guide}
--
-- Dependencies: `pl.utils`, `pl.tablex`
-- @module pl.func
local type,select,setmetatable,getmetatable,rawset = type,select,setmetatable,getmetatable,rawset
local concat,append = table.concat,table.insert
local max = math.max
local print,tostring = print,tostring
local pairs,ipairs,loadstring,rawget,unpack = pairs,ipairs,loadstring,rawget,unpack
local _G = _G
local utils = require 'pl.utils'
local tablex = require 'pl.tablex'
local map = tablex.map
local _DEBUG = rawget(_G,'_DEBUG')
local assert_arg = utils.assert_arg
local func = {}
-- metatable for Placeholder Expressions (PE)
local _PEMT = {}
local function P (t)
setmetatable(t,_PEMT)
return t
end
func.PE = P
local function isPE (obj)
return getmetatable(obj) == _PEMT
end
func.isPE = isPE
-- construct a placeholder variable (e.g _1 and _2)
local function PH (idx)
return P {op='X',repr='_'..idx, index=idx}
end
-- construct a constant placeholder variable (e.g _C1 and _C2)
local function CPH (idx)
return P {op='X',repr='_C'..idx, index=idx}
end
func._1,func._2,func._3,func._4,func._5 = PH(1),PH(2),PH(3),PH(4),PH(5)
func._0 = P{op='X',repr='...',index=0}
function func.Var (name)
local ls = utils.split(name,'[%s,]+')
local res = {}
for _,n in ipairs(ls) do
append(res,P{op='X',repr=n,index=0})
end
return unpack(res)
end
function func._ (value)
return P{op='X',repr=value,index='wrap'}
end
local repr
func.Nil = func.Var 'nil'
function _PEMT.__index(obj,key)
return P{op='[]',obj,key}
end
function _PEMT.__call(fun,...)
return P{op='()',fun,...}
end
function _PEMT.__tostring (e)
return repr(e)
end
function _PEMT.__unm(arg)
return P{op='-',arg}
end
function func.Not (arg)
return P{op='not',arg}
end
function func.Len (arg)
return P{op='#',arg}
end
local function binreg(context,t)
for name,op in pairs(t) do
rawset(context,name,function(x,y)
return P{op=op,x,y}
end)
end
end
local function import_name (name,fun,context)
rawset(context,name,function(...)
return P{op='()',fun,...}
end)
end
local imported_functions = {}
local function is_global_table (n)
return type(_G[n]) == 'table'
end
--- wrap a table of functions. This makes them available for use in
-- placeholder expressions.
-- @param tname a table name
-- @param context context to put results, defaults to environment of caller
function func.import(tname,context)
assert_arg(1,tname,'string',is_global_table,'arg# 1: not a name of a global table')
local t = _G[tname]
context = context or _G
for name,fun in pairs(t) do
import_name(name,fun,context)
imported_functions[fun] = name
end
end
--- register a function for use in placeholder expressions.
-- @param fun a function
-- @param name an optional name
-- @return a placeholder functiond
function func.register (fun,name)
assert_arg(1,fun,'function')
if name then
assert_arg(2,name,'string')
imported_functions[fun] = name
end
return function(...)
return P{op='()',fun,...}
end
end
function func.lookup_imported_name (fun)
return imported_functions[fun]
end
local function _arg(...) return ... end
function func.Args (...)
return P{op='()',_arg,...}
end
-- binary and unary operators, with their precedences (see 2.5.6)
local operators = {
['or'] = 0,
['and'] = 1,
['=='] = 2, ['~='] = 2, ['<'] = 2, ['>'] = 2, ['<='] = 2, ['>='] = 2,
['..'] = 3,
['+'] = 4, ['-'] = 4,
['*'] = 5, ['/'] = 5, ['%'] = 5,
['not'] = 6, ['#'] = 6, ['-'] = 6,
['^'] = 7
}
-- comparisons (as prefix functions)
binreg (func,{And='and',Or='or',Eq='==',Lt='<',Gt='>',Le='<=',Ge='>='})
-- standard binary operators (as metamethods)
binreg (_PEMT,{__add='+',__sub='-',__mul='*',__div='/',__mod='%',__pow='^',__concat='..'})
binreg (_PEMT,{__eq='=='})
--- all elements of a table except the first.
-- @param ls a list-like table.
function func.tail (ls)
assert_arg(1,ls,'table')
local res = {}
for i = 2,#ls do
append(res,ls[i])
end
return res
end
--- create a string representation of a placeholder expression.
-- @param e a placeholder expression
-- @param lastpred not used
function repr (e,lastpred)
local tail = func.tail
if isPE(e) then
local pred = operators[e.op]
local ls = map(repr,e,pred)
if pred then --unary or binary operator
if #ls ~= 1 then
local s = concat(ls,' '..e.op..' ')
if lastpred and lastpred > pred then
s = '('..s..')'
end
return s
else
return e.op..' '..ls[1]
end
else -- either postfix, or a placeholder
if e.op == '[]' then
return ls[1]..'['..ls[2]..']'
elseif e.op == '()' then
local fn
if ls[1] ~= nil then -- was _args, undeclared!
fn = ls[1]
else
fn = ''
end
return fn..'('..concat(tail(ls),',')..')'
else
return e.repr
end
end
elseif type(e) == 'string' then
return '"'..e..'"'
elseif type(e) == 'function' then
local name = func.lookup_imported_name(e)
if name then return name else return tostring(e) end
else
return tostring(e) --should not really get here!
end
end
func.repr = repr
-- collect all the non-PE values in this PE into vlist, and replace each occurence
-- with a constant PH (_C1, etc). Return the maximum placeholder index found.
local collect_values
function collect_values (e,vlist)
if isPE(e) then
if e.op ~= 'X' then
local m = 0
for i,subx in ipairs(e) do
local pe = isPE(subx)
if pe then
if subx.op == 'X' and subx.index == 'wrap' then
subx = subx.repr
pe = false
else
m = max(m,collect_values(subx,vlist))
end
end
if not pe then
append(vlist,subx)
e[i] = CPH(#vlist)
end
end
return m
else -- was a placeholder, it has an index...
return e.index
end
else -- plain value has no placeholder dependence
return 0
end
end
func.collect_values = collect_values
--- instantiate a PE into an actual function. First we find the largest placeholder used,
-- e.g. _2; from this a list of the formal parameters can be build. Then we collect and replace
-- any non-PE values from the PE, and build up a constant binding list.
-- Finally, the expression can be compiled, and e.__PE_function is set.
-- @param e a placeholder expression
-- @return a function
function func.instantiate (e)
local consts,values,parms = {},{},{}
local rep, err, fun
local n = func.collect_values(e,values)
for i = 1,#values do
append(consts,'_C'..i)
if _DEBUG then print(i,values[i]) end
end
for i =1,n do
append(parms,'_'..i)
end
consts = concat(consts,',')
parms = concat(parms,',')
rep = repr(e)
local fstr = ('return function(%s) return function(%s) return %s end end'):format(consts,parms,rep)
if _DEBUG then print(fstr) end
fun,err = loadstring(fstr,'fun')
if not fun then return nil,err end
fun = fun() -- get wrapper
fun = fun(unpack(values)) -- call wrapper (values could be empty)
e.__PE_function = fun
return fun
end
--- instantiate a PE unless it has already been done.
-- @param e a placeholder expression
-- @return the function
function func.I(e)
if rawget(e,'__PE_function') then
return e.__PE_function
else return func.instantiate(e)
end
end
utils.add_function_factory(_PEMT,func.I)
--- bind the first parameter of the function to a value.
-- @class function
-- @name func.curry
-- @param fn a function of one or more arguments
-- @param p a value
-- @return a function of one less argument
-- @usage (curry(math.max,10))(20) == math.max(10,20)
func.curry = utils.bind1
--- create a function which chains two functions.
-- @param f a function of at least one argument
-- @param g a function of at least one argument
-- @return a function
-- @usage printf = compose(io.write,string.format)
function func.compose (f,g)
return function(...) return f(g(...)) end
end
--- bind the arguments of a function to given values.
-- bind(fn,v,_2) is equivalent to curry(fn,v).
-- @param fn a function of at least one argument
-- @param ... values or placeholder variables
-- @return a function
-- @usage (bind(f,_1,a))(b) == f(a,b)
-- @usage (bind(f,_2,_1))(a,b) == f(b,a)
function func.bind(fn,...)
local args = table.pack(...)
local holders,parms,bvalues,values = {},{},{'fn'},{}
local nv,maxplace,varargs = 1,0,false
for i = 1,args.n do
local a = args[i]
if isPE(a) and a.op == 'X' then
append(holders,a.repr)
maxplace = max(maxplace,a.index)
if a.index == 0 then varargs = true end
else
local v = '_v'..nv
append(bvalues,v)
append(holders,v)
append(values,a)
nv = nv + 1
end
end
for np = 1,maxplace do
append(parms,'_'..np)
end
if varargs then append(parms,'...') end
bvalues = concat(bvalues,',')
parms = concat(parms,',')
holders = concat(holders,',')
local fstr = ([[
return function (%s)
return function(%s) return fn(%s) end
end
]]):format(bvalues,parms,holders)
if _DEBUG then print(fstr) end
local res,err = loadstring(fstr)
res = res()
return res(fn,unpack(values))
end
return func
| bsd-3-clause |
Enignite/darkstar | scripts/zones/Rolanberry_Fields/npcs/Saarlan.lua | 17 | 8643 | -----------------------------------
-- Area: Rolanberry Fields
-- NPC: Saarlan
-- Legion NPC
-- @pos 242 24.395 468
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/zones/Rolanberry_Fields/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TITLE = 0;
local MAXIMUS = 0;
local LP = player:getCurrency("legion_point");
local MINIMUS = 0;
if (player:hasKeyItem(LEGION_TOME_PAGE_MAXIMUS)) then
MAXIMUS = 1;
end
if (player:hasKeyItem(LEGION_TOME_PAGE_MINIMUS)) then
MINIMUS = 1;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_LOFTY)) then
TITLE = TITLE+1;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_MIRED)) then
TITLE = TITLE+2;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_SOARING)) then
TITLE = TITLE+4;
end
if (player:hasTitle(SUBJUGATOR_OF_THE_VEILED)) then
TITLE = TITLE+8;
end
if (player:hasTitle(LEGENDARY_LEGIONNAIRE)) then
TITLE = TITLE+16;
end
if (player:getVar("LegionStatus") == 0) then
player:startEvent(8004);
elseif (player:getVar("LegionStatus") == 1) then
player:startEvent(8005, 0, TITLE, MAXIMUS, LP, MINIMUS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u", csid);
-- printf("RESULT: %u", option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u", csid);
-- printf("RESULT: %u", option);
local GIL = player:getGil();
local LP = player:getCurrency("legion_point");
local LP_COST = 0;
local ITEM = 0;
if (csid == 8004) then
player:setVar("LegionStatus",1)
elseif (csid == 8005) then
if (option == 0x0001000A) then
if (GIL >= 360000) then
player:addKeyItem(LEGION_TOME_PAGE_MAXIMUS);
player:delGil(360000);
player:messageSpecial(KEYITEM_OBTAINED, LEGION_TOME_PAGE_MAXIMUS)
else
player:messageSpecial(NOT_ENOUGH_GIL);
end
elseif (option == 0x0001000B) then
if (GIL >= 180000) then
player:addKeyItem(LEGION_TOME_PAGE_MINIMUS);
player:delGil(180000);
player:messageSpecial(KEYITEM_OBTAINED, LEGION_TOME_PAGE_MINIMUS)
else
player:messageSpecial(NOT_ENOUGH_GIL);
end
elseif (option == 0x00000002) then -- Gaiardas Ring
LP_COST = 1000;
ITEM = 10775
elseif (option == 0x00010002) then -- Gaubious Ring
LP_COST = 1000;
ITEM = 10776;
elseif (option == 0x00020002) then -- Caloussu Ring
LP_COST = 1000;
ITEM = 10777;
elseif (option == 0x00030002) then -- Nanger Ring
LP_COST = 1000;
ITEM = 10778;
elseif (option == 0x00040002) then -- Sophia Ring
LP_COST = 1000;
ITEM = 10779;
elseif (option == 0x00050002) then -- Quies Ring
LP_COST = 1000;
ITEM = 10780;
elseif (option == 0x00060002) then -- Cynosure Ring
LP_COST = 1000;
ITEM = 10781;
elseif (option == 0x00070002) then -- Ambuscade Ring
LP_COST = 1000;
ITEM = 10782;
elseif (option == 0x00080002) then -- Veneficium Ring
LP_COST = 1000;
ITEM = 10783;
elseif (option == 0x00090002) then -- Calma Armet ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10890;
elseif (option == 0x000A0002) then -- Mustela Mask ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10891;
elseif (option == 0x000B0002) then -- Magavan Beret ...Requires title: "Subjugator of the Lofty"
LP_COST = 4500;
ITEM = 10892;
elseif (option == 0x000C0002) then -- Calma Gauntlets ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10512;
elseif (option == 0x000D0002) then -- Mustela Gloves ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10513;
elseif (option == 0x000E0002) then -- Magavan Mitts ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 10514;
elseif (option == 0x000F0002) then -- Calma Hose ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11980;
elseif (option == 0x00100002) then -- Mustela Brais ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11981;
elseif (option == 0x00110002) then -- Magavan Slops ...Requires title: "Subjugator of the Soaring"
LP_COST = 4500;
ITEM = 11982;
elseif (option == 0x00120002) then -- Calma Leggings ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10610;
elseif (option == 0x00130002) then -- Mustela Boots ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10611;
elseif (option == 0x00140002) then -- Magavan Clogs ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 10612;
elseif (option == 0x00150002) then -- Calma Breastplate ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10462;
elseif (option == 0x00160002) then -- Mustela Harness ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10463;
elseif (option == 0x00170002) then -- Magavan Frock ...Requires title: "Legendary Legionnaire"
LP_COST = 10000;
ITEM = 10464;
elseif (option == 0x00180002) then -- Corybant Pearl ...Requires title: "Subjugator of the Lofty"
LP_COST = 3000;
ITEM = 11044;
elseif (option == 0x00190002) then -- Saviesa Pearl ...Requires title: "Subjugator of the Mired"
LP_COST = 3000;
ITEM = 11045;
elseif (option == 0x001A0002) then -- Ouesk Pearl ...Requires title: "Subjugator of the Soaring"
LP_COST = 3000;
ITEM = 11046;
elseif (option == 0x001B0002) then -- Belatz Pearl ...Requires title: "Subjugator of the Soaring"
LP_COST = 3000;
ITEM = 11047;
elseif (option == 0x001C0002) then -- Cytherea Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11048;
elseif (option == 0x001D0002) then -- Myrddin Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11049;
elseif (option == 0x001E0002) then -- Puissant Pearl ...Requires title: "Subjugator of the Veiled"
LP_COST = 3000;
ITEM = 11050;
elseif (option == 0x001F0002) then -- Dhanurveda Ring ...Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10784;
elseif (option == 0000200002) then -- Provocare Ring ......Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10785;
elseif (option == 0000210002) then -- Mediator's Ring ...Requires title: "Legendary Legionnaire"
LP_COST = 6000;
ITEM = 10786;
end
end
if (LP < LP_COST) then
player:messageSpecial(LACK_LEGION_POINTS);
elseif (ITEM > 0) then
if (player:getFreeSlotsCount() >=1) then
player:delCurrency("legion_point", LP_COST);
player:addItem(ITEM, 1);
player:messageSpecial(ITEM_OBTAINED, ITEM);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, ITEM);
end
end
end; | gpl-3.0 |
SedueRey/interestelegram | plugins/invite.lua | 7 | 1036 | -- Invite other user to the chat group.
-- Use !invite name User_name or !invite id id_number
-- The User_name is the print_name (there are no spaces but _)
do
local function run(msg, matches)
-- User submitted a user name
if matches[1] == "name" then
user = matches[2]
user = string.gsub(user," ","_")
end
-- User submitted an id
if matches[1] == "id" then
user = matches[2]
user = 'user#id'..user
end
-- The message must come from a chat group
if msg.to.type == 'chat' then
chat = 'chat#id'..msg.to.id
else
return 'This isnt a chat group!'
end
print ("Trying to add: "..user.." to "..chat)
status = chat_add_user (chat, user, ok_cb, false)
if not status then
return "An error happened"
end
return "Added user: "..user.." to "..chat
end
return {
description = "Invite other user to the chat group",
usage = {
"!invite name [user_name]",
"!invite id [user_id]" },
patterns = {
"^!invite (name) (.*)$",
"^!invite (id) (%d+)$"
},
run = run
}
end | gpl-2.0 |
Enignite/darkstar | scripts/globals/items/balik_sis.lua | 35 | 1661 | -----------------------------------------
-- ID: 5600
-- Item: Balik Sis
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 4
-- Mind -2
-- Attack % 13
-- Attack Cap 40
-- Ranged ACC 1
-- Ranged ATT % 13
-- Ranged ATT Cap 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,1800,5600);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -2);
target:addMod(MOD_FOOD_ATTP, 13);
target:addMod(MOD_FOOD_ATT_CAP, 40);
target:addMod(MOD_RACC, 1);
target:addMod(MOD_FOOD_RATTP, 13);
target:addMod(MOD_FOOD_RATT_CAP, 40);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -2);
target:delMod(MOD_FOOD_ATTP, 13);
target:delMod(MOD_FOOD_ATT_CAP, 40);
target:delMod(MOD_RACC, 1);
target:delMod(MOD_FOOD_RATTP, 13);
target:delMod(MOD_FOOD_RATT_CAP, 40);
end;
| gpl-3.0 |
ntuhpc/modulefiles | all/PCRE/8.38-foss-2016b.lua | 1 | 1026 | help([[
The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax
and semantics as Perl 5.
- Homepage: http://www.pcre.org/]])
whatis([[Description:
The PCRE library is a set of functions that implement regular expression pattern matching using the same syntax
and semantics as Perl 5.
- Homepage: http://www.pcre.org/]])
local root = "/opt/apps/software/PCRE/8.38-foss-2016b"
conflict("PCRE")
if not isloaded("foss/2016b") then
load("foss/2016b")
end
prepend_path("CPATH", pathJoin(root, "include"))
prepend_path("LD_LIBRARY_PATH", pathJoin(root, "lib"))
prepend_path("LIBRARY_PATH", pathJoin(root, "lib"))
prepend_path("MANPATH", pathJoin(root, "share/man"))
prepend_path("PATH", pathJoin(root, "bin"))
prepend_path("PKG_CONFIG_PATH", pathJoin(root, "lib/pkgconfig"))
setenv("EBROOTPCRE", root)
setenv("EBVERSIONPCRE", "8.38")
setenv("EBDEVELPCRE", pathJoin(root, "easybuild/PCRE-8.38-foss-2016b-easybuild-devel"))
-- Built with EasyBuild version 3.1.0
| mit |
fcpxhacks/fcpxhacks | src/extensions/cp/i18n/language.lua | 2 | 37994 | --- === cp.i18n.language ===
---
--- Provides the set of ISO 693-1/2/3 language codes and names.
--- The return value can be iterated as a list, or you can find a
--- specific language by either its two-character code (`alpha2`), English-based three-character code (`alpha3B`),
--- local name, or English name.
---
--- For example:
---
--- ```lua
--- local lang = require("cp.i18n.language")
--- print(lang[1]) -- table for "Abkhaz" language
--- print(lang.fr) -- table for "French"
--- print(lang.fre) -- same table for "French"
--- print(lang["Français"]) -- same table for "French"
--- print(lang.French) -- same table for "French"
--- ```
---
--- This will return a table containing the following:
--- * `alpha2` - The 2-character language code (eg. "en", "fr").
--- * `alpha3` - The 3-character language code (eg. "eng", "fra").
--- * `alpha3B` - The 3-character English-derived language code (eg. "eng", "fre").
--- * `alpha3T` - The 3-character local-language-derived code (eg. "eng", "fra").
--- * `localName` - The name in the local language (eg. "English", "Français").
--- * `name` - The name in English (eg. "English", "French").
---
--- Note: This data was adapted from [arnubol's code](https://github.com/anurbol/languages-iso-639-1-2-3-json)
--- under an [MIT license](https://raw.githubusercontent.com/anurbol/languages-iso-639-1-2-3-json/master/LICENSE).
-- local log = require("hs.logger").new("language")
local language = {
{
alpha2 = "ab",
alpha3 = "abk",
alpha3B = "abk",
alpha3T = "abk",
alpha3X = "abk",
localName = "Аҧсуа",
name = "Abkhaz"
},
{
alpha2 = "aa",
alpha3 = "aar",
alpha3B = "aar",
alpha3T = "aar",
alpha3X = "aar",
localName = "Afaraf",
name = "Afar"
},
{
alpha2 = "af",
alpha3 = "afr",
alpha3B = "afr",
alpha3T = "afr",
alpha3X = "afr",
localName = "Afrikaans",
name = "Afrikaans"
},
{
alpha2 = "ak",
alpha3 = "aka",
alpha3B = "aka",
alpha3T = "aka",
alpha3X = "aka",
localName = "Akan",
name = "Akan"
},
{
alpha2 = "sq",
alpha3 = "sqi",
alpha3B = "alb",
alpha3T = "sqi",
alpha3X = "sqi",
localName = "Shqip",
name = "Albanian"
},
{
alpha2 = "am",
alpha3 = "amh",
alpha3B = "amh",
alpha3T = "amh",
alpha3X = "amh",
localName = "አማርኛ",
name = "Amharic"
},
{
alpha2 = "ar",
alpha3 = "ara",
alpha3B = "ara",
alpha3T = "ara",
alpha3X = "ara",
localName = "العربية",
name = "Arabic"
},
{
alpha2 = "an",
alpha3 = "arg",
alpha3B = "arg",
alpha3T = "arg",
alpha3X = "arg",
localName = "Aragonés",
name = "Aragonese"
},
{
alpha2 = "hy",
alpha3 = "hye",
alpha3B = "arm",
alpha3T = "hye",
alpha3X = "hye",
localName = "Հայերեն",
name = "Armenian"
},
{
alpha2 = "as",
alpha3 = "asm",
alpha3B = "asm",
alpha3T = "asm",
alpha3X = "asm",
localName = "অসমীয়া",
name = "Assamese"
},
{
alpha2 = "av",
alpha3 = "ava",
alpha3B = "ava",
alpha3T = "ava",
alpha3X = "ava",
localName = "Авар",
name = "Avaric"
},
{
alpha2 = "ae",
alpha3 = "ave",
alpha3B = "ave",
alpha3T = "ave",
alpha3X = "ave",
localName = "avesta",
name = "Avestan"
},
{
alpha2 = "ay",
alpha3 = "aym",
alpha3B = "aym",
alpha3T = "aym",
alpha3X = "aym",
localName = "Aymar",
name = "Aymara"
},
{
alpha2 = "az",
alpha3 = "aze",
alpha3B = "aze",
alpha3T = "aze",
alpha3X = "aze",
localName = "Azərbaycanca",
name = "Azerbaijani"
},
{
alpha2 = "bm",
alpha3 = "bam",
alpha3B = "bam",
alpha3T = "bam",
alpha3X = "bam",
localName = "Bamanankan",
name = "Bambara"
},
{
alpha2 = "ba",
alpha3 = "bak",
alpha3B = "bak",
alpha3T = "bak",
alpha3X = "bak",
localName = "Башҡортса",
name = "Bashkir"
},
{
alpha2 = "eu",
alpha3 = "eus",
alpha3B = "baq",
alpha3T = "eus",
alpha3X = "eus",
localName = "Euskara",
name = "Basque"
},
{
alpha2 = "be",
alpha3 = "bel",
alpha3B = "bel",
alpha3T = "bel",
alpha3X = "bel",
localName = "Беларуская",
name = "Belarusian"
},
{
alpha2 = "bn",
alpha3 = "ben",
alpha3B = "ben",
alpha3T = "ben",
alpha3X = "ben",
localName = "বাংলা",
name = "Bengali"
},
{
alpha2 = "bh",
alpha3 = "bih",
alpha3B = "bih",
alpha3T = "bih",
alpha3X = "bih",
localName = "भोजपुरी",
name = "Bihari"
},
{
alpha2 = "bi",
alpha3 = "bis",
alpha3B = "bis",
alpha3T = "bis",
alpha3X = "bis",
localName = "Bislama",
name = "Bislama"
},
{
alpha2 = "bs",
alpha3 = "bos",
alpha3B = "bos",
alpha3T = "bos",
alpha3X = "bos",
localName = "Bosanski",
name = "Bosnian"
},
{
alpha2 = "br",
alpha3 = "bre",
alpha3B = "bre",
alpha3T = "bre",
alpha3X = "bre",
localName = "Brezhoneg",
name = "Breton"
},
{
alpha2 = "bg",
alpha3 = "bul",
alpha3B = "bul",
alpha3T = "bul",
alpha3X = "bul",
localName = "Български",
name = "Bulgarian"
},
{
alpha2 = "my",
alpha3 = "mya",
alpha3B = "bur",
alpha3T = "mya",
alpha3X = "mya",
localName = "မြန်မာဘာသာ",
name = "Burmese"
},
{
alpha2 = "ca",
alpha3 = "cat",
alpha3B = "cat",
alpha3T = "cat",
alpha3X = "cat",
localName = "Català",
name = "Catalan"
},
{
alpha2 = "ch",
alpha3 = "cha",
alpha3B = "cha",
alpha3T = "cha",
alpha3X = "cha",
localName = "Chamoru",
name = "Chamorro"
},
{
alpha2 = "ce",
alpha3 = "che",
alpha3B = "che",
alpha3T = "che",
alpha3X = "che",
localName = "Нохчийн",
name = "Chechen"
},
{
alpha2 = "ny",
alpha3 = "nya",
alpha3B = "nya",
alpha3T = "nya",
alpha3X = "nya",
localName = "Chichewa",
name = "Chichewa"
},
{
alpha2 = "zh",
alpha3 = "zho",
alpha3B = "chi",
alpha3T = "zho",
alpha3X = "zho",
localName = "中文",
name = "Chinese"
},
{
alpha2 = "cv",
alpha3 = "chv",
alpha3B = "chv",
alpha3T = "chv",
alpha3X = "chv",
localName = "Чӑвашла",
name = "Chuvash"
},
{
alpha2 = "kw",
alpha3 = "cor",
alpha3B = "cor",
alpha3T = "cor",
alpha3X = "cor",
localName = "Kernewek",
name = "Cornish"
},
{
alpha2 = "co",
alpha3 = "cos",
alpha3B = "cos",
alpha3T = "cos",
alpha3X = "cos",
localName = "Corsu",
name = "Corsican"
},
{
alpha2 = "cr",
alpha3 = "cre",
alpha3B = "cre",
alpha3T = "cre",
alpha3X = "cre",
localName = "ᓀᐦᐃᔭᐍᐏᐣ",
name = "Cree"
},
{
alpha2 = "hr",
alpha3 = "hrv",
alpha3B = "hrv",
alpha3T = "hrv",
alpha3X = "hrv",
localName = "Hrvatski",
name = "Croatian"
},
{
alpha2 = "cs",
alpha3 = "ces",
alpha3B = "cze",
alpha3T = "ces",
alpha3X = "ces",
localName = "Čeština",
name = "Czech"
},
{
alpha2 = "da",
alpha3 = "dan",
alpha3B = "dan",
alpha3T = "dan",
alpha3X = "dan",
localName = "Dansk",
name = "Danish"
},
{
alpha2 = "dv",
alpha3 = "div",
alpha3B = "div",
alpha3T = "div",
alpha3X = "div",
localName = "Divehi",
name = "Divehi"
},
{
alpha2 = "nl",
alpha3 = "nld",
alpha3B = "dut",
alpha3T = "nld",
alpha3X = "nld",
localName = "Nederlands",
name = "Dutch"
},
{
alpha2 = "dz",
alpha3 = "dzo",
alpha3B = "dzo",
alpha3T = "dzo",
alpha3X = "dzo",
localName = "རྫོང་ཁ",
name = "Dzongkha"
},
{
alpha2 = "en",
alpha3 = "eng",
alpha3B = "eng",
alpha3T = "eng",
alpha3X = "eng",
localName = "English",
name = "English"
},
{
alpha2 = "eo",
alpha3 = "epo",
alpha3B = "epo",
alpha3T = "epo",
alpha3X = "epo",
localName = "Esperanto",
name = "Esperanto"
},
{
alpha2 = "et",
alpha3 = "est",
alpha3B = "est",
alpha3T = "est",
alpha3X = "est",
localName = "Eesti",
name = "Estonian"
},
{
alpha2 = "ee",
alpha3 = "ewe",
alpha3B = "ewe",
alpha3T = "ewe",
alpha3X = "ewe",
localName = "Eʋegbe",
name = "Ewe"
},
{
alpha2 = "fo",
alpha3 = "fao",
alpha3B = "fao",
alpha3T = "fao",
alpha3X = "fao",
localName = "Føroyskt",
name = "Faroese"
},
{
alpha2 = "fj",
alpha3 = "fij",
alpha3B = "fij",
alpha3T = "fij",
alpha3X = "fij",
localName = "Na Vosa Vaka-Viti",
name = "Fijian"
},
{
alpha2 = "fi",
alpha3 = "fin",
alpha3B = "fin",
alpha3T = "fin",
alpha3X = "fin",
localName = "Suomi",
name = "Finnish"
},
{
alpha2 = "fr",
alpha3 = "fra",
alpha3B = "fre",
alpha3T = "fra",
alpha3X = "fra",
localName = "Français",
name = "French"
},
{
alpha2 = "ff",
alpha3 = "ful",
alpha3B = "ful",
alpha3T = "ful",
alpha3X = "ful",
localName = "Fulfulde",
name = "Fula"
},
{
alpha2 = "gl",
alpha3 = "glg",
alpha3B = "glg",
alpha3T = "glg",
alpha3X = "glg",
localName = "Galego",
name = "Galician"
},
{
alpha2 = "ka",
alpha3 = "kat",
alpha3B = "geo",
alpha3T = "kat",
alpha3X = "kat",
localName = "ქართული",
name = "Georgian"
},
{
alpha2 = "de",
alpha3 = "deu",
alpha3B = "ger",
alpha3T = "deu",
alpha3X = "deu",
localName = "Deutsch",
name = "German"
},
{
alpha2 = "el",
alpha3 = "ell",
alpha3B = "gre",
alpha3T = "ell",
alpha3X = "ell",
localName = "Ελληνικά",
name = "Greek"
},
{
alpha2 = "gn",
alpha3 = "grn",
alpha3B = "grn",
alpha3T = "grn",
alpha3X = "grn",
localName = "Avañe'ẽ",
name = "Guaraní"
},
{
alpha2 = "gu",
alpha3 = "guj",
alpha3B = "guj",
alpha3T = "guj",
alpha3X = "guj",
localName = "ગુજરાતી",
name = "Gujarati"
},
{
alpha2 = "ht",
alpha3 = "hat",
alpha3B = "hat",
alpha3T = "hat",
alpha3X = "hat",
localName = "Kreyòl Ayisyen",
name = "Haitian"
},
{
alpha2 = "ha",
alpha3 = "hau",
alpha3B = "hau",
alpha3T = "hau",
alpha3X = "hau",
localName = "هَوُسَ",
name = "Hausa"
},
{
alpha2 = "he",
alpha3 = "heb",
alpha3B = "heb",
alpha3T = "heb",
alpha3X = "heb",
localName = "עברית",
name = "Hebrew"
},
{
alpha2 = "hz",
alpha3 = "her",
alpha3B = "her",
alpha3T = "her",
alpha3X = "her",
localName = "Otjiherero",
name = "Herero"
},
{
alpha2 = "hi",
alpha3 = "hin",
alpha3B = "hin",
alpha3T = "hin",
alpha3X = "hin",
localName = "हिन्दी",
name = "Hindi"
},
{
alpha2 = "ho",
alpha3 = "hmo",
alpha3B = "hmo",
alpha3T = "hmo",
alpha3X = "hmo",
localName = "Hiri Motu",
name = "Hiri Motu"
},
{
alpha2 = "hu",
alpha3 = "hun",
alpha3B = "hun",
alpha3T = "hun",
alpha3X = "hun",
localName = "Magyar",
name = "Hungarian"
},
{
alpha2 = "ia",
alpha3 = "ina",
alpha3B = "ina",
alpha3T = "ina",
alpha3X = "ina",
localName = "Interlingua",
name = "Interlingua"
},
{
alpha2 = "id",
alpha3 = "ind",
alpha3B = "ind",
alpha3T = "ind",
alpha3X = "ind",
localName = "Bahasa Indonesia",
name = "Indonesian"
},
{
alpha2 = "ie",
alpha3 = "ile",
alpha3B = "ile",
alpha3T = "ile",
alpha3X = "ile",
localName = "Interlingue",
name = "Interlingue"
},
{
alpha2 = "ga",
alpha3 = "gle",
alpha3B = "gle",
alpha3T = "gle",
alpha3X = "gle",
localName = "Gaeilge",
name = "Irish"
},
{
alpha2 = "ig",
alpha3 = "ibo",
alpha3B = "ibo",
alpha3T = "ibo",
alpha3X = "ibo",
localName = "Igbo",
name = "Igbo"
},
{
alpha2 = "ik",
alpha3 = "ipk",
alpha3B = "ipk",
alpha3T = "ipk",
alpha3X = "ipk",
localName = "Iñupiak",
name = "Inupiaq"
},
{
alpha2 = "io",
alpha3 = "ido",
alpha3B = "ido",
alpha3T = "ido",
alpha3X = "ido",
localName = "Ido",
name = "Ido"
},
{
alpha2 = "is",
alpha3 = "isl",
alpha3B = "ice",
alpha3T = "isl",
alpha3X = "isl",
localName = "Íslenska",
name = "Icelandic"
},
{
alpha2 = "it",
alpha3 = "ita",
alpha3B = "ita",
alpha3T = "ita",
alpha3X = "ita",
localName = "Italiano",
name = "Italian"
},
{
alpha2 = "iu",
alpha3 = "iku",
alpha3B = "iku",
alpha3T = "iku",
alpha3X = "iku",
localName = "ᐃᓄᒃᑎᑐᑦ",
name = "Inuktitut"
},
{
alpha2 = "ja",
alpha3 = "jpn",
alpha3B = "jpn",
alpha3T = "jpn",
alpha3X = "jpn",
localName = "日本語",
name = "Japanese"
},
{
alpha2 = "jv",
alpha3 = "jav",
alpha3B = "jav",
alpha3T = "jav",
alpha3X = "jav",
localName = "Basa Jawa",
name = "Javanese"
},
{
alpha2 = "kl",
alpha3 = "kal",
alpha3B = "kal",
alpha3T = "kal",
alpha3X = "kal",
localName = "Kalaallisut",
name = "Kalaallisut"
},
{
alpha2 = "kn",
alpha3 = "kan",
alpha3B = "kan",
alpha3T = "kan",
alpha3X = "kan",
localName = "ಕನ್ನಡ",
name = "Kannada"
},
{
alpha2 = "kr",
alpha3 = "kau",
alpha3B = "kau",
alpha3T = "kau",
alpha3X = "kau",
localName = "Kanuri",
name = "Kanuri"
},
{
alpha2 = "ks",
alpha3 = "kas",
alpha3B = "kas",
alpha3T = "kas",
alpha3X = "kas",
localName = "كشميري",
name = "Kashmiri"
},
{
alpha2 = "kk",
alpha3 = "kaz",
alpha3B = "kaz",
alpha3T = "kaz",
alpha3X = "kaz",
localName = "Қазақша",
name = "Kazakh"
},
{
alpha2 = "km",
alpha3 = "khm",
alpha3B = "khm",
alpha3T = "khm",
alpha3X = "khm",
localName = "ភាសាខ្មែរ",
name = "Khmer"
},
{
alpha2 = "ki",
alpha3 = "kik",
alpha3B = "kik",
alpha3T = "kik",
alpha3X = "kik",
localName = "Gĩkũyũ",
name = "Kikuyu"
},
{
alpha2 = "rw",
alpha3 = "kin",
alpha3B = "kin",
alpha3T = "kin",
alpha3X = "kin",
localName = "Kinyarwanda",
name = "Kinyarwanda"
},
{
alpha2 = "ky",
alpha3 = "kir",
alpha3B = "kir",
alpha3T = "kir",
alpha3X = "kir",
localName = "Кыргызча",
name = "Kyrgyz"
},
{
alpha2 = "kv",
alpha3 = "kom",
alpha3B = "kom",
alpha3T = "kom",
alpha3X = "kom",
localName = "Коми",
name = "Komi"
},
{
alpha2 = "kg",
alpha3 = "kon",
alpha3B = "kon",
alpha3T = "kon",
alpha3X = "kon",
localName = "Kongo",
name = "Kongo"
},
{
alpha2 = "ko",
alpha3 = "kor",
alpha3B = "kor",
alpha3T = "kor",
alpha3X = "kor",
localName = "한국어",
name = "Korean"
},
{
alpha2 = "ku",
alpha3 = "kur",
alpha3B = "kur",
alpha3T = "kur",
alpha3X = "kur",
localName = "Kurdî",
name = "Kurdish"
},
{
alpha2 = "kj",
alpha3 = "kua",
alpha3B = "kua",
alpha3T = "kua",
alpha3X = "kua",
localName = "Kuanyama",
name = "Kwanyama"
},
{
alpha2 = "la",
alpha3 = "lat",
alpha3B = "lat",
alpha3T = "lat",
alpha3X = "lat",
localName = "Latina",
name = "Latin"
},
{
alpha2 = "lb",
alpha3 = "ltz",
alpha3B = "ltz",
alpha3T = "ltz",
alpha3X = "ltz",
localName = "Lëtzebuergesch",
name = "Luxembourgish"
},
{
alpha2 = "lg",
alpha3 = "lug",
alpha3B = "lug",
alpha3T = "lug",
alpha3X = "lug",
localName = "Luganda",
name = "Ganda"
},
{
alpha2 = "li",
alpha3 = "lim",
alpha3B = "lim",
alpha3T = "lim",
alpha3X = "lim",
localName = "Limburgs",
name = "Limburgish"
},
{
alpha2 = "ln",
alpha3 = "lin",
alpha3B = "lin",
alpha3T = "lin",
alpha3X = "lin",
localName = "Lingála",
name = "Lingala"
},
{
alpha2 = "lo",
alpha3 = "lao",
alpha3B = "lao",
alpha3T = "lao",
alpha3X = "lao",
localName = "ພາສາລາວ",
name = "Lao"
},
{
alpha2 = "lt",
alpha3 = "lit",
alpha3B = "lit",
alpha3T = "lit",
alpha3X = "lit",
localName = "Lietuvių",
name = "Lithuanian"
},
{
alpha2 = "lu",
alpha3 = "lub",
alpha3B = "lub",
alpha3T = "lub",
alpha3X = "lub",
localName = "Tshiluba",
name = "Luba-Katanga"
},
{
alpha2 = "lv",
alpha3 = "lav",
alpha3B = "lav",
alpha3T = "lav",
alpha3X = "lav",
localName = "Latviešu",
name = "Latvian"
},
{
alpha2 = "gv",
alpha3 = "glv",
alpha3B = "glv",
alpha3T = "glv",
alpha3X = "glv",
localName = "Gaelg",
name = "Manx"
},
{
alpha2 = "mk",
alpha3 = "mkd",
alpha3B = "mac",
alpha3T = "mkd",
alpha3X = "mkd",
localName = "Македонски",
name = "Macedonian"
},
{
alpha2 = "mg",
alpha3 = "mlg",
alpha3B = "mlg",
alpha3T = "mlg",
alpha3X = "mlg",
localName = "Malagasy",
name = "Malagasy"
},
{
alpha2 = "ms",
alpha3 = "msa",
alpha3B = "may",
alpha3T = "msa",
alpha3X = "msa",
localName = "Bahasa Melayu",
name = "Malay"
},
{
alpha2 = "ml",
alpha3 = "mal",
alpha3B = "mal",
alpha3T = "mal",
alpha3X = "mal",
localName = "മലയാളം",
name = "Malayalam"
},
{
alpha2 = "mt",
alpha3 = "mlt",
alpha3B = "mlt",
alpha3T = "mlt",
alpha3X = "mlt",
localName = "Malti",
name = "Maltese"
},
{
alpha2 = "mi",
alpha3 = "mri",
alpha3B = "mao",
alpha3T = "mri",
alpha3X = "mri",
localName = "Māori",
name = "Māori"
},
{
alpha2 = "mr",
alpha3 = "mar",
alpha3B = "mar",
alpha3T = "mar",
alpha3X = "mar",
localName = "मराठी",
name = "Marathi"
},
{
alpha2 = "mh",
alpha3 = "mah",
alpha3B = "mah",
alpha3T = "mah",
alpha3X = "mah",
localName = "Kajin M̧ajeļ",
name = "Marshallese"
},
{
alpha2 = "mn",
alpha3 = "mon",
alpha3B = "mon",
alpha3T = "mon",
alpha3X = "mon",
localName = "Монгол",
name = "Mongolian"
},
{
alpha2 = "na",
alpha3 = "nau",
alpha3B = "nau",
alpha3T = "nau",
alpha3X = "nau",
localName = "Dorerin Naoero",
name = "Nauru"
},
{
alpha2 = "nv",
alpha3 = "nav",
alpha3B = "nav",
alpha3T = "nav",
alpha3X = "nav",
localName = "Diné Bizaad",
name = "Navajo"
},
{
alpha2 = "nd",
alpha3 = "nde",
alpha3B = "nde",
alpha3T = "nde",
alpha3X = "nde",
localName = "isiNdebele",
name = "Northern Ndebele"
},
{
alpha2 = "ne",
alpha3 = "nep",
alpha3B = "nep",
alpha3T = "nep",
alpha3X = "nep",
localName = "नेपाली",
name = "Nepali"
},
{
alpha2 = "ng",
alpha3 = "ndo",
alpha3B = "ndo",
alpha3T = "ndo",
alpha3X = "ndo",
localName = "Owambo",
name = "Ndonga"
},
{
alpha2 = "nb",
alpha3 = "nob",
alpha3B = "nob",
alpha3T = "nob",
alpha3X = "nob",
localName = "Norsk (Bokmål)",
name = "Norwegian Bokmål"
},
{
alpha2 = "nn",
alpha3 = "nno",
alpha3B = "nno",
alpha3T = "nno",
alpha3X = "nno",
localName = "Norsk (Nynorsk)",
name = "Norwegian Nynorsk"
},
{
alpha2 = "no",
alpha3 = "nor",
alpha3B = "nor",
alpha3T = "nor",
alpha3X = "nor",
localName = "Norsk",
name = "Norwegian"
},
{
alpha2 = "ii",
alpha3 = "iii",
alpha3B = "iii",
alpha3T = "iii",
alpha3X = "iii",
localName = "ꆈꌠ꒿ Nuosuhxop",
name = "Nuosu"
},
{
alpha2 = "nr",
alpha3 = "nbl",
alpha3B = "nbl",
alpha3T = "nbl",
alpha3X = "nbl",
localName = "isiNdebele",
name = "Southern Ndebele"
},
{
alpha2 = "oc",
alpha3 = "oci",
alpha3B = "oci",
alpha3T = "oci",
alpha3X = "oci",
localName = "Occitan",
name = "Occitan"
},
{
alpha2 = "oj",
alpha3 = "oji",
alpha3B = "oji",
alpha3T = "oji",
alpha3X = "oji",
localName = "ᐊᓂᔑᓈᐯᒧᐎᓐ",
name = "Ojibwe"
},
{
alpha2 = "cu",
alpha3 = "chu",
alpha3B = "chu",
alpha3T = "chu",
alpha3X = "chu",
localName = "Словѣ́ньскъ",
name = "Old Church Slavonic"
},
{
alpha2 = "om",
alpha3 = "orm",
alpha3B = "orm",
alpha3T = "orm",
alpha3X = "orm",
localName = "Afaan Oromoo",
name = "Oromo"
},
{
alpha2 = "or",
alpha3 = "ori",
alpha3B = "ori",
alpha3T = "ori",
alpha3X = "ori",
localName = "ଓଡି଼ଆ",
name = "Oriya"
},
{
alpha2 = "os",
alpha3 = "oss",
alpha3B = "oss",
alpha3T = "oss",
alpha3X = "oss",
localName = "Ирон æвзаг",
name = "Ossetian"
},
{
alpha2 = "pa",
alpha3 = "pan",
alpha3B = "pan",
alpha3T = "pan",
alpha3X = "pan",
localName = "ਪੰਜਾਬੀ",
name = "Panjabi"
},
{
alpha2 = "pi",
alpha3 = "pli",
alpha3B = "pli",
alpha3T = "pli",
alpha3X = "pli",
localName = "पाऴि",
name = "Pāli"
},
{
alpha2 = "fa",
alpha3 = "fas",
alpha3B = "per",
alpha3T = "fas",
alpha3X = "fas",
localName = "فارسی",
name = "Persian"
},
{
alpha2 = "pl",
alpha3 = "pol",
alpha3B = "pol",
alpha3T = "pol",
alpha3X = "pol",
localName = "Polski",
name = "Polish"
},
{
alpha2 = "ps",
alpha3 = "pus",
alpha3B = "pus",
alpha3T = "pus",
alpha3X = "pus",
localName = "پښتو",
name = "Pashto"
},
{
alpha2 = "pt",
alpha3 = "por",
alpha3B = "por",
alpha3T = "por",
alpha3X = "por",
localName = "Português",
name = "Portuguese"
},
{
alpha2 = "qu",
alpha3 = "que",
alpha3B = "que",
alpha3T = "que",
alpha3X = "que",
localName = "Runa Simi",
name = "Quechua"
},
{
alpha2 = "rm",
alpha3 = "roh",
alpha3B = "roh",
alpha3T = "roh",
alpha3X = "roh",
localName = "Rumantsch",
name = "Romansh"
},
{
alpha2 = "rn",
alpha3 = "run",
alpha3B = "run",
alpha3T = "run",
alpha3X = "run",
localName = "Kirundi",
name = "Kirundi"
},
{
alpha2 = "ro",
alpha3 = "ron",
alpha3B = "rum",
alpha3T = "ron",
alpha3X = "ron",
localName = "Română",
name = "Romanian"
},
{
alpha2 = "ru",
alpha3 = "rus",
alpha3B = "rus",
alpha3T = "rus",
alpha3X = "rus",
localName = "Русский",
name = "Russian"
},
{
alpha2 = "sa",
alpha3 = "san",
alpha3B = "san",
alpha3T = "san",
alpha3X = "san",
localName = "संस्कृतम्",
name = "Sanskrit"
},
{
alpha2 = "sc",
alpha3 = "srd",
alpha3B = "srd",
alpha3T = "srd",
alpha3X = "srd",
localName = "Sardu",
name = "Sardinian"
},
{
alpha2 = "sd",
alpha3 = "snd",
alpha3B = "snd",
alpha3T = "snd",
alpha3X = "snd",
localName = "سنڌي",
name = "Sindhi"
},
{
alpha2 = "se",
alpha3 = "sme",
alpha3B = "sme",
alpha3T = "sme",
alpha3X = "sme",
localName = "Sámegiella",
name = "Northern Sami"
},
{
alpha2 = "sm",
alpha3 = "smo",
alpha3B = "smo",
alpha3T = "smo",
alpha3X = "smo",
localName = "Gagana Sāmoa",
name = "Samoan"
},
{
alpha2 = "sg",
alpha3 = "sag",
alpha3B = "sag",
alpha3T = "sag",
alpha3X = "sag",
localName = "Sängö",
name = "Sango"
},
{
alpha2 = "sr",
alpha3 = "srp",
alpha3B = "srp",
alpha3T = "srp",
alpha3X = "srp",
localName = "Српски",
name = "Serbian"
},
{
alpha2 = "gd",
alpha3 = "gla",
alpha3B = "gla",
alpha3T = "gla",
alpha3X = "gla",
localName = "Gàidhlig",
name = "Gaelic"
},
{
alpha2 = "sn",
alpha3 = "sna",
alpha3B = "sna",
alpha3T = "sna",
alpha3X = "sna",
localName = "ChiShona",
name = "Shona"
},
{
alpha2 = "si",
alpha3 = "sin",
alpha3B = "sin",
alpha3T = "sin",
alpha3X = "sin",
localName = "සිංහල",
name = "Sinhala"
},
{
alpha2 = "sk",
alpha3 = "slk",
alpha3B = "slo",
alpha3T = "slk",
alpha3X = "slk",
localName = "Slovenčina",
name = "Slovak"
},
{
alpha2 = "sl",
alpha3 = "slv",
alpha3B = "slv",
alpha3T = "slv",
alpha3X = "slv",
localName = "Slovenščina",
name = "Slovene"
},
{
alpha2 = "so",
alpha3 = "som",
alpha3B = "som",
alpha3T = "som",
alpha3X = "som",
localName = "Soomaaliga",
name = "Somali"
},
{
alpha2 = "st",
alpha3 = "sot",
alpha3B = "sot",
alpha3T = "sot",
alpha3X = "sot",
localName = "Sesotho",
name = "Southern Sotho"
},
{
alpha2 = "es",
alpha3 = "spa",
alpha3B = "spa",
alpha3T = "spa",
alpha3X = "spa",
localName = "Español",
name = "Spanish"
},
{
alpha2 = "su",
alpha3 = "sun",
alpha3B = "sun",
alpha3T = "sun",
alpha3X = "sun",
localName = "Basa Sunda",
name = "Sundanese"
},
{
alpha2 = "sw",
alpha3 = "swa",
alpha3B = "swa",
alpha3T = "swa",
alpha3X = "swa",
localName = "Kiswahili",
name = "Swahili"
},
{
alpha2 = "ss",
alpha3 = "ssw",
alpha3B = "ssw",
alpha3T = "ssw",
alpha3X = "ssw",
localName = "SiSwati",
name = "Swati"
},
{
alpha2 = "sv",
alpha3 = "swe",
alpha3B = "swe",
alpha3T = "swe",
alpha3X = "swe",
localName = "Svenska",
name = "Swedish"
},
{
alpha2 = "ta",
alpha3 = "tam",
alpha3B = "tam",
alpha3T = "tam",
alpha3X = "tam",
localName = "தமிழ்",
name = "Tamil"
},
{
alpha2 = "te",
alpha3 = "tel",
alpha3B = "tel",
alpha3T = "tel",
alpha3X = "tel",
localName = "తెలుగు",
name = "Telugu"
},
{
alpha2 = "tg",
alpha3 = "tgk",
alpha3B = "tgk",
alpha3T = "tgk",
alpha3X = "tgk",
localName = "Тоҷикӣ",
name = "Tajik"
},
{
alpha2 = "th",
alpha3 = "tha",
alpha3B = "tha",
alpha3T = "tha",
alpha3X = "tha",
localName = "ภาษาไทย",
name = "Thai"
},
{
alpha2 = "ti",
alpha3 = "tir",
alpha3B = "tir",
alpha3T = "tir",
alpha3X = "tir",
localName = "ትግርኛ",
name = "Tigrinya"
},
{
alpha2 = "bo",
alpha3 = "bod",
alpha3B = "tib",
alpha3T = "bod",
alpha3X = "bod",
localName = "བོད་ཡིག",
name = "Tibetan Standard"
},
{
alpha2 = "tk",
alpha3 = "tuk",
alpha3B = "tuk",
alpha3T = "tuk",
alpha3X = "tuk",
localName = "Türkmençe",
name = "Turkmen"
},
{
alpha2 = "tl",
alpha3 = "tgl",
alpha3B = "tgl",
alpha3T = "tgl",
alpha3X = "tgl",
localName = "Tagalog",
name = "Tagalog"
},
{
alpha2 = "tn",
alpha3 = "tsn",
alpha3B = "tsn",
alpha3T = "tsn",
alpha3X = "tsn",
localName = "Setswana",
name = "Tswana"
},
{
alpha2 = "to",
alpha3 = "ton",
alpha3B = "ton",
alpha3T = "ton",
alpha3X = "ton",
localName = "faka Tonga",
name = "Tonga"
},
{
alpha2 = "tr",
alpha3 = "tur",
alpha3B = "tur",
alpha3T = "tur",
alpha3X = "tur",
localName = "Türkçe",
name = "Turkish"
},
{
alpha2 = "ts",
alpha3 = "tso",
alpha3B = "tso",
alpha3T = "tso",
alpha3X = "tso",
localName = "Xitsonga",
name = "Tsonga"
},
{
alpha2 = "tt",
alpha3 = "tat",
alpha3B = "tat",
alpha3T = "tat",
alpha3X = "tat",
localName = "Татарча",
name = "Tatar"
},
{
alpha2 = "tw",
alpha3 = "twi",
alpha3B = "twi",
alpha3T = "twi",
alpha3X = "twi",
localName = "Twi",
name = "Twi"
},
{
alpha2 = "ty",
alpha3 = "tah",
alpha3B = "tah",
alpha3T = "tah",
alpha3X = "tah",
localName = "Reo Mā’ohi",
name = "Tahitian"
},
{
alpha2 = "ug",
alpha3 = "uig",
alpha3B = "uig",
alpha3T = "uig",
alpha3X = "uig",
localName = "ئۇيغۇرچه",
name = "Uyghur"
},
{
alpha2 = "uk",
alpha3 = "ukr",
alpha3B = "ukr",
alpha3T = "ukr",
alpha3X = "ukr",
localName = "Українська",
name = "Ukrainian"
},
{
alpha2 = "ur",
alpha3 = "urd",
alpha3B = "urd",
alpha3T = "urd",
alpha3X = "urd",
localName = "اردو",
name = "Urdu"
},
{
alpha2 = "uz",
alpha3 = "uzb",
alpha3B = "uzb",
alpha3T = "uzb",
alpha3X = "uzb",
localName = "O‘zbek",
name = "Uzbek"
},
{
alpha2 = "ve",
alpha3 = "ven",
alpha3B = "ven",
alpha3T = "ven",
alpha3X = "ven",
localName = "Tshivenḓa",
name = "Venda"
},
{
alpha2 = "vi",
alpha3 = "vie",
alpha3B = "vie",
alpha3T = "vie",
alpha3X = "vie",
localName = "Tiếng Việt",
name = "Vietnamese"
},
{
alpha2 = "vo",
alpha3 = "vol",
alpha3B = "vol",
alpha3T = "vol",
alpha3X = "vol",
localName = "Volapük",
name = "Volapük"
},
{
alpha2 = "wa",
alpha3 = "wln",
alpha3B = "wln",
alpha3T = "wln",
alpha3X = "wln",
localName = "Walon",
name = "Walloon"
},
{
alpha2 = "cy",
alpha3 = "cym",
alpha3B = "wel",
alpha3T = "cym",
alpha3X = "cym",
localName = "Cymraeg",
name = "Welsh"
},
{
alpha2 = "wo",
alpha3 = "wol",
alpha3B = "wol",
alpha3T = "wol",
alpha3X = "wol",
localName = "Wolof",
name = "Wolof"
},
{
alpha2 = "fy",
alpha3 = "fry",
alpha3B = "fry",
alpha3T = "fry",
alpha3X = "fry",
localName = "Frysk",
name = "Western Frisian"
},
{
alpha2 = "xh",
alpha3 = "xho",
alpha3B = "xho",
alpha3T = "xho",
alpha3X = "xho",
localName = "isiXhosa",
name = "Xhosa"
},
{
alpha2 = "yi",
alpha3 = "yid",
alpha3B = "yid",
alpha3T = "yid",
alpha3X = "yid",
localName = "ייִדיש",
name = "Yiddish"
},
{
alpha2 = "yo",
alpha3 = "yor",
alpha3B = "yor",
alpha3T = "yor",
alpha3X = "yor",
localName = "Yorùbá",
name = "Yoruba"
},
{
alpha2 = "za",
alpha3 = "zha",
alpha3B = "zha",
alpha3T = "zha",
alpha3X = "zha",
localName = "Cuengh",
name = "Zhuang"
},
{
alpha2 = "zu",
alpha3 = "zul",
alpha3B = "zul",
alpha3T = "zul",
alpha3X = "zul",
localName = "isiZulu",
name = "Zulu"
}
}
local SEARCH_KEYS = {"alpha2", "alpha3B", "localName", "name"}
setmetatable(
language,
{
__index = function(self, key)
if type(key) == "string" then
for _, lang in ipairs(language) do
for _, prop in ipairs(SEARCH_KEYS) do
if lang[prop] == key then
rawset(self, key, lang)
return lang
end
end
end
end
return nil
end
}
)
return language
| mit |
Enignite/darkstar | scripts/zones/Temenos/mobs/Temenos_Weapon.lua | 16 | 1289 | -----------------------------------
-- Area: Temenos Central 1floor
-- NPC: Temenos_Weapon
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (IsMobDead(16929048)==true) then
mob:addStatusEffect(EFFECT_REGAIN,7,3,0);
mob:addStatusEffect(EFFECT_REGEN,50,3,0);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if (IsMobDead(16929046)==true and IsMobDead(16929047)==true and IsMobDead(16929048)==true and IsMobDead(16929049)==true and IsMobDead(16929050)==true and IsMobDead(16929051)==true) then
GetNPCByID(16928768+71):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+71):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+471):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
Enignite/darkstar | scripts/zones/Castle_Oztroja/npcs/Treasure_Chest.lua | 17 | 3300 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: Treasure Chest
-- Involved In Quest: Scattered into Shadow
-- @pos 7.378 -16.293 -193.590 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Castle_Oztroja/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 43;
local TreasureMinLvL = 33;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--trade:hasItemQty(1035,1); -- Treasure Key
--trade:hasItemQty(1115,1); -- Skeleton Key
--trade:hasItemQty(1023,1); -- Living Key
--trade:hasItemQty(1022,1); -- Thief's Tools
local questItemNeeded = 0;
-- Player traded a key.
if ((trade:hasItemQty(1035,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
local zone = player:getZoneID();
-- IMPORTANT ITEM: AF1 BST QUEST Beast collar -----------
if (player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW) == QUEST_ACCEPTED and
player:getVar("scatIntoShadowCS") == 1 and player:hasItem(13121) == false) then
questItemNeeded = 1;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if (pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if (success ~= -2) then
player:tradeComplete();
if (math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if (questItemNeeded == 1) then
player:addItem(13121);
player:messageSpecial(ITEM_OBTAINED,13121); -- Beast collar
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = chestLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if (loot[1]=="gil") then
player:addGil(loot[2]*GIL_RATE);
player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1035);
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.