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 |
|---|---|---|---|---|---|
n0xus/darkstar | scripts/globals/items/pipira.lua | 18 | 1400 | -----------------------------------------
-- ID: 5787
-- Item: pipira
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-- Attack % 14.5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5787);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
target:addMod(MOD_ATTP, 14.5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
target:delMod(MOD_ATTP, 14.5);
end;
| gpl-3.0 |
Python1320/wire | lua/entities/sent_deployableballoons.lua | 8 | 6928 | AddCSLuaFile()
DEFINE_BASECLASS( "base_wire_entity" )
ENT.PrintName = "Wire Balloon Deployer"
ENT.Author = "LuaPinapple"
ENT.Contact = "evilpineapple@cox.net"
ENT.Purpose = "It Deploys Balloons."
ENT.Instructions = "Use wire."
ENT.Category = "Wiremod"
ENT.Spawnable = true
ENT.AdminOnly = false
ENT.WireDebugName = "Balloon Deployer"
cleanup.Register("wire_deployers")
if CLIENT then
language.Add( "Cleanup_wire_deployers", "Balloon Deployers" )
language.Add( "Cleaned_wire_deployers", "Cleaned up Balloon Deployers" )
language.Add( "SBoxLimit_wire_deployers", "You have hit the Balloon Deployers limit!" )
return -- No more client
end
local material = "cable/rope"
local BalloonTypes =
{
Model("models/MaxOfS2D/balloon_classic.mdl"),
Model("models/balloons/balloon_classicheart.mdl"),
Model("models/balloons/balloon_dog.mdl"),
Model("models/balloons/balloon_star.mdl")
}
CreateConVar('sbox_maxwire_deployers', 2)
local DmgFilter
local function CreateDamageFilter()
if DmgFilter then return end
local DmgFilter = ents.Create("filter_activator_name")
DmgFilter:SetKeyValue("targetname", "DmgFilter")
DmgFilter:SetKeyValue("negated", "1")
DmgFilter:Spawn()
end
hook.Add("Initialize", "CreateDamageFilter", CreateDamageFilter)
local function MakeBalloonSpawner(pl, Data)
if not pl:CheckLimit("wire_deployers") then return nil end
local ent = ents.Create("sent_deployableballoons")
if not ent:IsValid() then return end
duplicator.DoGeneric(ent, Data)
ent:SetPlayer(pl)
ent:Spawn()
ent:Activate()
duplicator.DoGenericPhysics(ent, pl, Data)
pl:AddCount("wire_deployers", ent)
pl:AddCleanup("wire_deployers", ent)
return ent
end
hook.Add("Initialize", "DamageFilter", DamageFilter)
duplicator.RegisterEntityClass("sent_deployableballoons", MakeBalloonSpawner, "Data")
scripted_ents.Alias("gmod_iballoon", "gmod_balloon")
--Moves old "Lenght" input to new "Length" input for older dupes
WireLib.AddInputAlias( "Lenght", "Length" )
function ENT:SpawnFunction( ply, tr )
if (not tr.Hit) then return end
local SpawnPos = tr.HitPos+tr.HitNormal*16
local ent = MakeBalloonSpawner(ply, {Pos=SpawnPos})
return ent
end
function ENT:Initialize()
self:SetModel("models/props_junk/PropaneCanister001a.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid(SOLID_VPHYSICS)
self.Deployed = 0
self.Balloon = nil
self.Constraints = {}
self.force = 500
self.weld = false
self.popable = true
self.rl = 64
if WireAddon then
self.Inputs = Wire_CreateInputs(self,{ "Force", "Length", "Weld?", "Popable?", "BalloonType", "Deploy" })
self.Outputs=WireLib.CreateSpecialOutputs(self, { "Deployed", "BalloonEntity" }, {"NORMAL","ENTITY" })
Wire_TriggerOutput(self,"Deployed", self.Deployed)
--Wire_TriggerOutput(self,"Force", self.force)
end
local phys = self:GetPhysicsObject()
if(phys:IsValid()) then
phys:SetMass(250)
phys:Wake()
end
self:UpdateOverlay()
end
function ENT:TriggerInput(key,value)
if (key == "Deploy") then
if value ~= 0 then
if self.Deployed == 0 then
self:DeployBalloons()
self.Deployed = 1
end
Wire_TriggerOutput(self, "Deployed", self.Deployed)
else
if self.Deployed ~= 0 then
self:RetractBalloons()
self.Deployed = 0
end
Wire_TriggerOutput(self, "Deployed", self.Deployed)
end
elseif (key == "Force") then
self.force = value
if self.Deployed ~= 0 then
self.Balloon:SetForce(value)
end
elseif (key == "Length") then
self.rl = value
elseif (key == "Weld?") then
self.weld = value ~= 0
elseif (key == "Popable?") then
self.popable = value ~= 0
self:UpdatePopable()
elseif (key == "BalloonType") then
self.balloonType=value+1 --To correct for 1 based indexing
end
self:UpdateOverlay()
end
local balloon_registry = {}
hook.Add("EntityRemoved", "balloon_deployer", function(ent)
local deployer = balloon_registry[ent]
if IsValid(deployer) and deployer.TriggerInput then
deployer.Deployed = 0
deployer:TriggerInput("Deploy", 0)
end
end)
function ENT:UpdatePopable()
local balloon = self.Balloon
if balloon ~= nil and balloon:IsValid() then
if not self.popable then
balloon:Fire("setdamagefilter", "DmgFilter", 0);
else
balloon:Fire("setdamagefilter", "", 0);
end
end
end
function ENT:DeployBalloons()
local balloon
balloon = ents.Create("gmod_balloon") --normal balloon
local model = BalloonTypes[self.balloonType]
if(model==nil) then
model = BalloonTypes[1]
end
balloon:SetModel(model)
balloon:Spawn()
balloon:SetColor(Color(math.random(0,255), math.random(0,255), math.random(0,255), 255))
balloon:SetForce(self.force)
balloon:SetMaterial("models/balloon/balloon")
balloon:SetPlayer(self:GetPlayer())
duplicator.DoGeneric(balloon,{Pos = self:GetPos() + (self:GetUp()*25)})
duplicator.DoGenericPhysics(balloon,pl,{Pos = Pos})
local balloonPos = balloon:GetPos() -- the origin the balloon is at the bottom
local hitEntity = self
local hitPos = self:LocalToWorld(Vector(0, 0, self:OBBMaxs().z)) -- the top of the spawner
-- We trace from the balloon to us, and if there's anything in the way, we
-- attach a constraint to that instead - that way, the balloon spawner can
-- be hidden underneath a plate which magically gets balloons attached to it.
local balloonToSpawner = (hitPos - balloonPos):GetNormalized() * 250
local trace = util.QuickTrace(balloon:GetPos(), balloonToSpawner, balloon)
if constraint.CanConstrain(trace.Entity, trace.PhysicsBone) then
local phys = trace.Entity:GetPhysicsObjectNum(trace.PhysicsBone)
if IsValid(phys) then
hitEntity = trace.Entity
hitPos = trace.HitPos
end
end
if self.weld then
local constraint = constraint.Weld( balloon, hitEntity, 0, trace.PhysicsBone, 0)
balloon:DeleteOnRemove(constraint)
else
balloonPos = balloon:WorldToLocal(balloonPos)
hitPos = hitEntity:WorldToLocal(hitPos)
local constraint, rope = constraint.Rope(
balloon, hitEntity, 0, trace.PhysicsBone, balloonPos, hitPos,
0, self.rl, 0, 1.5, material, false)
if constraint then
balloon:DeleteOnRemove(constraint)
balloon:DeleteOnRemove(rope)
end
end
self:DeleteOnRemove(balloon)
self.Balloon = balloon
self:UpdatePopable()
balloon_registry[balloon] = self
Wire_TriggerOutput(self, "BalloonEntity", self.Balloon)
end
function ENT:OnRemove()
if self.Balloon then
balloon_registry[self.Balloon] = nil
end
Wire_Remove(self)
end
function ENT:RetractBalloons()
if self.Balloon:IsValid() then
local c = self.Balloon:GetColor()
local effectdata = EffectData()
effectdata:SetOrigin( self.Balloon:GetPos() )
effectdata:SetStart( Vector(c.r,c.g,c.b) )
util.Effect( "balloon_pop", effectdata )
self.Balloon:Remove()
else
self.Balloon = nil
end
end
function ENT:UpdateOverlay()
self:SetOverlayText( "Deployed = " .. ((self.Deployed ~= 0) and "yes" or "no") )
end
| apache-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-Cataclysm/GrimBatol/Erudax.lua | 1 | 1823 | local mod = DBM:NewMod(134, "DBM-Party-Cataclysm", 3, 71)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 79 $"):sub(12, -3))
mod:SetCreatureID(40484)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED",
"SPELL_AURA_REMOVED",
"SPELL_CAST_START"
)
local warnBinding = mod:NewTargetAnnounce(75861, 3)
local warnFeeble = mod:NewTargetAnnounce(75792, 3)
local warnGale = mod:NewSpellAnnounce(75664, 4)
local warnUmbralMending = mod:NewSpellAnnounce(75763, 4)
local timerBinding = mod:NewBuffFadesTimer(6, 75861)
local timerFeeble = mod:NewTargetTimer(3, 75792)
local timerGale = mod:NewCastTimer(5, 75664)
local timerGaleCD = mod:NewCDTimer(55, 75664)
local bindingTargets = {}
local bindingCount = 0
local function showBindingWarning()
warnBinding:Show(table.concat(bindingTargets, "<, >"))
table.wipe(bindingTargets)
timerBinding:Start()
end
function mod:OnCombatStart(delay)
table.wipe(bindingTargets)
bindingCount = 0
end
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 75861 then
bindingCount = bindingCount + 1
bindingTargets[#bindingTargets + 1] = args.destName
self:Unschedule(showBindingWarning)
self:Schedule(0.3, showBindingWarning)
elseif args.spellId == 75792 then
warnFeeble:Show(args.destName)
if self:IsDifficulty("heroic5") then
timerFeeble:Start(5, args.destName)
else
timerFeeble:Start(args.destName)
end
end
end
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 75861 then
bindingCount = bindingCount - 1
if bindingCount == 0 then
timerBinding:Cancel()
end
end
end
function mod:SPELL_CAST_START(args)
if args.spellId == 75664 then
warnGale:Show()
timerGale:Start()
timerGaleCD:Start()
elseif args:IsSpellID(75763, 79467) then
warnUmbralMending:Show()
end
end | gpl-2.0 |
behradhg/tagbot | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-3.0 |
xxlxx20/DEVKEEPER | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
n0xus/darkstar | scripts/zones/RuLude_Gardens/npcs/Goggehn.lua | 17 | 3000 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Goggehn
-- Involved in Mission: Bastok 3-3, 4-1
-- @zone 243
-- @pos 3 9 -76
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
package.loaded["scripts/globals/missions"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
pNation = player:getNation();
currentMission = player:getCurrentMission(BASTOK);
missionStatus = player:getVar("MissionStatus");
if (currentMission == JEUNO_MISSION and missionStatus == 1) then
player:startEvent(0x0029);
elseif (currentMission == JEUNO_MISSION and missionStatus == 2) then
player:startEvent(0x0042);
elseif (currentMission == JEUNO_MISSION and missionStatus == 3) then
player:startEvent(0x0026);
elseif (player:getRank() == 4 and player:getCurrentMission(BASTOK) == 255 and getMissionRankPoints(player,13) == 1) then
if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT)) then
player:startEvent(0x0081,1);
else
player:startEvent(0x0081); -- Start Mission 4-1 Magicite
end
elseif (currentMission == MAGICITE_BASTOK and missionStatus == 1) then
player:startEvent(0x0084);
elseif (currentMission == MAGICITE_BASTOK and missionStatus <= 5) then
player:startEvent(0x0087);
elseif (currentMission == MAGICITE_BASTOK and missionStatus == 6) then
player:startEvent(0x0023);
elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_BASTOK)) then
player:startEvent(0x0037);
elseif (pNation == WINDURST) then
player:startEvent(0x0004);
elseif (pNation == SANDORIA) then
player:startEvent(0x0002);
else
player:startEvent(0x0065);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0029) then
player:setVar("MissionStatus",2);
player:delKeyItem(LETTER_TO_THE_AMBASSADOR);
elseif (csid == 0x0081 and option == 1) then
player:setVar("MissionStatus",1);
if (player:hasKeyItem(ARCHDUCAL_AUDIENCE_PERMIT) == false) then
player:addKeyItem(ARCHDUCAL_AUDIENCE_PERMIT);
player:messageSpecial(KEYITEM_OBTAINED,ARCHDUCAL_AUDIENCE_PERMIT);
end
elseif (csid == 0x0026 or csid == 0x0023) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-BC/TK_Mechanar/Capacitus.lua | 1 | 1155 | local mod = DBM:NewMod(563, "DBM-Party-BC", 13, 258)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 526 $"):sub(12, -3))
mod:SetCreatureID(19219)
mod:RegisterCombat("combat")
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED",
"SPELL_CAST_START"
)
local warnPolarity = mod:NewCastAnnounce(39096)
local warnMagicShield = mod:NewSpellAnnounce(35158)
local warnDamageShield = mod:NewSpellAnnounce(35159)
local timerMagicShield = mod:NewBuffActiveTimer(10, 35158)
local timerDamageShield = mod:NewBuffActiveTimer(10, 35159)
local enrageTimer = mod:NewBerserkTimer(180)
function mod:OnCombatStart(delay)
if self:IsDifficulty("heroic5") then
enrageTimer:Start(-delay)
end
end
function mod:SPELL_CAST_START(args)
if args.spellId == 39096 then --Robo Thaddius AMG!
warnPolarity:Show()
end
end
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 35158 then --Magic Shield
warnMagicShield:Show(args.destName)
timerMagicShield:Start()
elseif args.spellId == 35159 then --Damage Shield
warnDamageShield:Show(args.destName)
timerDamageShield:Start()
end
end | gpl-2.0 |
n0xus/darkstar | scripts/globals/spells/bluemagic/wild_oats.lua | 18 | 1960 | -----------------------------------------
-- Spell: Wild Oats
-- Additional effect: Vitality Down. Duration of effect varies on TP
-- Spell cost: 9 MP
-- Monster Type: Plantoids
-- Spell Type: Physical (Piercing)
-- Blue Magic Points: 3
-- Stat Bonus: CHR+1, HP+10
-- Level: 4
-- Casting Time: 0.5 seconds
-- Recast Time: 7.25 seconds
-- Skillchain Element(s): Light (can open Compression, Reverberation, or Distortion; can close Transfixion)
-- Combos: Beast Killer
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_DURATION;
params.dmgtype = DMGTYPE_PIERCE;
params.scattr = SC_TRANSFIXION;
params.numhits = 1;
params.multiplier = 1.84;
params.tp150 = 1.84;
params.tp300 = 1.84;
params.azuretp = 1.84;
params.duppercap = 11;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.3;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
if (target:hasStatusEffect(EFFECT_VIT_DOWN)) then
spell:setMsg(75); -- no effect
else
target:addStatusEffect(EFFECT_VIT_DOWN,15,0,20);
end
return damage;
end; | gpl-3.0 |
GhoulofGSG9/BadgesPlus | lua/Badges+_ConsoleCommands.lua | 1 | 1701 | -- temp cache of often used function
local StringFormat = string.format
local function OnConsoleBadges()
local function RequestCallback(sClientBadges)
Print( "--Available Badges--" )
for i, sBadgeRows in pairs( sClientBadges ) do
Print( StringFormat( "Badge-Row %s:", i ))
for _, sBadge in ipairs( sBadgeRows ) do
Print( sBadge )
end
Print( "-------------" )
end
end
GetBadgeStrings( RequestCallback )
end
Event.Hook( "Console_badges", OnConsoleBadges )
local function OnConsoleBadge( sRequestedBadge, Row)
Row = tonumber( Row )
if not Row or Row < 0 or Row > 10 then Row = 3 end
local sSavedBadge = Client.GetOptionString( StringFormat( "Badge%s", Row ), "" )
if not sRequestedBadge or StringTrim( sRequestedBadge ) == "" then
Print( StringFormat( "Saved Badge: %s", sSavedBadge ))
elseif sRequestedBadge == "-" then
Client.SetOptionString( StringFormat("Badge%s", Row ), "" )
SelectBadge( "None", Row )
elseif sRequestedBadge ~= sSavedBadge and GetClientOwnBadge( sRequestedBadge, Row ) then
Client.SetOptionString( StringFormat( "Badge%s", Row ), sRequestedBadge )
SelectBadge( sRequestedBadge, Row )
Client.SendNetworkMessage( "Badge", { badge = kBadges[ sRequestedBadge ], badgerow = Row }, true)
elseif sRequestedBadge == sSavedBadge then
Print( "You already have selected the requested badge" )
else
Print( "Either you don't own the requested badge at this server or it doesn't exist." )
end
end
Event.Hook( "Console_badge", OnConsoleBadge )
local function OnConsoleAllBadges()
Print( "--All Badges--" )
for _, sBadge in ipairs( kBadges ) do
Print( ToString( sBadge ) )
end
end
Event.Hook( "Console_allbadges", OnConsoleAllBadges )
| mit |
davymai/CN-QulightUI | Interface/AddOns/Skada/lib/AceAddon-3.0/AceAddon-3.0.lua | 66 | 25788 | --- **AceAddon-3.0** provides a template for creating addon objects.
-- It'll provide you with a set of callback functions that allow you to simplify the loading
-- process of your addon.\\
-- Callbacks provided are:\\
-- * **OnInitialize**, which is called directly after the addon is fully loaded.
-- * **OnEnable** which gets called during the PLAYER_LOGIN event, when most of the data provided by the game is already present.
-- * **OnDisable**, which is only called when your addon is manually being disabled.
-- @usage
-- -- A small (but complete) addon, that doesn't do anything,
-- -- but shows usage of the callbacks.
-- local MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
--
-- function MyAddon:OnInitialize()
-- -- do init tasks here, like loading the Saved Variables,
-- -- or setting up slash commands.
-- end
--
-- function MyAddon:OnEnable()
-- -- Do more initialization here, that really enables the use of your addon.
-- -- Register Events, Hook functions, Create Frames, Get information from
-- -- the game that wasn't available in OnInitialize
-- end
--
-- function MyAddon:OnDisable()
-- -- Unhook, Unregister Events, Hide frames that you created.
-- -- You would probably only use an OnDisable if you want to
-- -- build a "standby" mode, or be able to toggle modules on/off.
-- end
-- @class file
-- @name AceAddon-3.0.lua
-- @release $Id: AceAddon-3.0.lua 1084 2013-04-27 20:14:11Z nevcairiel $
local MAJOR, MINOR = "AceAddon-3.0", 12
local AceAddon, oldminor = LibStub:NewLibrary(MAJOR, MINOR)
if not AceAddon then return end -- No Upgrade needed.
AceAddon.frame = AceAddon.frame or CreateFrame("Frame", "AceAddon30Frame") -- Our very own frame
AceAddon.addons = AceAddon.addons or {} -- addons in general
AceAddon.statuses = AceAddon.statuses or {} -- statuses of addon.
AceAddon.initializequeue = AceAddon.initializequeue or {} -- addons that are new and not initialized
AceAddon.enablequeue = AceAddon.enablequeue or {} -- addons that are initialized and waiting to be enabled
AceAddon.embeds = AceAddon.embeds or setmetatable({}, {__index = function(tbl, key) tbl[key] = {} return tbl[key] end }) -- contains a list of libraries embedded in an addon
-- Lua APIs
local tinsert, tconcat, tremove = table.insert, table.concat, table.remove
local fmt, tostring = string.format, tostring
local select, pairs, next, type, unpack = select, pairs, next, type, unpack
local loadstring, assert, error = loadstring, assert, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub, IsLoggedIn, geterrorhandler
--[[
xpcall safecall implementation
]]
local xpcall = xpcall
local function errorhandler(err)
return geterrorhandler()(err)
end
local function CreateDispatcher(argCount)
local code = [[
local xpcall, eh = ...
local method, ARGS
local function call() return method(ARGS) end
local function dispatch(func, ...)
method = func
if not method then return end
ARGS = ...
return xpcall(call, eh)
end
return dispatch
]]
local ARGS = {}
for i = 1, argCount do ARGS[i] = "arg"..i end
code = code:gsub("ARGS", tconcat(ARGS, ", "))
return assert(loadstring(code, "safecall Dispatcher["..argCount.."]"))(xpcall, errorhandler)
end
local Dispatchers = setmetatable({}, {__index=function(self, argCount)
local dispatcher = CreateDispatcher(argCount)
rawset(self, argCount, dispatcher)
return dispatcher
end})
Dispatchers[0] = function(func)
return xpcall(func, errorhandler)
end
local function safecall(func, ...)
-- we check to see if the func is passed is actually a function here and don't error when it isn't
-- this safecall is used for optional functions like OnInitialize OnEnable etc. When they are not
-- present execution should continue without hinderance
if type(func) == "function" then
return Dispatchers[select('#', ...)](func, ...)
end
end
-- local functions that will be implemented further down
local Enable, Disable, EnableModule, DisableModule, Embed, NewModule, GetModule, GetName, SetDefaultModuleState, SetDefaultModuleLibraries, SetEnabledState, SetDefaultModulePrototype
-- used in the addon metatable
local function addontostring( self ) return self.name end
-- Check if the addon is queued for initialization
local function queuedForInitialization(addon)
for i = 1, #AceAddon.initializequeue do
if AceAddon.initializequeue[i] == addon then
return true
end
end
return false
end
--- Create a new AceAddon-3.0 addon.
-- Any libraries you specified will be embeded, and the addon will be scheduled for
-- its OnInitialize and OnEnable callbacks.
-- The final addon object, with all libraries embeded, will be returned.
-- @paramsig [object ,]name[, lib, ...]
-- @param object Table to use as a base for the addon (optional)
-- @param name Name of the addon object to create
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a simple addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon", "AceEvent-3.0")
--
-- -- Create a Addon object based on the table of a frame
-- local MyFrame = CreateFrame("Frame")
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon(MyFrame, "MyAddon", "AceEvent-3.0")
function AceAddon:NewAddon(objectorname, ...)
local object,name
local i=1
if type(objectorname)=="table" then
object=objectorname
name=...
i=2
else
name=objectorname
end
if type(name)~="string" then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2)
end
if self.addons[name] then
error(("Usage: NewAddon([object,] name, [lib, lib, lib, ...]): 'name' - Addon '%s' already exists."):format(name), 2)
end
object = object or {}
object.name = name
local addonmeta = {}
local oldmeta = getmetatable(object)
if oldmeta then
for k, v in pairs(oldmeta) do addonmeta[k] = v end
end
addonmeta.__tostring = addontostring
setmetatable( object, addonmeta )
self.addons[name] = object
object.modules = {}
object.orderedModules = {}
object.defaultModuleLibraries = {}
Embed( object ) -- embed NewModule, GetModule methods
self:EmbedLibraries(object, select(i,...))
-- add to queue of addons to be initialized upon ADDON_LOADED
tinsert(self.initializequeue, object)
return object
end
--- Get the addon object by its name from the internal AceAddon registry.
-- Throws an error if the addon object cannot be found (except if silent is set).
-- @param name unique name of the addon object
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
function AceAddon:GetAddon(name, silent)
if not silent and not self.addons[name] then
error(("Usage: GetAddon(name): 'name' - Cannot find an AceAddon '%s'."):format(tostring(name)), 2)
end
return self.addons[name]
end
-- - Embed a list of libraries into the specified addon.
-- This function will try to embed all of the listed libraries into the addon
-- and error if a single one fails.
--
-- **Note:** This function is for internal use by :NewAddon/:NewModule
-- @paramsig addon, [lib, ...]
-- @param addon addon object to embed the libs in
-- @param lib List of libraries to embed into the addon
function AceAddon:EmbedLibraries(addon, ...)
for i=1,select("#", ... ) do
local libname = select(i, ...)
self:EmbedLibrary(addon, libname, false, 4)
end
end
-- - Embed a library into the addon object.
-- This function will check if the specified library is registered with LibStub
-- and if it has a :Embed function to call. It'll error if any of those conditions
-- fails.
--
-- **Note:** This function is for internal use by :EmbedLibraries
-- @paramsig addon, libname[, silent[, offset]]
-- @param addon addon object to embed the library in
-- @param libname name of the library to embed
-- @param silent marks an embed to fail silently if the library doesn't exist (optional)
-- @param offset will push the error messages back to said offset, defaults to 2 (optional)
function AceAddon:EmbedLibrary(addon, libname, silent, offset)
local lib = LibStub:GetLibrary(libname, true)
if not lib and not silent then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Cannot find a library instance of %q."):format(tostring(libname)), offset or 2)
elseif lib and type(lib.Embed) == "function" then
lib:Embed(addon)
tinsert(self.embeds[addon], libname)
return true
elseif lib then
error(("Usage: EmbedLibrary(addon, libname, silent, offset): 'libname' - Library '%s' is not Embed capable"):format(libname), offset or 2)
end
end
--- Return the specified module from an addon object.
-- Throws an error if the addon object cannot be found (except if silent is set)
-- @name //addon//:GetModule
-- @paramsig name[, silent]
-- @param name unique name of the module
-- @param silent if true, the module is optional, silently return nil if its not found (optional)
-- @usage
-- -- Get the Addon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- -- Get the Module
-- MyModule = MyAddon:GetModule("MyModule")
function GetModule(self, name, silent)
if not self.modules[name] and not silent then
error(("Usage: GetModule(name, silent): 'name' - Cannot find module '%s'."):format(tostring(name)), 2)
end
return self.modules[name]
end
local function IsModuleTrue(self) return true end
--- Create a new module for the addon.
-- The new module can have its own embeded libraries and/or use a module prototype to be mixed into the module.\\
-- A module has the same functionality as a real addon, it can have modules of its own, and has the same API as
-- an addon object.
-- @name //addon//:NewModule
-- @paramsig name[, prototype|lib[, lib, ...]]
-- @param name unique name of the module
-- @param prototype object to derive this module from, methods and values from this table will be mixed into the module (optional)
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create a module with some embeded libraries
-- MyModule = MyAddon:NewModule("MyModule", "AceEvent-3.0", "AceHook-3.0")
--
-- -- Create a module with a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- MyModule = MyAddon:NewModule("MyModule", prototype, "AceEvent-3.0", "AceHook-3.0")
function NewModule(self, name, prototype, ...)
if type(name) ~= "string" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - string expected got '%s'."):format(type(name)), 2) end
if type(prototype) ~= "string" and type(prototype) ~= "table" and type(prototype) ~= "nil" then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'prototype' - table (prototype), string (lib) or nil expected got '%s'."):format(type(prototype)), 2) end
if self.modules[name] then error(("Usage: NewModule(name, [prototype, [lib, lib, lib, ...]): 'name' - Module '%s' already exists."):format(name), 2) end
-- modules are basically addons. We treat them as such. They will be added to the initializequeue properly as well.
-- NewModule can only be called after the parent addon is present thus the modules will be initialized after their parent is.
local module = AceAddon:NewAddon(fmt("%s_%s", self.name or tostring(self), name))
module.IsModule = IsModuleTrue
module:SetEnabledState(self.defaultModuleState)
module.moduleName = name
if type(prototype) == "string" then
AceAddon:EmbedLibraries(module, prototype, ...)
else
AceAddon:EmbedLibraries(module, ...)
end
AceAddon:EmbedLibraries(module, unpack(self.defaultModuleLibraries))
if not prototype or type(prototype) == "string" then
prototype = self.defaultModulePrototype or nil
end
if type(prototype) == "table" then
local mt = getmetatable(module)
mt.__index = prototype
setmetatable(module, mt) -- More of a Base class type feel.
end
safecall(self.OnModuleCreated, self, module) -- Was in Ace2 and I think it could be a cool thing to have handy.
self.modules[name] = module
tinsert(self.orderedModules, module)
return module
end
--- Returns the real name of the addon or module, without any prefix.
-- @name //addon//:GetName
-- @paramsig
-- @usage
-- print(MyAddon:GetName())
-- -- prints "MyAddon"
function GetName(self)
return self.moduleName or self.name
end
--- Enables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:EnableAddon(), thus dispatching a OnEnable callback
-- and enabling all modules of the addon (unless explicitly disabled).\\
-- :Enable() also sets the internal `enableState` variable to true
-- @name //addon//:Enable
-- @paramsig
-- @usage
-- -- Enable MyModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
function Enable(self)
self:SetEnabledState(true)
-- nevcairiel 2013-04-27: don't enable an addon/module if its queued for init still
-- it'll be enabled after the init process
if not queuedForInitialization(self) then
return AceAddon:EnableAddon(self)
end
end
--- Disables the Addon, if possible, return true or false depending on success.
-- This internally calls AceAddon:DisableAddon(), thus dispatching a OnDisable callback
-- and disabling all modules of the addon.\\
-- :Disable() also sets the internal `enableState` variable to false
-- @name //addon//:Disable
-- @paramsig
-- @usage
-- -- Disable MyAddon
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:Disable()
function Disable(self)
self:SetEnabledState(false)
return AceAddon:DisableAddon(self)
end
--- Enables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Enable` on the module object.
-- @name //addon//:EnableModule
-- @paramsig name
-- @usage
-- -- Enable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Enable()
--
-- -- Enable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:EnableModule("MyModule")
function EnableModule(self, name)
local module = self:GetModule( name )
return module:Enable()
end
--- Disables the Module, if possible, return true or false depending on success.
-- Short-hand function that retrieves the module via `:GetModule` and calls `:Disable` on the module object.
-- @name //addon//:DisableModule
-- @paramsig name
-- @usage
-- -- Disable MyModule using :GetModule
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyModule = MyAddon:GetModule("MyModule")
-- MyModule:Disable()
--
-- -- Disable MyModule using the short-hand
-- MyAddon = LibStub("AceAddon-3.0"):GetAddon("MyAddon")
-- MyAddon:DisableModule("MyModule")
function DisableModule(self, name)
local module = self:GetModule( name )
return module:Disable()
end
--- Set the default libraries to be mixed into all modules created by this object.
-- Note that you can only change the default module libraries before any module is created.
-- @name //addon//:SetDefaultModuleLibraries
-- @paramsig lib[, lib, ...]
-- @param lib List of libraries to embed into the addon
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Configure default libraries for modules (all modules need AceEvent-3.0)
-- MyAddon:SetDefaultModuleLibraries("AceEvent-3.0")
-- -- Create a module
-- MyModule = MyAddon:NewModule("MyModule")
function SetDefaultModuleLibraries(self, ...)
if next(self.modules) then
error("Usage: SetDefaultModuleLibraries(...): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleLibraries = {...}
end
--- Set the default state in which new modules are being created.
-- Note that you can only change the default state before any module is created.
-- @name //addon//:SetDefaultModuleState
-- @paramsig state
-- @param state Default state for new modules, true for enabled, false for disabled
-- @usage
-- -- Create the addon object
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("MyAddon")
-- -- Set the default state to "disabled"
-- MyAddon:SetDefaultModuleState(false)
-- -- Create a module and explicilty enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
function SetDefaultModuleState(self, state)
if next(self.modules) then
error("Usage: SetDefaultModuleState(state): cannot change the module defaults after a module has been registered.", 2)
end
self.defaultModuleState = state
end
--- Set the default prototype to use for new modules on creation.
-- Note that you can only change the default prototype before any module is created.
-- @name //addon//:SetDefaultModulePrototype
-- @paramsig prototype
-- @param prototype Default prototype for the new modules (table)
-- @usage
-- -- Define a prototype
-- local prototype = { OnEnable = function(self) print("OnEnable called!") end }
-- -- Set the default prototype
-- MyAddon:SetDefaultModulePrototype(prototype)
-- -- Create a module and explicitly Enable it
-- MyModule = MyAddon:NewModule("MyModule")
-- MyModule:Enable()
-- -- should print "OnEnable called!" now
-- @see NewModule
function SetDefaultModulePrototype(self, prototype)
if next(self.modules) then
error("Usage: SetDefaultModulePrototype(prototype): cannot change the module defaults after a module has been registered.", 2)
end
if type(prototype) ~= "table" then
error(("Usage: SetDefaultModulePrototype(prototype): 'prototype' - table expected got '%s'."):format(type(prototype)), 2)
end
self.defaultModulePrototype = prototype
end
--- Set the state of an addon or module
-- This should only be called before any enabling actually happend, e.g. in/before OnInitialize.
-- @name //addon//:SetEnabledState
-- @paramsig state
-- @param state the state of an addon or module (enabled=true, disabled=false)
function SetEnabledState(self, state)
self.enabledState = state
end
--- Return an iterator of all modules associated to the addon.
-- @name //addon//:IterateModules
-- @paramsig
-- @usage
-- -- Enable all modules
-- for name, module in MyAddon:IterateModules() do
-- module:Enable()
-- end
local function IterateModules(self) return pairs(self.modules) end
-- Returns an iterator of all embeds in the addon
-- @name //addon//:IterateEmbeds
-- @paramsig
local function IterateEmbeds(self) return pairs(AceAddon.embeds[self]) end
--- Query the enabledState of an addon.
-- @name //addon//:IsEnabled
-- @paramsig
-- @usage
-- if MyAddon:IsEnabled() then
-- MyAddon:Disable()
-- end
local function IsEnabled(self) return self.enabledState end
local mixins = {
NewModule = NewModule,
GetModule = GetModule,
Enable = Enable,
Disable = Disable,
EnableModule = EnableModule,
DisableModule = DisableModule,
IsEnabled = IsEnabled,
SetDefaultModuleLibraries = SetDefaultModuleLibraries,
SetDefaultModuleState = SetDefaultModuleState,
SetDefaultModulePrototype = SetDefaultModulePrototype,
SetEnabledState = SetEnabledState,
IterateModules = IterateModules,
IterateEmbeds = IterateEmbeds,
GetName = GetName,
}
local function IsModule(self) return false end
local pmixins = {
defaultModuleState = true,
enabledState = true,
IsModule = IsModule,
}
-- Embed( target )
-- target (object) - target object to embed aceaddon in
--
-- this is a local function specifically since it's meant to be only called internally
function Embed(target, skipPMixins)
for k, v in pairs(mixins) do
target[k] = v
end
if not skipPMixins then
for k, v in pairs(pmixins) do
target[k] = target[k] or v
end
end
end
-- - Initialize the addon after creation.
-- This function is only used internally during the ADDON_LOADED event
-- It will call the **OnInitialize** function on the addon object (if present),
-- and the **OnEmbedInitialize** function on all embeded libraries.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- @param addon addon object to intialize
function AceAddon:InitializeAddon(addon)
safecall(addon.OnInitialize, addon)
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedInitialize, lib, addon) end
end
-- we don't call InitializeAddon on modules specifically, this is handled
-- from the event handler and only done _once_
end
-- - Enable the addon after creation.
-- Note: This function is only used internally during the PLAYER_LOGIN event, or during ADDON_LOADED,
-- if IsLoggedIn() already returns true at that point, e.g. for LoD Addons.
-- It will call the **OnEnable** function on the addon object (if present),
-- and the **OnEmbedEnable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is disabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Enable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:EnableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if self.statuses[addon.name] or not addon.enabledState then return false end
-- set the statuses first, before calling the OnEnable. this allows for Disabling of the addon in OnEnable.
self.statuses[addon.name] = true
safecall(addon.OnEnable, addon)
-- make sure we're still enabled before continueing
if self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedEnable, lib, addon) end
end
-- enable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:EnableAddon(modules[i])
end
end
return self.statuses[addon.name] -- return true if we're disabled
end
-- - Disable the addon
-- Note: This function is only used internally.
-- It will call the **OnDisable** function on the addon object (if present),
-- and the **OnEmbedDisable** function on all embeded libraries.\\
-- This function does not toggle the enable state of the addon itself, and will return early if the addon is still enabled.
--
-- **Note:** Do not call this function manually, unless you're absolutely sure that you know what you are doing.
-- Use :Disable on the addon itself instead.
-- @param addon addon object to enable
function AceAddon:DisableAddon(addon)
if type(addon) == "string" then addon = AceAddon:GetAddon(addon) end
if not self.statuses[addon.name] then return false end
-- set statuses first before calling OnDisable, this allows for aborting the disable in OnDisable.
self.statuses[addon.name] = false
safecall( addon.OnDisable, addon )
-- make sure we're still disabling...
if not self.statuses[addon.name] then
local embeds = self.embeds[addon]
for i = 1, #embeds do
local lib = LibStub:GetLibrary(embeds[i], true)
if lib then safecall(lib.OnEmbedDisable, lib, addon) end
end
-- disable possible modules.
local modules = addon.orderedModules
for i = 1, #modules do
self:DisableAddon(modules[i])
end
end
return not self.statuses[addon.name] -- return true if we're disabled
end
--- Get an iterator over all registered addons.
-- @usage
-- -- Print a list of all installed AceAddon's
-- for name, addon in AceAddon:IterateAddons() do
-- print("Addon: " .. name)
-- end
function AceAddon:IterateAddons() return pairs(self.addons) end
--- Get an iterator over the internal status registry.
-- @usage
-- -- Print a list of all enabled addons
-- for name, status in AceAddon:IterateAddonStatus() do
-- if status then
-- print("EnabledAddon: " .. name)
-- end
-- end
function AceAddon:IterateAddonStatus() return pairs(self.statuses) end
-- Following Iterators are deprecated, and their addon specific versions should be used
-- e.g. addon:IterateEmbeds() instead of :IterateEmbedsOnAddon(addon)
function AceAddon:IterateEmbedsOnAddon(addon) return pairs(self.embeds[addon]) end
function AceAddon:IterateModulesOfAddon(addon) return pairs(addon.modules) end
-- Event Handling
local function onEvent(this, event, arg1)
-- 2011-08-17 nevcairiel - ignore the load event of Blizzard_DebugTools, so a potential startup error isn't swallowed up
if (event == "ADDON_LOADED" and arg1 ~= "Blizzard_DebugTools") or event == "PLAYER_LOGIN" then
-- if a addon loads another addon, recursion could happen here, so we need to validate the table on every iteration
while(#AceAddon.initializequeue > 0) do
local addon = tremove(AceAddon.initializequeue, 1)
-- this might be an issue with recursion - TODO: validate
if event == "ADDON_LOADED" then addon.baseName = arg1 end
AceAddon:InitializeAddon(addon)
tinsert(AceAddon.enablequeue, addon)
end
if IsLoggedIn() then
while(#AceAddon.enablequeue > 0) do
local addon = tremove(AceAddon.enablequeue, 1)
AceAddon:EnableAddon(addon)
end
end
end
end
AceAddon.frame:RegisterEvent("ADDON_LOADED")
AceAddon.frame:RegisterEvent("PLAYER_LOGIN")
AceAddon.frame:SetScript("OnEvent", onEvent)
-- upgrade embeded
for name, addon in pairs(AceAddon.addons) do
Embed(addon, true)
end
-- 2010-10-27 nevcairiel - add new "orderedModules" table
if oldminor and oldminor < 10 then
for name, addon in pairs(AceAddon.addons) do
addon.orderedModules = {}
for module_name, module in pairs(addon.modules) do
tinsert(addon.orderedModules, module)
end
end
end
| gpl-2.0 |
Arashbrsh/lifeiran | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
alirezanile/Ldcxvx | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
shayanchabok007/antispamfox | plugins/wiki.lua | 735 | 4364 | -- http://git.io/vUA4M
local socket = require "socket"
local JSON = require "cjson"
local wikiusage = {
"!wiki [text]: Read extract from default Wikipedia (EN)",
"!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola",
"!wiki search [text]: Search articles on default Wikipedia (EN)",
"!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola",
}
local Wikipedia = {
-- http://meta.wikimedia.org/wiki/List_of_Wikipedias
wiki_server = "https://%s.wikipedia.org",
wiki_path = "/w/api.php",
wiki_load_params = {
action = "query",
prop = "extracts",
format = "json",
exchars = 300,
exsectionformat = "plain",
explaintext = "",
redirects = ""
},
wiki_search_params = {
action = "query",
list = "search",
srlimit = 20,
format = "json",
},
default_lang = "en",
}
function Wikipedia:getWikiServer(lang)
return string.format(self.wiki_server, lang or self.default_lang)
end
--[[
-- return decoded JSON table from Wikipedia
--]]
function Wikipedia:loadPage(text, lang, intro, plain, is_search)
local request, sink = {}, {}
local query = ""
local parsed
if is_search then
for k,v in pairs(self.wiki_search_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "srsearch=" .. URL.escape(text)
else
self.wiki_load_params.explaintext = plain and "" or nil
for k,v in pairs(self.wiki_load_params) do
query = query .. k .. '=' .. v .. '&'
end
parsed = URL.parse(self:getWikiServer(lang))
parsed.path = self.wiki_path
parsed.query = query .. "titles=" .. URL.escape(text)
end
-- HTTP request
request['url'] = URL.build(parsed)
print(request['url'])
request['method'] = 'GET'
request['sink'] = ltn12.sink.table(sink)
local httpRequest = parsed.scheme == 'http' and http.request or https.request
local code, headers, status = socket.skip(1, httpRequest(request))
if not headers or not sink then
return nil
end
local content = table.concat(sink)
if content ~= "" then
local ok, result = pcall(JSON.decode, content)
if ok and result then
return result
else
return nil
end
else
return nil
end
end
-- extract intro passage in wiki page
function Wikipedia:wikintro(text, lang)
local result = self:loadPage(text, lang, true, true)
if result and result.query then
local query = result.query
if query and query.normalized then
text = query.normalized[1].to or text
end
local page = query.pages[next(query.pages)]
if page and page.extract then
return text..": "..page.extract
else
local text = "Extract not found for "..text
text = text..'\n'..table.concat(wikiusage, '\n')
return text
end
else
return "Sorry an error happened"
end
end
-- search for term in wiki
function Wikipedia:wikisearch(text, lang)
local result = self:loadPage(text, lang, true, true, true)
if result and result.query then
local titles = ""
for i,item in pairs(result.query.search) do
titles = titles .. "\n" .. item["title"]
end
titles = titles ~= "" and titles or "No results found"
return titles
else
return "Sorry, an error occurred"
end
end
local function run(msg, matches)
-- TODO: Remember language (i18 on future version)
-- TODO: Support for non Wikipedias but Mediawikis
local search, term, lang
if matches[1] == "search" then
search = true
term = matches[2]
lang = nil
elseif matches[2] == "search" then
search = true
term = matches[3]
lang = matches[1]
else
term = matches[2]
lang = matches[1]
end
if not term then
term = lang
lang = nil
end
if term == "" then
local text = "Usage:\n"
text = text..table.concat(wikiusage, '\n')
return text
end
local result
if search then
result = Wikipedia:wikisearch(term, lang)
else
-- TODO: Show the link
result = Wikipedia:wikintro(term, lang)
end
return result
end
return {
description = "Searches Wikipedia and send results",
usage = wikiusage,
patterns = {
"^![Ww]iki(%w+) (search) (.+)$",
"^![Ww]iki (search) ?(.*)$",
"^![Ww]iki(%w+) (.+)$",
"^![Ww]iki ?(.*)$"
},
run = run
}
| gpl-2.0 |
CameronHynes/OpenRA | mods/cnc/maps/nod02a/nod02a.lua | 15 | 7806 | NodUnits = { "bggy", "e1", "e1", "e1", "e1", "e1", "bggy", "e1", "e1", "e1", "bggy" }
NodBaseBuildings = { "hand", "fact", "nuke" }
DfndActorTriggerActivator = { Refinery, Barracks, Powerplant, Yard }
Atk3ActorTriggerActivator = { Guard1, Guard2, Guard3, Guard4, Guard5, Guard6, Guard7 }
Atk1CellTriggerActivator = { CPos.New(45,37), CPos.New(44,37), CPos.New(45,36), CPos.New(44,36), CPos.New(45,35), CPos.New(44,35), CPos.New(45,34), CPos.New(44,34) }
Atk4CellTriggerActivator = { CPos.New(50,47), CPos.New(49,47), CPos.New(48,47), CPos.New(47,47), CPos.New(46,47), CPos.New(45,47), CPos.New(44,47), CPos.New(43,47), CPos.New(42,47), CPos.New(41,47), CPos.New(40,47), CPos.New(39,47), CPos.New(38,47), CPos.New(37,47), CPos.New(50,46), CPos.New(49,46), CPos.New(48,46), CPos.New(47,46), CPos.New(46,46), CPos.New(45,46), CPos.New(44,46), CPos.New(43,46), CPos.New(42,46), CPos.New(41,46), CPos.New(40,46), CPos.New(39,46), CPos.New(38,46) }
Atk2TriggerFunctionTime = DateTime.Seconds(40)
Atk5TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(15)
Atk6TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(20)
Atk7TriggerFunctionTime = DateTime.Seconds(50)
Pat1TriggerFunctionTime = DateTime.Seconds(30)
Atk1Waypoints = { waypoint2, waypoint4, waypoint5, waypoint6 }
Atk2Waypoints = { waypoint2, waypoint5, waypoint7, waypoint6 }
Atk3Waypoints = { waypoint2, waypoint4, waypoint5, waypoint9 }
Atk4Waypoints = { waypoint0, waypoint8, waypoint9 }
Pat1Waypoints = { waypoint0, waypoint1, waypoint2, waypoint3 }
UnitToRebuild = 'e1'
GDIStartUnits = 0
getActors = function(owner, units)
local maxUnits = 0
local actors = { }
for type, count in pairs(units) do
local globalActors = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == owner and actor.Type == type and not actor.IsDead
end)
if #globalActors < count then
maxUnits = #globalActors
else
maxUnits = count
end
for i = 1, maxUnits, 1 do
actors[#actors + 1] = globalActors[i]
end
end
return actors
end
InsertNodUnits = function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, NodUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
Reinforcements.Reinforce(player, { "mcv" }, { McvEntry.Location, McvRally.Location })
end
OnAnyDamaged = function(actors, func)
Utils.Do(actors, function(actor)
Trigger.OnDamaged(actor, func)
end)
end
CheckForBase = function(player)
local buildings = 0
Utils.Do(NodBaseBuildings, function(name)
if #player.GetActorsByType(name) > 0 then
buildings = buildings + 1
end
end)
return buildings == #NodBaseBuildings
end
DfndTriggerFunction = function()
local list = enemy.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
Atk2TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
end
Atk3TriggerFunction = function()
if not Atk3TriggerSwitch then
Atk3TriggerSwitch = true
MyActors = getActors(enemy, { ['e1'] = 4 })
Utils.Do(MyActors, function(actor)
Atk3Movement(actor)
end)
end
end
Atk5TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
end
Atk6TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 4 })
Utils.Do(MyActors, function(actor)
Atk3Movement(actor)
end)
end
Atk7TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Atk4Movement(actor)
end)
end
Pat1TriggerFunction = function()
local MyActors = getActors(enemy, { ['e1'] = 3 })
Utils.Do(MyActors, function(actor)
Pat1Movement(actor)
end)
end
Atk1Movement = function(unit)
Utils.Do(Atk1Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk2Movement = function(unit)
Utils.Do(Atk2Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk3Movement = function(unit)
Utils.Do(Atk3Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Atk4Movement = function(unit)
Utils.Do(Atk4Waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
Pat1Movement = function(unit)
Utils.Do(Pat1Waypoints, function(waypoint)
unit.Move(waypoint.Location)
end)
IdleHunt(unit)
end
WorldLoaded = function()
player = Player.GetPlayer("Nod")
enemy = Player.GetPlayer("GDI")
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
NodObjective1 = player.AddPrimaryObjective("Build a base.")
NodObjective2 = player.AddPrimaryObjective("Destroy the GDI base.")
GDIObjective = enemy.AddPrimaryObjective("Kill all enemies.")
OnAnyDamaged(Atk3ActorTriggerActivator, Atk3TriggerFunction)
Trigger.OnAllRemovedFromWorld(DfndActorTriggerActivator, DfndTriggerFunction)
Trigger.AfterDelay(Atk2TriggerFunctionTime, Atk2TriggerFunction)
Trigger.AfterDelay(Atk5TriggerFunctionTime, Atk5TriggerFunction)
Trigger.AfterDelay(Atk6TriggerFunctionTime, Atk6TriggerFunction)
Trigger.AfterDelay(Atk7TriggerFunctionTime, Atk7TriggerFunction)
Trigger.AfterDelay(Pat1TriggerFunctionTime, Pat1TriggerFunction)
Trigger.OnEnteredFootprint(Atk1CellTriggerActivator, function(a, id)
if a.Owner == player then
MyActors = getActors(enemy, { ['e1'] = 5 })
Utils.Do(MyActors, function(actor)
Atk1Movement(actor)
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(Atk4CellTriggerActivator, function(a, id)
if a.Owner == player then
MyActors = getActors(enemy, { ['e1'] = 3 } )
Utils.Do(MyActors, function(actor)
Atk2Movement(actor)
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(0, getStartUnits)
InsertNodUnits()
end
Tick = function()
if enemy.HasNoRequiredUnits() then
player.MarkCompletedObjective(NodObjective2)
end
if player.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
enemy.MarkCompletedObjective(GDIObjective)
end
end
if DateTime.GameTime % DateTime.Seconds(1) == 0 and not player.IsObjectiveCompleted(NodObjective1) and CheckForBase(player) then
player.MarkCompletedObjective(NodObjective1)
end
if DateTime.GameTime % DateTime.Seconds(3) == 0 and Barracks.IsInWorld and Barracks.Owner == enemy then
checkProduction(enemy)
end
end
checkProduction = function(player)
local Units = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == player and actor.Type == UnitToRebuild
end)
if #Units < GDIStartUnits then
local unitsToProduce = GDIStartUnits - #Units
if Barracks.IsInWorld and unitsToProduce > 0 then
local UnitsType = { }
for i = 1, unitsToProduce, 1 do
UnitsType[i] = UnitToRebuild
end
Barracks.Build(UnitsType)
end
end
end
getStartUnits = function()
local Units = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Owner == enemy
end)
Utils.Do(Units, function(unit)
if unit.Type == UnitToRebuild then
GDIStartUnits = GDIStartUnits + 1
end
end)
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
| gpl-3.0 |
TRex22/xenia | tools/build/scripts/test_suite.lua | 10 | 2547 | include("build_paths.lua")
include("util.lua")
newoption({
trigger = "test-suite-mode",
description = "Whether to merge all tests in a test_suite into a single project",
value = "MODE",
allowed = {
{ "individual", "One binary per test." },
{ "combined", "One binary per test suite (default)." },
},
})
local function combined_test_suite(test_suite_name, project_root, base_path, config)
group("tests")
project(test_suite_name)
kind("ConsoleApp")
language("C++")
includedirs(merge_arrays(config["includedirs"], {
project_root.."/"..build_tools,
project_root.."/"..build_tools_src,
project_root.."/"..build_tools.."/third_party/catch/include",
}))
libdirs(merge_arrays(config["libdirs"], {
project_root.."/"..build_bin,
}))
links(merge_arrays(config["links"], {
"gflags",
}))
files({
project_root.."/"..build_tools_src.."/test_suite_main.cc",
base_path.."/**_test.cc",
})
end
local function split_test_suite(test_suite_name, project_root, base_path, config)
local test_paths = os.matchfiles(base_path.."/**_test.cc")
for _, file_path in pairs(test_paths) do
local test_name = file_path:match("(.*).cc")
group("tests/"..test_suite_name)
project(test_suite_name.."-"..test_name)
kind("ConsoleApp")
language("C++")
includedirs(merge_arrays(config["includedirs"], {
project_root.."/"..build_tools,
project_root.."/"..build_tools_src,
project_root.."/"..build_tools.."/third_party/catch/include",
}))
libdirs(merge_arrays(config["libdirs"], {
project_root.."/"..build_bin,
}))
links(merge_arrays(config["links"], {
"gflags",
}))
files({
project_root.."/"..build_tools_src.."/test_suite_main.cc",
file_path,
})
end
end
-- Defines a test suite binary.
-- Can either be a single binary with all tests or one binary per test based on
-- the --test-suite-mode= option.
function test_suite(
test_suite_name, -- Project or group name for the entire suite.
project_root, -- Project root path (with build_tools/ under it).
base_path, -- Base source path to search for _test.cc files.
config) -- Include/lib directories and links for binaries.
if _OPTIONS["test-suite-mode"] == "individual" then
split_test_suite(test_suite_name, project_root, base_path, config)
else
combined_test_suite(test_suite_name, project_root, base_path, config)
end
end
| bsd-3-clause |
Python1320/wire | lua/wire/stools/output.lua | 9 | 1068 | WireToolSetup.setCategory( "Input, Output/Keyboard Interaction" )
WireToolSetup.open( "output", "Numpad Output", "gmod_wire_output", nil, "Numpad Outputs" )
if CLIENT then
language.Add( "Tool.wire_output.name", "Output Tool (Wire)" )
language.Add( "Tool.wire_output.desc", "Spawns an output for use with the wire system." )
language.Add( "Tool.wire_output.0", "Primary: Create/Update Output" )
language.Add( "Tool.wire_output.keygroup", "Key:" )
end
WireToolSetup.BaseLang()
WireToolSetup.SetupMax( 10 )
if SERVER then
ModelPlug_Register("Numpad")
function TOOL:GetConVars()
return self:GetClientNumber( "keygroup" )
end
end
TOOL.ClientConVar = {
model = "models/beer/wiremod/numpad.mdl",
modelsize = "",
keygroup = 1
}
function TOOL.BuildCPanel(panel)
WireToolHelpers.MakePresetControl(panel, "wire_output")
WireToolHelpers.MakeModelSizer(panel, "wire_output_modelsize")
ModelPlug_AddToCPanel(panel, "Numpad", "wire_output", true)
panel:AddControl("Numpad", {
Label = "#Tool.wire_output.keygroup",
Command = "wire_output_keygroup",
})
end
| apache-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-Cataclysm/HallsOfOrigination/Anraphet.lua | 1 | 2719 | local mod = DBM:NewMod(126, "DBM-Party-Cataclysm", 4, 70)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 79 $"):sub(12, -3))
mod:SetCreatureID(39788)
mod:SetZone()
mod:RegisterCombat("combat")
mod:RegisterEvents(
"CHAT_MSG_MONSTER_SAY"
)
mod:RegisterEventsInCombat(
"SPELL_AURA_APPLIED",
"SPELL_AURA_REMOVED",
"SPELL_CAST_START"
)
local warnAlphaBeams = mod:NewSpellAnnounce(76184, 4)
local warnOmegaStance = mod:NewSpellAnnounce(75622, 4)
local warnNemesis = mod:NewTargetAnnounce(75603, 3)
local warnBubble = mod:NewTargetAnnounce(77336, 3)
local warnImpale = mod:NewTargetAnnounce(77235, 3)
local warnInferno = mod:NewSpellAnnounce(77241, 3)
local specWarnAlphaBeams = mod:NewSpecialWarningMove(76956)
local timerAlphaBeams = mod:NewBuffActiveTimer(16, 76184)
local timerAlphaBeamsCD = mod:NewCDTimer(47, 76184)
local timerOmegaStance = mod:NewBuffActiveTimer(8, 75622)
local timerOmegaStanceCD = mod:NewCDTimer(47, 75622)
local timerNemesis = mod:NewTargetTimer(5, 75603)
local timerBubble = mod:NewCDTimer(15, 77336)
local timerImpale = mod:NewTargetTimer(3, 77235)
local timerImpaleCD = mod:NewCDTimer(20, 77235)
local timerInferno = mod:NewCDTimer(17, 77241)
local timerGauntlet = mod:NewAchievementTimer(300, 5296, "achievementGauntlet")
function mod:OnCombatStart(delay)
timerAlphaBeamsCD:Start(10-delay)
timerOmegaStanceCD:Start(35-delay)
timerGauntlet:Cancel()--it actually cancels a few seconds before engage but this doesn't require localisation and extra yell checks.
end
function mod:SPELL_AURA_APPLIED(args)
if args.spellId == 75603 then
warnNemesis:Show(args.destName)
timerNemesis:Start(args.destName)
elseif args.spellId == 77336 then
warnBubble:Show(args.destName)
timerBubble:Show()
elseif args.spellId == 77235 then
warnImpale:Show(args.destName)
timerImpale:Start(args.destName)
timerImpaleCD:Start()
elseif args.spellId == 76956 and args:IsPlayer() then
specWarnAlphaBeams:Show()
end
end
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 75603 then
timerNemesis:Cancel(args.destName)
end
end
function mod:SPELL_CAST_START(args)
if args.spellId == 76184 then
warnAlphaBeams:Show()
timerAlphaBeams:Start()
timerAlphaBeamsCD:Start()
elseif args.spellId == 75622 then
warnOmegaStance:Show()
timerOmegaStance:Start()
timerOmegaStanceCD:Start()
elseif args.spellId == 77241 then
warnInferno:Show()
timerInferno:Start()
end
end
function mod:CHAT_MSG_MONSTER_SAY(msg)
if msg == L.Brann or msg:find(L.Brann) then
self:SendSync("HoOGauntlet")
end
end
function mod:OnSync(msg)
if msg == "HoOGauntlet" then
if self:IsDifficulty("heroic5") then
timerGauntlet:Start()
end
end
end | gpl-2.0 |
xubigshu/skynet | 3rd/lpeg/re.lua | 160 | 6286 | -- $Id: re.lua,v 1.44 2013/03/26 20:11:40 roberto Exp $
-- imported functions and modules
local tonumber, type, print, error = tonumber, type, print, error
local setmetatable = setmetatable
local m = require"lpeg"
-- 'm' will be used to parse expressions, and 'mm' will be used to
-- create expressions; that is, 're' runs on 'm', creating patterns
-- on 'mm'
local mm = m
-- pattern's metatable
local mt = getmetatable(mm.P(0))
-- No more global accesses after this point
local version = _VERSION
if version == "Lua 5.2" then _ENV = nil end
local any = m.P(1)
-- Pre-defined names
local Predef = { nl = m.P"\n" }
local mem
local fmem
local gmem
local function updatelocale ()
mm.locale(Predef)
Predef.a = Predef.alpha
Predef.c = Predef.cntrl
Predef.d = Predef.digit
Predef.g = Predef.graph
Predef.l = Predef.lower
Predef.p = Predef.punct
Predef.s = Predef.space
Predef.u = Predef.upper
Predef.w = Predef.alnum
Predef.x = Predef.xdigit
Predef.A = any - Predef.a
Predef.C = any - Predef.c
Predef.D = any - Predef.d
Predef.G = any - Predef.g
Predef.L = any - Predef.l
Predef.P = any - Predef.p
Predef.S = any - Predef.s
Predef.U = any - Predef.u
Predef.W = any - Predef.w
Predef.X = any - Predef.x
mem = {} -- restart memoization
fmem = {}
gmem = {}
local mt = {__mode = "v"}
setmetatable(mem, mt)
setmetatable(fmem, mt)
setmetatable(gmem, mt)
end
updatelocale()
local I = m.P(function (s,i) print(i, s:sub(1, i-1)); return i end)
local function getdef (id, defs)
local c = defs and defs[id]
if not c then error("undefined name: " .. id) end
return c
end
local function patt_error (s, i)
local msg = (#s < i + 20) and s:sub(i)
or s:sub(i,i+20) .. "..."
msg = ("pattern error near '%s'"):format(msg)
error(msg, 2)
end
local function mult (p, n)
local np = mm.P(true)
while n >= 1 do
if n%2 >= 1 then np = np * p end
p = p * p
n = n/2
end
return np
end
local function equalcap (s, i, c)
if type(c) ~= "string" then return nil end
local e = #c + i
if s:sub(i, e - 1) == c then return e else return nil end
end
local S = (Predef.space + "--" * (any - Predef.nl)^0)^0
local name = m.R("AZ", "az", "__") * m.R("AZ", "az", "__", "09")^0
local arrow = S * "<-"
local seq_follow = m.P"/" + ")" + "}" + ":}" + "~}" + "|}" + (name * arrow) + -1
name = m.C(name)
-- a defined name only have meaning in a given environment
local Def = name * m.Carg(1)
local num = m.C(m.R"09"^1) * S / tonumber
local String = "'" * m.C((any - "'")^0) * "'" +
'"' * m.C((any - '"')^0) * '"'
local defined = "%" * Def / function (c,Defs)
local cat = Defs and Defs[c] or Predef[c]
if not cat then error ("name '" .. c .. "' undefined") end
return cat
end
local Range = m.Cs(any * (m.P"-"/"") * (any - "]")) / mm.R
local item = defined + Range + m.C(any)
local Class =
"["
* (m.C(m.P"^"^-1)) -- optional complement symbol
* m.Cf(item * (item - "]")^0, mt.__add) /
function (c, p) return c == "^" and any - p or p end
* "]"
local function adddef (t, k, exp)
if t[k] then
error("'"..k.."' already defined as a rule")
else
t[k] = exp
end
return t
end
local function firstdef (n, r) return adddef({n}, n, r) end
local function NT (n, b)
if not b then
error("rule '"..n.."' used outside a grammar")
else return mm.V(n)
end
end
local exp = m.P{ "Exp",
Exp = S * ( m.V"Grammar"
+ m.Cf(m.V"Seq" * ("/" * S * m.V"Seq")^0, mt.__add) );
Seq = m.Cf(m.Cc(m.P"") * m.V"Prefix"^0 , mt.__mul)
* (#seq_follow + patt_error);
Prefix = "&" * S * m.V"Prefix" / mt.__len
+ "!" * S * m.V"Prefix" / mt.__unm
+ m.V"Suffix";
Suffix = m.Cf(m.V"Primary" * S *
( ( m.P"+" * m.Cc(1, mt.__pow)
+ m.P"*" * m.Cc(0, mt.__pow)
+ m.P"?" * m.Cc(-1, mt.__pow)
+ "^" * ( m.Cg(num * m.Cc(mult))
+ m.Cg(m.C(m.S"+-" * m.R"09"^1) * m.Cc(mt.__pow))
)
+ "->" * S * ( m.Cg((String + num) * m.Cc(mt.__div))
+ m.P"{}" * m.Cc(nil, m.Ct)
+ m.Cg(Def / getdef * m.Cc(mt.__div))
)
+ "=>" * S * m.Cg(Def / getdef * m.Cc(m.Cmt))
) * S
)^0, function (a,b,f) return f(a,b) end );
Primary = "(" * m.V"Exp" * ")"
+ String / mm.P
+ Class
+ defined
+ "{:" * (name * ":" + m.Cc(nil)) * m.V"Exp" * ":}" /
function (n, p) return mm.Cg(p, n) end
+ "=" * name / function (n) return mm.Cmt(mm.Cb(n), equalcap) end
+ m.P"{}" / mm.Cp
+ "{~" * m.V"Exp" * "~}" / mm.Cs
+ "{|" * m.V"Exp" * "|}" / mm.Ct
+ "{" * m.V"Exp" * "}" / mm.C
+ m.P"." * m.Cc(any)
+ (name * -arrow + "<" * name * ">") * m.Cb("G") / NT;
Definition = name * arrow * m.V"Exp";
Grammar = m.Cg(m.Cc(true), "G") *
m.Cf(m.V"Definition" / firstdef * m.Cg(m.V"Definition")^0,
adddef) / mm.P
}
local pattern = S * m.Cg(m.Cc(false), "G") * exp / mm.P * (-any + patt_error)
local function compile (p, defs)
if mm.type(p) == "pattern" then return p end -- already compiled
local cp = pattern:match(p, 1, defs)
if not cp then error("incorrect pattern", 3) end
return cp
end
local function match (s, p, i)
local cp = mem[p]
if not cp then
cp = compile(p)
mem[p] = cp
end
return cp:match(s, i or 1)
end
local function find (s, p, i)
local cp = fmem[p]
if not cp then
cp = compile(p) / 0
cp = mm.P{ mm.Cp() * cp * mm.Cp() + 1 * mm.V(1) }
fmem[p] = cp
end
local i, e = cp:match(s, i or 1)
if i then return i, e - 1
else return i
end
end
local function gsub (s, p, rep)
local g = gmem[p] or {} -- ensure gmem[p] is not collected while here
gmem[p] = g
local cp = g[rep]
if not cp then
cp = compile(p)
cp = mm.Cs((cp / rep + 1)^0)
g[rep] = cp
end
return cp:match(s)
end
-- exported names
local re = {
compile = compile,
match = match,
find = find,
gsub = gsub,
updatelocale = updatelocale,
}
if version == "Lua 5.1" then _G.re = re end
return re
| mit |
shayanchabok007/antispamfox | plugins/media.lua | 297 | 1590 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
misterdustinface/gamelib-common-polyglot | src/param-adjuster/style.lua | 1 | 3041 | local palette = require 'palette'
return {
highlighted = palette.vibrant_sunset_orange,
selected = palette.vibrant_sky_blue,
pressed = palette.pastel_green,
background = palette.very_dark_gray,
background_alt = palette.true_black,
background_separator = palette.dark_gray,
element = palette.medium_gray,
element_text = palette.true_white,
progress_bar_background = palette.dark_gray,
progress_bar_foreground = palette.pastel_green,
scroll_bar_background = palette.medium_gray,
scroll_bar_foreground = palette.light_gray,
hint_background = palette.very_dark_gray,
hint_foreground = palette.true_white,
color_border = {255, 255, 255, 255},
color_border_pressed = {0, 0, 0, 255},
editor_close_button = palette.medium_gray,
editor_reset_button = palette.medium_gray,
editor_accept_button = palette.medium_gray,
editor_close_button_hover = palette.traffic_light_red,
editor_reset_button_hover = palette.traffic_light_yellow,
editor_accept_button_hover = palette.traffic_light_green,
editor_close_button_pressed = palette.lit_traffic_light_red,
editor_reset_button_pressed = palette.lit_traffic_light_yellow,
editor_accept_button_pressed = palette.lit_traffic_light_green,
progress_bar_red_foreground = {184, 13, 1, 255},
progress_bar_green_foreground = {5, 155, 7, 255},
progress_bar_blue_foreground = {3, 7, 180, 255},
progress_bar_red_background = {80, 0, 0, 255},
progress_bar_green_background = {0, 80, 0, 255},
progress_bar_blue_background = {0, 0, 80, 255},
}
-- return {
-- highlighted = {230, 120, 30, 255},
-- selected = {50, 157, 190, 255},
-- pressed = {99, 164, 120, 255},
-- background = {214, 214, 183, 255},
-- background_alt = {63, 0, 0, 255},
-- background_separator = {92, 60, 60, 255},
-- element = {80, 110, 80, 255},
-- element_text = {255, 255, 255, 255},
-- progress_bar_background = {92, 60, 60, 255},
-- progress_bar_foreground = {115, 145, 97, 255},
-- scroll_bar_background = {80, 110, 80, 255},
-- scroll_bar_foreground = {142, 53, 19, 255},
-- hint_background = {129, 96, 70, 255},
-- hint_foreground = {255, 255, 255, 255},
--
-- color_border = {255, 255, 255, 255},
-- color_border_pressed = {0, 0, 0, 255},
--
-- editor_close_button = {218, 73, 44, 255},
-- editor_reset_button = {210, 153, 59, 255},
-- editor_accept_button = {80, 255, 0, 255},
-- editor_close_button_hover = {255, 120, 0, 255},
-- editor_reset_button_hover = {255, 210, 47, 255},
-- editor_accept_button_hover = {187, 255, 8, 255},
-- editor_close_button_pressed = {255, 255, 255, 255},
-- editor_reset_button_pressed = {255, 255, 255, 255},
-- editor_accept_button_pressed = {255, 255, 255, 255},
--
-- progress_bar_red_foreground = {255, 0, 0, 255},
-- progress_bar_green_foreground = {0, 255, 0, 255},
-- progress_bar_blue_foreground = {0, 0, 255, 255},
-- progress_bar_red_background = {78, 0, 0, 255},
-- progress_bar_green_background = {0, 78, 0, 255},
-- progress_bar_blue_background = {0, 0, 73, 255},
-- }
| gpl-2.0 |
n0xus/darkstar | scripts/globals/abilities/pets/somnolence.lua | 12 | 1384 | ---------------------------------------------------
-- Somnolence
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill)
local spell = getSpell(165); --gave the ability the same power as Thunder II
local dmg = calculateMagicDamage(178,1,pet,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false);
local dINT = pet:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyPlayerResistance(pet,-1,target, dINT, ELEMENTAL_MAGIC_SKILL, ELE_DARK);
local tp = skill:getTP();
local duration = 120;
dmg = dmg*resist;
dmg = mobAddBonuses(pet,spell,target,dmg, ELE_DARK);
if (tp < 100) then
tp = 100;
end
dmg = dmg * tp / 100;
dmg = finalMagicAdjustments(pet,target,spell,dmg);
if (resist < 0.15) then --the gravity effect from this ability is more likely to land than Tail Whip
resist = 0;
end
duration = duration * resist;
if (duration > 0 and target:hasStatusEffect(EFFECT_WEIGHT) == false) then
target:addStatusEffect(EFFECT_WEIGHT, 50, 0, duration);
end
return dmg;
end | gpl-3.0 |
ozhanf/ozhanf--bot | libs/JSON.lua | 3765 | 34843 | -- -*- 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)
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
--
| gpl-2.0 |
MHPG/MHP | libs/JSON.lua | 3765 | 34843 | -- -*- 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)
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
--
| gpl-2.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/netlink.lua | 78 | 2765 | --[[
Luci configuration model for statistics - collectd netlink plugin configuration
(c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
require("luci.sys")
local devices = luci.sys.net.devices()
m = Map("luci_statistics",
translate("Netlink Plugin Configuration"),
translate(
"The netlink plugin collects extended informations like " ..
"qdisc-, class- and filter-statistics for selected interfaces."
))
-- collectd_netlink config section
s = m:section( NamedSection, "collectd_netlink", "luci_statistics" )
-- collectd_netlink.enable
enable = s:option( Flag, "enable", translate("Enable this plugin") )
enable.default = 0
-- collectd_netlink.interfaces (Interface)
interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") )
interfaces.widget = "select"
interfaces.optional = true
interfaces.size = #devices + 1
interfaces:depends( "enable", 1 )
interfaces:value("")
for i, v in ipairs(devices) do
interfaces:value(v)
end
-- collectd_netlink.verboseinterfaces (VerboseInterface)
verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") )
verboseinterfaces.widget = "select"
verboseinterfaces.optional = true
verboseinterfaces.size = #devices + 1
verboseinterfaces:depends( "enable", 1 )
verboseinterfaces:value("")
for i, v in ipairs(devices) do
verboseinterfaces:value(v)
end
-- collectd_netlink.qdiscs (QDisc)
qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") )
qdiscs.widget = "select"
qdiscs.optional = true
qdiscs.size = #devices + 1
qdiscs:depends( "enable", 1 )
qdiscs:value("")
for i, v in ipairs(devices) do
qdiscs:value(v)
end
-- collectd_netlink.classes (Class)
classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") )
classes.widget = "select"
classes.optional = true
classes.size = #devices + 1
classes:depends( "enable", 1 )
classes:value("")
for i, v in ipairs(devices) do
classes:value(v)
end
-- collectd_netlink.filters (Filter)
filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") )
filters.widget = "select"
filters.optional = true
filters.size = #devices + 1
filters:depends( "enable", 1 )
filters:value("")
for i, v in ipairs(devices) do
filters:value(v)
end
-- collectd_netlink.ignoreselected (IgnoreSelected)
ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") )
ignoreselected.default = 0
ignoreselected:depends( "enable", 1 )
return m
| gpl-2.0 |
erfan01311/supergroups | plugins/weather.lua | 274 | 1531 | do
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local function get_weather(location)
print("Finding weather in ", location)
location = string.gsub(location," ","+")
local url = BASE_URL
url = url..'?q='..location
url = url..'&units=metric'
url = url..'&appid=bd82977b86bf27fb59a04b61b657fb6f'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'The temperature in '..city
..' (' ..country..')'
..' is '..weather.main.temp..'°C'
local conditions = 'Current conditions are: '
.. weather.weather[1].description
if weather.weather[1].main == 'Clear' then
conditions = conditions .. ' ☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. ' ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. ' ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. ' ☔☔☔☔'
end
return temp .. '\n' .. conditions
end
local function run(msg, matches)
local city = 'Madrid,ES'
if matches[1] ~= '!weather' then
city = matches[1]
end
local text = get_weather(city)
if not text then
text = 'Can\'t get weather from that city.'
end
return text
end
return {
description = "weather in that city (Madrid is default)",
usage = "!weather (city)",
patterns = {
"^!weather$",
"^!weather (.*)$"
},
run = run
}
end
| gpl-2.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-BWL/localization.ru.lua | 1 | 4436 | if GetLocale() ~= "ruRU" then return end
local L
-----------------
-- Razorgore --
-----------------
L = DBM:GetModLocalization("Razorgore")
L:SetGeneralLocalization{
name = "Бритвосмерт Неукротимый"
}
L:SetTimerLocalization{
TimerAddsSpawn = "Появление аддов"
}
L:SetOptionLocalization{
TimerAddsSpawn = "Показывать таймер до первого появления аддов"
}
-------------------
-- Vaelastrasz --
-------------------
L = DBM:GetModLocalization("Vaelastrasz")
L:SetGeneralLocalization{
name = "Валестраз Порочный"
}
-----------------
-- Broodlord --
-----------------
L = DBM:GetModLocalization("Broodlord")
L:SetGeneralLocalization{
name = "Предводитель драконов Разящий Бич"
}
---------------
-- Firemaw --
---------------
L = DBM:GetModLocalization("Firemaw")
L:SetGeneralLocalization{
name = "Огнечрев"
}
---------------
-- Ebonroc --
---------------
L = DBM:GetModLocalization("Ebonroc")
L:SetGeneralLocalization{
name = "Черноскал"
}
----------------
-- Flamegor --
----------------
L = DBM:GetModLocalization("Flamegor")
L:SetGeneralLocalization{
name = "Пламегор"
}
------------------
-- Chromaggus --
------------------
L = DBM:GetModLocalization("Chromaggus")
L:SetGeneralLocalization{
name = "Хромаггус"
}
L:SetWarningLocalization{
WarnBreathSoon = "Скоро дыхание",
WarnBreath = "%s",
WarnPhase2Soon = "Скоро 2-ая фаза"
}
L:SetTimerLocalization{
TimerBreathCD = "%s восстановление"
}
L:SetOptionLocalization{
WarnBreathSoon = "Предварительное предупреждение Дыхания Хромаггуса",
WarnBreath = "Показывать предупреждение о дыханиях Хромаггуса",
TimerBreathCD = "Показывать время восстановления дыханий",
WarnPhase2Soon = "Предупреждать о второй фазе"
}
----------------
-- Nefarian --
----------------
L = DBM:GetModLocalization("Nefarian-Classic")
L:SetGeneralLocalization{
name = "Нефариан"
}
L:SetWarningLocalization{
WarnClassCallSoon = "Скоро вызов класса",
WarnClassCall = "Дебафф на %s",
WarnPhaseSoon = "Скоро фаза %s",
WarnPhase = "Фаза %s"
}
L:SetTimerLocalization{
TimerClassCall = "%s зов"
}
L:SetOptionLocalization{
TimerClassCall = "Показывать таймер классовых вызовов",
WarnClassCallSoon = "Предупреждение классовых вызовов",
WarnClassCall = "Объявлять классовый вызов",
WarnPhaseSoon = "Объявлять, когда следующая фаза скоро начнется",
WarnPhase = "Объявлять смену фаз"
}
L:SetMiscLocalization{
YellPull = "Ну что ж, поиграем!",
YellP2 = "Браво, слуги мои! Смертные утрачивают мужество! Поглядим же, как они справятся с истинным Повелителем Черной горы!!!",
YellP3 = "Не может быть! Восстаньте, мои прислужники! Послужите господину еще раз!",
YellShaman = "Шаманы, покажите, на что способны ваши тотемы!",
YellPaladin = "Паладины… Я слышал, у вас несколько жизней. Докажите.",
YellDruid = "Друиды и их дурацкие превращения… Ну что ж, поглядим!",
YellPriest = "Жрецы! Если вы собираетесь продолжать так лечить, то давайте хоть немного разнообразим процесс!",
YellWarrior = "Воины! Я знаю, вы можете бить сильнее! Ну-ка, покажите!",
YellRogue = "Rogues? Stop hiding and face me!",
YellWarlock = "Чернокнижники, ну не беритесь вы за волшебство, которого сами не понимаете! Видите, что получилось?",
YellHunter = "Охотники со своими жалкими пугачами!",
YellMage = "И маги тоже? Осторожнее надо быть, когда играешь с магией…"
} | gpl-2.0 |
RezaShomare1/xy | plugins/ingroup.lua | 527 | 44020 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Welcome to your new realm !')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been added!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'You have been promoted as the owner.')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Realm has been removed!')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'Chat rules:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setowner_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(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 = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'promote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'demote',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'about' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' then
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'about' then
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'help' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/luaexpat/tests/test.lua | 3 | 6859 | #!/usr/local/bin/lua5.1
-- See Copyright Notice in license.html
-- $Id: test.lua,v 1.6 2006/06/08 20:34:52 tomas Exp $
require"lxp"
print (lxp._VERSION)
-- basic test with no preamble
local p = lxp.new{}
p:setencoding("ISO-8859-1")
assert(p:parse[[<tag cap="5">hi</tag>]])
p:close()
preamble = [[
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE greeting [
<!ENTITY xuxu "is this a xuxu?">
<!ATTLIST to
method CDATA #FIXED "POST"
>
<!ENTITY test-entity
SYSTEM "entity1.xml">
<!NOTATION TXT SYSTEM "txt">
<!ENTITY test-unparsed SYSTEM "unparsed.txt" NDATA txt>
<!ATTLIST hihi
explanation ENTITY #REQUIRED>
]>
]]
local X
function getargs (...) X = arg end
function xgetargs (c)
return function (...)
table.insert(arg, 1, c)
table.insert(X, arg)
end
end
-------------------------------
print("testing start/end tags")
callbacks = {
StartElement = getargs,
EndElement = getargs,
}
p = lxp.new(callbacks)
assert(p:getcallbacks() == callbacks)
assert(p:parse(preamble))
assert(p:parse([[
<to priority="10" xu = "hi">
]]))
assert(X.n == 3 and X[1] == p and X[2] == "to")
x = X[3]
assert(x.priority=="10" and x.xu=="hi" and x.method=="POST")
assert(x[1] == "priority" and x[2] == "xu" and table.getn(x) == 2)
assert(p:parse("</to>"))
assert(p:parse())
p:close()
-------------------------------
print("testing CharacterData/Cdata")
callbacks = {
CharacterData = getargs,
}
p = lxp.new(callbacks)
assert(p:parse(preamble))
assert(p:parse"<to>a basic text<<![CDATA[<<ha>>]]></to>")
assert(X[1] == p and X[2] == "a basic text<<<ha>>")
callbacks.chardata = error -- no more calls to `chardata'
assert(p:parse(""))
assert(p:parse())
-- assert(p:parse()) -- no problem to finish twice. alas, it has problems
assert(p:getcallbacks() == callbacks)
p:close()
-------------------------------
callbacks = {
CharacterData = xgetargs"c",
StartCdataSection = xgetargs"s",
EndCdataSection = xgetargs"e",
}
X = {}
p = lxp.new(callbacks)
assert(p:parse(preamble))
assert(p:parse"<to>")
assert(p:parse"<![CDATA[hi]]>")
assert(table.getn(X) == 3)
assert(X[1][1] == "s" and X[1][2] == p)
assert(X[2][1] == "c" and X[2][2] == p and X[2][3] == "hi")
assert(X[3][1] == "e" and X[3][2] == p)
assert(p:parse"</to>")
p:close()
-------------------------------
print("testing ProcessingInstruction")
callbacks = {ProcessingInstruction = getargs}
p = lxp.new(callbacks)
assert(p:parse[[
<to>
<?lua how is this passed to <here>? ?>
</to>
]])
assert(X[1] == p and X[2] == "lua" and
X[3] == "how is this passed to <here>? ")
p:close()
------------------------------
print("testing Comment")
callbacks = {Comment = xgetargs"c"; CharacterData = xgetargs"t"}
X = {}
p = lxp.new(callbacks)
assert(p:parse[[
<to>some text
<!-- <a comment> with some & symbols -->
some more text</to>
]])
p:close()
assert(X[1][1] == "t" and X[2][1] == "c" and X[3][1] == "t")
assert(X[1][2] == X[2][2] and X[2][2] == X[3][2] and X[3][2] == p)
assert(X[1][3] == "some text\n")
assert(X[2][3] == " <a comment> with some & symbols ")
assert(X[3][3] == "\nsome more text")
----------------------------
print("testing ExternalEntity")
entities = {
["entity1.xml"] = "<hi/>"
}
callbacks = {StartElement = xgetargs"s", EndElement = xgetargs"e",
ExternalEntityRef = function (p, context, base, systemID, publicId)
assert(base == "/base")
return context:parse(entities[systemID])
end}
X = {}
p = lxp.new(callbacks)
p:setbase("/base")
assert(p:parse(preamble))
assert(p:parse[[
<to> &test-entity;
</to>
]])
assert(p:getbase() == "/base")
p:close()
assert(X[1][1] == "s" and X[1][3] == "to")
assert(X[2][1] == "s" and X[2][3] == "hi")
assert(X[3][1] == "e" and X[3][3] == "hi")
assert(X[4][1] == "e" and X[4][3] == "to")
----------------------------
print("testing default handles")
text = [[<to> hi &xuxu; </to>]]
local t = ""
callbacks = { Default = function (p, s) t = t .. s end }
p = lxp.new(callbacks)
assert(p:parse(preamble))
assert(p:parse(text))
p:close()
assert(t == preamble..text)
t = ""
callbacks = { DefaultExpand = function (p, s) t = t .. s end }
p = lxp.new(callbacks)
assert(p:parse(preamble))
assert(p:parse(text))
p:close()
assert(t == preamble..string.gsub(text, "&xuxu;", "is this a xuxu?"))
----------------------------
print("testing notation declarations and unparsed entities")
callbacks = {
UnparsedEntityDecl = getargs,
NotationDecl = function (p, name, base, systemId, publicId)
assert(name == "TXT" and systemId == "txt" and base == "/base")
end,
}
p = lxp.new(callbacks)
p:setbase("/base")
assert(p:parse(preamble))
assert(p:parse[[<hihi explanation="test-unparsed"/>]])
p:close()
assert(X[2] == "test-unparsed" and X[3] == "/base" and
X[4] == "unparsed.txt" and X[6] == "txt" and X.n == 6)
----------------------------
print("testing namespace declarations")
callbacks = { StartNamespaceDecl = xgetargs"sn",
EndNamespaceDecl = xgetargs"en",
StartElement = xgetargs"s",
EndElement = xgetargs"e",
}
X = {}
p = lxp.new(callbacks, "?")
assert(p:parse[[
<x xmlns:space='a/namespace'>
<space:a/>
</x>
]])
p:close()
x = X[1]
assert(x[1] == "sn" and x[3] == "space" and x[4] == "a/namespace" and table.getn(x) == 4)
x = X[3]
assert(x[1] == "s" and x[3] == "a/namespace?a")
x = X[4]
assert(x[1] == "e" and x[3] == "a/namespace?a")
x = X[6]
assert(x[1] == "en" and x[3] == "space" and table.getn(x) == 3)
-- Error reporting
p = lxp.new{}
data = [[
<tag>
<other< </other>
</tag>
]]
local status, msg, line, col, byte = p:parse(data)
assert(status == nil and type(msg) == "string" and line == 2 and col == 9)
assert(string.sub(data, byte, byte) == "<")
p = lxp.new{}
p:parse("<to>")
local status, msg, line, col, byte = p:parse()
assert(status == nil and line == 1 and col == 5 and byte == 5)
-- position reporting
callbacks = { ProcessingInstruction = function (p)
X = {p:pos()}
end
}
p = lxp.new(callbacks)
assert(p:parse[[
<to> <?test where is `pos'? ?>
</to>
]])
p:close()
assert(X[1] == 1 and X[2] == 6 and X[3] == 6) -- line, column, abs. position
print("testing errors")
-- invalid keys
assert(not pcall(lxp.new, {StatCdata=print}))
assert(pcall(lxp.new, {StatCdata=print, _nonstrict = true}))
-- invalid sequences
p = lxp.new{}
assert(p:parse[[<to></to>]])
assert(p:parse())
assert(p:parse(" ") == nil)
-- closing unfinished document
p = lxp.new{}
assert(p:parse[[<to>]])
local status, err = pcall(p.close, p)
assert(not status and string.find(err, "error closing parser"))
-- test for GC
print("\ntesting garbage collection")
collectgarbage(); collectgarbage()
local x = gcinfo()
for i=1,100000 do
-- due to a small bug in Lua...
if math.mod(i, 100) == 0 then collectgarbage() end
lxp.new({})
end
collectgarbage(); collectgarbage()
assert(math.abs(gcinfo() - x) <= 2)
print"OK"
| lgpl-3.0 |
xxlxx20/DEVKEEPER | libs/redis.lua | 566 | 1214 | local Redis = require 'redis'
local FakeRedis = require 'fakeredis'
local params = {
host = os.getenv('REDIS_HOST') or '127.0.0.1',
port = tonumber(os.getenv('REDIS_PORT') or 6379)
}
local database = os.getenv('REDIS_DB')
local password = os.getenv('REDIS_PASSWORD')
-- Overwrite HGETALL
Redis.commands.hgetall = Redis.command('hgetall', {
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
})
local redis = nil
-- Won't launch an error if fails
local ok = pcall(function()
redis = Redis.connect(params)
end)
if not ok then
local fake_func = function()
print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m')
end
fake_func()
fake = FakeRedis.new()
print('\27[31mRedis addr: '..params.host..'\27[39m')
print('\27[31mRedis port: '..params.port..'\27[39m')
redis = setmetatable({fakeredis=true}, {
__index = function(a, b)
if b ~= 'data' and fake[b] then
fake_func(b)
end
return fake[b] or fake_func
end })
else
if password then
redis:auth(password)
end
if database then
redis:select(database)
end
end
return redis
| gpl-2.0 |
mpeterv/busted | busted/languages/ua.lua | 15 | 1123 | local s = require('say')
s:set_namespace('ua')
-- 'Pending: test.lua @ 12 \n description
s:set('output.pending', 'Очікує')
s:set('output.failure', 'Зламався')
s:set('output.success', 'Пройшов')
s:set('output.pending_plural', 'очікують')
s:set('output.failure_plural', 'зламались')
s:set('output.success_plural', 'пройшли')
s:set('output.pending_zero', 'очікуючих')
s:set('output.failure_zero', 'зламаних')
s:set('output.success_zero', 'пройдених')
s:set('output.pending_single', 'очікує')
s:set('output.failure_single', 'зламався')
s:set('output.success_single', 'пройшов')
s:set('output.seconds', 'секунд')
---- definitions following are not used within the 'say' namespace
return {
failure_messages = {
'Ти зрадив %d тестів!',
'Ой йо..',
'Вороги поламали наші тести!'
},
success_messages = {
'Слава Україні! Героям Слава!',
'Тестування успішно пройдено!',
'Всі баги знищено!'
}
}
| mit |
n0xus/darkstar | scripts/zones/PsoXja/npcs/_09c.lua | 17 | 1614 | -----------------------------------
-- Area: Pso'Xja
-- NPC: _09c (Stone Gate)
-- Notes: Spawns Gargoyle when triggered
-- @pos -330.000 14.074 -261.600 9
-----------------------------------
package.loaded["scripts/zones/PsoXja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/PsoXja/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Z=player:getZPos();
if (npc:getAnimation() == 9) then
if (Z <= -19) then
if (GetMobAction(16814093) == 0) then
local Rand = math.random(1,10);
if (Rand <=9) then -- Spawn Gargoyle
player:messageSpecial(TRAP_ACTIVATED);
SpawnMob(16814093,120):updateClaim(player); -- Gargoyle
else
player:messageSpecial(TRAP_FAILS);
npc:openDoor(30);
end
else
player:messageSpecial(DOOR_LOCKED);
end
elseif (Z >= -18) then
player:startEvent(0x001A);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
if (csid == 0x001A and option == 1) then
player:setPos(260,-0.25,-20,254,111);
end
end; | gpl-3.0 |
DemonSinusa/SiemanC | LibsUser/luajit2/build/sg/lib/klass.lua | 4 | 5868 | -- $FILE klass.lua
-- $VERSION 0.0.5
-- $AUTHOR Ketmar
-- $DESCRIPTION
-- another simple prototype-based class engine with finalizers and support for 'inherited' calls
--
-- $LICENSE
-- WTFPL
--
-- $DEPENDS
-- kmodule
--
-- $USAGE
-- local newclass = class(nil, "baseclass")
-- function newclass:Method (...) print(self); end;
--
-- local class2 = class(newclass)
-- function class2:Method (...) print(self); inherited(self, ...); end;
--
-- local inst = class2("argument to Constructor!");
--
-- iherited() will do nothing if there's no inherited method. %-)
-- class can have 2 special methods:
-- :Constructor (...)
-- :Destructor ()
-- `Destructor' will be called when class is going to be destroyed by GC
--
-- DO NOT FORGET TO PASS `self' TO inherited()!
--
-- earch method can know it's name from variable (not field!) method
--
-- one can add/alter methods in class or instance in runtime.
--
-- $HISTORY
-- [+] works with Lua 5.2 beta
-- [+] added :isA(obj)
--
-- cache global functions
local assert, type, rawget, rawset = assert, type, rawget, rawset;
local getmetatable, setmetatable = getmetatable, setmetatable;
--local newproxy = newproxy;
local setfenv, getfenv = setfenv, getfenv;
local getinfo, getupvalue, setupvalue, upvaluejoin;
local newlua = false;
local _klassG;
--local print, tostring = print, tostring;
if not setfenv then
require "debug";
getinfo, getupvalue, setupvalue, upvaluejoin = debug.getinfo, debug.getupvalue, debug.setupvalue, debug.upvaluejoin;
newlua = true;
setfenv = function (f, t)
f = (type(f) == 'function' and f or getinfo(f+1, 'f').func);
local up, name = 0;
repeat
up = up+1;
name = getupvalue(f, up)
until name == '_ENV' or name == nil;
if name then
upvaluejoin(f, up, function() return name; end, 1); -- use unique upvalue
setupvalue(f, up, t);
end;
end;
getfenv = function (f)
f = (type(f) == 'function' and f or getinfo(f+1, 'f').func);
local up, name, val = 0;
repeat
up = up+1;
name, val = getupvalue(f, up);
until name == '_ENV' or name == nil;
return val;
end;
_klassG = _ENV;
end;
module(..., package.seeall);
local specialFields = {
_className=true,
_parent=true,
};
-- $DESCR
-- find field in class or in it's parents
-- $IN
-- class
-- class definition or instance
-- fld
-- field name (of any type)
-- $OUT
-- $OR good
-- value
-- $OR bad
-- nil
local function findField (class, fld)
if specialFields[fld] then return rawget(class, fld); end;
local res;
repeat
--print("findField", fld, class._className);
res = rawget(rawget(class, "_fields"), fld); if res ~= nil then return res; end;
-- not found, go up
class = rawget(class, "_parent");
until not class;
-- default result: nil
end;
-- metatable for 'see everything'
--local seeallmt = { __index = _G };
-- $DESCR
-- add field or method, install environment for method
-- $IN
-- class
-- class definition or instance
-- fld
-- field name (of any type)
-- value
-- field value or metod
-- $OUT
local function newField (class, fld, value)
local fields = rawget(class, "_fields");
if type(value) == "function" then
-- new method, change envtable to make inherited() visible
assert(not specialFields[fld]);
local inh = function (self, ...)
--print("inherited", fld, class._className);
local m = rawget(class, "_parent");
if m then
m = findField(m, fld); -- search upwards
if m then return m(self, ...); end;
end;
end;
--local env = { method = fld };
--setmetatable(env, seeallmt); setfenv(inh, env);
--print(tostring(_ENV), tostring(package.seeall));
local seeallmt;
if newlua then
seeallmt = { __index = _ENV };
else
seeallmt = { __index = _G };
end;
local env = { method = fld, inherited = inh };
setmetatable(env, seeallmt); setfenv(value, env);
end;
rawset(specialFields[fld] and class or fields, fld, value);
end;
local classNew;
-- $DESCR
-- create new class (with possible inheritance)
-- $IN
-- class parent
-- parent or nil
-- nil/str className
-- class name
-- $OUT
-- class
function class (parent, className)
if className == nil and type(parent) == "string" then className, parent = parent, nil; end;
local res = {
New = classNew,
_className = className or "<unnamed>",
_parent = parent,
_fields = {},
__call = classNew,
__index = findField,
__newindex = newField,
};
setmetatable(res, res);
if not res.isA then
-- no 'isA' method, add it
res.isA = function (self, class)
while self do
if self == class then return true; end;
self = rawget(self, "_parent");
end;
return false;
end;
end;
return res;
end;
-- $DESCR
-- create new class instance
-- $IN
-- class
-- class definition
-- ...
-- constructor args
-- $OUT
-- class_instance
classNew = function (classDef, ...)
local res = class(classDef, rawget(classDef, "_className"));
if not newlua then
-- this trick registers "object finalizer" in Lua 5.1
local proxy = newproxy(true); -- create proxy (userdata) with empty metatable
local mt = getmetatable(proxy);
mt.__gc = function ()
local dd = res.Destructor;
if dd then dd(res); end;
end;
rawset(res, "__gc", proxy);
else
-- this trick registers "object finalizer" in Lua 5.2
local mt = getmetatable(res);
rawset(mt, "__gc", function ()
local dd = res.Destructor;
if dd then dd(res); end;
end);
setmetatable(res, mt);
end;
-- end of "object finalizer" trick
local cc = res.Constructor; if cc then cc(res, ...); end;
return res;
end;
if newlua then
_klassG.class = class;
else
_G.class = class;
end;
| gpl-3.0 |
rekotc/game-engine-demo | Source/GCC4/3rdParty/luaplus51-all/Src/Modules/wxLua/samples/mdi.wx.lua | 4 | 3114 | -----------------------------------------------------------------------------
-- Name: mdi.wx.lua
-- Purpose: wxMdi wxLua sample
-- Author: J Winwood
-- Modified by:
-- Created: 16/11/2001
-- RCS-ID: $Id: mdi.wx.lua,v 1.15 2008/01/22 04:45:39 jrl1 Exp $
-- Copyright: (c) 2001 Lomtick Software. All rights reserved.
-- Licence: wxWidgets licence
-----------------------------------------------------------------------------
-- Load the wxLua module, does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit
package.cpath = package.cpath..";./?.dll;./?.so;../lib/?.so;../lib/vc_dll/?.dll;../lib/bcc_dll/?.dll;../lib/mingw_dll/?.dll;"
require("wx")
frame = nil
childList = {}
numChildren = 0
function CreateChild()
local child = wx.wxMDIChildFrame( frame, wx.wxID_ANY, "" )
child:SetSize(330,340)
childList[child:GetId()] = child
numChildren = numChildren + 1
child:SetTitle("Child "..numChildren)
function OnPaint(event)
local id = event:GetId()
local win = event:GetEventObject():DynamicCast("wxWindow")
local dc = wx.wxPaintDC(win) -- or can use childList[id]
dc:DrawRectangle(10, 10, 300, 300);
dc:DrawRoundedRectangle(20, 20, 280, 280, 20);
dc:DrawEllipse(30, 30, 260, 260);
dc:DrawText("A test string for window Id "..tostring(win:GetId()), 50, 150);
dc:delete() -- ALWAYS delete() any wxDCs created when done
end
child:Connect(wx.wxEVT_PAINT, OnPaint)
child:Show(true)
end
frame = wx.wxMDIParentFrame( wx.NULL, wx.wxID_ANY, "wxLua MDI Demo",
wx.wxDefaultPosition, wx.wxSize(450, 450),
wx.wxDEFAULT_FRAME_STYLE )
local fileMenu = wx.wxMenu()
fileMenu:Append(wx.wxID_NEW, "&New", "Create a new child window")
fileMenu:Append(wx.wxID_EXIT, "E&xit", "Quit the program")
local helpMenu = wx.wxMenu()
helpMenu:Append(wx.wxID_ABOUT, "&About", "About the wxLua MDI Application")
local menuBar = wx.wxMenuBar()
menuBar:Append(fileMenu, "&File")
menuBar:Append(helpMenu, "&Help")
frame:SetMenuBar(menuBar)
frame:CreateStatusBar(1)
frame:SetStatusText("Welcome to wxLua.")
frame:Connect(wx.wxID_NEW, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event) CreateChild() end )
frame:Connect(wx.wxID_EXIT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event) frame:Close() end )
frame:Connect(wx.wxID_ABOUT, wx.wxEVT_COMMAND_MENU_SELECTED,
function (event)
wx.wxMessageBox('This is the "About" dialog of the MDI wxLua sample.\n'..
wxlua.wxLUA_VERSION_STRING.." built with "..wx.wxVERSION_STRING,
"About wxLua",
wx.wxOK + wx.wxICON_INFORMATION,
frame )
end )
frame:Show(true)
-- Call wx.wxGetApp():MainLoop() last to start the wxWidgets event loop,
-- otherwise the wxLua program will exit immediately.
-- Does nothing if running from wxLua, wxLuaFreeze, or wxLuaEdit since the
-- MainLoop is already running or will be started by the C++ program.
wx.wxGetApp():MainLoop()
| lgpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-WotLK/HallsofReflection/LichKingEvent.lua | 1 | 1499 | local mod = DBM:NewMod(603, "DBM-Party-WotLK", 16, 276)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 155 $"):sub(12, -3))
--mod:SetEncounterID(843, 844)
mod:RegisterEvents(
"SPELL_AURA_REMOVED",
"CHAT_MSG_MONSTER_YELL"
)
local WarnWave = mod:NewAnnounce("WarnWave", 2)
local timerEscape = mod:NewAchievementTimer(360, 4526, "achievementEscape")
mod:RemoveOption("HealthFrame")
mod:RemoveOption("SpeedKillTimer")
local ragingGoul = EJ_GetSectionInfo(7276)
local witchDoctor = EJ_GetSectionInfo(7278)
local abomination = EJ_GetSectionInfo(7282)
local addWaves = {
[1] = { "6 "..ragingGoul, "1 "..witchDoctor },
[2] = { "6 "..ragingGoul, "2 "..witchDoctor, "1 "..abomination },
[3] = { "6 "..ragingGoul, "2 "..witchDoctor, "2 "..abomination },
[4] = { "12 "..ragingGoul, "3 "..witchDoctor, "3 "..abomination },
}
function mod:SPELL_AURA_REMOVED(args)
if args.spellId == 69708 then --Lich King has broken out of his iceblock, this starts actual event
if self:IsDifficulty("heroic5") then
timerEscape:Start()
end
end
end
function mod:CHAT_MSG_MONSTER_YELL(msg)
if msg == L.Wave1 or msg:find(L.Wave1) then
WarnWave:Show(table.concat(addWaves[1], ", "))
elseif msg == L.Wave2 or msg:find(L.Wave2) then
WarnWave:Show(table.concat(addWaves[2], ", "))
elseif msg == L.Wave3 or msg:find(L.Wave3) then
WarnWave:Show(table.concat(addWaves[3], ", "))
elseif msg == L.Wave4 or msg:find(L.Wave4) then
WarnWave:Show(table.concat(addWaves[4], ", "))
end
end | gpl-2.0 |
glycerine/goq | vendor/git.apache.org/thrift.git/lib/lua/TTransport.lua | 115 | 2800 | --
-- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
--
require 'Thrift'
TTransportException = TException:new {
UNKNOWN = 0,
NOT_OPEN = 1,
ALREADY_OPEN = 2,
TIMED_OUT = 3,
END_OF_FILE = 4,
INVALID_FRAME_SIZE = 5,
INVALID_TRANSFORM = 6,
INVALID_CLIENT_TYPE = 7,
errorCode = 0,
__type = 'TTransportException'
}
function TTransportException:__errorCodeToString()
if self.errorCode == self.NOT_OPEN then
return 'Transport not open'
elseif self.errorCode == self.ALREADY_OPEN then
return 'Transport already open'
elseif self.errorCode == self.TIMED_OUT then
return 'Transport timed out'
elseif self.errorCode == self.END_OF_FILE then
return 'End of file'
elseif self.errorCode == self.INVALID_FRAME_SIZE then
return 'Invalid frame size'
elseif self.errorCode == self.INVALID_TRANSFORM then
return 'Invalid transform'
elseif self.errorCode == self.INVALID_CLIENT_TYPE then
return 'Invalid client type'
else
return 'Default (unknown)'
end
end
TTransportBase = __TObject:new{
__type = 'TTransportBase'
}
function TTransportBase:isOpen() end
function TTransportBase:open() end
function TTransportBase:close() end
function TTransportBase:read(len) end
function TTransportBase:readAll(len)
local buf, have, chunk = '', 0
while have < len do
chunk = self:read(len - have)
have = have + string.len(chunk)
buf = buf .. chunk
if string.len(chunk) == 0 then
terror(TTransportException:new{
errorCode = TTransportException.END_OF_FILE
})
end
end
return buf
end
function TTransportBase:write(buf) end
function TTransportBase:flush() end
TServerTransportBase = __TObject:new{
__type = 'TServerTransportBase'
}
function TServerTransportBase:listen() end
function TServerTransportBase:accept() end
function TServerTransportBase:close() end
TTransportFactoryBase = __TObject:new{
__type = 'TTransportFactoryBase'
}
function TTransportFactoryBase:getTransport(trans)
return trans
end
| bsd-2-clause |
n0xus/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Mulnith.lua | 34 | 1299 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Mulnith
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/shop");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MULNITH_SHOP_DIALOG);
stock = {0x113A,344, -- Roast Mushroom
0x15DE,2000, -- Sis Kebabi (available when AC is in Al Zahbi)
0x15E0,3000} -- Balik Sis (available when AC is in Al Zahbi)
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 |
n0xus/darkstar | scripts/globals/bcnm.lua | 15 | 41974 | require("scripts/globals/status");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/quests");
-- NEW SYSTEM BCNM NOTES
-- The "core" functions TradeBCNM EventUpdateBCNM EventTriggerBCNM EventFinishBCNM all return TRUE if the action performed is covered by the function.
-- This means all the old code will still be executed if the new functions don't support it. This means that there is effectively 'backwards compatibility' with the old system.
-- array to map (for each zone) the item id of the valid trade item with the bcnmid in the database
-- e.g. zone, {itemid, bcnmid, itemid, bcnmid, itemid, bcnmid}
-- DO NOT INCLUDE MAAT FIGHTS
itemid_bcnmid_map = {6, {0, 0}, -- Bearclaw_Pinnacle
8, {0, 0}, -- Boneyard_Gully
10, {0, 0}, -- The_Shrouded_Maw
13, {0, 0}, -- Mine_Shaft_2716
17, {0, 0}, -- Spire of Holla
19, {0, 0}, -- Spire of Dem
21, {0, 0}, -- Spire of Mea
23, {0, 0}, -- Spire of Vahzl
31, {0, 0}, -- Monarch Linn
32, {0, 0}, -- Sealion's Den
35, {0, 0}, -- The Garden of RuHmet
36, {0, 0}, -- Empyreal Paradox
139, {1177, 4, 1552, 10, 1553, 11, 1131, 12, 1175, 15, 1180, 17}, -- Horlais Peak
140, {1551, 34, 1552, 35, 1552, 36}, -- Ghelsba Outpost
144, {1166, 68, 1178, 81, 1553, 76, 1180, 82, 1130, 79, 1552, 73}, -- Waughroon Shrine
146, {1553, 107, 1551, 105, 1177, 100}, -- Balgas Dias
163, {1130, 129}, -- Sacrificial Chamber
168, {0, 0}, -- Chamber of Oracles
170, {0, 0}, -- Full Moon Fountain
180, {1550, 293}, -- LaLoff Amphitheater
181, {0, 0}, -- The Celestial Nexus
201, {1546, 418, 1174, 417}, -- Cloister of Gales
202, {1548, 450, 1172, 449}, -- Cloister of Storms
203, {1545, 482, 1171, 481}, -- Cloister of Frost
206, {0, 0}, -- Qu'Bia Arena
207, {1544, 545}, -- Cloister of Flames
209, {1547, 578, 1169, 577}, -- Cloister of Tremors
211, {1549, 609}}; -- Cloister of Tides
-- array to map (for each zone) the BCNM ID to the Event Parameter corresponding to this ID.
-- DO NOT INCLUDE MAAT FIGHTS (only included one for testing!)
-- bcnmid, paramid, bcnmid, paramid, etc
-- The BCNMID is found via the database.
-- The paramid is a bitmask which you need to find out. Being a bitmask, it will be one of:
-- 0, 1, 2, 3, 4, 5, ...
bcnmid_param_map = {6, {640, 0},
8, {672, 0, 673, 1},
10, {704, 0, 706, 2},
13, {736, 0},
17, {768, 0},
19, {800, 0},
21, {832, 0},
23, {864, 0},
31, {960, 0, 961, 1},
32, {992, 0, 993, 1},
35, {1024, 0},
36, {1056, 0},
139, {0, 0, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 10, 10, 11, 11, 12, 12, 15, 15, 17, 17},
140, {32, 0, 33, 1, 34, 2, 35, 3, 36, 4},
144, {65, 1, 73, 9, 64, 0, 67, 3, 68, 4, 70, 6, 71, 7, 72, 8, 81, 17, 76, 12, 82, 18, 79, 15},
146, {99, 3, 96, 0, 101, 5, 102, 6, 103, 7, 107, 11, 105, 9},
163, {128, 0, 129, 1},
165, {160, 0, 161, 1},
168, {192, 0, 194, 2, 195, 3, 196, 4},
170, {224, 0, 225, 1},
179, {256, 0},
180, {293, 5, 288, 0, 289, 1, 290, 2, 291, 3, 292, 4},
181, {320, 0},
201, {416, 0, 417, 1, 418, 2, 420, 4},
202, {448, 0, 449, 1, 450, 2, 452, 4},
203, {480, 0, 481, 1, 482, 2, 484, 4},
206, {512, 0, 516, 4, 517, 5, 518, 6, 519, 7, 532, 20},
207, {544, 0, 545, 1, 547, 3},
209, {576, 0, 577, 1, 578, 2, 580, 4},
211, {608, 0, 609, 1, 611, 3}};
-- Call this onTrade for burning circles
function TradeBCNM(player, zone, trade, npc)
-- return false;
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then -- cant start a new bc
player:messageBasic(94, 0, 0);
return false;
elseif (player:hasWornItem(trade:getItem())) then -- If already used orb or testimony
player:messageBasic(56, 0, 0); -- i need correct dialog
return false;
end
if (CheckMaatFights(player, zone, trade, npc)) then -- This function returns true for maat fights
return true;
end
-- the following is for orb battles, etc
local id = ItemToBCNMID(player, zone, trade);
if (id == -1) then -- no valid BCNMs with this item
-- todo: display message based on zone text offset
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
return false;
else -- a valid BCNM with this item, start it.
mask = GetBattleBitmask(id, zone, 1);
if (mask == -1) then -- Cannot resolve this BCNMID to an event number, edit bcnmid_param_map!
print("Item is for a valid BCNM but cannot find the event parameter to display to client.");
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
return false;
end
if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances
print("all bcnm instances are currently occupied.");
npc:messageBasic(246, 0, 0); -- this wont look right in other languages!
return true;
end
player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0);
return true;
end
end;
function EventTriggerBCNM(player, npc)
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then
if (player:isInBcnm() == 1) then
player:startEvent(0x7d03); -- Run Away or Stay menu
else -- You're not in the BCNM but you have the Battlefield effect. Think: non-trader in a party
status = player:getStatusEffect(EFFECT_BATTLEFIELD);
playerbcnmid = status:getPower();
playermask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 1);
if (playermask~=-1) then
-- This gives players who did not trade to go in the option of entering the fight
player:startEvent(0x7d00, 0, 0, 0, playermask, 0, 0, 0, 0);
else
player:messageBasic(94, 0, 0);
end
end
return true;
else
if (checkNonTradeBCNM(player, npc)) then
return true;
end
end
return false;
end;
function EventUpdateBCNM(player, csid, option, entrance)
-- return false;
local id = player:getVar("trade_bcnmid"); -- this is 0 if the bcnm isnt handled by new functions
local skip = CutsceneSkip(player, npc);
print("UPDATE csid "..csid.." option "..option);
-- seen: option 2, 3, 0 in that order
if (csid == 0x7d03 and option == 2) then -- leaving a BCNM the player is currently in.
player:bcnmLeave(1);
return true;
end
if (option == 255 and csid == 0x7d00) then -- Clicked yes, try to register bcnmid
if (player:hasStatusEffect(EFFECT_BATTLEFIELD)) then
-- You're entering a bcnm but you already had the battlefield effect, so you want to go to the
-- instance that your battlefield effect represents.
player:setVar("bcnm_instanceid_tick", 0);
player:setVar("bcnm_instanceid", player:getBattlefieldID()); -- returns 255 if non-existent.
return true;
end
inst = player:bcnmRegister(id);
if (inst > 0) then
player:setVar("bcnm_instanceid", inst);
player:setVar("bcnm_instanceid_tick", 0);
player:updateEvent(0, 3, 0, 0, 1, 0);
if (entrance ~= nil and player:getBattlefield() ~= nil) then
player:getBattlefield():setEntrance(entrance);
end
-- player:tradeComplete();
else
-- no free battlefields at the moment!
print("no free instances");
player:setVar("bcnm_instanceid", 255);
player:setVar("bcnm_instanceid_tick", 0);
end
elseif (option == 0 and csid == 0x7d00) then -- Requesting an Instance
-- Increment the instance ticker.
-- The client will send a total of THREE EventUpdate packets for each one of the free instances.
-- If the first instance is free, it should respond to the first packet
-- If the second instance is free, it should respond to the second packet, etc
local instance = player:getVar("bcnm_instanceid_tick");
instance = instance + 1;
player:setVar("bcnm_instanceid_tick", instance);
if (instance == player:getVar("bcnm_instanceid")) then
-- respond to this packet
local mask = GetBattleBitmask(id, player:getZoneID(), 2);
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
local playerbcnmid = status:getPower();
if (mask < playerbcnmid) then
mask = GetBattleBitmask(playerbcnmid, player:getZoneID(), 2);
player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS
player:bcnmEnter(id);
player:setVar("bcnm_instanceid_tick", 0);
-- print("mask is "..mask)
-- print("playerbcnmid is "..playerbcnmid);
elseif (mask >= playerbcnmid) then
mask = GetBattleBitmask(id, player:getZoneID(), 2);
player:updateEvent(2, mask, 0, 1, 1, skip); -- Add mask number for the correct entering CS
player:bcnmEnter(id);
player:setVar("bcnm_instanceid_tick", 0);
-- print("mask2 is "..mask)
-- print("playerbcnmid2 is "..playerbcnmid);
end
if (entrance ~= nil and player:getBattlefield() ~= nil) then
player:getBattlefield():setEntrance(entrance);
end
elseif (player:getVar("bcnm_instanceid") == 255) then -- none free
-- print("nfa");
-- player:updateEvent(2, 5, 0, 0, 1, 0); -- @cs 32000 0 0 0 0 0 0 0 2
-- param1
-- 2=generic enter cs
-- 3=spam increment instance requests
-- 4=cleared to enter but cant while ppl engaged
-- 5=dont meet req, access denied.
-- 6=room max cap
-- param2 alters the eventfinish option (offset)
-- param7/8 = does nothing??
end
-- @pos -517 159 -209
-- @pos -316 112 -103
-- player:updateEvent(msgid, bcnmFight, 0, record, numadventurers, skip); skip=1 to skip anim
-- msgid 1=wait a little longer, 2=enters
end
return true;
end;
function EventFinishBCNM(player, csid, option)
print("FINISH csid "..csid.." option "..option);
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then -- Temp condition for normal bcnm (started with onTrigger)
return false;
else
local id = player:getVar("trade_bcnmid");
local item = player:getVar("trade_itemid");
if (id == 68 or id == 418 or id == 450 or id == 482 or id == 545 or id == 578 or id == 609 or id == 293) then
player:tradeComplete(); -- Removes the item
elseif ((item >= 1426 and item <= 1440) or item == 1130 or item == 1131 or item == 1175 or item == 1177 or item == 1180 or item == 1178 or item == 1551 or item == 1552 or item == 1553) then -- Orb and Testimony (one time item)
player:createWornItem(item);
end
return true;
end
end;
-- Returns TRUE if you're trying to do a maat fight, regardless of outcome e.g. if you trade testimony on wrong job, this will return true in order to prevent further execution of TradeBCNM. Returns FALSE if you're not doing a maat fight (in other words, not trading a testimony!!)
function CheckMaatFights(player, zone, trade, npc)
player:setVar("trade_bcnmid", 0);
player:setVar("trade_itemid", 0);
-- check for maat fights (one maat fight per zone in the db, but >1 mask entries depending on job, so we
-- need to choose the right one depending on the players job, and make sure the right testimony is traded,
-- and make sure the level is right!
local itemid = trade:getItem();
local job = player:getMainJob();
local lvl = player:getMainLvl();
if (itemid >= 1426 and itemid <= 1440) then -- The traded item IS A TESTIMONY
if (lvl < 66) then
return true;
end
if (player:isBcnmsFull() == 1) then -- temp measure, this will precheck the instances
print("all bcnm instances are currently occupied.");
npc:messageBasic(246, 0, 0);
return true;
end
-- Zone, {item, job, menu, bcnmid, ...}
maatList = {139, {1426, 1, 32, 5, 1429, 4, 64, 6, 1436, 11, 128, 7}, -- Horlais Peak [WAR BLM RNG]
144, {1430, 5, 64, 70, 1431, 6, 128, 71, 1434, 9, 256, 72}, -- Waughroon Shrine [RDM THF BST]
146, {1427, 2, 32, 101, 1428, 3, 64, 102, 1440, 15, 128, 103}, -- Balga's Dais [MNK WHM SMN]
168, {1437, 12, 4, 194, 1438, 13, 8, 195, 1439, 14, 16, 196}, -- Chamber of Oracles [SAM NIN DRG]
206, {1432, 7, 32, 517, 1433, 8, 64, 518, 1435, 10, 128, 519} };-- Qu'Bia Arena [PLD DRK BRD]
for nb = 1, table.getn(maatList), 2 do
if (maatList[nb] == zone) then
for nbi = 1, table.getn(maatList[nb + 1]), 4 do
if (itemid == maatList[nb + 1][nbi] and job == maatList[nb + 1][nbi + 1]) then
player:startEvent(0x7d00, 0, 0, 0, maatList[nb + 1][nbi + 2], 0, 0, 0, 0);
player:setVar("trade_bcnmid", maatList[nb + 1][nbi + 3]);
player:setVar("trade_itemid", maatList[nb + 1][nbi]);
break;
end
end
end
end
return true;
end
-- if it got this far then its not a testimony
return false;
end;
function GetBattleBitmask(id, zone, mode)
-- normal sweep for NON MAAT FIGHTS
local ret = -1;
local mask = 0;
for zoneindex = 1, table.getn(bcnmid_param_map), 2 do
if (zone==bcnmid_param_map[zoneindex]) then -- matched zone
for bcnmindex = 1, table.getn(bcnmid_param_map[zoneindex + 1]), 2 do -- loop bcnms in this zone
if (id==bcnmid_param_map[zoneindex+1][bcnmindex]) then -- found bcnmid
if (mode == 1) then
ret = mask + (2^bcnmid_param_map[zoneindex+1][bcnmindex+1]); -- for trigger (mode 1): 1, 2, 4, 8, 16, 32, ...
else
ret = mask + bcnmid_param_map[zoneindex+1][bcnmindex+1]; -- for update (mode 2): 0, 1, 2, 3, 4, 5, 6, ...
end
end
end
end
end
return ret;
end;
function ItemToBCNMID(player, zone, trade)
for zoneindex = 1, table.getn(itemid_bcnmid_map), 2 do
if (zone==itemid_bcnmid_map[zoneindex]) then -- matched zone
for bcnmindex = 1, table.getn(itemid_bcnmid_map[zoneindex + 1]), 2 do -- loop bcnms in this zone
if (trade:getItem()==itemid_bcnmid_map[zoneindex+1][bcnmindex]) then
local item = trade:getItem();
local questTimelineOK = 0;
-- Job/lvl condition for smn battle lvl20
if (item >= 1544 and item <= 1549 and player:getMainJob() == 15 and player:getMainLvl() >= 20) then
questTimelineOK = 1;
elseif (item == 1166 and player:getVar("aThiefinNorgCS") == 6) then -- AF3 SAM condition
questTimelineOK = 1;
elseif (item == 1551) then -- BCNM20
questTimelineOK = 1;
elseif (item == 1552) then -- BCNM30
questTimelineOK = 1;
elseif (item == 1131) then -- BCNM40
questTimelineOK = 1;
elseif (item == 1177) then -- BCNM50
questTimelineOK = 1;
elseif (item == 1130) then -- BCNM60
questTimelineOK = 1;
elseif (item == 1175) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1178) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1180) then -- KSNM30
questTimelineOK = 1;
elseif (item == 1553) then -- KSNM99
questTimelineOK = 1;
elseif (item == 1550 and (player:getQuestStatus(OUTLANDS, DIVINE_MIGHT) == QUEST_ACCEPTED or player:getQuestStatus(OUTLANDS, DIVINE_MIGHT_REPEAT) == QUEST_ACCEPTED)) then -- Divine Might
questTimelineOK = 1;
elseif (item == 1169 and player:getVar("ThePuppetMasterProgress") == 2) then -- The Puppet Master
questTimelineOK = 1;
elseif (item == 1171 and player:getVar("ClassReunionProgress") == 5) then -- Class Reunion
questTimelineOK = 1;
elseif (item == 1172 and player:getVar("CarbuncleDebacleProgress") == 3) then -- Carbuncle Debacle (Gremlims)
questTimelineOK = 1;
elseif (item == 1174 and player:getVar("CarbuncleDebacleProgress") == 6) then -- Carbuncle Debacle (Ogmios)
questTimelineOK = 1;
end
if (questTimelineOK == 1) then
player:setVar("trade_bcnmid", itemid_bcnmid_map[zoneindex+1][bcnmindex+1]);
player:setVar("trade_itemid", itemid_bcnmid_map[zoneindex+1][bcnmindex]);
return itemid_bcnmid_map[zoneindex+1][bcnmindex+1];
end
end
end
end
end
return -1;
end;
-- E.g. mission checks go here, you must know the right bcnmid for the mission you want to code.
-- You also need to know the bitmask (event param) which should be put in bcnmid_param_map
function checkNonTradeBCNM(player, npc)
local mask = 0;
local Zone = player:getZoneID();
if (Zone == 6) then -- Bearclaw_Pinnacle
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 6) then -- flames_for_the_dead
mask = GetBattleBitmask(640, Zone, 1);
player:setVar("trade_bcnmid", 640);
end
elseif (Zone == 8) then -- Boneyard_Gully
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 5) then -- head_wind
mask = GetBattleBitmask(672, Zone, 1);
player:setVar("trade_bcnmid", 672);
elseif (player:hasKeyItem(MIASMA_FILTER)==true) then
mask = GetBattleBitmask(673, Zone, 1);
player:setVar("trade_bcnmid", 673);
else
end
elseif (Zone == 10) then -- The_Shrouded_Maw
if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then-- DARKNESS_NAMED
mask = GetBattleBitmask(704, Zone, 1);
player:setVar("trade_bcnmid", 704);
elseif (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==true) then -- waking_dreams (diabolos avatar quest)
mask = GetBattleBitmask(706, Zone, 1);
player:setVar("trade_bcnmid", 706);
end
elseif (Zone == 13) then -- Mine_Shaft_2716
if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 5) then -- century_of_hardship
mask = GetBattleBitmask(736, Zone, 1);
player:setVar("trade_bcnmid", 736);
end
elseif (Zone == 17) then -- Spire of Holla
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(768, Zone, 1);
player:setVar("trade_bcnmid", 768);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_HOLLA) == false) then -- light of holla
mask = GetBattleBitmask(768, Zone, 1);
player:setVar("trade_bcnmid", 768);
end
elseif (Zone == 19) then -- Spire of Dem
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(800, Zone, 1);
player:setVar("trade_bcnmid", 800);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_DEM) == false) then -- light of dem
mask = GetBattleBitmask(800, Zone, 1);
player:setVar("trade_bcnmid", 800);
end
elseif (Zone == 21) then -- Spire of Mea
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") ==1 ) then
mask = GetBattleBitmask(832, Zone, 1);
player:setVar("trade_bcnmid", 832);
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and player:hasKeyItem(LIGHT_OF_MEA) == false) then -- light of mea
mask = GetBattleBitmask(832, Zone, 1);
player:setVar("trade_bcnmid", 832);
end
elseif (Zone == 23) then -- Spire of vahzl
if (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus")==8) then -- desires of emptiness
mask = GetBattleBitmask(864, Zone, 1);
player:setVar("trade_bcnmid", 864);
end
elseif (Zone == 31) then -- Monarch Linn
if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then -- Ancient Vows bcnm
mask = GetBattleBitmask(960, Zone, 1);
player:setVar("trade_bcnmid", 960);
elseif (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 1) then
mask = GetBattleBitmask(961, Zone, 1);
player:setVar("trade_bcnmid", 961);
end
elseif (Zone == 32) then -- Sealion's Den
if (player:getCurrentMission(COP) == ONE_TO_BE_FEARED and player:getVar("PromathiaStatus")==2) then -- one_to_be_feared
mask = GetBattleBitmask(992, Zone, 1);
player:setVar("trade_bcnmid", 992);
elseif (player:getCurrentMission(COP) == THE_WARRIOR_S_PATH) then -- warriors_path
mask = GetBattleBitmask(993, Zone, 1);
player:setVar("trade_bcnmid", 993);
end
elseif (Zone == 35) then -- The Garden of RuHmet
if (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus")==4) then -- when_angels_fall
mask = GetBattleBitmask(1024, Zone, 1);
player:setVar("trade_bcnmid", 1024);
end
elseif (Zone == 36) then -- Empyreal Paradox
if (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==2) then -- dawn
mask = GetBattleBitmask(1056, Zone, 1);
player:setVar("trade_bcnmid", 1056);
end
elseif (Zone == 139) then -- Horlais Peak
if ((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or
player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") == 9) then -- Mission 2-3
mask = GetBattleBitmask(0, Zone, 1);
player:setVar("trade_bcnmid", 0);
elseif (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") == 2) then
mask = GetBattleBitmask(3, Zone, 1)
player:setVar("trade_bcnmid", 3);
end
elseif (Zone == 140) then -- Ghelsba Outpost
local MissionStatus = player:getVar("MissionStatus");
local sTcCompleted = player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN)
if (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and (sTcCompleted and MissionStatus <= 2 or sTcCompleted == false and MissionStatus == 2)) then -- Sandy Mission 1-3
mask = GetBattleBitmask(32, Zone, 1);
player:setVar("trade_bcnmid", 32);
elseif (player:hasKeyItem(DRAGON_CURSE_REMEDY)) then -- DRG Flag Quest
mask = GetBattleBitmask(33, Zone, 1);
player:setVar("trade_bcnmid", 33);
end
elseif (Zone == 144) then -- Waughroon Shrine
if ((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or
player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") == 10) then -- Mission 2-3
mask = GetBattleBitmask(64, Zone, 1);
player:setVar("trade_bcnmid", 64);
elseif ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then
mask = GetBattleBitmask(67, Zone, 1);
player:setVar("trade_bcnmid", 67);
end
elseif (Zone == 146) then -- Balga's Dais
if (player:hasKeyItem(DARK_KEY)) then -- Mission 2-3
mask = GetBattleBitmask(96, Zone, 1);
player:setVar("trade_bcnmid", 96);
elseif ((player:getCurrentMission(WINDURST) == SAINTLY_INVITATION) and (player:getVar("MissionStatus") == 1)) then -- Mission 6-2
mask = GetBattleBitmask(99, Zone, 1);
player:setVar("trade_bcnmid", 99);
end
elseif (Zone == 163) then -- Sacrificial Chamber
if (player:getCurrentMission(ZILART) == THE_TEMPLE_OF_UGGALEPIH) then -- Zilart Mission 4
mask = GetBattleBitmask(128, Zone, 1);
player:setVar("trade_bcnmid", 128);
end
elseif (Zone == 165) then -- Throne Room
if (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") == 3) then -- Mission 5-2
mask = GetBattleBitmask(160, Zone, 1);
player:setVar("trade_bcnmid", 160);
elseif (player:getCurrentMission(BASTOK) == WHERE_TWO_PATHS_CONVERGE and player:getVar("BASTOK92") == 1) then -- bastok 9-2
mask = GetBattleBitmask(161, Zone, 1);
player:setVar("trade_bcnmid", 161);
end
elseif (Zone == 168) then -- Chamber of Oracles
if (player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES or player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then -- Zilart Mission 6
mask = GetBattleBitmask(192, Zone, 1);
player:setVar("trade_bcnmid", 192);
end
elseif (Zone == 170) then -- Full Moon Fountain
if (player:hasKeyItem(MOON_BAUBLE)) then -- The Moonlit Path
mask = GetBattleBitmask(224, Zone, 1);
player:setVar("trade_bcnmid", 224);
elseif ((player:getCurrentMission(WINDURST) == MOON_READING) and player:getVar("WINDURST92") == 2) then -- Moon reading
mask = GetBattleBitmask(225, Zone, 1);
player:setVar("trade_bcnmid", 225);
end
elseif (Zone == 179) then -- Stellar Fulcrum
if (player:getCurrentMission(ZILART) == RETURN_TO_DELKFUTTS_TOWER and player:getVar("ZilartStatus") == 3) then -- Zilart Mission 8
mask = GetBattleBitmask(256, Zone, 1);
player:setVar("trade_bcnmid", 256);
end
elseif (Zone == 180) then -- La'Loff Amphitheater
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
local qmid = npc:getID();
if (qmid == 17514791 and player:hasKeyItem(SHARD_OF_APATHY) == false) then -- Hume, Ark Angels 1
mask = GetBattleBitmask(288, Zone, 1);
player:setVar("trade_bcnmid", 288);
elseif (qmid == 17514792 and player:hasKeyItem(SHARD_OF_COWARDICE) == false) then -- Tarutaru, Ark Angels 2
mask = GetBattleBitmask(289, Zone, 1);
player:setVar("trade_bcnmid", 289);
elseif (qmid == 17514793 and player:hasKeyItem(SHARD_OF_ENVY) == false) then -- Mithra, Ark Angels 3
mask = GetBattleBitmask(290, Zone, 1);
player:setVar("trade_bcnmid", 290);
elseif (qmid == 17514794 and player:hasKeyItem(SHARD_OF_ARROGANCE) == false) then -- Elvaan, Ark Angels 4
mask = GetBattleBitmask(291, Zone, 1);
player:setVar("trade_bcnmid", 291);
elseif (qmid == 17514795 and player:hasKeyItem(SHARD_OF_RAGE) == false) then -- Galka, Ark Angels 5
mask = GetBattleBitmask(292, Zone, 1);
player:setVar("trade_bcnmid", 292);
end
end
elseif (Zone == 181) then -- The Celestial Nexus
if (player:getCurrentMission(ZILART) == THE_CELESTIAL_NEXUS) then -- Zilart Mission 16
mask = GetBattleBitmask(320, Zone, 1);
player:setVar("trade_bcnmid", 320);
end
elseif (Zone == 201) then -- Cloister of Gales
if (player:hasKeyItem(TUNING_FORK_OF_WIND)) then -- Trial by Wind
mask = GetBattleBitmask(416, Zone, 1);
player:setVar("trade_bcnmid", 416);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_EMERALD_SEAL)) then
mask = GetBattleBitmask(420, Zone, 1);
player:setVar("trade_bcnmid", 420);
end
elseif (Zone == 202) then -- Cloister of Storms
if (player:hasKeyItem(TUNING_FORK_OF_LIGHTNING)) then -- Trial by Lightning
mask = GetBattleBitmask(448, Zone, 1);
player:setVar("trade_bcnmid", 448);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_VIOLET_SEAL)) then
mask = GetBattleBitmask(452, Zone, 1);
player:setVar("trade_bcnmid", 452);
end
elseif (Zone == 203) then -- Cloister of Frost
if (player:hasKeyItem(TUNING_FORK_OF_ICE)) then -- Trial by Ice
mask = GetBattleBitmask(480, Zone, 1);
player:setVar("trade_bcnmid", 480);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AZURE_SEAL)) then
mask = GetBattleBitmask(484, Zone, 1);
player:setVar("trade_bcnmid", 484);
end
elseif (Zone == 206) then -- Qu'Bia Arena
if (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") == 11) then -- Mission 5-1
mask = GetBattleBitmask(512, Zone, 1);
player:setVar("trade_bcnmid", 512);
elseif (player:getCurrentMission(SANDORIA) == THE_HEIR_TO_THE_LIGHT and player:getVar("MissionStatus") == 3) then -- sando 9-2
mask = GetBattleBitmask(516, Zone, 1);
player:setVar("trade_bcnmid", 516);
-- Temp disabled pending BCNM mob fixes
-- elseif (player:getCurrentMission(ACP) >= THOSE_WHO_LURK_IN_SHADOWS_III and player:hasKeyItem(MARK_OF_SEED)) then -- ACP Mission 7
-- mask = GetBattleBitmask(532, Zone, 1);
-- player:setVar("trade_bcnmid", 532);
end
elseif (Zone == 207) then -- Cloister of Flames
if (player:hasKeyItem(TUNING_FORK_OF_FIRE)) then -- Trial by Fire
mask = GetBattleBitmask(544, Zone, 1);
player:setVar("trade_bcnmid", 544);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_SCARLET_SEAL)) then
mask = GetBattleBitmask(547, Zone, 1);
player:setVar("trade_bcnmid", 547);
end
elseif (Zone == 209) then -- Cloister of Tremors
if (player:hasKeyItem(TUNING_FORK_OF_EARTH)) then -- Trial by Earth
mask = GetBattleBitmask(576, Zone, 1);
player:setVar("trade_bcnmid", 576);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_AMBER_SEAL)) then
mask = GetBattleBitmask(580, Zone, 1);
player:setVar("trade_bcnmid", 580);
end
elseif (Zone == 211) then -- Cloister of Tides
if (player:hasKeyItem(TUNING_FORK_OF_WATER)) then -- Trial by Water
mask = GetBattleBitmask(608, Zone, 1);
player:setVar("trade_bcnmid", 608);
elseif (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE and player:hasKeyItem(DOMINAS_CERULEAN_SEAL)) then
mask = GetBattleBitmask(611, Zone, 1);
player:setVar("trade_bcnmid", 611);
end
end
if (mask == -1) then
print("BCNMID/Mask pair not found"); -- something went wrong
return true;
elseif (mask ~= 0) then
player:startEvent(0x7d00, 0, 0, 0, mask, 0, 0, 0, 0);
print("BCNMID found with mask "..mask);
return true;
else
return false;
end
end;
function CutsceneSkip(player, npc)
local skip = 0;
local Zone = player:getZoneID();
if (Zone == 6) then -- Bearclaw Pinnacle
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 6)) then -- flames_for_the_dead
skip = 1;
end
elseif (Zone == 8) then -- Boneyard Gully
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") > 5)) then -- head_wind
skip = 1;
end
elseif (Zone == 10) then -- The_Shrouded_Maw
if ((player:hasCompletedMission(COP, DARKNESS_NAMED)) or (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") > 2)) then -- DARKNESS_NAMED
skip = 1;
elseif ((player:hasCompleteQuest(WINDURST, WAKING_DREAMS)) or (player:hasKeyItem(WHISPER_OF_DREAMS))) then -- waking_dreams (diabolos avatar quest)
skip = 1;
end
elseif (Zone == 13) then -- Mine Shaft 2716
if ((player:hasCompletedMission(COP, THREE_PATHS)) or (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") > 5)) then -- century_of_hardship
skip = 1;
end
elseif (Zone == 17) then -- Spire of Holla
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_HOLLA))) then -- light of holla
skip = 1;
end
elseif (Zone == 19) then -- Spire of Dem
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_DEM))) then -- light of dem
skip = 1;
end
elseif (Zone == 21) then -- Spire of Mea
if ((player:hasCompletedMission(COP, THE_MOTHERCRYSTALS)) or (player:hasKeyItem(LIGHT_OF_MEA))) then -- light of mea
skip = 1;
end
elseif (Zone == 23) then -- Spire of Vahzl
if ((player:hasCompletedMission(COP, DESIRES_OF_EMPTINESS)) or (player:getCurrentMission(COP) == DESIRES_OF_EMPTINESS and player:getVar("PromathiaStatus") > 8)) then -- desires of emptiness
skip = 1;
end
elseif (Zone == 31) then -- Monarch Linn
if (player:hasCompletedMission(COP, ANCIENT_VOWS)) then -- Ancient Vows
skip = 1;
elseif ((player:hasCompletedMission(COP, THE_SAVAGE)) or (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") > 1)) then
skip = 1;
end
elseif (Zone == 32) then -- Sealion's Den
if (player:hasCompletedMission(COP, ONE_TO_BE_FEARED)) then -- one_to_be_feared
skip = 1;
elseif (player:hasCompletedMission(COP, THE_WARRIOR_S_PATH)) then -- warriors_path
skip = 1;
end
elseif (Zone == 35) then -- The Garden of RuHmet
if ((player:hasCompletedMission(COP, WHEN_ANGELS_FALL)) or (player:getCurrentMission(COP) == WHEN_ANGELS_FALL and player:getVar("PromathiaStatus") > 4)) then -- when_angels_fall
skip = 1;
end
elseif (Zone == 36) then -- Empyreal Paradox
if ((player:hasCompletedMission(COP, DAWN)) or (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus") > 2)) then -- dawn
skip = 1;
end
elseif (Zone == 139) then -- Horlais Peak
if ((player:hasCompletedMission(BASTOK, THE_EMISSARY_SANDORIA2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_SANDORIA2)) or
((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") > 9)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(SANDORIA, THE_SECRET_WEAPON)) or (player:getCurrentMission(SANDORIA) == THE_SECRET_WEAPON and player:getVar("SecretWeaponStatus") > 2)) then
skip = 1;
end
elseif (Zone == 140) then -- Ghelsba Outpost
if ((player:hasCompletedMission(SANDORIA, SAVE_THE_CHILDREN)) or (player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and player:getVar("MissionStatus") > 2)) then -- Sandy Mission 1-3
skip = 1;
elseif (player:hasCompleteQuest(SANDORIA, THE_HOLY_CREST)) then -- DRG Flag Quest
skip = 1;
end
elseif (Zone == 144) then -- Waughroon Shrine
if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_BASTOK2) or player:hasCompletedMission(WINDURST, THE_THREE_KINGDOMS_BASTOK2)) or
((player:getCurrentMission(SANDORIA) == JOURNEY_TO_BASTOK2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_BASTOK2) and player:getVar("MissionStatus") > 10)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(BASTOK, ON_MY_WAY)) or (player:getCurrentMission(BASTOK) == ON_MY_WAY and player:getVar("MissionStatus") > 2)) then
skip = 1;
end
elseif (Zone == 146) then -- Balga's Dais
if ((player:hasCompletedMission(SANDORIA, JOURNEY_TO_WINDURST2) or player:hasCompletedMission(BASTOK, THE_EMISSARY_WINDURST2)) or
((player:getCurrentMission(SANDORIA) == JOURNEY_TO_WINDURST2 or player:getCurrentMission(BASTOK) == THE_EMISSARY_WINDURST2) and player:getVar("MissionStatus") > 8)) then -- Mission 2-3
skip = 1;
elseif ((player:hasCompletedMission(WINDURST, SAINTLY_INVITATION)) or (player:getCurrentMission(WINDURST) == SAINTLY_INVITATION and player:getVar("MissionStatus") > 1)) then -- Mission 6-2
skip = 1;
end
elseif (Zone == 165) then -- Throne Room
if ((player:hasCompletedMission(player:getNation(), 15)) or (player:getCurrentMission(player:getNation()) == 15 and player:getVar("MissionStatus") > 3)) then -- Mission 5-2
skip = 1;
end
elseif (Zone == 168) then -- Chamber of Oracles
if (player:hasCompletedMission(ZILART, THROUGH_THE_QUICKSAND_CAVES)) then -- Zilart Mission 6
skip = 1;
end
elseif (Zone == 170) then -- Full Moon Fountain
if ((player:hasCompleteQuest(WINDURST, THE_MOONLIT_PATH)) or (player:hasKeyItem(WHISPER_OF_THE_MOON))) then -- The Moonlit Path
skip = 1;
end
elseif (Zone == 179) then -- Stellar Fulcrum
if (player:hasCompletedMission(ZILART, RETURN_TO_DELKFUTTS_TOWER)) then -- Zilart Mission 8
skip = 1;
end
elseif (Zone == 180) then -- La'Loff Amphitheater
if (player:hasCompletedMission(ZILART, ARK_ANGELS)) then
skip = 1;
end
elseif (Zone == 181) then -- The Celestial Nexus
if (player:hasCompletedMission(ZILART, THE_CELESTIAL_NEXUS)) then -- Zilart Mission 16
skip = 1;
end
elseif (Zone == 201) then -- Cloister of Gales
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WIND)) or (player:hasKeyItem(WHISPER_OF_GALES))) then -- Trial by Wind
skip = 1;
end
elseif (Zone == 202) then -- Cloister of Storms
if ((player:hasCompleteQuest(OTHER_AREAS, TRIAL_BY_LIGHTNING)) or (player:hasKeyItem(WHISPER_OF_STORMS))) then -- Trial by Lightning
skip = 1;
end
elseif (Zone == 203) then -- Cloister of Frost
if ((player:hasCompleteQuest(SANDORIA, TRIAL_BY_ICE)) or (player:hasKeyItem(WHISPER_OF_FROST))) then -- Trial by Ice
skip = 1;
end
elseif (Zone == 206) then -- Qu'Bia Arena
if ((player:hasCompletedMission(player:getNation(), 14)) or (player:getCurrentMission(player:getNation()) == 14 and player:getVar("MissionStatus") > 11)) then -- Mission 5-1
skip = 1;
elseif ((player:hasCompletedMission(player:getNation(), 23)) or (player:getCurrentMission(player:getNation()) == 23 and player:getVar("MissionStatus") > 4)) then -- Mission 9-2
skip = 1;
end
elseif (Zone == 207) then -- Cloister of Flames
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_FIRE)) or (player:hasKeyItem(WHISPER_OF_FLAMES))) then -- Trial by Fire
skip = 1;
end
elseif (Zone == 209) then -- Cloister of Tremors
if ((player:hasCompleteQuest(BASTOK, TRIAL_BY_EARTH)) or (player:hasKeyItem(WHISPER_OF_TREMORS))) then -- Trial by Earth
skip = 1;
end
elseif (Zone == 211) then -- Cloister of Tides
if ((player:hasCompleteQuest(OUTLANDS, TRIAL_BY_WATER)) or (player:hasKeyItem(WHISPER_OF_TIDES))) then -- Trial by Water
skip = 1;
end
end
return skip;
end;
| gpl-3.0 |
n0xus/darkstar | scripts/globals/weaponskills/blade_jin.lua | 30 | 1426 | -----------------------------------
-- Blade Jin
-- Katana weapon skill
-- Skill Level: 200
-- Delivers a three-hit attack. Chance of params.critical varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget & Thunder Gorget.
-- Aligned with the Breeze Belt & Thunder Belt.
-- Element: Wind
-- Modifiers: STR:30% ; DEX:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 3;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.3; 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.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.375; params.ftp200 = 1.375; params.ftp300 = 1.375;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
n0xus/darkstar | scripts/zones/The_Shrouded_Maw/bcnms/darkness_named.lua | 17 | 2518 | -----------------------------------
-- Area: The_Shrouded_Maw
-- Name: darkness_named
-----------------------------------
package.loaded["scripts/zones/The_Shrouded_Maw/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/zones/The_Shrouded_Maw/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
local inst = player:getBattlefieldID();
if (inst == 1) then
local TileOffset = 16818258;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
elseif (inst == 2) then
local TileOffset = 16818266;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
elseif (inst == 3) then
local TileOffset = 16818274;
for i = TileOffset, TileOffset+7 do
local TileOffsetA = GetNPCByID(i):getAnimation();
if (TileOffsetA == 8) then
GetNPCByID(i):setAnimation(9);
end
end
end
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:addExp(1000);
if (player:getCurrentMission(COP) == DARKNESS_NAMED and player:getVar("PromathiaStatus") == 2) then
player:addTitle(TRANSIENT_DREAMER);
player:setVar("PromathiaStatus",3);
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
end;
| gpl-3.0 |
n0xus/darkstar | scripts/globals/abilities/pets/zantetsuken.lua | 21 | 1387 | ---------------------------------------------------
-- Zantetsuken
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/magic");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, master)
local power = master:getMP() / master:getMaxMP();
if (target:isNM()) then
local dmg = 0.1 * target:getHP() + 0.1 * target:getHP() * power;
if (dmg > 9999) then
dmg = 9999;
end
dmg = MobMagicalMove(pet,target,skill,dmg,ELE_DARK,1,TP_NO_EFFECT,0);
dmg = mobAddBonuses(pet, nil, target, dmg.dmg, ELE_DARK);
dmg = AvatarFinalAdjustments(dmg,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1);
target:delHP(dmg);
target:updateEnmityFromDamage(pet,dmg);
return dmg;
else
local chance = (100 * power) / skill:getTotalTargets();
if math.random(0,99) < chance and target:getAnimation() ~= 33 then
skill:setMsg(MSG_ENFEEB_IS);
target:delHP(target:getHP());
return EFFECT_KO;
else
skill:setMsg(282);
return 0;
end
end
end | gpl-3.0 |
n0xus/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Goblin_Statue.lua | 12 | 3366 | -----------------------------------
-- Area: Dynamis Beaucedine
-- NPC: Goblin Statue
-- Map Position: http://images1.wikia.nocookie.net/__cb20090312005233/ffxi/images/thumb/b/b6/Bea.jpg/375px-Bea.jpg
-----------------------------------
package.loaded["scripts/zones/Dynamis-Beaucedine/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Beaucedine/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
local X = mob:getXPos();
local Y = mob:getYPos();
local Z = mob:getZPos();
local spawnList = beaucedineGoblinList;
if (mob:getStatPoppedMobs() == false) then
mob:setStatPoppedMobs(true);
for nb = 1, table.getn(spawnList), 2 do
if (mob:getID() == spawnList[nb]) then
for nbi = 1, table.getn(spawnList[nb + 1]), 1 do
if ((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end
local mobNBR = spawnList[nb + 1][nbi];
if (mobNBR <= 20) then
if (mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY)
local DynaMob = getDynaMob(target,mobNBR,2);
if (DynaMob ~= nil) then
-- Spawn Mob
SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob):setPos(X,Y,Z);
GetMobByID(DynaMob):setSpawn(X,Y,Z);
-- Spawn Pet for BST, DRG, and SMN
if (mobNBR == 9 or mobNBR == 15) then
SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(DynaMob + 1):setPos(X,Y,Z);
GetMobByID(DynaMob + 1):setSpawn(X,Y,Z);
end
end
elseif (mobNBR > 20) then
SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
local MJob = GetMobByID(mobNBR):getMainJob();
if (MJob == 9 or MJob == 15) then
-- Spawn Pet for BST, DRG, and SMN
SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());
GetMobByID(mobNBR + 1):setPos(X,Y,Z);
GetMobByID(mobNBR + 1):setSpawn(X,Y,Z);
end
end
end
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- Time Bonus: 031 046
if (mobID == 17326860 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
elseif (mobID == 17326875 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(15);
mob:addInBattlefieldList();
-- HP Bonus: 037 041 044 051 053
elseif (mobID == 17326866 or mobID == 17326870 or mobID == 17326873 or mobID == 17326880 or mobID == 17326882) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- MP Bonus: 038 040 045 049 052 104
elseif (mobID == 17326867 or mobID == 17326869 or mobID == 17326874 or mobID == 17326878 or mobID == 17326881 or mobID == 17326933) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
feiying1460/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/base/luasrc/sgi/cgi.lua | 87 | 2260 | --[[
LuCI - SGI-Module for CGI
Description:
Server Gateway Interface for CGI
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
exectime = os.clock()
module("luci.sgi.cgi", package.seeall)
local ltn12 = require("luci.ltn12")
require("nixio.util")
require("luci.http")
require("luci.sys")
require("luci.dispatcher")
-- Limited source to avoid endless blocking
local function limitsource(handle, limit)
limit = limit or 0
local BLOCKSIZE = ltn12.BLOCKSIZE
return function()
if limit < 1 then
handle:close()
return nil
else
local read = (limit > BLOCKSIZE) and BLOCKSIZE or limit
limit = limit - read
local chunk = handle:read(read)
if not chunk then handle:close() end
return chunk
end
end
end
function run()
local r = luci.http.Request(
luci.sys.getenv(),
limitsource(io.stdin, tonumber(luci.sys.getenv("CONTENT_LENGTH"))),
ltn12.sink.file(io.stderr)
)
local x = coroutine.create(luci.dispatcher.httpdispatch)
local hcache = ""
local active = true
while coroutine.status(x) ~= "dead" do
local res, id, data1, data2 = coroutine.resume(x, r)
if not res then
print("Status: 500 Internal Server Error")
print("Content-Type: text/plain\n")
print(id)
break;
end
if active then
if id == 1 then
io.write("Status: " .. tostring(data1) .. " " .. data2 .. "\r\n")
elseif id == 2 then
hcache = hcache .. data1 .. ": " .. data2 .. "\r\n"
elseif id == 3 then
io.write(hcache)
io.write("\r\n")
elseif id == 4 then
io.write(tostring(data1 or ""))
elseif id == 5 then
io.flush()
io.close()
active = false
elseif id == 6 then
data1:copyz(nixio.stdout, data2)
data1:close()
end
end
end
end
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Dynamis-Beaucedine/mobs/Angra_Mainyu.lua | 11 | 2401 | -----------------------------------
-- Area: Dynamis Beaucedine
-- NPC: Angra Mainyu
-- Mega Boss
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
SpawnMob(17326082):updateEnmity(target); -- Fire_Pukis
SpawnMob(17326083):updateEnmity(target); -- Poison_Pukis
SpawnMob(17326084):updateEnmity(target); -- Wind_Pukis
SpawnMob(17326085):updateEnmity(target); -- Petro_Pukis
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
if (GetMobAction(17326082) == 0 and GetMobAction(17326279) ~= 0) then
SpawnMob(17326082):updateEnmity(target);
end
if (GetMobAction(17326083) == 0 and GetMobAction(17326468) ~= 0) then
SpawnMob(17326083):updateEnmity(target);
end
if (GetMobAction(17326084) == 0 and GetMobAction(17326353) ~= 0) then
SpawnMob(17326084):updateEnmity(target);
end
if (GetMobAction(17326085) == 0 and GetMobAction(17326207) ~= 0) then
SpawnMob(17326085):updateEnmity(target);
end
end;
-- Return the selected spell ID.
function onMonsterMagicPrepare(mob, target)
if (mob:getHPP() <= 25) then
return 244; -- Death
else
-- Can cast Blindga, Death, Graviga, Silencega, and Sleepga II.
-- Casts Graviga every time before he teleports.
rnd = math.random();
if (rnd < 0.2) then
return 361; -- Blindga
elseif (rnd < 0.4) then
return 244; -- Death
elseif (rnd < 0.6) then
return 366; -- Graviga
elseif (rnd < 0.8) then
return 274; -- Sleepga II
else
return 359; -- Silencega
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
killer:addTitle(DYNAMISBEAUCEDINE_INTERLOPER); -- Add title
killer:setVar("DynaBeaucedine_Win",1);
if (killer:hasKeyItem(HYDRA_CORPS_INSIGNIA) == false) then
killer:addKeyItem(HYDRA_CORPS_INSIGNIA);
killer:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_INSIGNIA);
end
end;
| gpl-3.0 |
CodedNil/Azure | lua/azure/sv_azure.lua | 1 | 1220 | include("sh_util.lua")
AddCSLuaFile("sh_util.lua")
util.AddNetworkString("azure_AdminChat")
hook.Add("PlayerSay", "azure_PlayerSay", function(Client, Text)
if (string.StartWith(Text, azure.CmdStart)) then
Text = Text:sub(#azure.CmdStart + 1)
local Command = Text:match("([_%w]+)")
if (Command) then
Command = Command:lower()
local Arguments = string.Explode(" ", Text:sub(#Command + 2))
local Message = azure.RunCommand(Client, Command, Arguments)
if (Message) then
Client:ChatPrint(Message)
end
end
return ""
elseif (string.StartWith(Text, azure.AdminCmdStart)) then -- Todo make it only show to those with a permission
local Players = player.GetAll()
Text = Text:sub(#azure.AdminCmdStart + 1)
net.Start("azure_AdminChat")
net.WriteUInt(Client:EntIndex(), 8)
net.WriteString(Text)
net.Send(Players)
return ""
end
end)
function AzureCommand(Client, Command, Arguments)
local NewArguments = {}
for i, v in ipairs(Arguments) do
if (i ~= 1) then
table.insert(NewArguments, v)
end
end
local Message = azure.RunCommand(Client, Arguments[1], NewArguments)
if (Message) then
Client:ChatPrint(Message)
end
end
concommand.Add("az", AzureCommand) | gpl-3.0 |
davymai/CN-QulightUI | Interface/AddOns/Broker_Garrison/Libs/AceGUI-3.0-SharedMediaWidgets/Libs/AceGUI-3.0/widgets/AceGUIWidget-Slider.lua | 42 | 8139 | --[[-----------------------------------------------------------------------------
Slider Widget
Graphical Slider, like, for Range values.
-------------------------------------------------------------------------------]]
local Type, Version = "Slider", 21
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local min, max, floor = math.min, math.max, math.floor
local tonumber, pairs = tonumber, pairs
-- WoW APIs
local PlaySound = PlaySound
local CreateFrame, UIParent = CreateFrame, UIParent
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: GameFontHighlightSmall
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function UpdateText(self)
local value = self.value or 0
if self.ispercent then
self.editbox:SetText(("%s%%"):format(floor(value * 1000 + 0.5) / 10))
else
self.editbox:SetText(floor(value * 100 + 0.5) / 100)
end
end
local function UpdateLabels(self)
local min, max = (self.min or 0), (self.max or 100)
if self.ispercent then
self.lowtext:SetFormattedText("%s%%", (min * 100))
self.hightext:SetFormattedText("%s%%", (max * 100))
else
self.lowtext:SetText(min)
self.hightext:SetText(max)
end
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Frame_OnMouseDown(frame)
frame.obj.slider:EnableMouseWheel(true)
AceGUI:ClearFocus()
end
local function Slider_OnValueChanged(frame)
local self = frame.obj
if not frame.setup then
local newvalue = frame:GetValue()
if self.step and self.step > 0 then
local min_value = self.min or 0
newvalue = floor((newvalue - min_value) / self.step + 0.5) * self.step + min_value
end
if newvalue ~= self.value and not self.disabled then
self.value = newvalue
self:Fire("OnValueChanged", newvalue)
end
if self.value then
UpdateText(self)
end
end
end
local function Slider_OnMouseUp(frame)
local self = frame.obj
self:Fire("OnMouseUp", self.value)
end
local function Slider_OnMouseWheel(frame, v)
local self = frame.obj
if not self.disabled then
local value = self.value
if v > 0 then
value = min(value + (self.step or 1), self.max)
else
value = max(value - (self.step or 1), self.min)
end
self.slider:SetValue(value)
end
end
local function EditBox_OnEscapePressed(frame)
frame:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
if self.ispercent then
value = value:gsub('%%', '')
value = tonumber(value) / 100
else
value = tonumber(value)
end
if value then
PlaySound("igMainMenuOptionCheckBoxOn")
self.slider:SetValue(value)
self:Fire("OnMouseUp", value)
end
end
local function EditBox_OnEnter(frame)
frame:SetBackdropBorderColor(0.5, 0.5, 0.5, 1)
end
local function EditBox_OnLeave(frame)
frame:SetBackdropBorderColor(0.3, 0.3, 0.3, 0.8)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetWidth(200)
self:SetHeight(44)
self:SetDisabled(false)
self:SetIsPercent(nil)
self:SetSliderValues(0,100,1)
self:SetValue(0)
self.slider:EnableMouseWheel(false)
end,
-- ["OnRelease"] = nil,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.slider:EnableMouse(false)
self.label:SetTextColor(.5, .5, .5)
self.hightext:SetTextColor(.5, .5, .5)
self.lowtext:SetTextColor(.5, .5, .5)
--self.valuetext:SetTextColor(.5, .5, .5)
self.editbox:SetTextColor(.5, .5, .5)
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
else
self.slider:EnableMouse(true)
self.label:SetTextColor(1, .82, 0)
self.hightext:SetTextColor(1, 1, 1)
self.lowtext:SetTextColor(1, 1, 1)
--self.valuetext:SetTextColor(1, 1, 1)
self.editbox:SetTextColor(1, 1, 1)
self.editbox:EnableMouse(true)
end
end,
["SetValue"] = function(self, value)
self.slider.setup = true
self.slider:SetValue(value)
self.value = value
UpdateText(self)
self.slider.setup = nil
end,
["GetValue"] = function(self)
return self.value
end,
["SetLabel"] = function(self, text)
self.label:SetText(text)
end,
["SetSliderValues"] = function(self, min, max, step)
local frame = self.slider
frame.setup = true
self.min = min
self.max = max
self.step = step
frame:SetMinMaxValues(min or 0,max or 100)
UpdateLabels(self)
frame:SetValueStep(step or 1)
if self.value then
frame:SetValue(self.value)
end
frame.setup = nil
end,
["SetIsPercent"] = function(self, value)
self.ispercent = value
UpdateLabels(self)
UpdateText(self)
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local SliderBackdrop = {
bgFile = "Interface\\Buttons\\UI-SliderBar-Background",
edgeFile = "Interface\\Buttons\\UI-SliderBar-Border",
tile = true, tileSize = 8, edgeSize = 8,
insets = { left = 3, right = 3, top = 6, bottom = 6 }
}
local ManualBackdrop = {
bgFile = "Interface\\ChatFrame\\ChatFrameBackground",
edgeFile = "Interface\\ChatFrame\\ChatFrameBackground",
tile = true, edgeSize = 1, tileSize = 5,
}
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:EnableMouse(true)
frame:SetScript("OnMouseDown", Frame_OnMouseDown)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormal")
label:SetPoint("TOPLEFT")
label:SetPoint("TOPRIGHT")
label:SetJustifyH("CENTER")
label:SetHeight(15)
local slider = CreateFrame("Slider", nil, frame)
slider:SetOrientation("HORIZONTAL")
slider:SetHeight(15)
slider:SetHitRectInsets(0, 0, -10, 0)
slider:SetBackdrop(SliderBackdrop)
slider:SetThumbTexture("Interface\\Buttons\\UI-SliderBar-Button-Horizontal")
slider:SetPoint("TOP", label, "BOTTOM")
slider:SetPoint("LEFT", 3, 0)
slider:SetPoint("RIGHT", -3, 0)
slider:SetValue(0)
slider:SetScript("OnValueChanged",Slider_OnValueChanged)
slider:SetScript("OnEnter", Control_OnEnter)
slider:SetScript("OnLeave", Control_OnLeave)
slider:SetScript("OnMouseUp", Slider_OnMouseUp)
slider:SetScript("OnMouseWheel", Slider_OnMouseWheel)
local lowtext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
lowtext:SetPoint("TOPLEFT", slider, "BOTTOMLEFT", 2, 3)
local hightext = slider:CreateFontString(nil, "ARTWORK", "GameFontHighlightSmall")
hightext:SetPoint("TOPRIGHT", slider, "BOTTOMRIGHT", -2, 3)
local editbox = CreateFrame("EditBox", nil, frame)
editbox:SetAutoFocus(false)
editbox:SetFontObject(GameFontHighlightSmall)
editbox:SetPoint("TOP", slider, "BOTTOM")
editbox:SetHeight(14)
editbox:SetWidth(70)
editbox:SetJustifyH("CENTER")
editbox:EnableMouse(true)
editbox:SetBackdrop(ManualBackdrop)
editbox:SetBackdropColor(0, 0, 0, 0.5)
editbox:SetBackdropBorderColor(0.3, 0.3, 0.30, 0.80)
editbox:SetScript("OnEnter", EditBox_OnEnter)
editbox:SetScript("OnLeave", EditBox_OnLeave)
editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed)
editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed)
local widget = {
label = label,
slider = slider,
lowtext = lowtext,
hightext = hightext,
editbox = editbox,
alignoffset = 25,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
slider.obj, editbox.obj = widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type,Constructor,Version)
| gpl-2.0 |
n0xus/darkstar | scripts/zones/Port_Jeuno/npcs/Rinzei.lua | 34 | 1369 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Rinzei
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,18) == false) then
player:startEvent(315);
else
player:startEvent(0x38);
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 == 315) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",18,true);
end
end;
| gpl-3.0 |
n0xus/darkstar | scripts/zones/Windurst_Waters/npcs/Clais.lua | 36 | 1715 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Clais
-- Involved In Quest: Hat in Hand
-- @zone = 238
-- @pos = -31 -3 11
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND);
if ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and testflag(tonumber(player:getVar("QuestHatInHand_var")),8) == false) then
player:startEvent(0x0039); -- Show Off Hat
else
player:startEvent(0x025a); -- Standard Conversation
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);
if (csid == 0x0039) then -- Show Off Hat
player:setVar("QuestHatInHand_var",player:getVar("QuestHatInHand_var")+8);
player:setVar("QuestHatInHand_count",player:getVar("QuestHatInHand_count")+1);
end
end;
| gpl-3.0 |
rmobis/Raphael-Library | src/Events.lua | 1 | 5765 | --[[
* Handles talking to a NPC. Takes care of all waiting times and checks if NPCs
* channel is open. By default, it uses a waiting method that waits until it
* sees the the message was actually sent. Optionally, you can opt for the
* original waitping() solution, passing `normalWait` as true.
*
* @since 0.1.0
* @updated 1.4.0
*
* @param {string...} messages - Messages to be said
* @param {boolean} [normalWait] - If waitping should be used as
* waiting method; defaults to false
*
* @returns {boolean} - A value indicating whether all
* messages were correctly said
--]]
function npctalk(...)
local args = {...}
-- Checks for NPCs around
-- Blatantly (almost) copied from @Colandus' lib
local npcFound = false
foreach creature c 'nfs' do
if c.dist <= 3 then
npcFound = true
break
end
end
if not npcFound then
return false
end
-- Checks for aditional parameters
local normalWait = false
if type(table.last(args)) == 'boolean' then
normalWait = table.remove(args)
end
-- Use specified waiting method
local waitFunction = waitmessage
if normalWait then
waitFunction = function()
waitping()
return true
end
end
-- We gotta convert all args to strings because there may be some numbers
-- in between and those wouldn't be correctly said by the bot.
table.map(args, tostring)
local msgSuccess = false
-- Open NPCs channel if needed
if not ischannel('NPCs') then
while not msgSuccess do
say(args[1])
msgSuccess = waitFunction($name, args[1], 3000, true, MSG_DEFAULT)
end
table.remove(args, 1)
wait(400, 600)
end
for k, v in ipairs(args) do
msgSuccess = false
while not msgSuccess do
-- When we have fast hotkeys enabled, the bot sends the messages way
-- too fast and this ends up causing a huge problem because the
-- server can't properly read them. So we simulate the time it would
-- take to actually type the text.
if $fasthotkeys then
local minWait, maxWait = get('Settings/TypeWaitTime'):match(REGEX_RANGE)
minWait, maxWait = tonumber(minWait), tonumber(maxWait)
-- Even though values can go as low as 10 x 10 ms, there's a
-- physical cap at about 30 x 30 ms.
minWait, maxWait = math.max(minWait, 30), math.max(maxWait, 30)
local waitTime = 0
for i = 1, #v do
waitTime = waitTime + math.random(minWait, maxWait)
end
-- My measurements indicate at least 15% extra time to actually
-- press the keys then it should take, even with relatively
-- high settings. However, the measurements go relatively high
-- when using extremely short strings. So I made up this weird
-- formula with the help of Wolfram Alpha.
waitTime = waitTime * (1 + (3 * (1.15 / #v)^1.15))
wait(waitTime)
end
say('NPCs', v)
msgSuccess = waitFunction($name, v, 3000, true, MSG_SENT)
if not msgSuccess then
if not ischannel('NPCs') then
return npctalk(select(k, ...))
end
end
end
end
return true
end
--[[
* Handles pressing specific keys in the given sentence. It reads the `keys`
* argument and presses the keys as if a human was writing it. For special
* keys, make use of brackets. For instance, to press delete, use [DELETE].
*
* @since 0.1.0
*
* @param {string} keys - Keys to be pressed
--]]
function press(keys)
keys = keys:upper()
for i, j, k in string.gmatch(keys .. '[]', '([^%[]-)%[(.-)%]([^%[]-)') do
for n = 1, #i do
keyevent(KEYS[i:at(n)])
end
if #j then
keyevent(KEYS[j])
end
for n = 1, #k do
keyevent(KEYS[k:at(n)])
end
end
end
--[[
* Closes the battle list.
*
* NOTE: This is pretty much an alias to openbattlelist(true), because I found
* that boolean parameter to be pretty stupid.
*
* @since 1.5.0
--]]
function closebattlelist()
openbattlelist(true)
end
--[[
* Sends a private message to a given player.
*
* @since 1.6.0
*
* @param {string} name - Name of the player to send the
* message to
* @param {string} message - Message content
--]]
function pm(name, message)
say(('*%s* %s'):format(name, message))
end
--[[
* Yells message on a given channel.
*
* @since 1.6.0
*
* @param {string} [channel] - Channel to yell the message on message to
* @param {string} message - Message content
--]]
function yell(channel, message)
if not message then
message, channel = channel, 'Default'
end
say(channel, ('#y %s'):format(message))
end
--[[
* Whispers message on a given channel.
*
* @since 1.6.0
*
* @param {string} [channel] - Channel to whisper the message on message to
* @param {string} message - Message content
--]]
function whisper(channel, message)
if not message then
message, channel = channel, 'Default'
end
say(channel, ('#w %s'):format(message))
end
| mit |
n0xus/darkstar | scripts/zones/Dragons_Aery/npcs/relic.lua | 38 | 1837 | -----------------------------------
-- Area: Dragon's Aery
-- NPC: <this space intentionally left blank>
-- @pos -20 -2 61 154
-----------------------------------
package.loaded["scripts/zones/Dragons_Aery/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Dragons_Aery/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Working on correct relic, 4 items, Stage 4 item, Shard, Necropsyche, currencypiece
if (player:getVar("RELIC_IN_PROGRESS") == 18275 and trade:getItemCount() == 4 and trade:hasItemQty(18275,1) and
trade:hasItemQty(1573,1) and trade:hasItemQty(1589,1) and trade:hasItemQty(1454,1)) then
player:startEvent(3,18276);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 3) then
if (player:getFreeSlotsCount() < 2) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18276);
player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,1453);
else
player:tradeComplete();
player:addItem(18276);
player:addItem(1453,30);
player:messageSpecial(ITEM_OBTAINED,18276);
player:messageSpecial(ITEMS_OBTAINED,1453,30);
player:setVar("RELIC_IN_PROGRESS",0);
end
end
end; | gpl-3.0 |
n0xus/darkstar | scripts/zones/Fort_Ghelsba/npcs/Treasure_Chest.lua | 19 | 2565 | -----------------------------------
-- Area: Fort Ghelsba
-- NPC: Treasure Chest
-- @zone 141
-----------------------------------
package.loaded["scripts/zones/Fort_Ghelsba/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/treasure");
require("scripts/zones/Fort_Ghelsba/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1024,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(1024,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();
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);
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
UpdateTreasureSpawnPoint(npc:getID());
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1024);
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 |
RockySeven3161/Unknown.. | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
n0xus/darkstar | scripts/globals/items/beluga.lua | 41 | 1064 | -----------------------------------------
-- ID: Beluga
-- Beluga
-- Additional Effect: Ice Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_WATER, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_WATER,0);
dmg = adjustForTarget(target,dmg,ELE_WATER);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_WATER,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_WATER_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
xopxe/LuPA | lib/environment_bobot.lua | 1 | 5740 | #!/usr/bin/lua
--[[
Copyright 2008 MINA Group, Facultad de Ingenieria, Universidad de la
Republica, Uruguay.
This file is part of the RAN System.
The RAN System is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
The RAN System 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 the RAN System. If not, see <http://www.gnu.org/licenses/>.
--]]
--This module reads the device's configuration
module(..., package.seeall);
local util = require("util")
local run_shell = util.run_shell
package.path=package.path .. ";../bobot/?.lua"
local bobot = require("bobot")
local baseboards = bobot.baseboards
local get_device_name=function (n)
if not devices[n] then return n end
local i=2
local nn=n.."#"..i
while devices[nn] do
i=i+1
nn=n.."#"..i
end
return nn
end
local function read_devices_list()
print("=Listing Devices")
local bfound
devices={}
for b_name, bb in pairs(baseboards) do
print("===board", b_name)
for d_name,d in pairs(bb.devices) do
local regname = get_device_name(d_name)
devices[regname]=d
print("=====d_name", d_name, "regname", regname)
end
bfound = true
end
if not bfound then print ("WARN: No Baseboard found.") end
end
read_devices_list()
function purge_cache()
end
local function check_open_device(d, ep1, ep2)
if not d then return end
if d.handler then
--print ("ls:Already open", d.name, d.handler)
return true
else
print ("ls:Opening", d.name, d.handler)
return d:open(ep1 or 1, ep2 or 1) --TODO asignacion de ep?
end
end
local function split_words(s)
words={}
for p in string.gmatch(s, "%S+") do
words[#words+1]=p
end
return words
end
commands = {}
commands["LIST"] = function ()
local ret,comma = "", ""
for d_name, _ in pairs(devices) do
ret = ret .. comma .. d_name
comma=","
end
return {value = ret}
end
commands["OPEN"] = function (parameters)
local d, ep1, ep2 = parameters.d, tonumber(parameters.ep1), tonumber(parameters.ep2)
if not d then
print("ls:Missing 'device' parameter")
return
end
local device = devices[d]
if check_open_device(device, ep1, ep2) then
return {value = "ok"}
else
return {value = "fail"}
end
end
commands["DESCRIBE"] = function (parameters)
local d, ep1, ep2 = parameters.d, tonumber(parameters.ep1), tonumber(parameters.ep2)
if not d then
print("ls:Missing 'device' parameter")
return {err = "Missing 'device' parameter"}
end
local device = devices[d]
if not check_open_device(device, ep1, ep2) then
return {err = "Failure to open"}
end
local ret = "{"
for fname, fdef in pairs(device.api) do
ret = ret .. fname .. "={"
ret = ret .. " parameters={"
for i,pars in ipairs(fdef.parameters) do
ret = ret .. "[" ..i.."]={"
for k, v in pairs(pars) do
ret = ret .."[".. k .."]='"..tostring(v).."',"
end
ret = ret .. "},"
end
ret = ret .. "}, returns={"
for i,rets in ipairs(fdef.returns) do
ret = ret .. "[" ..i.."]={"
for k, v in pairs(rets) do
ret = ret .."[".. k .."]='"..tostring(v).."',"
end
ret = ret .. "},"
end
ret = ret .. "}},"
end
ret=ret.."}"
return {value = ret}
end
commands["CALL"] = function (parameters)
local d, call, params = parameters.device, parameters.call, parameters.call_params
local words=split_words(params or '')
if not (d and call) then
print("ls:Missing parameters", d, call)
return {err = "Missing parameter"}
end
local device = devices[d]
if not check_open_device(device, nil, nil) then
return {err = "Failure to open"}
end
local api_call=device.api[call];
if api_call and api_call.call then
local ret = api_call.call(unpack(words))
return {value = ret}
end
end
commands["CLOSEALL"] = function ()
if baseboards then
for _, bb in pairs(baseboards) do
---bb:close_all()
bb:force_close_all() --modif andrew
end
end
return {value = "ok"}
end
--Table with querying functions
--getval[evname]=function
getval = {}
--------------------------------------------------------
--Functions for reading attributes
getval["CALL"] = function (parameters)
local d, call, params = parameters.device, parameters.call, parameters.call_params
local words=split_words(params or '')
if not (d and call) then
print("ls:Missing parameters", d, call)
return "Missing parameters"
end
local device = devices[d]
if not check_open_device(device, nil, nil) then
return "fail"
end
local api_call=device.api[call];
if api_call and api_call.call then
local ret = api_call.call(unpack(words))
return ret
end
end
getval["processes_running"] = function ()
--local res=run_shell("ps -A | wc -l")-2 --minus header and ps line
local res=run_shell("ps | wc -l")-2 --minus header and ps line
return res
end
getval["process_running"] = function (parameters)
local process=parameters.process
local process_s = process --.. "\n"
local _, res = string.gsub(run_shell("ps w"), process_s, process_s)
return res
end
getval["free_ram"] = function ()
local res = string.match(run_shell("cat /proc/meminfo"), "MemFree:%s+(%d+)")
return res
end
getval["cpu_load_avg"] = function ()
local res = string.match(run_shell("cat /proc/loadavg"), "^(%S+)")
return res
end
getval["uptime"] = function ()
local res = string.match(run_shell("cat /proc/uptime"), "^(%S+)")
return res
end
| gpl-3.0 |
ozhanf/ozhanf--bot | plugins/vote.lua | 615 | 2128 | do
local _file_votes = './data/votes.lua'
function read_file_votes ()
local f = io.open(_file_votes, "r+")
if f == nil then
print ('Created voting file '.._file_votes)
serialize_to_file({}, _file_votes)
else
print ('Values loaded: '.._file_votes)
f:close()
end
return loadfile (_file_votes)()
end
function clear_votes (chat)
local _votes = read_file_votes ()
_votes [chat] = {}
serialize_to_file(_votes, _file_votes)
end
function votes_result (chat)
local _votes = read_file_votes ()
local results = {}
local result_string = ""
if _votes [chat] == nil then
_votes[chat] = {}
end
for user,vote in pairs (_votes[chat]) do
if (results [vote] == nil) then
results [vote] = user
else
results [vote] = results [vote] .. ", " .. user
end
end
for vote,users in pairs (results) do
result_string = result_string .. vote .. " : " .. users .. "\n"
end
return result_string
end
function save_vote(chat, user, vote)
local _votes = read_file_votes ()
if _votes[chat] == nil then
_votes[chat] = {}
end
_votes[chat][user] = vote
serialize_to_file(_votes, _file_votes)
end
function run(msg, matches)
if (matches[1] == "ing") then
if (matches [2] == "reset") then
clear_votes (tostring(msg.to.id))
return "Voting statistics reset.."
elseif (matches [2] == "stats") then
local votes_result = votes_result (tostring(msg.to.id))
if (votes_result == "") then
votes_result = "[No votes registered]\n"
end
return "Voting statistics :\n" .. votes_result
end
else
save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2])))
return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2]))
end
end
return {
description = "Plugin for voting in groups.",
usage = {
"!voting reset: Reset all the votes.",
"!vote [number]: Cast the vote.",
"!voting stats: Shows the statistics of voting."
},
patterns = {
"^!vot(ing) (reset)",
"^!vot(ing) (stats)",
"^!vot(e) ([0-9]+)$"
},
run = run
}
end | gpl-2.0 |
QVaucher/Gwynt-Lua | assets/gameboard2.lua | 1 | 40933 | return {
version = "1.1",
luaversion = "5.1",
tiledversion = "1.0.2",
orientation = "orthogonal",
renderorder = "left-up",
width = 66,
height = 40,
tilewidth = 50,
tileheight = 50,
nextobjectid = 148,
properties = {},
tilesets = {
{
name = "i2yHbmQ",
firstgid = 1,
tilewidth = 50,
tileheight = 50,
spacing = 0,
margin = 0,
image = "i2yHbmQ.jpg",
imagewidth = 3366,
imageheight = 1660,
tileoffset = {
x = 0,
y = 0
},
grid = {
orientation = "orthogonal",
width = 50,
height = 50
},
properties = {},
terrains = {},
tilecount = 2211,
tiles = {}
}
},
layers = {
{
type = "tilelayer",
name = "BACKGROUND",
x = 0,
y = 0,
width = 66,
height = 40,
visible = true,
opacity = 1,
offsetx = 0,
offsety = 0,
properties = {},
encoding = "lua",
data = {
2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67,
69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 133, 134,
136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147, 148, 149, 150, 151, 152, 153, 154, 155, 156, 157, 158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 200, 201,
873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 240, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, 255, 256, 257, 258, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 267, 268,
940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 293, 294, 295, 296, 297, 298, 299, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309, 310, 311, 312, 313, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323, 324, 325, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 334, 335,
1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 349, 350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362, 363, 364, 365, 366, 367, 368, 369, 370, 371, 372, 373, 374, 375, 376, 377, 378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391, 392, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 401, 402,
1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 416, 417, 418, 419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435, 436, 437, 438, 439, 440, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450, 451, 452, 453, 454, 455, 456, 457, 458, 459, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 468, 469,
1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 483, 484, 485, 486, 487, 488, 489, 490, 491, 492, 493, 494, 495, 496, 497, 498, 499, 500, 501, 502, 503, 504, 505, 506, 507, 508, 509, 510, 511, 512, 513, 514, 515, 516, 517, 518, 519, 520, 521, 522, 523, 524, 525, 526, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 535, 536,
1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 550, 551, 552, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563, 564, 565, 566, 567, 568, 569, 570, 571, 572, 573, 574, 575, 576, 577, 578, 579, 580, 581, 582, 583, 584, 585, 586, 587, 588, 589, 590, 591, 592, 593, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 602, 603,
1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 617, 618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630, 631, 632, 633, 634, 635, 636, 637, 638, 639, 640, 641, 642, 643, 644, 645, 646, 647, 648, 649, 650, 651, 652, 653, 654, 655, 656, 657, 658, 659, 660, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 669, 670,
672, 673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685, 686, 687, 688, 689, 690, 691, 692, 693, 694, 695, 696, 697, 698, 699, 700, 701, 702, 703, 704, 705, 706, 707, 708, 709, 710, 711, 712, 713, 714, 715, 716, 717, 718, 719, 720, 721, 722, 723, 724, 725, 726, 727, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 736, 737,
739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 758, 759, 760, 761, 762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774, 775, 776, 777, 778, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788, 789, 790, 791, 792, 793, 794, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 803, 804,
806, 807, 808, 809, 810, 811, 812, 813, 814, 815, 816, 817, 818, 819, 820, 821, 822, 823, 824, 825, 826, 827, 828, 829, 830, 831, 832, 833, 834, 835, 836, 837, 838, 839, 840, 841, 842, 843, 844, 845, 846, 847, 848, 849, 850, 851, 852, 853, 854, 855, 856, 857, 858, 859, 860, 861, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 870, 871,
807, 807, 873, 874, 875, 878, 879, 882, 883, 884, 816, 816, 885, 886, 887, 888, 889, 890, 891, 892, 893, 894, 895, 896, 897, 898, 899, 900, 901, 902, 903, 904, 905, 906, 907, 908, 909, 910, 911, 912, 913, 914, 915, 916, 917, 918, 919, 920, 921, 922, 923, 924, 925, 926, 927, 928, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 937, 938,
807, 807, 940, 941, 943, 945, 946, 949, 950, 951, 816, 816, 952, 953, 954, 955, 956, 957, 958, 959, 960, 961, 962, 963, 964, 965, 966, 967, 968, 969, 970, 971, 972, 973, 974, 975, 976, 977, 978, 979, 980, 981, 982, 983, 984, 985, 986, 987, 988, 989, 990, 991, 992, 993, 994, 995, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1004, 1005,
1007, 807, 1007, 1008, 1010, 1012, 1013, 1016, 1017, 1018, 816, 816, 1019, 1020, 1021, 1022, 1023, 1024, 1025, 1026, 1027, 1028, 1029, 1030, 1031, 1032, 1033, 1034, 1035, 1036, 1037, 1038, 1039, 1040, 1041, 1042, 1043, 1044, 1045, 1046, 1047, 1048, 1049, 1050, 1051, 1052, 1053, 1054, 1055, 1056, 1057, 1058, 1059, 1060, 1061, 1062, 1063, 1064, 1065, 1066, 1067, 1068, 1069, 1070, 1071, 1072,
1074, 807, 1074, 1075, 1077, 1079, 1080, 1083, 1084, 1085, 816, 816, 1086, 1087, 1088, 1089, 1090, 1091, 1092, 1093, 1094, 1095, 1096, 1097, 1098, 1099, 1100, 1101, 1102, 1103, 1104, 1105, 1106, 1107, 1108, 1109, 1110, 1111, 1112, 1113, 1114, 1115, 1116, 1117, 1118, 1119, 1120, 1121, 1122, 1123, 1124, 1125, 1126, 1127, 1128, 1129, 1130, 1131, 1132, 1133, 1134, 1135, 1136, 1137, 1138, 1139,
807, 807, 1141, 1142, 1144, 1146, 1147, 1150, 1151, 1152, 816, 816, 1153, 1154, 1155, 1156, 1157, 1158, 1159, 1160, 1161, 1162, 1163, 1164, 1165, 1166, 1167, 1168, 1169, 1170, 1171, 1172, 1173, 1174, 1175, 1176, 1177, 1178, 1179, 1180, 1181, 1182, 1183, 1184, 1185, 1186, 1187, 1188, 1189, 1190, 1191, 1192, 1193, 1194, 1195, 1196, 1197, 1198, 1199, 1200, 1201, 1202, 1203, 1204, 1205, 1206,
807, 807, 1208, 1209, 1211, 1213, 1214, 1217, 1218, 1219, 816, 816, 1220, 1221, 1222, 1223, 1224, 1225, 1226, 1227, 1228, 1229, 1230, 1231, 1232, 1233, 1234, 1235, 1236, 1237, 1238, 1239, 1240, 1241, 1242, 1243, 1244, 1245, 1246, 1247, 1248, 1249, 1250, 1251, 1252, 1253, 1254, 1255, 1256, 1257, 1258, 1259, 1260, 1261, 1262, 1263, 1264, 1265, 1266, 1267, 1268, 1269, 1270, 1271, 1272, 1273,
807, 807, 1275, 1276, 1277, 1280, 1281, 1284, 1285, 1286, 816, 816, 1287, 1288, 1289, 1290, 1291, 1292, 1293, 1294, 1295, 1296, 1297, 1298, 1299, 1300, 1301, 1302, 1303, 1304, 1305, 1306, 1307, 1308, 1309, 1310, 1311, 1312, 1313, 1314, 1315, 1316, 1317, 1318, 1319, 1320, 1321, 1322, 1323, 1324, 1325, 1326, 1327, 1328, 1329, 1330, 1331, 1332, 1333, 1334, 1335, 1336, 1337, 1338, 1339, 1340,
1342, 1343, 1344, 1345, 1346, 1347, 1348, 1349, 1350, 1351, 1352, 1353, 1354, 1355, 1356, 1357, 1358, 1359, 1360, 1361, 1362, 1363, 1364, 1365, 1366, 1367, 1368, 1369, 1370, 1371, 1372, 1373, 1374, 1375, 1376, 1377, 1378, 1379, 1380, 1381, 1382, 1383, 1384, 1385, 1386, 1387, 1388, 1389, 1390, 1391, 1392, 1393, 1394, 1395, 1396, 1397, 1398, 1399, 1400, 1401, 1402, 1403, 1404, 1405, 1406, 1407,
1409, 1410, 1411, 1412, 1413, 1414, 1415, 1416, 1417, 1418, 1419, 1420, 1421, 1422, 1423, 1424, 1425, 1426, 1427, 1428, 1429, 1430, 1431, 1432, 1433, 1434, 1435, 1436, 1437, 1438, 1439, 1440, 1441, 1442, 1443, 1444, 1445, 1446, 1447, 1448, 1449, 1450, 1451, 1452, 1453, 1454, 1455, 1456, 1457, 1458, 1459, 1460, 1461, 1462, 1463, 1464, 1465, 1466, 1467, 1468, 1469, 1470, 1471, 1472, 1473, 1474,
1476, 1477, 1478, 1479, 1480, 1481, 1482, 1483, 1484, 1485, 1486, 1487, 1488, 1489, 1490, 1491, 1492, 1493, 1494, 1495, 1496, 1497, 1498, 1499, 1500, 1501, 1502, 1503, 1504, 1505, 1506, 1507, 1508, 1509, 1510, 1511, 1512, 1513, 1514, 1515, 1516, 1517, 1518, 1519, 1520, 1521, 1522, 1523, 1524, 1525, 1526, 1527, 1528, 1529, 1530, 1531, 1532, 1533, 1534, 1535, 1536, 1537, 1538, 1539, 1540, 1541,
873, 874, 875, 876, 877, 878, 879, 880, 881, 882, 883, 884, 1555, 1556, 1557, 1558, 1559, 1560, 1561, 1562, 1563, 1564, 1565, 1566, 1567, 1568, 1569, 1570, 1571, 1572, 1573, 1574, 1575, 1576, 1577, 1578, 1579, 1580, 1581, 1582, 1583, 1584, 1585, 1586, 1587, 1588, 1589, 1590, 1591, 1592, 1593, 1594, 1595, 1596, 1597, 1598, 1599, 1600, 1601, 1602, 1603, 1604, 1605, 1606, 1607, 1608,
940, 941, 942, 943, 944, 945, 946, 947, 948, 949, 950, 951, 1622, 1623, 1624, 1625, 1626, 1627, 1628, 1629, 1630, 1631, 1632, 1633, 1634, 1635, 1636, 1637, 1638, 1639, 1640, 1641, 1642, 1643, 1644, 1645, 1646, 1647, 1648, 1649, 1650, 1651, 1652, 1653, 1654, 1655, 1656, 1657, 1658, 1659, 1660, 1661, 1662, 1663, 1664, 1665, 1666, 1667, 1668, 1669, 1670, 1671, 1672, 1673, 1674, 1675,
1007, 1008, 1009, 1010, 1011, 1012, 1013, 1014, 1015, 1016, 1017, 1018, 1689, 1690, 1691, 1692, 1693, 1694, 1695, 1696, 1697, 1698, 1699, 1700, 1701, 1702, 1703, 1704, 1705, 1706, 1707, 1708, 1709, 1710, 1711, 1712, 1713, 1714, 1715, 1716, 1717, 1718, 1719, 1720, 1721, 1722, 1723, 1724, 1725, 1726, 1727, 1728, 1729, 1730, 1731, 1732, 1733, 1734, 1735, 1736, 1737, 1738, 1739, 1740, 1741, 1742,
1074, 1075, 1076, 1077, 1078, 1079, 1080, 1081, 1082, 1083, 1084, 1085, 1756, 1757, 1758, 1759, 1760, 1761, 1762, 1763, 1764, 1765, 1766, 1767, 1768, 1769, 1770, 1771, 1772, 1773, 1774, 1775, 1776, 1777, 1778, 1779, 1780, 1781, 1782, 1783, 1784, 1785, 1786, 1787, 1788, 1789, 1790, 1791, 1792, 1793, 1794, 1795, 1796, 1797, 1798, 1799, 1800, 1801, 1802, 1803, 1804, 1336, 1337, 1338, 1808, 1809,
1141, 1142, 1143, 1144, 1145, 1146, 1147, 1148, 1149, 1150, 1151, 1152, 1823, 1824, 1825, 1826, 1827, 1828, 1829, 1830, 1831, 1832, 1833, 1834, 1835, 1836, 1837, 1838, 1839, 1840, 1841, 1842, 1843, 1844, 1845, 1846, 1847, 1848, 1849, 1850, 1851, 1852, 1853, 1854, 1855, 1856, 1857, 1858, 1859, 1860, 1861, 1862, 1863, 1864, 1865, 1866, 1867, 1868, 1869, 1870, 1871, 1403, 1404, 1405, 1875, 1876,
1208, 1209, 1210, 1211, 1212, 1213, 1214, 1215, 1216, 1217, 1218, 1219, 1890, 1891, 1892, 1893, 1894, 1895, 1896, 1897, 1898, 1899, 1900, 1901, 1902, 1903, 1904, 1905, 1906, 1907, 1908, 1909, 1910, 1911, 1912, 1913, 1914, 1915, 1916, 1917, 1918, 1919, 1920, 1921, 1922, 1923, 1924, 1925, 1926, 1927, 1928, 1929, 1930, 1931, 1932, 1933, 1934, 1935, 1936, 1937, 1938, 1470, 1471, 1472, 1942, 1943,
1275, 1276, 1277, 1278, 1279, 1280, 1281, 1282, 1283, 1284, 1285, 1286, 1957, 1958, 1959, 1960, 1961, 1962, 1963, 1964, 1965, 1966, 1967, 1968, 1969, 1970, 1971, 1972, 1973, 1974, 1975, 1976, 1977, 1978, 1979, 1980, 1981, 1982, 1983, 1984, 1985, 1986, 1987, 1988, 1989, 1990, 1991, 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003, 2004, 2005, 1537, 1538, 1539, 2009, 2010,
2012, 2013, 2014, 2015, 2016, 2017, 2018, 2019, 2020, 2021, 2022, 2023, 2024, 2025, 2026, 2027, 2028, 2029, 2030, 2031, 2032, 2033, 2034, 2035, 2036, 2037, 2038, 2039, 2040, 2041, 2042, 2043, 2044, 2045, 2046, 2047, 2048, 2049, 2050, 2051, 2052, 2053, 2054, 2055, 2056, 2057, 2058, 2059, 2060, 2061, 2062, 2063, 2064, 2065, 2066, 2067, 2068, 2069, 2070, 2071, 2072, 1604, 1605, 1606, 2076, 2077,
2079, 2080, 2081, 2082, 2083, 2084, 2085, 2086, 2087, 2088, 2089, 2090, 2091, 2092, 2093, 2094, 2095, 2096, 2097, 2098, 2099, 2100, 2101, 2102, 2103, 2104, 2105, 2106, 2107, 2108, 2109, 2110, 2111, 2112, 2113, 2114, 2115, 2116, 2117, 2118, 2119, 2120, 2121, 2122, 2123, 2124, 2125, 2126, 2127, 2128, 2129, 2130, 2131, 2132, 2133, 2134, 2135, 2136, 2137, 2138, 2139, 1671, 1672, 1673, 2143, 2144,
2146, 2147, 2148, 2149, 2150, 2151, 2152, 2153, 2154, 2155, 2156, 2157, 2158, 2159, 2160, 2161, 2162, 2163, 2164, 2165, 2166, 2167, 2168, 2169, 2170, 2171, 2172, 2173, 2174, 2175, 2176, 2177, 2178, 2179, 2180, 2181, 2182, 2183, 2184, 2185, 2186, 2187, 2188, 2189, 2190, 2191, 2192, 2193, 2194, 2195, 2196, 2197, 2198, 2199, 2200, 2201, 2202, 2203, 2204, 2205, 2206, 2207, 2208, 2209, 2210, 2211,
873, 875, 875, 875, 875, 875, 875, 875, 875, 875, 875, 875, 875, 875, 875, 876, 876, 876, 876, 876, 876, 876, 876, 876, 876, 876, 876, 876, 878, 878, 878, 878, 878, 878, 878, 878, 878, 878, 879, 879, 879, 879, 879, 879, 879, 879, 879, 880, 880, 880, 880, 880, 880, 880, 880, 881, 881, 881, 881, 881, 881, 882, 882, 882, 882, 884,
940, 1342, 1343, 1344, 1344, 1344, 1344, 1344, 1344, 1345, 1345, 1345, 1345, 1345, 1346, 1346, 1346, 1346, 1346, 1346, 1346, 1346, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1348, 1348, 1348, 1348, 1348, 1348, 1349, 1349, 1349, 1349, 1349, 1349, 1349, 1350, 1350, 1350, 1350, 1350, 1351, 1351, 1351, 1351, 1351, 1352, 1352, 1352, 1352, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 951,
1007, 1409, 1410, 1411, 1411, 1411, 1411, 1411, 1411, 1412, 1412, 1412, 1412, 1412, 1413, 1413, 1413, 1413, 1413, 1413, 1413, 1413, 1414, 1414, 1414, 1414, 1414, 1414, 1414, 1415, 1415, 1415, 1415, 1415, 1415, 1416, 1416, 1416, 1416, 1416, 1416, 1416, 1417, 1417, 1417, 1417, 1417, 1418, 1418, 1418, 1418, 1418, 1419, 1419, 1419, 1419, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1018,
1074, 1342, 1343, 1344, 1478, 1344, 1344, 1344, 1344, 1345, 1345, 1345, 1345, 1345, 1346, 1346, 1346, 1346, 1346, 1346, 1346, 1346, 1347, 1347, 1347, 1347, 1347, 1347, 1347, 1348, 1348, 1348, 1348, 1348, 1348, 1349, 1349, 1349, 1349, 1349, 1349, 1349, 1350, 1350, 1350, 1350, 1350, 1351, 1351, 1351, 1351, 1351, 1352, 1352, 1352, 1352, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 1353, 1085,
1141, 1409, 1410, 1411, 1344, 1411, 1411, 1411, 1411, 1412, 1412, 1412, 1412, 1412, 1413, 1413, 1413, 1413, 1413, 1413, 1413, 1413, 1414, 1414, 1414, 1414, 1414, 1414, 1414, 1415, 1415, 1415, 1415, 1415, 1415, 1416, 1416, 1416, 1416, 1416, 1416, 1416, 1417, 1417, 1417, 1417, 1417, 1418, 1418, 1418, 1418, 1418, 1419, 1419, 1419, 1419, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1420, 1152,
1208, 1476, 1477, 1478, 1411, 1478, 1478, 1478, 1478, 1479, 1479, 1479, 1479, 1479, 1480, 1480, 1480, 1480, 1480, 1480, 1480, 1480, 1481, 1481, 1481, 1481, 1481, 1481, 1481, 1482, 1482, 1482, 1482, 1482, 1482, 1483, 1483, 1483, 1483, 1483, 1483, 1483, 1484, 1484, 1484, 1484, 1484, 1485, 1485, 1485, 1485, 1485, 1486, 1486, 1486, 1486, 1487, 1487, 1487, 1487, 1487, 1487, 1487, 1487, 1487, 1219,
1275, 1276, 1276, 1276, 1277, 1277, 1277, 1277, 1277, 1277, 1277, 1277, 1278, 1278, 1278, 1278, 1278, 1278, 1279, 1279, 1279, 1279, 1279, 1279, 1280, 1280, 1280, 1280, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1281, 1282, 1282, 1282, 1282, 1282, 1282, 1282, 1282, 1283, 1283, 1283, 1283, 1283, 1284, 1284, 1284, 1284, 1284, 1284, 1284, 1285, 1285, 1285, 1285, 1285, 1286
}
},
{
type = "objectgroup",
name = "HAND",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 3,
name = "CARD1",
type = "",
shape = "rectangle",
x = 650,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 5,
name = "CARD2",
type = "",
shape = "rectangle",
x = 950,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 6,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1250,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 7,
name = "CARD4",
type = "",
shape = "rectangle",
x = 1550,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 8,
name = "CARD5",
type = "",
shape = "rectangle",
x = 1850,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 9,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2147.33,
y = 1707.8,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 10,
name = "CARD7",
type = "",
shape = "rectangle",
x = 2450,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 11,
name = "CARD8",
type = "",
shape = "rectangle",
x = 2750,
y = 1700,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "HELP",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 12,
name = "CARD1",
type = "",
shape = "rectangle",
x = 2856,
y = 980,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 141,
name = "CARD1",
type = "",
shape = "rectangle",
x = 2853.39,
y = 1335.08,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "DISPLAY",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "topdown",
properties = {},
objects = {
{
id = 142,
name = "",
type = "",
shape = "rectangle",
x = 2830.3,
y = 93.9394,
width = 421.22,
height = 600,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "ZONES",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 104,
name = "MELEE",
type = "",
shape = "rectangle",
x = 1145,
y = 842.2,
width = 1630.3,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 102,
name = "DISTANCE",
type = "",
shape = "rectangle",
x = 1145,
y = 1109,
width = 1630.3,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 103,
name = "SIEGE",
type = "",
shape = "rectangle",
x = 1145,
y = 1393.94,
width = 1630.3,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 132,
name = "WEATHER",
type = "",
shape = "rectangle",
x = 150,
y = 700,
width = 300,
height = 252,
rotation = 0,
visible = true,
properties = {}
},
{
id = 131,
name = "BOOST",
type = "",
shape = "rectangle",
x = 875,
y = 850,
width = 270,
height = 785,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "BOOST",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 134,
name = "CARD1",
type = "",
shape = "rectangle",
x = 924,
y = 850,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 135,
name = "CARD2",
type = "",
shape = "rectangle",
x = 924,
y = 1115,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 136,
name = "CARD3",
type = "",
shape = "rectangle",
x = 924,
y = 1380,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "BOOST_AD",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 138,
name = "CARD1",
type = "",
shape = "rectangle",
x = 924,
y = 564.288,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 139,
name = "CARD2",
type = "",
shape = "rectangle",
x = 924,
y = 298.167,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 140,
name = "CARD3",
type = "",
shape = "rectangle",
x = 924,
y = 21.5,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "MELEE",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 29,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1250,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 27,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.8,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 26,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.6,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 30,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.4,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 31,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.2,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 129,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2514,
y = 842.198,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "MELEE_AD",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 109,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1250,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 110,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.8,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 111,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.6,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 113,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.4,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 114,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.2,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 116,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2514,
y = 575,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "DISTANCE",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 38,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1250,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 35,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.8,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 33,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.6,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 36,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.4,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 32,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.2,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 37,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2514,
y = 1109.96,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "DISTANCE_AD",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 120,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1249.91,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 117,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.71,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 118,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.51,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 119,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.31,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 121,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.11,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 122,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2513.91,
y = 300,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "SIEGE",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 17,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1250,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 18,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.8,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 19,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.6,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 20,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.4,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 21,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.2,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 22,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2514,
y = 1393.94,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "SIEGE_AD",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 126,
name = "CARD1",
type = "",
shape = "rectangle",
x = 1250,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 123,
name = "CARD2",
type = "",
shape = "rectangle",
x = 1502.8,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 124,
name = "CARD3",
type = "",
shape = "rectangle",
x = 1755.6,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 125,
name = "CARD4",
type = "",
shape = "rectangle",
x = 2008.4,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 127,
name = "CARD5",
type = "",
shape = "rectangle",
x = 2261.2,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 128,
name = "CARD6",
type = "",
shape = "rectangle",
x = 2514,
y = 25,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "WEATHER",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 97,
name = "CARD1",
type = "",
shape = "rectangle",
x = 218,
y = 702,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "ZONES_SCORES",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 107,
name = "SCORE_MELEE",
type = "",
shape = "rectangle",
x = 760,
y = 933,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
},
{
id = 105,
name = "SCORE_DISTANCE",
type = "",
shape = "rectangle",
x = 760,
y = 1200,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
},
{
id = 108,
name = "SCORE_SIEGE",
type = "",
shape = "rectangle",
x = 760,
y = 1477,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "ZONES_SCORES_AD",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "index",
properties = {},
objects = {
{
id = 144,
name = "SCORE_MELEE_AD",
type = "",
shape = "rectangle",
x = 760,
y = 636,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
},
{
id = 146,
name = "SCORE_DISTANCE_AD",
type = "",
shape = "rectangle",
x = 760,
y = 392.893,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
},
{
id = 147,
name = "SCORE_SIEGE_AD",
type = "",
shape = "rectangle",
x = 760,
y = 106.5,
width = 1,
height = 1,
rotation = 0,
visible = true,
properties = {}
}
}
},
{
type = "objectgroup",
name = "SCORE",
visible = false,
opacity = 1,
offsetx = 0,
offsety = 0,
draworder = "topdown",
properties = {},
objects = {
{
id = 76,
name = "LEADERCARD",
type = "",
shape = "rectangle",
x = 62,
y = 1205,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 77,
name = "LEADERCARD_AD",
type = "",
shape = "rectangle",
x = 62,
y = 205,
width = 172,
height = 245,
rotation = 0,
visible = true,
properties = {}
},
{
id = 78,
name = "GEM1_AD",
type = "",
shape = "rectangle",
x = 380,
y = 1228,
width = 50,
height = 50,
rotation = 0,
visible = true,
properties = {}
},
{
id = 80,
name = "GEM2",
type = "",
shape = "rectangle",
x = 468,
y = 1228,
width = 50,
height = 50,
rotation = 0,
visible = true,
properties = {}
},
{
id = 81,
name = "GEM1_AD",
type = "",
shape = "rectangle",
x = 380,
y = 220.075,
width = 50,
height = 50,
rotation = 0,
visible = true,
properties = {}
},
{
id = 82,
name = "GEM2_AD",
type = "",
shape = "rectangle",
x = 468,
y = 220.835,
width = 50,
height = 50,
rotation = 0,
visible = true,
properties = {}
},
{
id = 83,
name = "TOTALICON_AD",
type = "",
shape = "rectangle",
x = 280,
y = 325,
width = 100,
height = 100,
rotation = 0,
visible = true,
properties = {}
},
{
id = 85,
name = "TOTAL_AD",
type = "",
shape = "rectangle",
x = 418,
y = 325,
width = 100,
height = 100,
rotation = 0,
visible = true,
properties = {}
},
{
id = 86,
name = "TOTALICON",
type = "",
shape = "rectangle",
x = 280,
y = 1325,
width = 100,
height = 100,
rotation = 0,
visible = true,
properties = {}
},
{
id = 87,
name = "TOTAL",
type = "",
shape = "rectangle",
x = 418,
y = 1326.52,
width = 100,
height = 100,
rotation = 0,
visible = true,
properties = {}
}
}
}
}
}
| mit |
davymai/CN-QulightUI | Interface/AddOns/DBM-Party-WoD/Skyreach/SkyreachTrash.lua | 1 | 2005 | local mod = DBM:NewMod("SkyreachTrash", "DBM-Party-WoD", 7)
local L = mod:GetLocalizedStrings()
mod:SetRevision(("$Revision: 12088 $"):sub(12, -3))
--mod:SetModelID(47785)
mod:SetZone()
mod.isTrashMod = true
mod:RegisterEvents(
"SPELL_AURA_APPLIED 160303 160288",
"SPELL_AURA_REMOVED 160303 160288"
)
local specWarnSolarDetonation = mod:NewSpecialWarningMoveAway(160288)
local voiceSolarDetonation = mod:NewVoice(160288)
mod:AddRangeFrameOption(3, 160288)--Range guessed. Maybe 5. one tooltip says 1.5 but it def seemed bigger then that. closer to 3-5
mod:RemoveOption("HealthFrame")
mod:RemoveOption("SpeedKillTimer")
mod.vb.debuffCount = 0
local Debuff = GetSpellInfo(160288)
local UnitDebuff = UnitDebuff
local debuffFilter
do
debuffFilter = function(uId)
return UnitDebuff(uId, Debuff)
end
end
function mod:SPELL_AURA_APPLIED(args)
if not self.Options.Enabled or self:IsDifficulty("normal5") then return end
local spellId = args.spellId
if spellId == 160303 or spellId == 160288 then
self.vb.debuffCount = self.vb.debuffCount + 1
if self.Options.RangeFrame then
if UnitDebuff("player", Debuff) then--You have debuff, show everyone
DBM.RangeCheck:Show(3, nil)
else--You do not have debuff, only show players who do
DBM.RangeCheck:Show(3, debuffFilter)
end
end
if args:IsPlayer() then
specWarnSolarDetonation:Show()
voiceSolarDetonation:Play("runout")
end
end
end
function mod:SPELL_AURA_REMOVED(args)
if not self.Options.Enabled or self:IsDifficulty("normal5") then return end
local spellId = args.spellId
if spellId == 160303 or spellId == 160288 then
self.vb.debuffCount = self.vb.debuffCount - 1
if self.Options.RangeFrame then
if self.vb.debuffCount == 0 then
DBM.RangeCheck:Hide()
else
if UnitDebuff("player", Debuff) then--You have debuff, show everyone
DBM.RangeCheck:Show(3, nil)
else--You do not have debuff, only show players who do
DBM.RangeCheck:Show(3, debuffFilter)
end
end
end
end
end
| gpl-2.0 |
karamage/waifu2x | train.lua | 33 | 5163 | require './lib/portable'
require 'optim'
require 'xlua'
require 'pl'
local settings = require './lib/settings'
local minibatch_adam = require './lib/minibatch_adam'
local iproc = require './lib/iproc'
local reconstruct = require './lib/reconstruct'
local pairwise_transform = require './lib/pairwise_transform'
local image_loader = require './lib/image_loader'
local function save_test_scale(model, rgb, file)
local up = reconstruct.scale(model, settings.scale, rgb, settings.block_offset)
image.save(file, up)
end
local function save_test_jpeg(model, rgb, file)
local im, count = reconstruct.image(model, rgb, settings.block_offset)
image.save(file, im)
end
local function split_data(x, test_size)
local index = torch.randperm(#x)
local train_size = #x - test_size
local train_x = {}
local valid_x = {}
for i = 1, train_size do
train_x[i] = x[index[i]]
end
for i = 1, test_size do
valid_x[i] = x[index[train_size + i]]
end
return train_x, valid_x
end
local function make_validation_set(x, transformer, n)
n = n or 4
local data = {}
for i = 1, #x do
for k = 1, n do
local x, y = transformer(x[i], true)
table.insert(data, {x = x:reshape(1, x:size(1), x:size(2), x:size(3)),
y = y:reshape(1, y:size(1), y:size(2), y:size(3))})
end
xlua.progress(i, #x)
collectgarbage()
end
return data
end
local function validate(model, criterion, data)
local loss = 0
for i = 1, #data do
local z = model:forward(data[i].x:cuda())
loss = loss + criterion:forward(z, data[i].y:cuda())
xlua.progress(i, #data)
if i % 10 == 0 then
collectgarbage()
end
end
return loss / #data
end
local function train()
local model, offset = settings.create_model(settings.color)
assert(offset == settings.block_offset)
local criterion = nn.MSECriterion():cuda()
local x = torch.load(settings.images)
local lrd_count = 0
local train_x, valid_x = split_data(x,
math.floor(settings.validation_ratio * #x),
settings.validation_crops)
local test = image_loader.load_float(settings.test)
local adam_config = {
learningRate = settings.learning_rate,
xBatchSize = settings.batch_size,
}
local ch = nil
if settings.color == "y" then
ch = 1
elseif settings.color == "rgb" then
ch = 3
end
local transformer = function(x, is_validation)
if is_validation == nil then is_validation = false end
if settings.method == "scale" then
return pairwise_transform.scale(x,
settings.scale,
settings.crop_size, offset,
{ color_augment = not is_validation,
random_half = settings.random_half,
rgb = (settings.color == "rgb")
})
elseif settings.method == "noise" then
return pairwise_transform.jpeg(x,
settings.noise_level,
settings.crop_size, offset,
{ color_augment = not is_validation,
random_half = settings.random_half,
rgb = (settings.color == "rgb")
})
elseif settings.method == "noise_scale" then
return pairwise_transform.jpeg_scale(x,
settings.scale,
settings.noise_level,
settings.crop_size, offset,
{ color_augment = not is_validation,
random_half = settings.random_half,
rgb = (settings.color == "rgb")
})
end
end
local best_score = 100000.0
print("# make validation-set")
local valid_xy = make_validation_set(valid_x, transformer, 20)
valid_x = nil
collectgarbage()
model:cuda()
print("load .. " .. #train_x)
for epoch = 1, settings.epoch do
model:training()
print("# " .. epoch)
print(minibatch_adam(model, criterion, train_x, adam_config,
transformer,
{ch, settings.crop_size, settings.crop_size},
{ch, settings.crop_size - offset * 2, settings.crop_size - offset * 2}
))
model:evaluate()
print("# validation")
local score = validate(model, criterion, valid_xy)
if score < best_score then
lrd_count = 0
best_score = score
print("* update best model")
torch.save(settings.model_file, model)
if settings.method == "noise" then
local log = path.join(settings.model_dir,
("noise%d_best.png"):format(settings.noise_level))
save_test_jpeg(model, test, log)
elseif settings.method == "scale" then
local log = path.join(settings.model_dir,
("scale%.1f_best.png"):format(settings.scale))
save_test_scale(model, test, log)
elseif settings.method == "noise_scale" then
local log = path.join(settings.model_dir,
("noise%d_scale%.1f_best.png"):format(settings.noise_level,
settings.scale))
save_test_scale(model, test, log)
end
else
lrd_count = lrd_count + 1
if lrd_count > 5 then
lrd_count = 0
adam_config.learningRate = adam_config.learningRate * 0.8
print("* learning rate decay: " .. adam_config.learningRate)
end
end
print("current: " .. score .. ", best: " .. best_score)
collectgarbage()
end
end
torch.manualSeed(settings.seed)
cutorch.manualSeed(settings.seed)
print(settings)
train()
| mit |
n0xus/darkstar | scripts/zones/Dynamis-Valkurm/mobs/Cirrate_Christelle.lua | 16 | 4114 | -----------------------------------
-- Area: Dynamis Valkurm
-- NPC: Cirrate_Christelle
-----------------------------------
package.loaded["scripts/zones/Dynamis-Valkurm/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Valkurm/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
if (GetServerVariable("[DynaValkurm]Boss_Trigger")==0) then
--spwan additional mob :
-- print("Serjeant_Tombstone:");
for Serjeant_Tombstone = 16937494, 16937499, 1 do
-- printf("addmob %u \n",Serjeant_Tombstone);
SpawnMob(Serjeant_Tombstone);
end
-- print("Adamantking_Effigy:");
for Adamantking_Effigy = 16937519, 16937524, 1 do
-- printf("addmob %u \n",Adamantking_Effigy);
SpawnMob(Adamantking_Effigy);
end
-- print("Manifest_Icon:");
for Manifest_Icon = 16937544, 16937549, 1 do
-- printf("addmob %u \n",Manifest_Icon);
SpawnMob(Manifest_Icon);
end
-- print("Goblin_Replica:");
for Goblin_Replica = 16937569, 16937574, 1 do
-- printf("addmob %u \n",Goblin_Replica);
SpawnMob(Goblin_Replica);
end
----
-- print("Nightmare_Hippogryph:");
for Nightmare_Hippogryph = 16937377, 16937394, 1 do
-- printf("addmob %u \n",Nightmare_Hippogryph);
SpawnMob(Nightmare_Hippogryph);
end
-- print("Nightmare_Sheep:");
for Nightmare_Sheep = 16937169, 16937189, 1 do
-- printf("addmob %u \n",Nightmare_Sheep);
SpawnMob(Nightmare_Sheep);
end
for Nightmare_Sheep2 = 16937433,16937436, 1 do
-- printf("addmob %u \n",Nightmare_Sheep2);
SpawnMob(Nightmare_Sheep2);
end
-- print("Nightmare_Sabotender:");
for Nightmare_Sabotender = 16937136, 16937139, 1 do
-- printf("addmob %u \n",Nightmare_Sabotender);
SpawnMob(Nightmare_Sabotender);
end
-- SpawnMob(16937115);
for Nightmare_Sabotender2 = 16937312, 16937333, 1 do
-- printf("addmob %u \n",Nightmare_Sabotender2);
SpawnMob(Nightmare_Sabotender2);
end
-- print("Nightmare_Manticore:");
for Nightmare_Manticore = 16936987, 16937011, 1 do
-- printf("addmob %u \n",Nightmare_Manticore);
SpawnMob(Nightmare_Manticore);
end
-- print("Nightmare_Funguar:");
for Nightmare_Funguar = 16937416, 16937431, 1 do
-- printf("addmob %u \n",Nightmare_Funguar);
SpawnMob(Nightmare_Funguar);
end
-- print("Nightmare_Fly:");
for Nightmare_Fly = 16937455, 16937475, 1 do
-- printf("addmob %u \n",Nightmare_Fly);
SpawnMob(Nightmare_Fly);
end
-- print("Nightmare_Treant:");
for Nightmare_Treant = 16937395, 16937415, 1 do
-- printf("addmob %u \n",Nightmare_Treant);
SpawnMob(Nightmare_Treant);
end
-- print("Nightmare_Flytrap:");
for Nightmare_Flytrap = 16937334, 16937354, 1 do
-- printf("addmob %u \n",Nightmare_Flytrap);
SpawnMob(Nightmare_Flytrap);
end
-- print("Nightmare_Goobbue:");
for Nightmare_Goobbue = 16937291, 16937310, 1 do
-- printf("addmob %u \n",Nightmare_Goobbue);
SpawnMob(Nightmare_Goobbue);
end
SetServerVariable("[DynaValkurm]Boss_Trigger",1);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if (killer:hasKeyItem(DYNAMIS_VALKURM_SLIVER ) == false) then
killer:addKeyItem(DYNAMIS_VALKURM_SLIVER);
killer:messageSpecial(KEYITEM_OBTAINED,DYNAMIS_VALKURM_SLIVER);
end
killer:addTitle(DYNAMISVALKURM_INTERLOPER);
end; | gpl-3.0 |
VincentGong/chess | cocos2d-x/tests/lua-tests/src/mainMenu.lua | 2 | 11419 | require "Cocos2d"
require "Cocos2dConstants"
require "Opengl"
require "OpenglConstants"
require "StudioConstants"
require "GuiConstants"
require "src/helper"
require "src/testResource"
require "src/VisibleRect"
require "src/AccelerometerTest/AccelerometerTest"
require "src/ActionManagerTest/ActionManagerTest"
require "src/ActionsEaseTest/ActionsEaseTest"
require "src/ActionsProgressTest/ActionsProgressTest"
require "src/ActionsTest/ActionsTest"
require "src/AssetsManagerTest/AssetsManagerTest"
require "src/BugsTest/BugsTest"
require "src/ClickAndMoveTest/ClickAndMoveTest"
require "src/CocosDenshionTest/CocosDenshionTest"
require "src/CocoStudioTest/CocoStudioTest"
require "src/CurrentLanguageTest/CurrentLanguageTest"
require "src/DrawPrimitivesTest/DrawPrimitivesTest"
require "src/EffectsTest/EffectsTest"
require "src/EffectsAdvancedTest/EffectsAdvancedTest"
require "src/ExtensionTest/ExtensionTest"
require "src/FontTest/FontTest"
require "src/IntervalTest/IntervalTest"
require "src/KeypadTest/KeypadTest"
require "src/LabelTest/LabelTest"
require "src/LabelTestNew/LabelTestNew"
require "src/LayerTest/LayerTest"
require "src/MenuTest/MenuTest"
require "src/MotionStreakTest/MotionStreakTest"
require "src/NewEventDispatcherTest/NewEventDispatcherTest"
require "src/NodeTest/NodeTest"
require "src/OpenGLTest/OpenGLTest"
require "src/ParallaxTest/ParallaxTest"
require "src/ParticleTest/ParticleTest"
require "src/PerformanceTest/PerformanceTest"
require "src/RenderTextureTest/RenderTextureTest"
require "src/RotateWorldTest/RotateWorldTest"
require "src/Sprite3DTest/Sprite3DTest"
require "src/SpriteTest/SpriteTest"
require "src/SceneTest/SceneTest"
require "src/SpineTest/SpineTest"
require "src/Texture2dTest/Texture2dTest"
require "src/TileMapTest/TileMapTest"
require "src/TouchesTest/TouchesTest"
require "src/TransitionsTest/TransitionsTest"
require "src/UserDefaultTest/UserDefaultTest"
require "src/ZwoptexTest/ZwoptexTest"
require "src/LuaBridgeTest/LuaBridgeTest"
require "src/XMLHttpRequestTest/XMLHttpRequestTest"
require "src/PhysicsTest/PhysicsTest"
local LINE_SPACE = 40
local CurPos = {x = 0, y = 0}
local BeginPos = {x = 0, y = 0}
local _allTests = {
{ isSupported = true, name = "Accelerometer" , create_func= AccelerometerMain },
{ isSupported = true, name = "ActionManagerTest" , create_func = ActionManagerTestMain },
{ isSupported = true, name = "ActionsEaseTest" , create_func = EaseActionsTest },
{ isSupported = true, name = "ActionsProgressTest" , create_func = ProgressActionsTest },
{ isSupported = true, name = "ActionsTest" , create_func = ActionsTest },
{ isSupported = true, name = "AssetsManagerTest" , create_func = AssetsManagerTestMain },
{ isSupported = false, name = "Box2dTest" , create_func= Box2dTestMain },
{ isSupported = false, name = "Box2dTestBed" , create_func= Box2dTestBedMain },
{ isSupported = true, name = "BugsTest" , create_func= BugsTestMain },
{ isSupported = false, name = "ChipmunkAccelTouchTest" , create_func= ChipmunkAccelTouchTestMain },
{ isSupported = true, name = "ClickAndMoveTest" , create_func = ClickAndMoveTest },
{ isSupported = true, name = "CocosDenshionTest" , create_func = CocosDenshionTestMain },
{ isSupported = true, name = "CocoStudioTest" , create_func = CocoStudioTestMain },
{ isSupported = false, name = "CurlTest" , create_func= CurlTestMain },
{ isSupported = true, name = "CurrentLanguageTest" , create_func= CurrentLanguageTestMain },
{ isSupported = true, name = "DrawPrimitivesTest" , create_func= DrawPrimitivesTest },
{ isSupported = true, name = "EffectsTest" , create_func = EffectsTest },
{ isSupported = true, name = "EffectAdvancedTest" , create_func = EffectAdvancedTestMain },
{ isSupported = true, name = "ExtensionsTest" , create_func= ExtensionsTestMain },
{ isSupported = true, name = "FontTest" , create_func = FontTestMain },
{ isSupported = true, name = "IntervalTest" , create_func = IntervalTestMain },
{ isSupported = true, name = "KeypadTest" , create_func= KeypadTestMain },
{ isSupported = true, name = "LabelTest" , create_func = LabelTest },
{ isSupported = true, name = "LabelTestNew" , create_func = LabelTestNew },
{ isSupported = true, name = "LayerTest" , create_func = LayerTestMain },
{ isSupported = true, name = "LuaBridgeTest" , create_func = LuaBridgeMainTest },
{ isSupported = true, name = "MenuTest" , create_func = MenuTestMain },
{ isSupported = true, name = "MotionStreakTest" , create_func = MotionStreakTest },
{ isSupported = false, name = "MutiTouchTest" , create_func= MutiTouchTestMain },
{ isSupported = true, name = "NewEventDispatcherTest" , create_func = NewEventDispatcherTest },
{ isSupported = true, name = "NodeTest" , create_func = CocosNodeTest },
{ isSupported = true, name = "OpenGLTest" , create_func= OpenGLTestMain },
{ isSupported = true, name = "ParallaxTest" , create_func = ParallaxTestMain },
{ isSupported = true, name = "ParticleTest" , create_func = ParticleTest },
{ isSupported = true, name = "PerformanceTest" , create_func= PerformanceTestMain },
{ isSupported = true, name = "PhysicsTest" , create_func = PhysicsTest },
{ isSupported = true, name = "RenderTextureTest" , create_func = RenderTextureTestMain },
{ isSupported = true, name = "RotateWorldTest" , create_func = RotateWorldTest },
{ isSupported = true, name = "SceneTest" , create_func = SceneTestMain },
{ isSupported = true, name = "SpineTest" , create_func = SpineTestMain },
{ isSupported = false, name = "SchdulerTest" , create_func= SchdulerTestMain },
{ isSupported = false, name = "ShaderTest" , create_func= ShaderTestMain },
{ isSupported = true, name = "Sprite3DTest" , create_func = Sprite3DTest },
{ isSupported = true, name = "SpriteTest" , create_func = SpriteTest },
{ isSupported = false, name = "TextInputTest" , create_func= TextInputTestMain },
{ isSupported = true, name = "Texture2DTest" , create_func = Texture2dTestMain },
{ isSupported = false, name = "TextureCacheTest" , create_func= TextureCacheTestMain },
{ isSupported = true, name = "TileMapTest" , create_func = TileMapTestMain },
{ isSupported = true, name = "TouchesTest" , create_func = TouchesTest },
{ isSupported = true, name = "TransitionsTest" , create_func = TransitionsTest },
{ isSupported = true, name = "UserDefaultTest" , create_func= UserDefaultTestMain },
{ isSupported = true, name = "XMLHttpRequestTest" , create_func = XMLHttpRequestTestMain },
{ isSupported = true, name = "ZwoptexTest" , create_func = ZwoptexTestMain }
}
local TESTS_COUNT = table.getn(_allTests)
-- create scene
local function CreateTestScene(nIdx)
cc.Director:getInstance():purgeCachedData()
local scene = _allTests[nIdx].create_func()
return scene
end
-- create menu
function CreateTestMenu()
local menuLayer = cc.Layer:create()
local function closeCallback()
cc.Director:getInstance():endToLua()
end
local function menuCallback(tag)
print(tag)
local Idx = tag - 10000
local testScene = CreateTestScene(Idx)
if testScene then
cc.Director:getInstance():replaceScene(testScene)
end
end
-- add close menu
local s = cc.Director:getInstance():getWinSize()
local CloseItem = cc.MenuItemImage:create(s_pPathClose, s_pPathClose)
CloseItem:registerScriptTapHandler(closeCallback)
CloseItem:setPosition(cc.p(s.width - 30, s.height - 30))
local CloseMenu = cc.Menu:create()
CloseMenu:setPosition(0, 0)
CloseMenu:addChild(CloseItem)
menuLayer:addChild(CloseMenu)
local targetPlatform = cc.Application:getInstance():getTargetPlatform()
if (cc.PLATFORM_OS_IPHONE == targetPlatform) or (cc.PLATFORM_OS_IPAD == targetPlatform) then
CloseMenu:setVisible(false)
end
-- add menu items for tests
local MainMenu = cc.Menu:create()
local index = 0
local obj = nil
for index, obj in pairs(_allTests) do
local testLabel = cc.Label:createWithTTF(obj.name, s_arialPath, 24)
testLabel:setAnchorPoint(cc.p(0.5, 0.5))
local testMenuItem = cc.MenuItemLabel:create(testLabel)
if not obj.isSupported then
testMenuItem:setEnabled(false)
end
testMenuItem:registerScriptTapHandler(menuCallback)
testMenuItem:setPosition(cc.p(s.width / 2, (s.height - (index) * LINE_SPACE)))
MainMenu:addChild(testMenuItem, index + 10000, index + 10000)
end
MainMenu:setContentSize(cc.size(s.width, (TESTS_COUNT + 1) * (LINE_SPACE)))
MainMenu:setPosition(CurPos.x, CurPos.y)
menuLayer:addChild(MainMenu)
-- handling touch events
local function onTouchBegan(touch, event)
BeginPos = touch:getLocation()
-- CCTOUCHBEGAN event must return true
return true
end
local function onTouchMoved(touch, event)
local location = touch:getLocation()
local nMoveY = location.y - BeginPos.y
local curPosx, curPosy = MainMenu:getPosition()
local nextPosy = curPosy + nMoveY
local winSize = cc.Director:getInstance():getWinSize()
if nextPosy < 0 then
MainMenu:setPosition(0, 0)
return
end
if nextPosy > ((TESTS_COUNT + 1) * LINE_SPACE - winSize.height) then
MainMenu:setPosition(0, ((TESTS_COUNT + 1) * LINE_SPACE - winSize.height))
return
end
MainMenu:setPosition(curPosx, nextPosy)
BeginPos = {x = location.x, y = location.y}
CurPos = {x = curPosx, y = nextPosy}
end
local listener = cc.EventListenerTouchOneByOne:create()
listener:registerScriptHandler(onTouchBegan,cc.Handler.EVENT_TOUCH_BEGAN )
listener:registerScriptHandler(onTouchMoved,cc.Handler.EVENT_TOUCH_MOVED )
local eventDispatcher = menuLayer:getEventDispatcher()
eventDispatcher:addEventListenerWithSceneGraphPriority(listener, menuLayer)
return menuLayer
end
| mit |
Keithenneu/Dota2-FullOverwrite | itemPurchase/enigma.lua | 2 | 1340 | -------------------------------------------------------------------------------
--- AUTHOR: Keithen
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
-------------------------------------------------------------------------------
BotsInit = require( "game/botsinit" )
local thisBot = BotsInit.CreateGeneric()
local generic = dofile( GetScriptDirectory().."/itemPurchase/generic" )
generic.ItemsToBuyAsJungler = {
StartingItems = {
"item_clarity",
"item_clarity",
"item_sobi_mask",
"item_ring_of_regen",
"item_recipe_soul_ring"
},
UtilityItems = {
},
CoreItems = {
"item_arcane_boots",
"item_blink"
},
ExtensionItems = {
OffensiveItems = {
"item_refresher"
},
DefensiveItems = {
"item_black_king_bar"
}
},
SellItems = {
}
}
----------------------------------------------------------------------------------------------------
function thisBot:Init()
generic:InitTable()
end
function thisBot:GetPurchaseOrder()
return generic:GetPurchaseOrder()
end
function thisBot:UpdateTeamBuyList(sItem)
generic:UpdateTeamBuyList( sItem )
end
function thisBot:ItemPurchaseThink(bot)
generic:Think(bot)
end
return thisBot
----------------------------------------------------------------------------------------------------
| gpl-3.0 |
LiberatorUSA/GUCEF | projects/premake5/targets/GUCEF_exe_MyGUI.ImageSetViewer/premake5.lua | 1 | 1778 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
workspace( "GUCEF_exe_MyGUI.ImageSetViewer" )
platforms( { "ALL", "LINUX32", "LINUX64", "WIN32", "WIN64" } )
location( "projects\premake5\targets" )
--
-- Includes for all modules in the solution:
--
filter "ALL"
include( "dependencies/MyGui/Tools/ImageSetViewer" )
filter "LINUX32"
include( "dependencies/MyGui/MyGUIEngine" )
include( "dependencies/MyGui/Platforms/OpenGL/OpenGLPlatform" )
include( "dependencies/MyGui/Tools/ImageSetViewer" )
include( "dependencies/freetype" )
include( "dependencies/zlib" )
filter "LINUX64"
include( "dependencies/MyGui/MyGUIEngine" )
include( "dependencies/MyGui/Platforms/OpenGL/OpenGLPlatform" )
include( "dependencies/MyGui/Tools/ImageSetViewer" )
include( "dependencies/freetype" )
include( "dependencies/zlib" )
filter "WIN32"
include( "dependencies/MyGui/MyGUIEngine" )
include( "dependencies/MyGui/Platforms/OpenGL/OpenGLPlatform" )
include( "dependencies/MyGui/Tools/ImageSetViewer" )
include( "dependencies/freetype" )
include( "dependencies/zlib" )
filter "WIN64"
include( "dependencies/MyGui/MyGUIEngine" )
include( "dependencies/MyGui/Platforms/OpenGL/OpenGLPlatform" )
include( "dependencies/MyGui/Tools/ImageSetViewer" )
include( "dependencies/freetype" )
include( "dependencies/zlib" )
| apache-2.0 |
jshackley/darkstar | scripts/globals/mobskills/Gregale_Wing.lua | 18 | 1239 | ---------------------------------------------
-- Gregale Wing
--
-- Description: An icy wind deals Ice damage to enemies within a very wide area of effect. Additional effect: Paralyze
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: 30' radial.
-- Notes: Used only by Jormungand and Isgebind
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:hasStatusEffect(EFFECT_BLOOD_WEAPON)) then
return 1;
elseif (mob:AnimationSub() == 1) then
return 1;
elseif (target:isBehind(mob, 48) == true) then
return 1;
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local typeEffect = EFFECT_PARALYSIS;
MobStatusEffectMove(mob, target, typeEffect, 40, 0, 120);
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_ICE,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_WIPE_SHADOWS);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
kubernetes/ingress-nginx | rootfs/etc/nginx/lua/util/nodemap.lua | 4 | 3832 | local math_random = require("math").random
local util_tablelength = require("util").tablelength
local ngx = ngx
local pairs = pairs
local string = string
local setmetatable = setmetatable
local _M = {}
--- create_map generates the node hash table
-- @tparam {[string]=number} nodes A table with the node as a key and its weight as a value.
-- @tparam string salt A salt that will be used to generate salted hash keys.
local function create_map(nodes, salt)
local hash_map = {}
for endpoint, _ in pairs(nodes) do
-- obfuscate the endpoint with a shared key to prevent brute force
-- and rainbow table attacks which could reveal internal endpoints
local key = salt .. endpoint
local hash_key = ngx.md5(key)
hash_map[hash_key] = endpoint
end
return hash_map
end
--- get_random_node picks a random node from the given map.
-- @tparam {[string], ...} map A key to node hash table.
-- @treturn string,string The node and its key
local function get_random_node(map)
local size = util_tablelength(map)
if size < 1 then
return nil, nil
end
local index = math_random(1, size)
local count = 1
for key, endpoint in pairs(map) do
if count == index then
return endpoint, key
end
count = count + 1
end
ngx.log(ngx.ERR, string.format("Failed to find node %d of %d! "
.. "This is a bug, please report!", index, size))
return nil, nil
end
--- new constructs a new instance of the node map
--
-- The map uses MD5 to create hash keys for a given node. For security reasons it supports
-- salted hash keys, to prevent attackers from using rainbow tables or brute forcing
-- the node endpoints, which would reveal cluster internal network information.
--
-- To make sure hash keys are reproducible on different ingress controller instances the salt
-- needs to be shared and therefore is not simply generated randomly.
--
-- @tparam {[string]=number} endpoints A table with the node endpoint
-- as a key and its weight as a value.
-- @tparam[opt] string hash_salt A optional hash salt that will be used to obfuscate the hash key.
function _M.new(self, endpoints, hash_salt)
if hash_salt == nil then
hash_salt = ''
end
-- the endpoints have to be saved as 'nodes' to keep compatibility to balancer.resty
local o = {
salt = hash_salt,
nodes = endpoints,
map = create_map(endpoints, hash_salt)
}
setmetatable(o, self)
self.__index = self
return o
end
--- reinit reinitializes the node map reusing the original salt
-- @tparam {[string]=number} nodes A table with the node as a key and its weight as a value.
function _M.reinit(self, nodes)
self.nodes = nodes
self.map = create_map(nodes, self.salt)
end
--- find looks up a node by hash key.
-- @tparam string key The hash key.
-- @treturn string The node.
function _M.find(self, key)
return self.map[key]
end
--- random picks a random node from the hashmap.
-- @treturn string,string A random node and its key or both nil.
function _M.random(self)
return get_random_node(self.map)
end
--- random_except picks a random node from the hashmap, ignoring the nodes in the given table
-- @tparam {string, } ignore_nodes A table of nodes to ignore, the node needs to be the key,
-- the value needs to be set to true
-- @treturn string,string A random node and its key or both nil.
function _M.random_except(self, ignore_nodes)
local valid_nodes = {}
-- avoid generating the map if no ignores where provided
if ignore_nodes == nil or util_tablelength(ignore_nodes) == 0 then
return get_random_node(self.map)
end
-- generate valid endpoints
for key, endpoint in pairs(self.map) do
if not ignore_nodes[endpoint] then
valid_nodes[key] = endpoint
end
end
return get_random_node(valid_nodes)
end
return _M
| apache-2.0 |
jshackley/darkstar | scripts/globals/abilities/water_maneuver.lua | 35 | 1609 | -----------------------------------
-- Ability: Water Maneuver
-- Enhances the effect of water attachments. Must have animator equipped.
-- Obtained: Puppetmaster level 1
-- Recast Time: 10 seconds (shared with all maneuvers)
-- Duration: 1 minute
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getWeaponSubSkillType(SLOT_RANGED) == 10 and
not player:hasStatusEffect(EFFECT_OVERLOAD)) then
return 0,0;
else
return 71,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local burden = 15;
if (target:getStat(MOD_MND) < target:getPet():getStat(MOD_MND)) then
burden = 20;
end
local overload = target:addBurden(ELE_WATER-1, burden);
if (overload ~= 0) then
target:removeAllManeuvers();
target:addStatusEffect(EFFECT_OVERLOAD, 0, 0, overload);
else
local level;
if (target:getMainJob() == JOB_PUP) then
level = target:getMainLvl()
else
level = target:getSubLvl()
end
local bonus = 1 + (level/15) + target:getMod(MOD_MANEUVER_BONUS);
if (target:getActiveManeuvers() == 3) then
target:removeOldestManeuver();
end
target:addStatusEffect(EFFECT_WATER_MANEUVER, bonus, 0, 60);
end
return EFFECT_WATER_MANEUVER;
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Apollyon/mobs/Inhumer.lua | 1 | 1166 | -----------------------------------
-- Area: Apollyon SE
-- NPC: Inhumer
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local mobID = mob:getID();
if (mobID ==16933025) then -- time
GetNPCByID(16932864+246):setPos(343,-1,-296);
GetNPCByID(16932864+246):setStatus(STATUS_NORMAL);
elseif (mobID ==16933028) then -- recover
GetNPCByID(16932864+248):setPos(376,-1,-259);
GetNPCByID(16932864+248):setStatus(STATUS_NORMAL);
elseif (mobID ==16933022) then -- item
GetNPCByID(16932864+247):setPos(307,-1,-309);
GetNPCByID(16932864+247):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/mobskills/Pinning_Shot.lua | 25 | 1052 | ---------------------------------------------
-- Pinning Shot
--
-- Description: Delivers a threefold ranged attack to targets in an area of effect. Additional effect: Bind
-- Type: Physical
-- Utsusemi/Blink absorb: 2-3 shadows
-- Range: Unknown
-- Notes: Used only by Medusa.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = math.random(2, 3);
local accmod = 1;
local dmgmod = 1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_PIERCE,info.hitslanded);
local typeEffect = EFFECT_BIND;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
shagu/pfQuest | database.lua | 1 | 52296 | -- multi api compat
local compat = pfQuestCompat
pfDatabase = {}
local loc = GetLocale()
local dbs = { "items", "quests", "quests-itemreq", "objects", "units", "zones", "professions", "areatrigger", "refloot" }
local noloc = { "items", "quests", "objects", "units" }
pfDB.locales = {
["enUS"] = "English",
["koKR"] = "Korean",
["frFR"] = "French",
["deDE"] = "German",
["zhCN"] = "Chinese",
["esES"] = "Spanish",
["ruRU"] = "Russian",
}
-- Patch databases to further expansions
local function patchtable(base, diff)
for k, v in pairs(diff) do
if base[k] and type(v) == "table" then
patchtable(base[k], v)
elseif type(v) == "string" and v == "_" then
base[k] = nil
else
base[k] = v
end
end
end
-- Return the best cluster point for a coordiante table
local best, neighbors = { index = 1, neighbors = 0 }, 0
local cache, cacheindex = {}
local ymin, ymax, xmin, ymax
local function getcluster(tbl, name)
local count = 0
best.index, best.neighbors = 1, 0
cacheindex = string.format("%s:%s", name, table.getn(tbl))
-- calculate new cluster if nothing is cached
if not cache[cacheindex] then
for index, data in pairs(tbl) do
-- precalculate the limits, and compare directly.
-- This way is much faster than the math.abs function.
xmin, xmax = data[1] - 5, data[1] + 5
ymin, ymax = data[2] - 5, data[2] + 5
neighbors = 0
count = count + 1
for _, compare in pairs(tbl) do
if compare[1] > xmin and compare[1] < xmax and compare[2] > ymin and compare[2] < ymax then
neighbors = neighbors + 1
end
end
if neighbors > best.neighbors then
best.neighbors = neighbors
best.index = index
end
end
cache[cacheindex] = { tbl[best.index][1] + .001, tbl[best.index][2] + .001, count }
end
return cache[cacheindex][1], cache[cacheindex][2], cache[cacheindex][3]
end
-- Detects if a non indexed table is empty
local function isempty(tbl)
for _ in pairs(tbl) do return end
return true
end
-- Returns the levenshtein distance between two strings
-- based on: https://gist.github.com/Badgerati/3261142
local len1, len2, cost, best
local levcache = {}
local function lev(str1, str2, limit)
if levcache[str1..":"..str2] then
return levcache[str1..":"..str2]
end
len1, len2, cost = string.len(str1), string.len(str2), 0
-- abort early on empty strings
if len1 == 0 then
return len2
elseif len2 == 0 then
return len1
elseif str1 == str2 then
return 0
end
-- initialise the base matrix
local matrix = {}
for i = 0, len1, 1 do
matrix[i] = { [0] = i }
end
for j = 0, len2, 1 do
matrix[0][j] = j
end
-- levenshtein algorithm
for i = 1, len1, 1 do
best = limit
for j = 1, len2, 1 do
cost = string.byte(str1,i) == string.byte(str2,j) and 0 or 1
matrix[i][j] = math.min(matrix[i-1][j] + 1, matrix[i][j-1] + 1, matrix[i-1][j-1] + cost)
if limit and matrix[i][j] < limit then
best = matrix[i][j]
end
end
if limit and best >= limit then
levcache[str1..":"..str2] = limit
return limit
end
end
-- return the levenshtein distance
levcache[str1..":"..str2] = matrix[len1][len2]
return matrix[len1][len2]
end
local loc_core, loc_update
for _, exp in pairs({ "-tbc", "-wotlk" }) do
for _, db in pairs(dbs) do
if pfDB[db]["data"..exp] then
patchtable(pfDB[db]["data"], pfDB[db]["data"..exp])
end
for loc, _ in pairs(pfDB.locales) do
if pfDB[db][loc] and pfDB[db][loc..exp] then
loc_update = pfDB[db][loc..exp] or pfDB[db]["enUS"..exp]
patchtable(pfDB[db][loc], loc_update)
end
end
end
loc_core = pfDB["professions"][loc] or pfDB["professions"]["enUS"]
loc_update = pfDB["professions"][loc..exp] or pfDB["professions"]["enUS"..exp]
if loc_update then patchtable(loc_core, loc_update) end
if pfDB["minimap"..exp] then patchtable(pfDB["minimap"], pfDB["minimap"..exp]) end
if pfDB["meta"..exp] then patchtable(pfDB["meta"], pfDB["meta"..exp]) end
end
-- detect installed locales
for key, name in pairs(pfDB.locales) do
if not pfDB["quests"][key] then pfDB.locales[key] = nil end
end
-- detect localized databases
pfDatabase.dbstring = ""
for id, db in pairs(dbs) do
-- assign existing locale
pfDB[db]["loc"] = pfDB[db][loc] or pfDB[db]["enUS"] or {}
pfDatabase.dbstring = pfDatabase.dbstring .. " |cffcccccc[|cffffffff" .. db .. "|cffcccccc:|cff33ffcc" .. ( pfDB[db][loc] and loc or "enUS" ) .. "|cffcccccc]"
end
-- track questitems to maintain object requirements
pfDatabase.itemlist = CreateFrame("Frame", "pfDatabaseQuestItemTracker", UIParent)
pfDatabase.itemlist.update = 0
pfDatabase.itemlist.db = {}
pfDatabase.itemlist.db_tmp = {}
pfDatabase.itemlist.registry = {}
pfDatabase.TrackQuestItemDependency = function(self, item, qid)
self.itemlist.registry[item] = qid
self.itemlist.update = GetTime() + .5
self.itemlist:Show()
end
pfDatabase.itemlist:RegisterEvent("BAG_UPDATE")
pfDatabase.itemlist:SetScript("OnEvent", function()
this.update = GetTime() + .5
this:Show()
end)
pfDatabase.itemlist:SetScript("OnUpdate", function()
if GetTime() < this.update then return end
-- remove obsolete registry entries
for item, qid in pairs(this.registry) do
if not pfQuest.questlog[qid] then
this.registry[item] = nil
end
end
-- save and clean previous items
local previous = this.db
this.db = {}
-- fill new item db with bag items
for bag = 4, 0, -1 do
for slot = 1, GetContainerNumSlots(bag) do
local link = GetContainerItemLink(bag,slot)
local _, _, parse = strfind((link or ""), "(%d+):")
if parse then
local item = GetItemInfo(parse)
if item then this.db[item] = true end
end
end
end
-- fill new item db with equipped items
for i=1,19 do
if GetInventoryItemLink("player", i) then
local _, _, link = string.find(GetInventoryItemLink("player", i), "(item:%d+:%d+:%d+:%d+)");
local item = GetItemInfo(link)
if item then this.db[item] = true end
end
end
-- find new items
for item in pairs(this.db) do
if not previous[item] and this.registry[item] then
pfQuest.questlog[this.registry[item]] = nil
pfQuest:UpdateQuestlog()
end
end
-- find removed items
for item in pairs(previous) do
if not this.db[item] and this.registry[item] then
pfQuest.questlog[this.registry[item]] = nil
pfQuest:UpdateQuestlog()
end
end
this:Hide()
end)
-- check for unlocalized servers and fallback to enUS databases when the server
-- returns item names that are different to the database ones. (check via. Hearthstone)
CreateFrame("Frame"):SetScript("OnUpdate", function()
-- throttle to to one item per second
if ( this.tick or 0) > GetTime() then return else this.tick = GetTime() + 1 end
-- give the server one iteration to return the itemname.
-- this is required for clients that use a clean wdb folder.
if not this.sentquery then
ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
ItemRefTooltip:SetHyperlink("item:6948:0:0:0")
ItemRefTooltip:Hide()
this.sentquery = true
return
end
ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
ItemRefTooltip:SetHyperlink("item:6948:0:0:0")
if ItemRefTooltipTextLeft1 and ItemRefTooltipTextLeft1:IsVisible() then
local name = ItemRefTooltipTextLeft1:GetText()
ItemRefTooltip:Hide()
-- check for noloc
if name and name ~= "" and pfDB["items"][loc][6948] then
if not strfind(name, pfDB["items"][loc][6948], 1) then
for id, db in pairs(noloc) do
pfDB[db]["loc"] = pfDB[db]["enUS"] or {}
end
end
this:Hide()
end
end
-- set a detection timeout to 15 seconds
if GetTime() > 15 then this:Hide() end
end)
-- sanity check the databases
if isempty(pfDB["quests"]["loc"]) then
CreateFrame("Frame"):SetScript("OnUpdate", function()
if GetTime() < 3 then return end
DEFAULT_CHAT_FRAME:AddMessage("|cffff5555 !! |cffffaaaaWrong version of |cff33ffccpf|cffffffffQuest|cffffaaaa detected.|cffff5555 !!")
DEFAULT_CHAT_FRAME:AddMessage("|cffffccccThe language pack does not match the gameclient's language.")
DEFAULT_CHAT_FRAME:AddMessage("|cffffccccYou'd either need to pick the complete or the " .. GetLocale().."-version.")
DEFAULT_CHAT_FRAME:AddMessage("|cffffccccFor more details, see: https://shagu.org/pfQuest")
this:Hide()
end)
end
-- add database shortcuts
local items, units, objects, quests, zones, refloot, itemreq, areatrigger, professions
pfDatabase.Reload = function()
items = pfDB["items"]["data"]
units = pfDB["units"]["data"]
objects = pfDB["objects"]["data"]
quests = pfDB["quests"]["data"]
zones = pfDB["zones"]["data"]
refloot = pfDB["refloot"]["data"]
itemreq = pfDB["quests-itemreq"]["data"]
areatrigger = pfDB["areatrigger"]["data"]
professions = pfDB["professions"]["loc"]
end
pfDatabase.Reload()
local bitraces = {
[1] = "Human",
[2] = "Orc",
[4] = "Dwarf",
[8] = "NightElf",
[16] = "Scourge",
[32] = "Tauren",
[64] = "Gnome",
[128] = "Troll"
}
-- append with playable races by expansion
if pfQuestCompat.client > 11200 then
bitraces[512] = "BloodElf"
bitraces[1024] = "Draenei"
end
local bitclasses = {
[1] = "WARRIOR",
[2] = "PALADIN",
[4] = "HUNTER",
[8] = "ROGUE",
[16] = "PRIEST",
[64] = "SHAMAN",
[128] = "MAGE",
[256] = "WARLOCK",
[1024] = "DRUID"
}
function pfDatabase:BuildQuestDescription(meta)
if not meta.title or not meta.quest or not meta.QTYPE then return end
if meta.QTYPE == "NPC_START" then
return string.format(pfQuest_Loc["Speak with |cff33ffcc%s|r to obtain |cffffcc00[!]|cff33ffcc %s|r"], (meta.spawn or UNKNOWN), (meta.quest or UNKNOWN))
elseif meta.QTYPE == "OBJECT_START" then
return string.format(pfQuest_Loc["Interact with |cff33ffcc%s|r to obtain |cffffcc00[!]|cff33ffcc %s|r"], (meta.spawn or UNKNOWN), (meta.quest or UNKNOWN))
elseif meta.QTYPE == "NPC_END" then
return string.format(pfQuest_Loc["Speak with |cff33ffcc%s|r to complete |cffffcc00[?]|cff33ffcc %s|r"], (meta.spawn or UNKNOWN), (meta.quest or UNKNOWN))
elseif meta.QTYPE == "OBJECT_END" then
return string.format(pfQuest_Loc["Interact with |cff33ffcc%s|r to complete |cffffcc00[?]|cff33ffcc %s|r"], (meta.spawn or UNKNOWN), (meta.quest or UNKNOWN))
elseif meta.QTYPE == "UNIT_OBJECTIVE" then
return string.format(pfQuest_Loc["Kill |cff33ffcc%s|r"], (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "UNIT_OBJECTIVE_ITEMREQ" then
return string.format(pfQuest_Loc["Use |cff33ffcc%s|r on |cff33ffcc%s|r"], (meta.itemreq or UNKNOWN), (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "OBJECT_OBJECTIVE" then
return string.format(pfQuest_Loc["Interact with |cff33ffcc%s|r"], (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "OBJECT_OBJECTIVE_ITEMREQ" then
return string.format(pfQuest_Loc["Use |cff33ffcc%s|r at |cff33ffcc%s|r"], (meta.itemreq or UNKNOWN), (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "ITEM_OBJECTIVE_LOOT" then
return string.format(pfQuest_Loc["Loot |cff33ffcc[%s]|r from |cff33ffcc%s|r"], (meta.item or UNKNOWN), (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "ITEM_OBJECTIVE_USE" then
return string.format(pfQuest_Loc["Loot and/or Use |cff33ffcc[%s]|r from |cff33ffcc%s|r"], (meta.item or UNKNOWN), (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "AREATRIGGER_OBJECTIVE" then
return string.format(pfQuest_Loc["Explore |cff33ffcc%s|r"], (meta.spawn or UNKNOWN))
elseif meta.QTYPE == "ZONE_OBJECTIVE" then
return string.format(pfQuest_Loc["Use Quest Item at |cff33ffcc%s|r"], (meta.spawn or UNKNOWN))
end
end
-- ShowExtendedTooltip
-- Draws quest informations into a tooltip
function pfDatabase:ShowExtendedTooltip(id, tooltip, parent, anchor, offx, offy)
local tooltip = tooltip or GameTooltip
local parent = parent or this
local anchor = anchor or "ANCHOR_LEFT"
tooltip:SetOwner(parent, anchor, offx, offy)
local locales = pfDB["quests"]["loc"][id]
local data = pfDB["quests"]["data"][id]
if locales then
tooltip:SetText((locales["T"] or UNKNOWN), .3, 1, .8)
tooltip:AddLine(" ")
else
tooltip:SetText(UNKNOWN, .3, 1, .8)
end
if data then
-- quest start
if data["start"] then
for key, db in pairs({["U"]="units", ["O"]="objects", ["I"]="items"}) do
if data["start"][key] then
local entries = ""
for _, id in pairs(data["start"][key]) do
entries = entries .. (entries == "" and "" or ", ") .. ( pfDB[db]["loc"][id] or UNKNOWN )
end
tooltip:AddDoubleLine(pfQuest_Loc["Quest Start"]..":", entries, 1,1,1, 1,1,.8)
end
end
end
-- quest end
if data["end"] then
for key, db in pairs({["U"]="units", ["O"]="objects"}) do
if data["end"][key] then
local entries = ""
for _, id in ipairs(data["end"][key]) do
entries = entries .. (entries == "" and "" or ", ") .. ( pfDB[db]["loc"][id] or UNKNOWN )
end
tooltip:AddDoubleLine(pfQuest_Loc["Quest End"]..":", entries, 1,1,1, 1,1,.8)
end
end
end
end
if locales then
-- obectives
if locales["O"] and locales["O"] ~= "" then
tooltip:AddLine(" ")
tooltip:AddLine(pfDatabase:FormatQuestText(locales["O"]),1,1,1,true)
end
-- details
if locales["D"] and locales["D"] ~= "" then
tooltip:AddLine(" ")
tooltip:AddLine(pfDatabase:FormatQuestText(locales["D"]),.6,.6,.6,true)
end
end
-- add levels
if data then
if data["lvl"] or data["min"] then
tooltip:AddLine(" ")
end
if data["lvl"] then
local questlevel = tonumber(data["lvl"])
local color = GetDifficultyColor(questlevel)
tooltip:AddLine("|cffffffff" .. pfQuest_Loc["Quest Level"] .. ": |r" .. questlevel, color.r, color.g, color.b)
end
if data["min"] then
local questlevel = tonumber(data["min"])
local color = GetDifficultyColor(questlevel)
tooltip:AddLine("|cffffffff" .. pfQuest_Loc["Required Level"] .. ": |r" .. questlevel, color.r, color.g, color.b)
end
end
tooltip:Show()
end
-- GetPlayerSkill
-- Returns false if the player doesn't have the required skill, or their rank if they do
function pfDatabase:GetPlayerSkill(skill)
if not professions[skill] then return false end
for i=0,GetNumSkillLines() do
local skillName, _, _, skillRank = GetSkillLineInfo(i)
if skillName == professions[skill] then
return skillRank
end
end
return false
end
-- GetBitByRace
-- Returns bit of the current race
function pfDatabase:GetBitByRace(model)
-- scan for regular bitmasks
for bit, v in pairs(bitraces) do
if model == v then return bit end
end
-- return alliance/horde racemask as fallback for unknown races
return UnitFactionGroup("player") == "Alliance" and 77 or 178
end
-- GetBitByClass
-- Returns bit of the current class
function pfDatabase:GetBitByClass(class)
for bit, v in pairs(bitclasses) do
if class == v then return bit end
end
end
-- GetHexDifficultyColor
-- Returns a string with the difficulty color of the given level
function pfDatabase:GetHexDifficultyColor(level, force)
if force and UnitLevel("player") < level then
return "|cffff5555"
else
local c = GetDifficultyColor(level)
return string.format("|cff%02x%02x%02x", c.r*255, c.g*255, c.b*255)
end
end
-- GetRaceMaskByID
function pfDatabase:GetRaceMaskByID(id, db)
-- 64 + 8 + 4 + 1 = 77 = Alliance
-- 128 + 32 + 16 + 2 = 178 = Horde
local factionMap = {["A"]=77, ["H"]=178, ["AH"]=255, ["HA"]=255}
local raceMask = 0
if db == "quests" then
raceMask = quests[id]["race"] or raceMask
if (quests[id]["start"]) then
local questStartRaceMask = 0
-- get quest starter faction
if (quests[id]["start"]["U"]) then
for _, startUnitId in ipairs(quests[id]["start"]["U"]) do
if units[startUnitId] and units[startUnitId]["fac"] and factionMap[units[startUnitId]["fac"]] then
questStartRaceMask = bit.bor(factionMap[units[startUnitId]["fac"]])
end
end
end
-- get quest object starter faction
if (quests[id]["start"]["O"]) then
for _, startObjectId in ipairs(quests[id]["start"]["O"]) do
if objects[startObjectId] and objects[startObjectId]["fac"] and factionMap[objects[startObjectId]["fac"]] then
questStartRaceMask = bit.bor(factionMap[objects[startObjectId]["fac"]])
end
end
end
-- apply starter faction as racemask
if questStartRaceMask > 0 and questStartRaceMask ~= raceMask then
raceMask = questStartRaceMask
end
end
elseif pfDB[db] and pfDB[db]["data"] and pfDB[db]["data"]["fac"] then
raceMask = factionMap[pfDB[db]["data"]["fac"]]
end
return raceMask
end
-- GetIDByName
-- Scans localization tables for matching IDs
-- Returns table with all IDs
function pfDatabase:GetIDByName(name, db, partial, server)
if not pfDB[db] then return nil end
local ret = {}
for id, loc in pairs(pfDB[db]["loc"]) do
if db == "quests" then loc = loc["T"] end
local custom = server and pfQuest_server[db] and pfQuest_server[db][id] or not server
if loc and name then
if partial == true and strfind(strlower(loc), strlower(name), 1, true) and custom then
ret[id] = loc
elseif partial == "LOWER" and strlower(loc) == strlower(name) and custom then
ret[id] = loc
elseif loc == name and custom then
ret[id] = loc
end
end
end
return ret
end
-- GetIDByIDPart
-- Scans localization tables for matching IDs
-- Returns table with all IDs
function pfDatabase:GetIDByIDPart(idPart, db)
if not pfDB[db] then return nil end
local ret = {}
for id, loc in pairs(pfDB[db]["loc"]) do
if db == "quests" then loc = loc["T"] end
if idPart and loc and strfind(tostring(id), idPart) then
ret[id] = loc
end
end
return ret
end
-- GetBestMap
-- Scans a map table for all spawns
-- Returns the map with most spawns
function pfDatabase:GetBestMap(maps)
local bestmap, bestscore = nil, 0
-- calculate best map results
for map, count in pairs(maps or {}) do
if count > bestscore or ( count == 0 and bestscore == 0 ) then
bestscore = count
bestmap = map
end
end
return bestmap or nil, bestscore or nil
end
-- SearchAreaTriggerID
-- Scans for all mobs with a specified ID
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchAreaTriggerID(id, meta, maps, prio)
if not areatrigger[id] or not areatrigger[id]["coords"] then return maps end
local maps = maps or {}
local prio = prio or 1
for _, data in pairs(areatrigger[id]["coords"]) do
local x, y, zone = unpack(data)
if zone > 0 then
-- add all gathered data
meta = meta or {}
meta["spawn"] = pfQuest_Loc["Exploration Mark"]
meta["spawnid"] = id
meta["item"] = nil
meta["title"] = meta["quest"] or meta["item"] or meta["spawn"]
meta["zone"] = zone
meta["x"] = x
meta["y"] = y
meta["level"] = pfQuest_Loc["N/A"]
meta["spawntype"] = pfQuest_Loc["Trigger"]
meta["respawn"] = pfQuest_Loc["N/A"]
maps[zone] = maps[zone] and maps[zone] + prio or prio
pfMap:AddNode(meta)
end
end
return maps
end
-- SearchMobID
-- Scans for all mobs with a specified ID
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchMobID(id, meta, maps, prio)
if not units[id] or not units[id]["coords"] then return maps end
local maps = maps or {}
local prio = prio or 1
for _, data in pairs(units[id]["coords"]) do
local x, y, zone, respawn = unpack(data)
if zone > 0 then
-- add all gathered data
meta = meta or {}
meta["spawn"] = pfDB.units.loc[id]
meta["spawnid"] = id
meta["title"] = meta["quest"] or meta["item"] or meta["spawn"]
meta["zone"] = zone
meta["x"] = x
meta["y"] = y
meta["level"] = units[id]["lvl"] or UNKNOWN
meta["spawntype"] = pfQuest_Loc["Unit"]
meta["respawn"] = respawn > 0 and SecondsToTime(respawn)
maps[zone] = maps[zone] and maps[zone] + prio or prio
pfMap:AddNode(meta)
end
end
return maps
end
-- Search MetaRelation
-- Scans for all entries within the specified meta name
-- Adds map nodes for each and returns its map table
-- query = { relation-name, relation-min, relation-max }
local alias = {
["flightmaster"] = "flight",
["taxi"] = "flight",
["flights"] = "flight",
["raremobs"] = "rares",
}
function pfDatabase:SearchMetaRelation(query, meta, show)
local maps = {}
local faction
local relname = query[1] -- search name (chests)
local relmins = query[2] -- min skill level
local relmaxs = query[3] -- max skill level
relname = alias[relname] or relname
if pfDB["meta"] and pfDB["meta"][relname] then
if relname == "flight" then
meta["texture"] = pfQuestConfig.path.."\\img\\available_c"
meta["vertex"] = { .4, 1, .4 }
if relmins then
faction = string.lower(relmins)
else
faction = string.lower(UnitFactionGroup("player"))
end
faction = faction == "horde" and "H" or faction == "alliance" and "A" or ""
elseif relname == "rares" then
meta["texture"] = pfQuestConfig.path.."\\img\\fav"
end
for id, skill in pairs(pfDB["meta"][relname]) do
if ( not tonumber(relmins) or tonumber(relmins) <= skill ) and
( not tonumber(relmaxs) or tonumber(relmaxs) >= skill ) and
( not faction or string.find(skill, faction))
then
if id < 0 then
pfDatabase:SearchObjectID(math.abs(id), meta, maps)
else
pfDatabase:SearchMobID(id, meta, maps)
end
end
end
end
return maps
end
-- SearchMob
-- Scans for all mobs with a specified name
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchMob(mob, meta, partial)
local maps = {}
for id in pairs(pfDatabase:GetIDByName(mob, "units", partial)) do
if units[id] and units[id]["coords"] then
maps = pfDatabase:SearchMobID(id, meta, maps)
end
end
return maps
end
-- SearchZoneID
-- Scans for all zones with a specific ID
-- Add nodes to the center of that location
function pfDatabase:SearchZoneID(id, meta, maps, prio)
if not zones[id] then return maps end
local maps = maps or {}
local prio = prio or 1
local zone, width, height, x, y, ex, ey = unpack(zones[id])
if zone > 0 then
maps[zone] = maps[zone] and maps[zone] + prio or prio
meta = meta or {}
meta["spawn"] = pfDB.zones.loc[id] or UNKNOWN
meta["spawnid"] = id
meta["title"] = meta["quest"] or meta["item"] or meta["spawn"]
meta["zone"] = zone
meta["level"] = "N/A"
meta["spawntype"] = pfQuest_Loc["Area/Zone"]
meta["respawn"] = "N/A"
meta["x"] = x
meta["y"] = y
pfMap:AddNode(meta)
return maps
end
return maps
end
-- SearchZone
-- Scans for all zones with a specified name
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchZone(obj, meta, partial)
local maps = {}
for id in pairs(pfDatabase:GetIDByName(obj, "zones", partial)) do
if zones[id] then
maps = pfDatabase:SearchZoneID(id, meta, maps)
end
end
return maps
end
-- Scans for all objects with a specified ID
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchObjectID(id, meta, maps, prio)
if not objects[id] or not objects[id]["coords"] then return maps end
local maps = maps or {}
local prio = prio or 1
for _, data in pairs(objects[id]["coords"]) do
local x, y, zone, respawn = unpack(data)
if zone > 0 then
-- add all gathered data
meta = meta or {}
meta["spawn"] = pfDB.objects.loc[id]
meta["spawnid"] = id
meta["title"] = meta["quest"] or meta["item"] or meta["spawn"]
meta["zone"] = zone
meta["x"] = x
meta["y"] = y
meta["level"] = nil
meta["spawntype"] = pfQuest_Loc["Object"]
meta["respawn"] = respawn and SecondsToTime(respawn)
maps[zone] = maps[zone] and maps[zone] + prio or prio
pfMap:AddNode(meta)
end
end
return maps
end
-- SearchObject
-- Scans for all objects with a specified name
-- Adds map nodes for each and returns its map table
function pfDatabase:SearchObject(obj, meta, partial)
local maps = {}
for id in pairs(pfDatabase:GetIDByName(obj, "objects", partial)) do
if objects[id] and objects[id]["coords"] then
maps = pfDatabase:SearchObjectID(id, meta, maps)
end
end
return maps
end
-- SearchItemID
-- Scans for all items with a specified ID
-- Adds map nodes for each drop and vendor
-- Returns its map table
function pfDatabase:SearchItemID(id, meta, maps, allowedTypes)
if not items[id] then return maps end
local maps = maps or {}
local meta = meta or {}
meta["itemid"] = id
meta["item"] = pfDB.items.loc[id]
local minChance = tonumber(pfQuest_config.mindropchance)
if not minChance then minChance = 0 end
-- search unit drops
if items[id]["U"] and ((not allowedTypes) or allowedTypes["U"]) then
for unit, chance in pairs(items[id]["U"]) do
if chance >= minChance then
meta["texture"] = nil
meta["droprate"] = chance
meta["sellcount"] = nil
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
end
-- search object loot (veins, chests, ..)
if items[id]["O"] and ((not allowedTypes) or allowedTypes["O"]) then
for object, chance in pairs(items[id]["O"]) do
if chance >= minChance and chance > 0 then
meta["texture"] = nil
meta["droprate"] = chance
meta["sellcount"] = nil
maps = pfDatabase:SearchObjectID(object, meta, maps)
end
end
end
-- search reference loot (objects, creatures)
if items[id]["R"] then
for ref, chance in pairs(items[id]["R"]) do
if chance >= minChance and refloot[ref] then
-- ref creatures
if refloot[ref]["U"] and ((not allowedTypes) or allowedTypes["U"]) then
for unit in pairs(refloot[ref]["U"]) do
meta["texture"] = nil
meta["droprate"] = chance
meta["sellcount"] = nil
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
-- ref objects
if refloot[ref]["O"] and ((not allowedTypes) or allowedTypes["O"]) then
for object in pairs(refloot[ref]["O"]) do
meta["texture"] = nil
meta["droprate"] = chance
meta["sellcount"] = nil
maps = pfDatabase:SearchObjectID(object, meta, maps)
end
end
end
end
end
-- search vendor goods
if items[id]["V"] and ((not allowedTypes) or allowedTypes["V"]) then
for unit, chance in pairs(items[id]["V"]) do
meta["texture"] = pfQuestConfig.path.."\\img\\icon_vendor"
meta["droprate"] = nil
meta["sellcount"] = chance
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
return maps
end
-- SearchItem
-- Scans for all items with a specified name
-- Adds map nodes for each drop and vendor
-- Returns its map table
function pfDatabase:SearchItem(item, meta, partial)
local maps = {}
local bestmap, bestscore = nil, 0
for id in pairs(pfDatabase:GetIDByName(item, "items", partial)) do
maps = pfDatabase:SearchItemID(id, meta, maps)
end
return maps
end
-- SearchVendor
-- Scans for all items with a specified name
-- Adds map nodes for each vendor
-- Returns its map table
function pfDatabase:SearchVendor(item, meta)
local maps = {}
local meta = meta or {}
local bestmap, bestscore = nil, 0
for id in pairs(pfDatabase:GetIDByName(item, "items")) do
meta["itemid"] = id
meta["item"] = pfDB.items.loc[id]
-- search vendor goods
if items[id] and items[id]["V"] then
for unit, chance in pairs(items[id]["V"]) do
meta["texture"] = pfQuestConfig.path.."\\img\\icon_vendor"
meta["droprate"] = nil
meta["sellcount"] = chance
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
end
return maps
end
-- SearchQuestID
-- Scans for all quests with a specified ID
-- Adds map nodes for each objective and involved units
-- Returns its map table
function pfDatabase:SearchQuestID(id, meta, maps)
if not quests[id] then return end
local maps = maps or {}
local meta = meta or {}
meta["questid"] = id
meta["quest"] = pfDB.quests.loc[id] and pfDB.quests.loc[id].T
meta["qlvl"] = quests[id]["lvl"]
meta["qmin"] = quests[id]["min"]
-- clear previous unified quest nodes
pfMap.unifiedcache[meta.quest] = {}
if pfQuest_config["currentquestgivers"] == "1" then
-- search quest-starter
if quests[id]["start"] and not meta["qlogid"] then
-- units
if quests[id]["start"]["U"] then
for _, unit in pairs(quests[id]["start"]["U"]) do
meta = meta or {}
meta["QTYPE"] = "NPC_START"
meta["layer"] = meta["layer"] or 4
meta["texture"] = pfQuestConfig.path.."\\img\\available_c"
maps = pfDatabase:SearchMobID(unit, meta, maps, 0)
end
end
-- objects
if quests[id]["start"]["O"] then
for _, object in pairs(quests[id]["start"]["O"]) do
meta = meta or {}
meta["QTYPE"] = "OBJECT_START"
meta["texture"] = pfQuestConfig.path.."\\img\\available_c"
maps = pfDatabase:SearchObjectID(object, meta, maps, 0)
end
end
end
-- search quest-ender
if quests[id]["end"] then
-- units
if quests[id]["end"]["U"] then
for _, unit in pairs(quests[id]["end"]["U"]) do
meta = meta or {}
if meta["qlogid"] then
local _, _, _, _, _, complete = compat.GetQuestLogTitle(meta["qlogid"])
complete = complete or GetNumQuestLeaderBoards(meta["qlogid"]) == 0 and true or nil
if complete then
meta["texture"] = pfQuestConfig.path.."\\img\\complete_c"
else
meta["texture"] = pfQuestConfig.path.."\\img\\complete"
end
else
meta["texture"] = pfQuestConfig.path.."\\img\\complete_c"
end
meta["QTYPE"] = "NPC_END"
maps = pfDatabase:SearchMobID(unit, meta, maps, 0)
end
end
-- objects
if quests[id]["end"]["O"] then
for _, object in pairs(quests[id]["end"]["O"]) do
meta = meta or {}
if meta["qlogid"] then
local _, _, _, _, _, complete = compat.GetQuestLogTitle(meta["qlogid"])
complete = complete or GetNumQuestLeaderBoards(meta["qlogid"]) == 0 and true or nil
if complete then
meta["texture"] = pfQuestConfig.path.."\\img\\complete_c"
else
meta["texture"] = pfQuestConfig.path.."\\img\\complete"
end
else
meta["texture"] = pfQuestConfig.path.."\\img\\complete_c"
end
meta["QTYPE"] = "OBJECT_END"
maps = pfDatabase:SearchObjectID(object, meta, maps, 0)
end
end
end
end
local parse_obj = {
["U"] = {},
["O"] = {},
["I"] = {},
}
-- If QuestLogID is given, scan and add all finished objectives to blacklist
if meta["qlogid"] then
local objectives = GetNumQuestLeaderBoards(meta["qlogid"])
local _, _, _, _, _, complete = compat.GetQuestLogTitle(meta["qlogid"])
if complete then return maps end
if objectives then
for i=1, objectives, 1 do
local text, type, done = GetQuestLogLeaderBoard(i, meta["qlogid"])
-- spawn data
if type == "monster" then
local i, j, monsterName, objNum, objNeeded = strfind(text, pfUI.api.SanitizePattern(QUEST_MONSTERS_KILLED))
for id in pairs(pfDatabase:GetIDByName(monsterName, "units")) do
parse_obj["U"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG"
end
for id in pairs(pfDatabase:GetIDByName(monsterName, "objects")) do
parse_obj["O"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG"
end
end
-- item data
if type == "item" then
local i, j, itemName, objNum, objNeeded = strfind(text, pfUI.api.SanitizePattern(QUEST_OBJECTS_FOUND))
for id in pairs(pfDatabase:GetIDByName(itemName, "items")) do
parse_obj["I"][id] = ( objNum + 0 >= objNeeded + 0 or done ) and "DONE" or "PROG"
end
end
end
end
end
-- search quest-objectives
if quests[id]["obj"] then
local skip_objects
local skip_creatures
-- item requirements
if quests[id]["obj"]["IR"] then
local requirement
for _, item in pairs(quests[id]["obj"]["IR"]) do
if itemreq[item] then
requirement = pfDB["items"]["loc"][item] or UNKNOWN
for object, spell in pairs(itemreq[item]) do
if object < 0 then
-- gameobject
meta["texture"] = nil
meta["layer"] = 2
meta["QTYPE"] = "OBJECT_OBJECTIVE_ITEMREQ"
meta.itemreq = requirement
skip_objects = skip_objects or {}
skip_objects[math.abs(object)] = true
pfDatabase:TrackQuestItemDependency(requirement, id)
if pfDatabase.itemlist.db[requirement] then
maps = pfDatabase:SearchObjectID(math.abs(object), meta, maps)
end
elseif object > 0 then
-- creature
meta["texture"] = nil
meta["layer"] = 2
meta["QTYPE"] = "UNIT_OBJECTIVE_ITEMREQ"
meta.itemreq = requirement
skip_creatures = skip_creatures or {}
skip_creatures[math.abs(object)] = true
pfDatabase:TrackQuestItemDependency(requirement, id)
if pfDatabase.itemlist.db[requirement] then
maps = pfDatabase:SearchMobID(math.abs(object), meta, maps)
end
end
end
end
end
end
-- units
if quests[id]["obj"]["U"] then
for _, unit in pairs(quests[id]["obj"]["U"]) do
if not parse_obj["U"][unit] or parse_obj["U"][unit] ~= "DONE" then
if not skip_creatures or not skip_creatures[unit] then
meta = meta or {}
meta["texture"] = nil
meta["QTYPE"] = "UNIT_OBJECTIVE"
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
end
end
-- objects
if quests[id]["obj"]["O"] then
for _, object in pairs(quests[id]["obj"]["O"]) do
if not parse_obj["O"][object] or parse_obj["O"][object] ~= "DONE" then
if not skip_objects or not skip_objects[object] then
meta = meta or {}
meta["texture"] = nil
meta["layer"] = 2
meta["QTYPE"] = "OBJECT_OBJECTIVE"
maps = pfDatabase:SearchObjectID(object, meta, maps)
end
end
end
end
-- items
if quests[id]["obj"]["I"] then
for _, item in pairs(quests[id]["obj"]["I"]) do
if not parse_obj["I"][item] or parse_obj["I"][item] ~= "DONE" then
meta = meta or {}
meta["texture"] = nil
meta["layer"] = 2
if parse_obj["I"][item] then
meta["QTYPE"] = "ITEM_OBJECTIVE_LOOT"
else
meta["QTYPE"] = "ITEM_OBJECTIVE_USE"
end
maps = pfDatabase:SearchItemID(item, meta, maps)
end
end
end
-- areatrigger
if quests[id]["obj"]["A"] then
for _, areatrigger in pairs(quests[id]["obj"]["A"]) do
meta = meta or {}
meta["texture"] = nil
meta["layer"] = 2
meta["QTYPE"] = "AREATRIGGER_OBJECTIVE"
maps = pfDatabase:SearchAreaTriggerID(areatrigger, meta, maps)
end
end
-- zones
if quests[id]["obj"]["Z"] then
for _, zone in pairs(quests[id]["obj"]["Z"]) do
meta = meta or {}
meta["texture"] = nil
meta["layer"] = 2
meta["QTYPE"] = "ZONE_OBJECTIVE"
maps = pfDatabase:SearchZoneID(zone, meta, maps)
end
end
end
-- prepare unified quest location markers
local addon = meta["addon"] or "PFDB"
if pfMap.nodes[addon] then
for map in pairs(pfMap.nodes[addon]) do
if pfMap.unifiedcache[meta.quest] and pfMap.unifiedcache[meta.quest][map] then
for hash, data in pairs(pfMap.unifiedcache[meta.quest][map]) do
meta = data.meta
meta["title"] = meta["quest"]
meta["cluster"] = true
meta["zone"] = map
local icon = pfQuest_config["clustermono"] == "1" and "_mono" or ""
if meta.item then
meta["x"], meta["y"], meta["priority"] = getcluster(data.coords, meta["quest"]..hash..map)
meta["texture"] = pfQuestConfig.path.."\\img\\cluster_item" .. icon
pfMap:AddNode(meta, true)
elseif meta.spawntype and meta.spawntype == pfQuest_Loc["Unit"] and meta.spawn and not meta.itemreq then
meta["x"], meta["y"], meta["priority"] = getcluster(data.coords, meta["quest"]..hash..map)
meta["texture"] = pfQuestConfig.path.."\\img\\cluster_mob" .. icon
pfMap:AddNode(meta, true)
else
meta["x"], meta["y"], meta["priority"] = getcluster(data.coords, meta["quest"]..hash..map)
meta["texture"] = pfQuestConfig.path.."\\img\\cluster_misc" .. icon
pfMap:AddNode(meta, true)
end
end
end
end
end
return maps
end
-- SearchQuest
-- Scans for all quests with a specified name
-- Adds map nodes for each objective and involved unit
-- Returns its map table
function pfDatabase:SearchQuest(quest, meta, partial)
local maps = {}
for id in pairs(pfDatabase:GetIDByName(quest, "quests", partial)) do
maps = pfDatabase:SearchQuestID(id, meta, maps)
end
return maps
end
function pfDatabase:QuestFilter(id, plevel, pclass, prace)
-- hide active quest
if pfQuest.questlog[id] then return end
-- hide completed quests
if pfQuest_history[id] then return end
-- hide broken quests without names
if not pfDB.quests.loc[id] or not pfDB.quests.loc[id].T then return end
-- hide missing pre-quests
if quests[id]["pre"] then
-- check all pre-quests for one to be completed
local one_complete = nil
for _, prequest in pairs(quests[id]["pre"]) do
if pfQuest_history[prequest] then
one_complete = true
end
end
-- hide if none of the pre-quests has been completed
if not one_complete then return end
end
-- hide non-available quests for your race
if quests[id]["race"] and not ( bit.band(quests[id]["race"], prace) == prace ) then return end
-- hide non-available quests for your class
if quests[id]["class"] and not ( bit.band(quests[id]["class"], pclass) == pclass ) then return end
-- hide non-available quests for your profession
if quests[id]["skill"] and not pfDatabase:GetPlayerSkill(quests[id]["skill"]) then return end
-- hide lowlevel quests
if quests[id]["lvl"] and quests[id]["lvl"] < plevel - 4 and pfQuest_config["showlowlevel"] == "0" then return end
-- hide highlevel quests (or show those that are 3 levels above)
if quests[id]["min"] and quests[id]["min"] > plevel + ( pfQuest_config["showhighlevel"] == "1" and 3 or 0 ) then return end
-- hide event quests
if quests[id]["event"] and pfQuest_config["showfestival"] == "0" then return end
return true
end
-- SearchQuests
-- Scans for all available quests
-- Adds map nodes for each quest starter and ender
-- Returns its map table
function pfDatabase:SearchQuests(meta, maps)
local level, minlvl, maxlvl, race, class, prof, festival
local maps = maps or {}
local meta = meta or {}
local plevel = UnitLevel("player")
local pfaction = UnitFactionGroup("player")
if pfaction == "Horde" then
pfaction = "H"
elseif pfaction == "Alliance" then
pfaction = "A"
else
pfaction = "GM"
end
local _, race = UnitRace("player")
local prace = pfDatabase:GetBitByRace(race)
local _, class = UnitClass("player")
local pclass = pfDatabase:GetBitByClass(class)
for id in pairs(quests) do
if pfDatabase:QuestFilter(id, plevel, pclass, prace) then
-- set metadata
meta["quest"] = ( pfDB.quests.loc[id] and pfDB.quests.loc[id].T ) or UNKNOWN
meta["questid"] = id
meta["texture"] = pfQuestConfig.path.."\\img\\available_c"
meta["qlvl"] = quests[id]["lvl"]
meta["qmin"] = quests[id]["min"]
meta["vertex"] = { 0, 0, 0 }
meta["layer"] = 3
-- tint high level quests red
if quests[id]["min"] and quests[id]["min"] > plevel then
meta["texture"] = pfQuestConfig.path.."\\img\\available"
meta["vertex"] = { 1, .6, .6 }
meta["layer"] = 2
end
-- tint low level quests grey
if quests[id]["lvl"] and quests[id]["lvl"] + 10 < plevel then
meta["texture"] = pfQuestConfig.path.."\\img\\available"
meta["vertex"] = { 1, 1, 1 }
meta["layer"] = 2
end
-- tint event quests as blue
if quests[id]["event"] then
meta["texture"] = pfQuestConfig.path.."\\img\\available"
meta["vertex"] = { .2, .8, 1 }
meta["layer"] = 2
end
-- iterate over all questgivers
if quests[id]["start"] then
-- units
if quests[id]["start"]["U"] then
meta["QTYPE"] = "NPC_START"
for _, unit in pairs(quests[id]["start"]["U"]) do
if units[unit] and strfind(units[unit]["fac"] or pfaction, pfaction) then
maps = pfDatabase:SearchMobID(unit, meta, maps)
end
end
end
-- objects
if quests[id]["start"]["O"] then
meta["QTYPE"] = "OBJECT_START"
for _, object in pairs(quests[id]["start"]["O"]) do
if objects[object] and strfind(objects[object]["fac"] or pfaction, pfaction) then
maps = pfDatabase:SearchObjectID(object, meta, maps)
end
end
end
end
end
end
end
function pfDatabase:FormatQuestText(questText)
questText = string.gsub(questText, "$[Nn]", UnitName("player"))
questText = string.gsub(questText, "$[Cc]", strlower(UnitClass("player")))
questText = string.gsub(questText, "$[Rr]", strlower(UnitRace("player")))
questText = string.gsub(questText, "$[Bb]", "\n")
-- UnitSex("player") returns 2 for male and 3 for female
-- that's why there is an unused capture group around the $[Gg]
return string.gsub(questText, "($[Gg])([^:]+):([^;]+);", "%"..UnitSex("player"))
end
-- GetQuestIDs
-- Try to guess the quest ID based on the questlog ID
-- Returns possible quest IDs
function pfDatabase:GetQuestIDs(qid)
if GetQuestLink then
local questLink = GetQuestLink(qid)
if questLink then
local _, _, id = strfind(questLink, "|c.*|Hquest:([%d]+):([%d]+)|h%[(.*)%]|h|r")
if id then return { [1] = tonumber(id) } end
end
end
local oldID = GetQuestLogSelection()
SelectQuestLogEntry(qid)
local text, objective = GetQuestLogQuestText()
local title, level, _, header = compat.GetQuestLogTitle(qid)
SelectQuestLogEntry(oldID)
if header or not title then return end
local identifier = title .. ":" .. ( level or "") .. ":" .. ( objective or "") .. ":" .. ( text or "")
if pfQuest_questcache[identifier] and pfQuest_questcache[identifier][1] then
return pfQuest_questcache[identifier]
end
local _, race = UnitRace("player")
local prace = pfDatabase:GetBitByRace(race)
local _, class = UnitClass("player")
local pclass = pfDatabase:GetBitByClass(class)
local best = 0
local results = {}
local tcount = 0
-- check if multiple quests share the same name
for id, data in pairs(pfDB["quests"]["loc"]) do
if quests[id] and data.T == title then tcount = tcount + 1 end
end
-- no title was found, run levenshtein on titles
if tcount == 0 and title then
local tlen = string.len(title)
local tscore, tbest, ttitle = nil, math.min(tlen/2, 5), nil
for id, data in pairs(pfDB["quests"]["loc"]) do
if quests[id] and data.T then
tscore = lev(data.T, title, tbest)
if tscore < tbest then
tbest = tscore
ttitle = data.T
end
end
end
-- set title to new title
if not ttitle then
pfQuest_questcache[identifier] = { title }
return
else
title = ttitle
end
end
for id, data in pairs(pfDB["quests"]["loc"]) do
local score = 0
if quests[id] and data.T and data.T == title then
-- low score for same name
score = 1
-- check level and set score
if quests[id]["lvl"] == level then
score = score + 8
end
-- check race and set score
if quests[id]["race"] and ( bit.band(quests[id]["race"], prace) == prace ) then
score = score + 8
end
-- check class and set score
if quests[id]["class"] and ( bit.band(quests[id]["class"], pclass) == pclass ) then
score = score + 8
end
-- if multiple quests share the same name, use levenshtein algorithm,
-- to compare quest text distances in order to estimate the best quest id
if tcount > 1 then
-- check objective and calculate score
score = score + max(24 - lev(pfDatabase:FormatQuestText(pfDB.quests.loc[id]["O"]), objective, 24),0)
-- check description and calculate score
score = score + max(24 - lev(pfDatabase:FormatQuestText(pfDB.quests.loc[id]["D"]), text, 24),0)
end
if score > best then best = score end
results[score] = results[score] or {}
if score > 0 then table.insert(results[score], id) end
end
end
-- cache for next time
pfQuest_questcache[identifier] = results[best]
return results[best]
end
-- browser search related defaults and values
pfDatabase.lastSearchQuery = ""
pfDatabase.lastSearchResults = {["items"] = {}, ["quests"] = {}, ["objects"] = {}, ["units"] = {}}
-- BrowserSearch
-- Search for a list of IDs of the specified `searchType` based on if `query` is
-- part of the name or ID of the database entry it is compared against.
--
-- `query` must be a string. If the string represents a number, the search is
-- based on IDs, otherwise it compares names.
--
-- `searchType` must be one of these strings: "items", "quests", "objects" or
-- "units"
--
-- Returns a table and an integer, the latter being the element count of the
-- former. The table contains the ID as keys for the name of the search result.
-- E.g.: {{[5] = "Some Name", [231] = "Another Name"}, 2}
-- If the query doesn't satisfy the minimum search length requiered for its
-- type (number/string), the favourites for the `searchType` are returned.
function pfDatabase:BrowserSearch(query, searchType)
local queryLength = strlen(query) -- needed for some checks
local queryNumber = tonumber(query) -- if nil, the query is NOT a number
local results = {} -- save results
local resultCount = 0; -- count results
-- Set the DB to be searched
local minChars = 3
local minInts = 1
if (queryLength >= minChars) or (queryNumber and (queryLength >= minInts)) then -- make sure this is no fav display
if ((queryLength > minChars) or (queryNumber and (queryLength > minInts)))
and (pfDatabase.lastSearchQuery ~= "" and queryLength > strlen(pfDatabase.lastSearchQuery))
then
-- there are previous search results to use
local searchDatabase = pfDatabase.lastSearchResults[searchType]
-- iterate the last search
for id, _ in pairs(searchDatabase) do
local dbLocale = pfDB[searchType]["loc"][id]
if (dbLocale) then
local compare
local search = query
if (queryNumber) then
-- do number search
compare = tostring(id)
else
-- do name search
search = strlower(query)
if (searchType == "quests") then
compare = strlower(dbLocale["T"])
else
compare = strlower(dbLocale)
end
end
-- search and save on match
if (strfind(compare, search)) then
results[id] = dbLocale
resultCount = resultCount + 1
end
end
end
return results, resultCount
else
-- no previous results, search whole DB
if (queryNumber) then
results = pfDatabase:GetIDByIDPart(query, searchType)
else
results = pfDatabase:GetIDByName(query, searchType, true)
end
local resultCount = 0
for _,_ in pairs(results) do
resultCount = resultCount + 1
end
return results, resultCount
end
else
-- minimal search length not satisfied, reset search results and return favourites
return pfBrowser_fav[searchType], -1
end
end
local function LoadCustomData(always)
-- table.getn doesn't work here :/
local icount = 0
for _,_ in pairs(pfQuest_server["items"]) do
icount = icount + 1
end
if icount > 0 or always then
for id, name in pairs(pfQuest_server["items"]) do
pfDB["items"]["loc"][id] = name
end
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccpf|cffffffffQuest: |cff33ffcc" .. icount .. "|cffffffff " .. pfQuest_Loc["custom items loaded."])
end
end
local pfServerScan = CreateFrame("Frame", "pfServerItemScan", UIParent)
pfServerScan:SetWidth(200)
pfServerScan:SetHeight(100)
pfServerScan:SetPoint("TOP", 0, 0)
pfServerScan:Hide()
pfServerScan.scanID = 1
pfServerScan.max = 100000
pfServerScan.perloop = 100
pfServerScan.header = pfServerScan:CreateFontString("Caption", "LOW", "GameFontWhite")
pfServerScan.header:SetFont(STANDARD_TEXT_FONT, 13, "OUTLINE")
pfServerScan.header:SetJustifyH("CENTER")
pfServerScan.header:SetPoint("CENTER", 0, 0)
pfServerScan:RegisterEvent("VARIABLES_LOADED")
pfServerScan:SetScript("OnEvent", function()
pfQuest_server = pfQuest_server or { }
pfQuest_server["items"] = pfQuest_server["items"] or {}
LoadCustomData()
end)
pfServerScan:SetScript("OnHide", function()
ItemRefTooltip:Show()
LoadCustomData(true)
end)
pfServerScan:SetScript("OnShow", function()
this.scanID = 1
pfQuest_server["items"] = {}
DEFAULT_CHAT_FRAME:AddMessage("|cff33ffccpf|cffffffffQuest: " .. pfQuest_Loc["Server scan started..."])
end)
local ignore, custom_id, custom_skip = {}, nil, nil
pfServerScan:SetScript("OnUpdate", function()
if this.scanID >= this.max then
this:Hide()
return
end
-- scan X items per update
for i=this.scanID,this.scanID+this.perloop do
pfServerScan.header:SetText(pfQuest_Loc["Scanning server for items..."] .. " " .. string.format("%.1f",100*i/this.max) .. "%")
local link = "item:" .. i .. ":0:0:0"
ItemRefTooltip:SetOwner(UIParent, "ANCHOR_PRESERVE")
ItemRefTooltip:SetHyperlink(link)
if ItemRefTooltipTextLeft1 and ItemRefTooltipTextLeft1:IsVisible() then
local name = ItemRefTooltipTextLeft1:GetText()
ItemRefTooltip:Hide()
-- skip-wait for item retrieval
if name == (RETRIEVING_ITEM_INFO or "") then
if not ignore[i] then
if custom_id == i and custom_skip >= 3 then
-- ignore item and proceed
ignore[i] = true
elseif custom_id == i then
-- try again up to 3 times
custom_skip = custom_skip + 1
return
elseif custom_id ~= i then
-- give it another try
custom_id = i
custom_skip = 0
return
end
end
end
-- assign item to custom server table
if not pfDB["items"]["loc"][i] and not ignore[i] then
pfQuest_server["items"][i] = name
end
end
end
this.scanID = this.scanID+this.perloop
end)
function pfDatabase:ScanServer()
pfServerScan:Show()
end
| mit |
DipColor/mehrabon3 | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
LiberatorUSA/GUCEF | dependencies/tolua/src/bin/lua/compat.lua | 7 | 4170 | -------------------------------------------------------------------
-- Real globals
-- _ALERT
-- _ERRORMESSAGE
-- _VERSION
-- _G
-- assert
-- error
-- metatable
-- next
-- print
-- require
-- tonumber
-- tostring
-- type
-------------------------------------------------------------------
-- collectgarbage
-- gcinfo
-- globals
-- call -> protect(f, err)
-- rawget
-- rawset
-- getargs = Main.getargs ??
rawtype = type
function do_ (f, err)
if not f then print(err); return end
local a,b = pcall(f)
if not a then print(b); return nil
else return b or true
end
end
function dostring(s) return do_(load(s)) end
-------------------------------------------------------------------
-- Table library
local tab = table
foreach = function(t,f)
for k,v in pairs(t) do
f(k,v)
end
end
foreachi = function(t,f)
for i,v in ipairs(t) do
f(i,v)
end
end
getn = function(t)
return #t
end
tinsert = tab.insert
tremove = tab.remove
sort = tab.sort
-------------------------------------------------------------------
-- Debug library
local dbg = debug
getinfo = dbg.getinfo
getlocal = dbg.getlocal
setcallhook = function () error"`setcallhook' is deprecated" end
setlinehook = function () error"`setlinehook' is deprecated" end
setlocal = dbg.setlocal
-------------------------------------------------------------------
-- math library
local math = math
abs = math.abs
acos = function (x) return math.deg(math.acos(x)) end
asin = function (x) return math.deg(math.asin(x)) end
atan = function (x) return math.deg(math.atan(x)) end
atan2 = function (x,y) return math.deg(math.atan2(x,y)) end
ceil = math.ceil
cos = function (x) return math.cos(math.rad(x)) end
deg = math.deg
exp = math.exp
floor = math.floor
frexp = math.frexp
ldexp = math.ldexp
log = math.log
log10 = math.log10
max = math.max
min = math.min
mod = math.mod
PI = math.pi
--??? pow = math.pow
rad = math.rad
random = math.random
randomseed = math.randomseed
sin = function (x) return math.sin(math.rad(x)) end
sqrt = math.sqrt
tan = function (x) return math.tan(math.rad(x)) end
-------------------------------------------------------------------
-- string library
local str = string
strbyte = str.byte
strchar = str.char
strfind = str.find
format = str.format
gsub = str.gsub
strlen = str.len
strlower = str.lower
strrep = str.rep
strsub = str.sub
strupper = str.upper
-------------------------------------------------------------------
-- os library
clock = os.clock
date = os.date
difftime = os.difftime
execute = os.execute --?
exit = os.exit
getenv = os.getenv
remove = os.remove
rename = os.rename
setlocale = os.setlocale
time = os.time
tmpname = os.tmpname
-------------------------------------------------------------------
-- compatibility only
getglobal = function (n) return _G[n] end
setglobal = function (n,v) _G[n] = v end
-------------------------------------------------------------------
local io, tab = io, table
-- IO library (files)
_STDIN = io.stdin
_STDERR = io.stderr
_STDOUT = io.stdout
_INPUT = io.stdin
_OUTPUT = io.stdout
seek = io.stdin.seek -- sick ;-)
tmpfile = io.tmpfile
closefile = io.close
openfile = io.open
function flush (f)
if f then f:flush()
else _OUTPUT:flush()
end
end
function readfrom (name)
if name == nil then
local f, err, cod = io.close(_INPUT)
_INPUT = io.stdin
return f, err, cod
else
local f, err, cod = io.open(name, "r")
_INPUT = f or _INPUT
return f, err, cod
end
end
function writeto (name)
if name == nil then
local f, err, cod = io.close(_OUTPUT)
_OUTPUT = io.stdout
return f, err, cod
else
local f, err, cod = io.open(name, "w")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
end
function appendto (name)
local f, err, cod = io.open(name, "a")
_OUTPUT = f or _OUTPUT
return f, err, cod
end
function read (...)
local f = _INPUT
local arg = {...}
if rawtype(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:read(table.unpack(arg))
end
function write (...)
local f = _OUTPUT
local arg = {...}
if rawtype(arg[1]) == 'userdata' then
f = tab.remove(arg, 1)
end
return f:write(table.unpack(arg))
end
| apache-2.0 |
jshackley/darkstar | scripts/zones/Lower_Jeuno/npcs/_l00.lua | 36 | 1563 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Streetlamp
-- Involved in Quests: Community Service
-- @zone 245
-- @pos -109.065 0 -158.032
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
if (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (player:getVar("cService") == 11) then
player:setVar("cService",12);
end
elseif (hour >= 18 and hour < 21) then
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (player:getVar("cService") == 24) then
player:setVar("cService",25);
end
end
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
SpRoXx/GTW-RPG | [misc]/modshop/client.lua | 3 | 8332 | -- NOTE:
-- You may change the upgrade prices or names but DO NOT change anything else
-- if you still do, the script may get bugged and breaks!
-- Modshop resource by Dennis aka UniOn
-- Some global variables you can change to whatever you want
shopName = "Transfender"
colorPickerName = "Modshop Color Picker"
-- A table that containts all the upgrades, their names and prices
upgradesTable = {
-- All the vehicle upgrades
[ "Upgrades" ] = {
[ 1000 ] = { "Pro", 40 },
[ 1001 ] = { "Win", 55 },
[ 1002 ] = { "Drag", 20 },
[ 1003 ] = { "Alpha", 25 },
[ 1004 ] = { "Champ Scoop", 10 },
[ 1005 ] = { "Fury Scoop", 15 },
[ 1006 ] = { "Roof Scoop", 8 },
[ 1007 ] = { "R Sideskirt", 50 },
[ 1009 ] = { "2x Nitrous", 20 },
[ 1008 ] = { "5x Nitrous", 50 },
[ 1010 ] = { "10x Nitrous", 100 },
[ 1011 ] = { "Race Scoop", 22 },
[ 1012 ] = { "Worx Scoop", 25 },
[ 1013 ] = { "Round Fog Lamp", 10 },
[ 1014 ] = { "Champ Spoiler", 40 },
[ 1015 ] = { "Race Spoiler", 50 },
[ 1016 ] = { "Worx Spoiler", 20 },
[ 1017 ] = { "L Sideskirt", 50 },
[ 1018 ] = { "Upsweptc Exhaust", 35 },
[ 1019 ] = { "Twin Cylinder Exhaust", 30 },
[ 1020 ] = { "Large Exhaust", 25 },
[ 1021 ] = { "Medium Exhaust", 20 },
[ 1022 ] = { "Small Exhaust", 15 },
[ 1023 ] = { "Fury Spoiler", 35 },
[ 1024 ] = { "Square Fog Lamp", 5 },
[ 1025 ] = { "Off Road", 100 },
[ 1026 ] = { "R Alien Sideskirt", 48 },
[ 1027 ] = { "L Alien Sideskirt", 48 },
[ 1028 ] = { "Alien Exhaust", 77 },
[ 1029 ] = { "X-Flow Exhaust", 68 },
[ 1030 ] = { "L X-Flow Sideskirt", 37 },
[ 1031 ] = { "R X-Flow Sideskirt", 37 },
[ 1032 ] = { "Alien Roof Scoop", 17 },
[ 1033 ] = { "X-Flow Roof Scoop", 12 },
[ 1034 ] = { "Alien Exhaust", 79 },
[ 1035 ] = { "X-Flow Exhaust", 15 },
[ 1036 ] = { "R Alien Sideskirt", 50 },
[ 1037 ] = { "X-Flow Exhaust", 69 },
[ 1038 ] = { "Alien Roof Scoop", 19 },
[ 1039 ] = { "L X-Flow Sideskirt", 39 },
[ 1040 ] = { "L Alien Sideskirt", 50 },
[ 1041 ] = { "R X-Flow Sideskirt", 39 },
[ 1042 ] = { "R Chrome Sideskirt", 100 },
[ 1043 ] = { "Slamin Exhaust", 50 },
[ 1044 ] = { "Chrome Exhaust", 50 },
[ 1045 ] = { "X-Flow Exhaust", 51 },
[ 1046 ] = { "Alien Exhaust", 71 },
[ 1047 ] = { "R Alien Sideskirt", 67 },
[ 1048 ] = { "R X-Flow Sideskirt", 53 },
[ 1049 ] = { "Alien Spoiler", 81 },
[ 1050 ] = { "X-Flow Spoiler", 62 },
[ 1051 ] = { "L Alien Sideskirt", 67 },
[ 1052 ] = { "L X-Flow Sideskirt", 53 },
[ 1053 ] = { "X-Flow Roof Scoop", 13 },
[ 1054 ] = { "Alien Roof Scoop", 21 },
[ 1055 ] = { "Alien Roof Scoop", 23 },
[ 1056 ] = { "R Alien Sideskirt", 52 },
[ 1057 ] = { "R X-Flow Sideskirt", 43 },
[ 1058 ] = { "Alien Spoiler", 62 },
[ 1059 ] = { "X-Flow Exhaust", 72 },
[ 1060 ] = { "X-Flow Spoiler", 53 },
[ 1061 ] = { "X-Flow Roof Scoop", 18 },
[ 1062 ] = { "L Alien Sideskirt", 52 },
[ 1063 ] = { "L X-Flow Sideskirt", 43 },
[ 1064 ] = { "Alien Exhaust", 83 },
[ 1065 ] = { "Alien Exhaust", 85 },
[ 1066 ] = { "X-Flow Exhaust", 75 },
[ 1067 ] = { "Alien Roof Scoop", 25 },
[ 1068 ] = { "X-Flow Roof Scoop", 20 },
[ 1069 ] = { "R Alien Sideskirt", 55 },
[ 1070 ] = { "R X-Flow Sideskirt", 45 },
[ 1071 ] = { "L Alien Sideskirt", 55 },
[ 1072 ] = { "L X-Flow SIdeskirt", 45 },
[ 1073 ] = { "Shadow", 110 },
[ 1074 ] = { "Mega", 103 },
[ 1075 ] = { "Rimshine", 98 },
[ 1076 ] = { "Wires", 156 },
[ 1077 ] = { "Classic", 162 },
[ 1078 ] = { "Twist", 120 },
[ 1079 ] = { "Cutter", 103 },
[ 1080 ] = { "Switch", 90 },
[ 1081 ] = { "Grove", 123 },
[ 1082 ] = { "Import", 82 },
[ 1083 ] = { "Dollar", 156 },
[ 1084 ] = { "Trance", 135 },
[ 1085 ] = { "Atomic", 77 },
[ 1086 ] = { "Stereo", 10 },
[ 1087 ] = { "Hydraulics", 150 },
[ 1088 ] = { "Alien Roof Scoop", 15 },
[ 1089 ] = { "X-Flow Exhaust", 65 },
[ 1090 ] = { "R Alien Sideskirt", 45 },
[ 1091 ] = { "X-Flow Exhaust", 10 },
[ 1092 ] = { "Alien Exhaust", 75 },
[ 1093 ] = { "R X-Flow Sideskirt", 35 },
[ 1094 ] = { "L Alien Sideskirt", 45 },
[ 1095 ] = { "R X-Flow Sideskirt", 35 },
[ 1096 ] = { "Ahab", 100 },
[ 1097 ] = { "Virtual", 62 },
[ 1098 ] = { "Access", 114 },
[ 1099 ] = { "L Chrome Sideskirt", 100 },
[ 1100 ] = { "Chrome Grill", 94 },
[ 1101 ] = { "L Chrome Flames", 78 },
[ 1102 ] = { "L Chrome Strip", 83 },
[ 1103 ] = { "Convertible Roof", 325 },
[ 1104 ] = { "Chrome Exhaust", 161 },
[ 1105 ] = { "Slamin Exhaust", 154 },
[ 1106 ] = { "R Chrome Arches", 78 },
[ 1107 ] = { "L Chrome Strip", 78 },
[ 1108 ] = { "R Chrome Strip", 78 },
[ 1109 ] = { "Chrome R Bullbars", 161 },
[ 1110 ] = { "Slamin R Bullbars", 154 },
[ 1111 ] = { "Front Sign", 10 },
[ 1112 ] = { "Front Sign", 10 },
[ 1113 ] = { "Chrome Exhaust", 165 },
[ 1114 ] = { "Slamin Exhaust", 159 },
[ 1115 ] = { "Chrome Bullbars", 213 },
[ 1116 ] = { "Slamin Bullbars", 205 },
[ 1117 ] = { "Chrome F Bumper", 204 },
[ 1118 ] = { "R Chrome Trim", 72 },
[ 1119 ] = { "R WHeelcovers", 94 },
[ 1120 ] = { "L Chrome Trim", 94 },
[ 1121 ] = { "L Wheelcovers", 94 },
[ 1122 ] = { "R Chrome Flames", 78 },
[ 1123 ] = { "Chrome Bars", 86 },
[ 1124 ] = { "L Chrome Arches", 78 },
[ 1125 ] = { "Chrome Lights", 112 },
[ 1126 ] = { "Chrome Exhaust", 334 },
[ 1127 ] = { "Slamin Exhaust", 325 },
[ 1128 ] = { "Vinyl Hardtop", 334 },
[ 1129 ] = { "Chrome Exhaust", 165 },
[ 1130 ] = { "Hardtop", 338 },
[ 1131 ] = { "Softtop", 329 },
[ 1132 ] = { "Slamin Exhaust", 159 },
[ 1133 ] = { "R Chrome Strip", 83 },
[ 1134 ] = { "R Chrome Strip", 80 },
[ 1135 ] = { "Slamin Exhaust", 150 },
[ 1136 ] = { "Chrome Exhaust", 100 },
[ 1137 ] = { "L Chrome Strip", 80 },
[ 1138 ] = { "Alien Spoiler", 58 },
[ 1139 ] = { "X-Flow Spoiler", 47 },
[ 1140 ] = { "X-Flow R Bumper", 87 },
[ 1141 ] = { "ALien R Bumper", 98 },
[ 1142 ] = { "Left Oval Vents", 50 },
[ 1143 ] = { "R Oval Vents", 50 },
[ 1144 ] = { "L Square Vents", 50 },
[ 1145 ] = { "R Square Vents", 50 },
[ 1146 ] = { "X-Flow Spoiler", 49 },
[ 1147 ] = { "Alien Spoiler", 50 },
[ 1148 ] = { "X-Flow R Bumper", 50 },
[ 1149 ] = { "EAlien R Bumper", 100 },
[ 1150 ] = { "Alien R Bumper", 109 },
[ 1151 ] = { "X-Flow R Bumper", 84 },
[ 1152 ] = { "X-Flow F Bumper", 91 },
[ 1153 ] = { "Alien F Bumper", 120 },
[ 1154 ] = { "Alien R Bumper", 103 },
[ 1155 ] = { "Alien F Bumper", 103 },
[ 1156 ] = { "X-Flow R Bumper", 92 },
[ 1157 ] = { "X-Flow F Bumper", 93 },
[ 1158 ] = { "X-Flow Spoiler", 55 },
[ 1159 ] = { "Alien R Bumper", 105 },
[ 1160 ] = { "Alien F Bumper", 105 },
[ 1161 ] = { "X-Flow R Bumper", 95 },
[ 1162 ] = { "Alien Spoiler", 65 },
[ 1163 ] = { "X-Flow Spoiler", 45 },
[ 1164 ] = { "Alien Spoiler", 55 },
[ 1165 ] = { "X-Flow F Bumper", 85 },
[ 1166 ] = { "Alien F Bumper", 95 },
[ 1167 ] = { "X-Flow R Bumper", 85 },
[ 1168 ] = { "Alien R Bumper", 95 },
[ 1169 ] = { "Alien F Bumper", 97 },
[ 1170 ] = { "X-Flow F Bumper", 88 },
[ 1171 ] = { "Alien F Bumper", 99 },
[ 1172 ] = { "X-Flow F Bumper", 90 },
[ 1173 ] = { "X-Flow F Bumper", 95 },
[ 1174 ] = { "Chrome F Bumper", 100 },
[ 1175 ] = { "Slamin R Bumper", 90 },
[ 1176 ] = { "Chrome F Bumper", 100 },
[ 1177 ] = { "Slamin R Bumper", 90 },
[ 1178 ] = { "Slamin R Bumper", 205 },
[ 1179 ] = { "Chrome F Bumper", 215 },
[ 1180 ] = { "Chrome R Bumper", 213 },
[ 1181 ] = { "Slamin F Bumper", 204 },
[ 1182 ] = { "Chrome F Bumper", 215 },
[ 1183 ] = { "Slamin R Bumper", 205 },
[ 1184 ] = { "Chrome R Bumper", 215 },
[ 1185 ] = { "Slamin F Bumper", 204 },
[ 1186 ] = { "Slamin R Bumper", 209 },
[ 1187 ] = { "Chrome R Bumper", 217 },
[ 1188 ] = { "Slamin F Bumper", 208 },
[ 1189 ] = { "Chrome F Bumper", 220 },
[ 1190 ] = { "Slamin F Bumper", 120 },
[ 1191 ] = { "Chrome F Bumper", 104 },
[ 1192 ] = { "Chrome R Bumper", 94 },
[ 1193 ] = { "Slamin R Bumper", 110 },
},
-- The vehicle painjobs
[ "Paintjobs" ] = {
[ 0 ] = { "Paintjob 1", 80 },
[ 1 ] = { "Paintjob 2", 80 },
[ 2 ] = { "Paintjob 3", 80 },
},
-- The vehicle colors
[ "Colors" ] = {
[ 1 ] = { "Vehicle Color 1", 50 },
[ 2 ] = { "Vehicle Color 2", 50 },
},
-- The vehicle headlights
[ "Headlights" ] = {
[ 1 ] = { "Headlight Color 1", 20 },
},
}
| bsd-2-clause |
jshackley/darkstar | scripts/zones/Port_San_dOria/TextIDs.lua | 14 | 4857 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED_1 = 6422; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>.<<<Prompt>>>
ITEM_CANNOT_BE_OBTAINED_2 = 6423; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. Come back after sorting your inventory.
ITEM_CANNOT_BE_OBTAINED_3 = 6425; -- You cannot obtain the item. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6427; -- You cannot obtain the <<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6428; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>#<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>.
GIL_OBTAINED = 6429; -- Obtained <<<Numeric Parameter 0>>> gil.
KEYITEM_OBTAINED = 6431; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>3<<<BAD CHAR: 8280>>><<<BAD CHAR: 80>>><<<BAD CHAR: 80>>>.
HOMEPOINT_SET = 24; -- Home point set!
FISHING_MESSAGE_OFFSET = 7218; -- You can't fish here.
ITEM_DELIVERY_DIALOG = 7933; -- Now delivering parcels to rooms everywhere!
-- Dialogs
FLYER_REFUSED = 7545; -- This person isn't interested.
FLYER_ALREADY = 7546; -- This person already has a flyer.
FLYER_ACCEPTED = 7547; -- Your flyer is accepted!
FLYERS_HANDED = 7548; -- You've handed outflyer(s).
PORTAURE_DIALOG = 7810; -- What's this? A magic shop? Hmm...I could use a new line of work, and magic just might be the ticket!
ANSWALD_DIALOG = 7830; -- A magic shop? Oh, it's right near here. I'll go check it out sometime.
PRIETTA_DIALOG = 7854; -- This is the first I've heard of a magic shop here in San d'Oria. Such arts have never been popular in the Kingdom.
AUVARE_DIALOG = 7861; -- What have I got here? Look, I can't read, but I takes what I gets, and you ain't getting it back!
MIENE_DIALOG = 7914; -- Oh, a magic shop... Here in San d'Oria? I'd take a look if I got more allowance.
ANSWALD_MESSAGE = 8407; -- Answald looks over curiously for a moment.
PRIETTA_MESSAGE = 8408; -- Prietta looks over curiously for a moment.
MIENE_MESSAGE = 8409; -- Miene looks over curiously for a moment.
PORTAURE_MESSAGE = 8410; -- Portaure looks over curiously for a moment.
AUVARE_MESSAGE = 8411; -- Auvare looks over curiously for a moment.
-- Shop Texts
ALBINIE_SHOP_DIALOG = 7874; -- Welcome to my simple shop.
COULLAVE_SHOP_DIALOG = 7920; -- Can I help you?
CROUMANGUE_SHOP_DIALOG = 7921; -- Can't fight on an empty stomach. How about some nourishment?
VENDAVOQ_OPEN_DIALOG = 7928; -- Vandoolin! Vendavoq vring voods vack vrom Vovalpolos! Vuy! Vuy!
VENDAVOQ_CLOSED_DIALOG = 7929; -- Vandoolin... Vendavoq's vream vo vell voods vrom vometown vf Vovalpolos...
FIVA_OPEN_DIALOG = 7922; -- I've got imports from Kolshushu!
MILVA_OPEN_DIALOG = 7923; -- How about some produce from Sarutabaruta?
FIVA_CLOSED_DIALOG = 7924; -- I'm trying to sell goods from Kolshushu. But I can't because we don't have enough influence there.
MILVA_CLOSED_DIALOG = 7925; -- I want to import produce from Sarutabaruta... But I can't do anything until we control that region!
NIMIA_CLOSED_DIALOG = 7926; -- I can't sell goods from the lowlands of Elshimo because it's under foreign control.
PATOLLE_CLOSED_DIALOG = 7927; -- I'm trying to find goods from Kuzotz. But how can I when it's under foreign control?
DEGUERENDARS_OPEN_DIALOG = 7930; -- Welcome! Have a look at these rare goods from Tavnazia!
DEGUERENDARS_CLOSED_DIALOG = 7931; -- With that other nation in control of the region, there is no way for me to import goods from Tavnazia...
DEGUERENDARS_COP_NOT_COMPLETED = 7932; -- Why must I wait for the Kingdom to issue a permit allowing me to set up shop? How am I to feed my children in the meantime!?
BONMAURIEUT_CLOSED_DIALOG = 8267; -- I would like to sell goods from the Elshimo Uplands, but I cannot, as it's under foreign control.
NIMIA_OPEN_DIALOG = 8268; -- Hello, friend! Can I interest you in specialty goods from the Elshimo Lowlands?
PATOLLE_OPEN_DIALOG = 8269; -- How about some specialty goods from Kuzotz?
BONMAURIEUT_OPEN_DIALOG = 8270; -- My shipment is in! Would you like to see what has just arrived from the Elshimo Uplands?
-- conquest Base
CONQUEST_BASE = 7059; -- Tallying conquest results...
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/HomePoint#1.lua | 17 | 1265 | -----------------------------------
-- Area: Windurst_Waters_[S]
-- NPC: HomePoint#1
-- @pos -32 -5 131 94
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 70);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Gevarg.lua | 38 | 1052 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Gevarg
-- Type: Past Event Watcher
-- @zone: 94
-- @pos -46.448 -6.312 212.384
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0000);
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 |
SpRoXx/GTW-RPG | [maps]/GTWjailmap/jail_map.lua | 2 | 29830 | --[[
********************************************************************************
Project owner: RageQuit community
Project name: GTW-RPG
Developers: Mr_Moose
Source code: https://github.com/GTWCode/GTW-RPG/
Bugtracker: http://forum.404rq.com/bug-reports/
Suggestions: http://forum.404rq.com/mta-servers-development/
Version: Open source
License: BSD 2-Clause
Status: Stable release
********************************************************************************
]]--
for i,v in ipairs({
{9956,-3025.2002,2302.6006,-12,0,0,90,1,0,0, true},
{9954,-2913.0996,2200.2002,-12.02,0,0,147.986,1,0,0, true},
{744,-2949.3,2246.3,0,0,0,0,1,0,0, false},
{17028,-2904.7,2233,2,0,0,172,1,0,0, true},
{17028,-2912,2219.5,2,0,0,155.996,1,0,0, true},
{17028,-2911.7998,2282.1006,0.6,0,0,191.992,1,0,0, true},
{17028,-2912.5996,2288.7998,2,0,0,191.992,1,0,0, true},
{17028,-2912.2002,2297.7002,2,0,0,191.992,1,0,0, true},
{17028,-2910.8,2301.7,2,0,0,149.991,1,0,0, true},
{17028,-2933,2278.3999,2,0,0,113.989,1,0,0, true},
{17028,-2919.0996,2278,2,0,0,141.987,1,0,0, true},
{17028,-2923.2002,2357.2998,2,0,0,179.991,1,0,0, true},
{17028,-2932.0996,2362.6006,2,0,0,179.984,1,0,0, true},
{17028,-2936.2,2372.3999,2,0,0,179.989,1,0,0, true},
{17028,-2924.8999,2374,2,0,0,179.989,1,0,0, true},
{17028,-2915.5,2382.3999,2,0,0,181.984,1,0,0, true},
{17028,-2905.19995,2389.3999,2,0,0,179.989,1,0,0, true},
{671,-2969,2367.1001,6.5,0,0,0,1,0,0, false},
{683,-2959.2002,2375.5,4,0,0,0,1,0,0, false},
{683,-2972.3999,2371.3,4,0,0,0,1,0,0, false},
{683,-2951.3994,2359.2002,3.3,0,0,0,1,0,0, false},
{683,-2952.2,2308.8999,5.6,0,0,0,1,0,0, false},
{683,-2952.5,2285.4004,5.6,0,0,0,1,0,0, false},
{683,-2944.8,2237,4.9,0,0,0,1,0,0, false},
{683,-2952.8,2296,5.8,0,0,34,1,0,0, false},
{17028,-2915.8994,2420.1006,2,0,0,166.229,1,0,0, true},
{17028,-2916.8,2427.5,2,0,0,148.229,1,0,0, true},
{683,-2950.8999,2435.7,4,0,0,0,1,0,0, false},
{13367,-2940.7002,2129.2002,27.4,0,0,12.25,1,0,0, false},
{3279,-3050.8,2207.1001,0.9,0,0,69,1,0,0, true},
{3279,-2983.2,2362.3,6.3,0,0,179.743,1,0,0, false},
{987,-2955.5,2345.7,6.3,0,0,344,1,0,0, true},
{987,-2987.5,2358.7002,6.3,0,0,352.491,1,0,0, true},
{987,-2976.5,2357.1001,6.3,0,0,330.993,1,0,0, true},
{987,-2966.0996,2351.2998,6.3,0,0,331.996,1,0,0, true},
{987,-2994,2358.7002,6.3,0,0,179.995,1,0,0, true},
{987,-3112.8999,2349.1001,6.3,0,0,0,1,0,0, true},
{987,-2914.2,2098.1001,-2,0,0,197.99,1,0,0, true},
{360,-2983.8999,2331,6.7,0,0,0,1,0,0, false},
{360,-2983.8999,2282.3,6.3,0,0,0,1,0,0, false},
{6973,-2966,2383.7998,-2,0,0,351.991,1,0,0, false},
{691,-2956.6001,2310.6001,6,0,0,301.998,0.4,0,0, true},
{691,-2948.1001,2245.8999,5.7,0,0,0,1,0,0, true},
{360,-2981.8999,2415.8999,3.3,0,0,0,1,0,0, false},
{17033,-3113.1001,2302.6001,-1.2,0,0,0,1,0,0, false},
{17033,-3114.2,2310.2,-1.2,0,0,24,1,0,0, false},
{17033,-3117.6001,2309.3999,-1.2,0,0,98,1,0,0, false},
{660,-3133.3994,2303.5,1.3,0,0,0,1,0,0, false},
{660,-3118.8994,2312.7998,1.9,0,0,0,1,0,0, false},
{660,-3106.7,2340.3,1,0,0,0,1,0,0, false},
{660,-3116.0996,2308,3.2,0,0,0,1,0,0, false},
{660,-3118.5,2300.2,1.5,0,0,0,1,0,0, false},
{17033,-3105.2,2342.6001,-1.2,0,0,131.998,1,0,0, false},
{660,-3114.8994,2317.4004,1.3,0,0,0,1,0,0, false},
{660,-3102.2998,2340.2998,0.5,0,0,0,1,0,0, false},
{660,-3111.8994,2339.9004,1,0,0,0,1,0,0, false},
{17033,-3130.1001,2304.8999,-1.2,0,0,15.998,1,0,0, false},
{17033,-3129.8999,2297.1001,-1.2,0,0,217.996,1,0,0, false},
{17033,-3133.8994,2297.5,-1.2,0,0,69.988,1,0,0, false},
{660,-3120.2998,2307.2998,0.4,0,0,0,1,0,0, false},
{660,-3132.6001,2295.2,3.7,0,0,0,1,0,0, false},
{660,-3126.8999,2298,1.2,0,0,0,1,0,0, false},
{17033,-3109.2998,2367.5,-1.2,0,0,333.99,1,0,0, false},
{660,-3112.8999,2368.3,1.8,0,0,0,1,0,0, false},
{660,-3049,2368.3999,1.7,0,0,0,1,0,0, false},
{17033,-3112.8994,2253.1006,-1.2,0,0,37.991,1,0,0, false},
{17033,-3118,2241.5,-1.2,0,0,7.985,1,0,0, false},
{17033,-3109.8,2243.3,-1.2,0,0,151.982,1,0,0, false},
{17033,-3101.7,2248.6001,-1.2,0,0,151.979,1,0,0, false},
{660,-3103,2246.2998,2.6,0,0,0,1,0,0, false},
{660,-3115.5996,2251.2998,3,0,0,0,1,0,0, false},
{660,-3121.2,2240.3,1,0,0,0,1,0,0, false},
{660,-3112.5996,2243.9004,4.4,0,0,0,1,0,0, false},
{17033,-3038.8999,2249.3999,-1.2,0,0,133.979,1,0,0, false},
{17033,-2990,2244.4004,-1.2,0,0,31.976,1,0,0, false},
{17033,-2991.3994,2238.1006,-1.2,0,0,5.966,1,0,0, false},
{17033,-2986.8994,2231.9004,-1.2,0,0,137.961,1,0,0, false},
{660,-2990.7,2247.6001,2,0,0,0,1,0,0, false},
{660,-3043.2002,2247.1006,1.8,0,0,0,1,0,0, false},
{660,-3036.7998,2247.6006,1.3,0,0,0,1,0,0, false},
{660,-2993.5996,2241.4004,1.2,0,0,0,1,0,0, false},
{660,-2966.7002,2155.1006,1.4,0,0,0,1,0,0, false},
{17033,-2964.5996,2158.2002,-1.2,0,0,53.97,1,0,0, false},
{660,-2994.2,2232,1,0,0,0,1,0,0, false},
{660,-2967.2998,2161.7998,2,0,0,0,1,0,0, false},
{18096,-2967.3,2346.3999,7.3,0,0,0,1,0,0, false},
{1297,-2970.3999,2216.3999,9.7,0,0,13.25,1,0,0, false},
{1297,-2959.3,2168.1001,9.7,0,0,15.491,1,0,0, false},
{1297,-2949.5,2125.3999,9.7,0,0,15.491,1,0,0, false},
{1297,-3100.6001,2266.5,9.7,0,0,272,1,0,0, false},
{1297,-3056.8,2266.5,9.7,0,0,270,1,0,0, false},
{1297,-3004.3,2266.5,9.7,0,0,269.995,1,0,0, false},
{1297,-3004.3,2311.1001,9.7,0,0,269.995,1,0,0, false},
{1297,-3056.8999,2311.1001,9.7,0,0,269.995,1,0,0, false},
{1297,-3100.7,2311.2,9.7,0,0,269.995,1,0,0, false},
{1297,-3100.8,2359.8999,9.7,0,0,269.995,1,0,0, false},
{1297,-3054,2359.8,9.7,0,0,269.995,1,0,0, false},
{1297,-3001.3999,2359.8999,9.7,0,0,269.995,1,0,0, false},
{16095,-2931.8,2251.1001,6.3,0,0,15,1,0,0, false},
{3279,-3114.7,2302.2,6.3,0,0,89.995,1,0,0, false},
{1368,-2975.2002,2335.5,6.8,0,0,0,1,0,0, false},
{1368,-2962.5,2291.2,6.8,0,0,269.742,1,0,0, false},
{1368,-2965.3994,2335.6006,6.8,0,0,0,1,0,0, false},
{946,-2962.8999,2323.5,8.5,0,0,90,1,0,0, false},
{1946,-2963.7,2320.1001,6.5,0,0,0,1,0,0, false},
{3279,-3110.3999,2354.1001,6.3,0,0,90,1,0,0, false},
{3279,-3109.8994,2254.7998,6.3,0,0,0,1,0,0, false},
{17033,-3158.5,2336.9004,-1.2,0,0,69.983,1,0,0, false},
{17033,-3153.8,2344.7,-1.2,0,0,209.988,1,0,0, false},
{17033,-3159.7,2348.8,-1.2,0,0,29.987,1,0,0, false},
{17033,-3156.8,2345.8999,-1.2,0,0,29.982,1,0,0, false},
{660,-3162,2347,1.3,0,0,0,1,0,0, false},
{660,-3159.5996,2338.5,5.2,0,0,0,1,0,0, false},
{660,-3158.0996,2343.7002,2.9,0,0,0,1,0,0, false},
{660,-3155.7998,2349.4004,4.2,0,0,0,1,0,0, false},
{660,-3161,2355.6001,1.5,0,0,0,1,0,0, false},
{17033,-2977.3999,2090.6001,-1.2,0,0,9.97,1,0,0, false},
{17033,-2969.7998,2086.5,-1.2,0,0,139.966,1,0,0, false},
{17033,-2970.2998,2090,-1.2,0,0,331.963,1,0,0, false},
{17033,-2963,2088,-1.2,0,0,229.963,1,0,0, false},
{987,-2925.5,2094.3999,-2,0,0,197.99,1,0,0, true},
{987,-2936.8999,2090.7,-2,0,0,181.99,1,0,0, true},
{987,-2948.8,2090.3,-2,0,0,181.989,1,0,0, true},
{660,-2971.5,2084.3999,1.6,0,0,0,1,0,0, false},
{660,-2916.5,2101.1001,1.4,0,0,0,1,0,0, false},
{660,-2973,2092.9004,2.5,0,0,0,1,0,0, false},
{660,-2965.5996,2083.2002,0.9,0,0,0,1,0,0, false},
{660,-2978.3994,2085.7002,2.8,0,0,0,1,0,0, false},
{17033,-3012.7002,2130.7998,-1.2,0,0,9.97,1,0,0, false},
{17033,-3007.6001,2130,-1.2,0,0,149.969,1,0,0, false},
{17033,-3006.3994,2133.2998,-1.2,0,0,9.965,1,0,0, false},
{660,-3015.1001,2129.6001,1.8,0,0,0,1,0,0, false},
{660,-3012.5,2134,1.8,0,0,0,1,0,0, false},
{660,-3005.8994,2130.1006,3,0,0,0,1,0,0, false},
{660,-3005.8994,2137.2002,2,0,0,0,1,0,0, false},
{987,-2960.8,2089.8999,-2,0,0,189.989,1,0,0, true},
{987,-2978.8,2091.3,-2,0,0,141.987,1,0,0, true},
{987,-2988.2998,2098.6006,-2,0,0,160.98,1,0,0, true},
{987,-3017.2,2131.8,-2,0,0,114.217,1,0,0, true},
{987,-3022.1001,2142.7,-2,0,0,89.967,1,0,0, true},
{3886,-2979.3999,2215.2,0,0,0,192.997,1,0,0, false},
{3886,-2977,2205,0,0,0,193.497,1,0,0, false},
{3886,-2974.6001,2194.8,0,0,0,193.497,1,0,0, false},
{1505,-2970.7,2219.7,6.3,0,0,283.2,1,0,0, true},
{1505,-2978.0498,2218.4102,0.9,0,0,283.195,1,0,0, true},
{17033,-3030.8994,2173.2998,-1.2,0,0,9.965,1,0,0, false},
{17033,-3029.2,2171.3,-1.2,0,0,213.97,1,0,0, false},
{987,-3022,2154.6001,-2,0,0,99.962,1,0,0, true},
{987,-3024.1001,2166.3,-2,0,0,117.959,1,0,0, true},
{660,-3035.5996,2174,1.1,0,0,0,1,0,0, false},
{660,-3030.0996,2167.2998,4.6,0,0,0,1,0,0, false},
{660,-3032.3994,2171.7998,2.9,0,0,0,1,0,0, false},
{660,-3029.5996,2177,3.4,0,0,0,1,0,0, false},
{17033,-3000.3,2113.2,-1.2,0,0,320.213,1,0,0, false},
{660,-3002.7,2114.6001,1.3,0,0,0,1,0,0, false},
{660,-2996.3999,2115.3999,2,0,0,0,1,0,0, false},
{17033,-2913.8994,2096.7998,-1.2,0,5.999,41.957,1,0,0, false},
{660,-2965.7002,2086.9004,4.3,0,0,0,1,0,0, false},
{660,-2915.8994,2094.1006,2,0,0,0,1,0,0, false},
{3886,-3045.1001,2211.3,0,0,0,339.489,1,0,0, false},
{17033,-3051.7998,2202.1006,-1.2,0,0,207.966,1,0,0, false},
{17033,-3057.1001,2198.8999,-1.2,0,0,49.966,1,0,0, false},
{17033,-3054.0996,2207.9004,-1.2,0,0,65.956,1,0,0, false},
{3279,-2986.2002,2233.9004,6.3,0,0,56.739,1,0,0, false},
{660,-3054.5,2193.2,1.6,0,0,0,1,0,0, false},
{660,-3059.3999,2197.3999,1.2,0,0,0,1,0,0, false},
{660,-3057.8994,2210.2998,1.7,0,0,0,1,0,0, false},
{17033,-3051.7,2366.6001,-1.2,0,0,311.99,1,0,0, false},
{660,-3103.3994,2371.7002,3,0,0,0,1,0,0, false},
{660,-3054.8999,2369.2,1.3,0,0,0,1,0,0, false},
{17033,-3013.6001,2446.2,-1.2,0,0,311.99,1,0,0, false},
{17033,-3011.3994,2440.5,-1.2,0,0,103.986,1,0,0, false},
{17033,-3001.7998,2442,-1.2,0,0,123.981,1,0,0, false},
{3279,-3008,2442.2998,3.4,0,0,331.996,1,0,0, false},
{3886,-3005.0996,2434.5,0,0,0,297.493,1,0,0, false},
{660,-3019.1001,2443.7,3.5,0,0,0,1,0,0, false},
{660,-3014.3999,2448.5,3.4,0,0,0,1,0,0, false},
{660,-2999.5996,2441.9004,3,0,0,0,1,0,0, false},
{17033,-2988.2,2237.5,-1.2,0,0,5.971,1,0,0, false},
{17033,-2986.6001,2246.1001,-1.2,0,0,5.971,1,0,0, false},
{17033,-2937.1001,2237.8999,-1.2,0,0,315.971,1,0,0, false},
{17033,-2953.6001,2247.3999,-1.2,0,0,315.967,1,0,0, false},
{17033,-2971.7,2051.3,-1.2,0,0,197.966,1,0,0, false},
{17033,-2978.6001,2055.6001,-1.2,0,0,299.963,1,0,0, false},
{17033,-2977.7,2052.8999,-1.2,0,0,131.96,1,0,0, false},
{17033,-2979.8,2049.3,-1.2,0,0,101.957,1,0,0, false},
{3279,-2978.8999,2042.7,0.5,0,358,316,1,0,0, false},
{3886,-2976.6001,2038.9,0,0,0,311.494,1,0,0, false},
{17033,-2987.6001,2044.4,-1.2,0,0,239.963,1,0,0, false},
{17033,-2965.1001,2051.5,-1.2,0,0,129.963,1,0,0, false},
{660,-2985.7,2055.1001,2.2,0,0,0,1,0,0, false},
{660,-2968.8994,2050.9004,3.5,0,0,0,1,0,0, false},
{660,-2963.2002,2050.1006,1.2,0,0,0,1,0,0, false},
{660,-2980.2002,2057.2998,3,0,0,0,1,0,0, false},
{660,-2988.7,2040.4,1.9,0,0,0,1,0,0, false},
{660,-2988.7002,2045.4004,4.4,0,0,0,1,0,0, false},
{660,-2987.5,2035.1,1.3,0,0,0,1,0,0, false},
{8674,-2918.2002,2096.7998,2.7,0,0,17.496,1,0,0, true},
{8674,-2920.7,2096,5.6,0,0,17.496,1,0,0, true},
{660,-2920.8999,2094.8,0.2,0,0,0,1,0,0, false},
{17033,-2919.7998,2088.2998,-1.2,0,5.999,357.957,1,0,0, false},
{660,-2919.3,2086.2,4,0,0,0,1,0,0, false},
{660,-2924.5996,2087.2998,2.5,0,0,0,1,0,0, false},
{17033,-2912.8999,2089.3999,-1.2,0,5.999,131.957,1,0,0, false},
{8674,-2918.2002,2096.7998,8.4,0,0,17.496,1,0,0, true},
{8674,-2928.1001,2093.7,5.6,0,0,17.496,1,0,0, true},
{8674,-2928.0996,2093.7002,0,0,0,17.496,1,0,0, true},
{8674,-2958.1001,2090.1001,5.6,0,0,1.996,1,0,0, true},
{8674,-2958.0996,2090.1006,0,0,0,1.994,1,0,0, true},
{8674,-2958.0996,2090.1006,2.7,0,0,1.994,1,0,0, true},
{8674,-2968.3,2088.8,8.5,0,0,11.994,1,0,0, true},
{8674,-2968.2998,2088.7998,5.6,0,0,11.992,1,0,0, true},
{8674,-2958.0996,2090.1006,8.5,0,0,1.989,1,0,0, true},
{8674,-2977.3999,2091,0,0,0,321.242,1,0,0, true},
{8674,-2977.3994,2091,8.5,0,0,321.24,1,0,0, true},
{8674,-2977.3994,2091,5.6,0,0,321.24,1,0,0, true},
{8674,-2977.3994,2091,2.7,0,0,321.235,1,0,0, true},
{17033,-2959.8,2086.5,-1.2,0,0,237.963,1,0,0, false},
{660,-2967.8,2093.3999,1,0,0,0,1,0,0, false},
{660,-2961.8999,2091.8999,3,0,0,0,1,0,0, false},
{660,-2956.8,2087.3,0.8,0,0,0,1,0,0, false},
{8674,-2928.0996,2093.7002,2.7,0,0,17.496,1,0,0, true},
{987,-2999.6001,2102.5,-2,0,0,125.227,1,0,0, true},
{987,-3012.3,2120.8,-2,0,0,114.214,1,0,0, true},
{987,-3005.5,2110.8999,-2,0,0,125.222,1,0,0, true},
{8674,-3006.3999,2112.2,0,0,0,305.24,1,0,0, true},
{8674,-3006.39941,2112.2002,5.6,0,0,305.239,1,0,0, true},
{8674,-3006.3994,2112.2002,2.7,0,0,305.239,1,0,0, true},
{8674,-3014.8,2126.6001,2.7,0,0,293.739,1,0,0, true},
{8674,-3014.7998,2126.6006,5.6,0,0,293.739,1,0,0, true},
{8674,-3014.7998,2126.6006,0,0,0,293.736,1,0,0, true},
{8674,-3014.7998,2126.6006,8.4,0,0,293.736,1,0,0, true},
{660,-3016.6001,2126.5,2,0,0,0,1,0,0, false},
{8674,-3019,2136,5.6,0,0,293.73,1,0,0, true},
{8674,-3019,2136,2.7,0,0,293.736,1,0,0, true},
{8674,-3019,2136,0,0,0,293.736,1,0,0, true},
{8674,-3026.7,2171.3,2.7,0,0,297.986,1,0,0, true},
{8674,-3026.7002,2171.2998,5.6,0,0,297.986,1,0,0, true},
{8674,-3026.7002,2171.2998,0,0,0,297.982,1,0,0, true},
{8674,-3026.7002,2171.2998,8.4,0,0,297.982,1,0,0, true},
{8674,-3030.3,2178.1001,0,0,0,297.982,1,0,0, true},
{8674,-3030.2998,2178.1006,8.4,0,0,297.982,1,0,0, true},
{8674,-3030.2998,2178.1006,5.6,0,0,297.982,1,0,0, true},
{8674,-3030.2998,2178.1006,2.7,0,0,297.982,1,0,0, true},
{660,-3024.8999,2179.3999,1,0,0,0,1,0,0, false},
{17033,-3050.2,2210.7,-1.2,0,0,24.956,1,0,0, false},
{660,-3051.5,2216.3999,1,0,0,0,1,0,0, false},
{17033,-2951.1001,2308.5,1,0,0,10.997,1,0,0, true},
{17033,-2945.8,2302.1001,1,0,0,44.997,1,0,0, true},
{17033,-2945.0996,2292.5,1,0,0,44.995,1,0,0, true},
{17033,-2946.5996,2275.6006,1,0,0,26.993,1,0,0, true},
{17033,-2943.5996,2270.6006,1,0,0,294.988,1,0,0, true},
{17033,-2968.6001,2358,1,0,0,138.997,1,0,0, true},
{660,-2976.5996,2357,7,0,0,0,1,0,0, false},
{1368,-2962.5996,2280.7002,6.8,0,0,269.742,1,0,0, false},
{987,-2991.6001,2252.69995,6.3,0,0,90.483,1,0,0, true},
{987,-2976.0996,2253.1006,6.3,0,0,273.73,1,0,0, true},
{987,-2975.2998,2241.1006,6.3,0,0,234.977,1,0,0, true},
{17033,-2949.1001,2227.8,1,0,0,90.991,1,0,0, true},
{17033,-2928.8999,2215.3,1,0,0,124.991,1,0,0, true},
{17033,-2934.6001,2238.3,1,0,0,124.991,1,0,0, true},
{17033,-2936.8999,2231.3999,1,0,0,52.991,1,0,0, true},
{17033,-2969.8,2481,-1.2,0,0,123.981,1,0,0, false},
{17033,-2971.3,2489.3,-1.2,0,0,263.981,1,0,0, false},
{17033,-2981.1001,2487.3,-1.2,0,0,81.976,1,0,0, false},
{17033,-2971.7,2486,-1.2,0,0,81.974,1,0,0, false},
{17033,-2977.2,2485.6001,-1.2,0,0,81.974,1,0,0, false},
{660,-2983.5,2490,4.1,0,0,0,1,0,0, false},
{660,-2980.5996,2484,2.7,0,0,0,1,0,0, false},
{660,-2977.3999,2481.1001,5.2,0,0,0,1,0,0, false},
{660,-2968.8994,2478.4004,1.2,0,0,0,1,0,0, false},
{660,-2943.3,2529.1001,2.6,0,0,0,1,0,0, false},
{660,-2977.5996,2495.2998,3.6,0,0,0,1,0,0, false},
{660,-2984.6001,2495.3,1.8,0,0,0,1,0,0, false},
{17033,-2981.5996,2493.5,-1.2,0,0,321.976,1,0,0, false},
{17033,-2941,2523.8,-1.2,0,0,43.976,1,0,0, false},
{660,-2971.2998,2490.6006,4.5,0,0,0,1,0,0, false},
{660,-2944.8994,2521.7998,1.3,0,0,0,1,0,0, false},
{16095,-2939.1001,2535.8999,0.5,0,0,0,1,0,0, true},
{3886,-2943.6001,2536.6001,0,0,0,179.993,1,0,0, false},
{660,-2945.5,2527.8999,0.4,0,0,0,1,0,0, false},
{17033,-2938.3,2542.3999,-1.2,0,0,73.973,1,0,0, false},
{17033,-2939.8,2551.7,-1.2,0,0,9.971,1,0,0, false},
{660,-2940.7,2543.5,3.4,0,0,0,1,0,0, false},
{660,-2943.2,2550.3,1.8,0,0,0,1,0,0, false},
{660,-2938.5,2556.2,3.5,0,0,0,1,0,0, false},
{17033,-3187,2285.5,-1.2,0,0,279.983,1,0,0, false},
{17033,-3188.3999,2278.6001,-1.2,0,0,61.981,1,0,0, false},
{17033,-3184.2,2275.5,-1.2,0,0,233.979,1,0,0, false},
{660,-3192.6001,2283.3999,2.5,0,0,0,1,0,0, false},
{660,-3187.7,2283.8,5.2,0,0,0,1,0,0, false},
{660,-3187,2273.2,2.5,0,0,0,1,0,0, false},
{660,-3181.2002,2267.9004,0.6,0,0,0,1,0,0, false},
{16095,-2948.5,2335.30005,6.3,0,0,0,1,0,0, false},
{660,-2962.5,2349.5,6.5,0,0,0,1,0,0, false},
{660,-2949.5,2320.2,10,0,0,0,1,0,0, false},
{660,-2953.7998,2343.9004,7,0,0,0,1,0,0, false},
{660,-2951.2998,2325.2998,8.7,0,0,0,1,0,0, false},
{660,-2953.0996,2319.7002,7.9,0,0,0,1,0,0, false},
{983,-3003.24023,2432.91992,-7.01135,0,0,0,1,0,0, false},
{987,-3084.8999,2318.8,6.3,0,0,179.75,1,0,0, true},
{987,-3096.8999,2318.8999,6.3,0,0,179.747,1,0,0, true},
{660,-3109,2319,6.3,0,0,0,1,0,0, false},
{17033,-3063.5996,2274.7998,-1.2,0,0,321.987,1,0,0, false},
{660,-3059.8999,2278.3,1.5,0,0,0,1,0,0, false},
{660,-3066.7998,2277.4004,1.4,0,0,0,1,0,0, false},
{987,-3112.8999,2297.3999,6.3,0,0,0.484,1,0,0, true},
{17033,-2953.6001,2231.5,-1.2,0,0,239.965,1,0,0, false},
{8674,-2932.1001,2239.2,7.7,0,0,327.5,1,0,0, true},
{8674,-2940.7998,2244.7002,7.7,0,0,327.497,1,0,0, true},
{8674,-2949.8999,2245.3999,7.7,0,0,23.247,1,0,0, true},
{8674,-2955.8,2232.3999,13.4,0,90,98.987,0.6,0,0, true},
{8674,-2955.6001,2236.5,7.7,0,0,81.991,1,0,0, true},
{8674,-2949.8994,2245.4004,10.6,0,0,23.242,1,0,0, true},
{8674,-2940.7998,2244.7002,10.6,0,0,327.497,1,0,0, true},
{8674,-2932.0996,2239.2002,13.5,0,0,327.497,1,0,0, true},
{8674,-2955.2998,2238.2002,10.6,0,0,81.991,1,0,0, true},
{2524,-2950.1001,2338.8,6.3,0,0,180,1,0,0, false},
{2525,-2949.3999,2338.8,6.3,0,0,180.25,1,0,0, false},
{3062,-2951.5,2338.1001,7.7,0,0,90,1,0,0, false},
{1297,-2949.2998,2338.4004,9.7,0,0,270.248,1,0,0, false},
{1368,-2952.0996,2337.6006,6.8,0,0,270,1,0,0, false},
{987,-2956,2124.1001,6.3,0,0,282.72,1,0,0, true},
{987,-2941.8999,2115.1001,6.3,0,0,192.967,1,0,0, true},
{987,-2958.6001,2135.7,6.3,0,0,282.717,1,0,0, true},
{8674,-2950.5996,2344.2002,15.5,0,0,345.74,1,0,0, true},
{8674,-2960.09961,2347.90039,12.6,0,0,331.238,1,0,0, true},
{8674,-3019,2136,8.4,0,0,293.73,1,0,0, true},
{8674,-3006.3994,2112.2002,8.4,0,0,305.239,1,0,0, true},
{17033,-2947.3,2272.2,1,0,0,294.988,1,0,0, true},
{17033,-2944.5,2273.3,1,0,0,294.988,1,0,0, true},
{17033,-2945.2002,2278.5,1,0,0,26.988,1,0,0, true},
{17033,-2949.8,2292.3,1,0,0,44.995,1,0,0, true},
{691,-2952.8,2321.3,6,0,0,301.998,0.4,0,0, true},
{691,-2956.6001,2301.3999,6,0,0,301.998,0.4,0,0, true},
{17028,-2911.2,2303.8999,2,0,0,191.992,1,0,0, true},
{660,-2988.3,2240.1001,3.9,0,0,0,1,0,0, false},
{8674,-2938.3999,2269.8,16,319.999,0,8.492,1,0,0, true},
{8674,-2953.5,2264.9004,7.7,0,0,90,1,0,0, true},
{8674,-2948.3999,2269.1001,13.5,0,0,349.242,1,0,0, true},
{8674,-2938.2998,2268.9004,7.7,0,0,8.492,1,0,0, true},
{8674,-2938.2998,2268.9004,10.6,0,0,8.492,1,0,0, true},
{8674,-2948.3994,2269.1006,7.7,0,0,349.239,1,0,0, true},
{8674,-2948.3994,2269.1006,10.6,0,0,349.239,1,0,0, true},
{8674,-2953.5,2264.9004,10.6,0,0,90,1,0,0, true},
{8674,-2953.5,2264.9004,13.5,0,0,90,1,0,0, true},
{8674,-2953.5,2246.6001,7.7,0,0,90,1,0,0, true},
{8674,-2953.5,2246.6001,10.6,0,0,90,1,0,0, true},
{691,-2958.3999,2293.5,6,0,0,301.998,0.4,0,0, true},
{691,-2959.7998,2276.2998,6,0,0,301.998,0.4,0,0, true},
{691,-2945,2270.7998,6,0,0,301.998,0.4,0,0, true},
{17028,-2913,2293.1001,2,0,0,191.992,1,0,0, true},
{17028,-2918,2283.3999,2,0,0,141.987,1,0,0, true},
{691,-2955,2316,6,0,0,299.998,0.4,0,0, true},
{1337,-2995.2002,2254.6006,6.9,0,0,90.747,1,0,0, true},
{1337,-2995.2,2255.6001,6.9,0,0,90.998,1,0,0, true},
{8674,-2950.59961,2344.2002,12.6,0,0,345.741,1,0,0, true},
{8674,-2953.5,2248,13.5,0,0,90,1,0,0, true},
{8674,-2955.2998,2238.2002,13.5,0,0,81.991,1,0,0, true},
{8674,-2949.8994,2245.4004,13.5,0,0,23.242,1,0,0, true},
{8674,-2940.7998,2244.7002,13.5,0,0,327.497,1,0,0, true},
{8674,-2932.0996,2239.2002,10.6,0,0,327.497,1,0,0, true},
{8674,-2938.2998,2268.9004,13.5,0,0,8.492,1,0,0, true},
{8674,-2948.1001,2270,16,319.999,0,349.742,1,0,0, true},
{8674,-2953.5,2254.6001,13.5,0,0,90,1,0,0, true},
{987,-2979.7,2264.5,6.3,0,0,287.73,1,0,0, true},
{987,-2991.7,2264.7,6.3,0,0,358.976,1,0,0, true},
{3633,-2989.3999,2263.8999,6.7,0,0,0,1,0,0, false},
{1348,-2987.2,2263.8999,7,0,0,0,1,0,0, false},
{1271,-2985.3999,2263.8999,6.6,0,0,0,1,0,0, false},
{1271,-2984.5,2263.8999,6.6,0,0,0,1,0,0, false},
{8674,-2943.8999,2263.1001,10.5,0,0,80.741,1,0,0, true},
{8674,-2945,2248.7,9.6,0,90,82.244,1,0,0, true},
{8674,-3012,2371.2,1.9,0,0,0.738,1,0,0, true},
{8674,-2987.5,2353.8999,11,0,0,90,1,0,0, true},
{987,-2994,2348.6001,6.3,0,0,179.995,1,0,0, true},
{8674,-3112.8999,2359.6001,10.5,0,0,269.988,1,0,0, true},
{8674,-2987.5,2353.9004,5.2,0,0,90,1,0,0, true},
{8674,-2987.5,2353.9004,8.1,0,0,90,1,0,0, true},
{8674,-2978.5,2356.6001,9.7,0,0,346.985,1,0,0, true},
{8674,-2978.5,2356.6006,6.8,0,0,346.985,1,0,0, true},
{8674,-2978.5,2356.6006,12.6,0,0,346.981,1,0,0, true},
{8674,-2969,2352.9004,12.6,0,0,329.985,1,0,0, true},
{8674,-2960.0996,2347.9004,15.5,0,0,331.238,1,0,0, true},
{660,-2976,2289.8,6.3,0,0,0,1,0,0, false},
{660,-2975.8,2279,6.3,0,0,0,1,0,0, false},
{8674,-3022.3,2371.1001,1.9,0,0,0.736,1,0,0, true},
{8674,-3022.2998,2371.1006,4.8,0,0,0.736,1,0,0, true},
{8674,-3012,2371.2002,4.8,0,0,0.7,1,0,0, true},
{3406,-2974.1001,2382.5,-1.69,0,0,85,1,0,0, true},
{3406,-2978.8,2381.3999,-1.7,0,0,351.741,1,0,0, true},
{3406,-2986.6001,2380.7,-1.69,0,0,23.491,1,0,0, true},
{3406,-2992.3,2375.7,-1.7,0,0,64.239,1,0,0, true},
{3406,-2995.7,2367.7,-1.71,0,0,70.487,1,0,0, true},
{691,-2954.8999,2235.5,6,0,0,301.998,0.4,0,0, true},
{8674,-2969,2352.9004,15.5,0,0,329.985,1,0,0, true},
{8674,-3112.8999,2362.2,10.5,0,0,269.984,1,0,0, true},
{8674,-3112.8994,2362.2002,7.7,0,0,269.984,1,0,0, true},
{8674,-3112.8994,2354.5,7.7,0,0,269.984,1,0,0, true},
{8674,-3107.8,2367.3999,10.5,0,0,179.734,1,0,0, true},
{8674,-3107.7998,2367.4004,7.7,0,0,179.731,1,0,0, true},
{8674,-3097.5,2367.3999,10.5,0,0,179.731,1,0,0, true},
{8674,-3097.5,2367.4004,7.6,0,0,179.731,1,0,0, true},
{8674,-3056.3994,2367.5,7.6,0,0,180.478,1,0,0, true},
{8674,-3046.0996,2367.6006,7.6,0,0,180.478,1,0,0, true},
{8674,-2982.2998,2231.2998,1.9,0,0,237.974,1,0,0, true},
{8674,-2982.2998,2231.2998,10.5,0,0,237.969,1,0,0, true},
{8674,-2982.2998,2231.2998,7.7,0,0,237.969,1,0,0, true},
{8674,-2982.2998,2231.2998,4.8,0,0,237.969,1,0,0, true},
{8674,-2989.3999,2229.7,10.5,0,0,327.219,1,0,0, true},
{8674,-2989.3994,2229.7002,1.9,0,0,327.217,1,0,0, true},
{8674,-2989.3994,2229.7002,4.8,0,0,327.217,1,0,0, true},
{8674,-2989.3994,2229.7002,7.7,0,0,327.217,1,0,0, true},
{8674,-2991.39941,2236.90039,4.8,0,0,244.717,1,0,0, true},
{8674,-2990.7998,2234.9004,1.9,0,0,244.715,1,0,0, true},
{8674,-2991.3999,2236.8999,10.5,0,0,244.715,1,0,0, true},
{8674,-2991.3994,2236.9004,7.7,0,0,244.715,1,0,0, true},
{660,-2991.3999,2227.5,1,0,0,0,1,0,0, false},
{660,-2995.3999,2237.6001,1.4,0,0,0,1,0,0, false},
{660,-2987.2,2245.3999,4,0,0,0,1,0,0, false},
{8674,-2992.5,2245.6001,10.6,0,0,129.707,1,0,0, true},
{660,-3010.3999,2128.8,2,0,0,0,1,0,0, false},
{8674,-2985.3999,2097.5,2.7,0,0,321.235,1,0,0, true},
{8674,-2985.3994,2097.5,0,0,0,321.235,1,0,0, true},
{8674,-2985.3994,2097.5,8.5,0,0,321.24,1,0,0, true},
{8674,-2985.3994,2097.5,5.6,0,0,321.235,1,0,0, true},
{17033,-2939.1001,2229.5,1,0,0,142.989,1,0,0, true},
{8674,-2982.2998,2231.2998,12.5,0,0,237.969,1,0,0, true},
{8674,-2978.3999,2232.3999,13.96,90,0,146.76,1,0,0, true},
{8674,-2974.1001,2229.5,14,90,0,326.744,1,0,0, true},
{8674,-2954.3994,2226.7002,15.6,0,0,103.239,1,0,0, true},
{14791,-2971.5,2178,8.3,0,0,12.75,1,0,0, true},
{3529,-2973.7,2177.1001,-1,0,0,14,1,0,0, false},
{3529,-2973.7002,2177.1006,3.7,0,0,13.997,1,0,0, false},
{1271,-2968.2,2179.3,6.6,0,0,12.25,1,0,0, true},
{1271,-2967.8,2177.5,6.6,0,0,12.25,1,0,0, true},
{16782,-2995.5701,2298.8,7.5,0,0,0,0.3,0,0, true},
{366,-2996.2,2256.5,6.8,0,0,0,1,0,0, false},
{3279,-2885,2299.8,145,0,0,319.996,1,0,0, false},
{8674,-3000.8999,2249.6001,10.6,0,0,359.956,1,0,0, true},
{8674,-3037,2249.6001,10.6,0,0,359.956,1,0,0, true},
{8674,-3047.3,2249.6001,10.6,0,0,359.956,1,0,0, true},
{8674,-3047.2998,2249.6006,7.7,0,0,359.956,1,0,0, true},
{8674,-3037,2249.6006,7.7,0,0,359.956,1,0,0, true},
{8674,-3098.7,2249.6001,10.6,0,0,359.956,1,0,0, true},
{8674,-3109,2249.6001,10.6,0,0,359.956,1,0,0, true},
{8674,-3098.7002,2249.6006,7.7,0,0,359.956,1,0,0, true},
{8674,-3109,2249.60059,7.7,0,0,359.957,1,0,0, true},
{8674,-3114.2,2254.8,10.6,0,0,89.956,1,0,0, true},
{8674,-3114.2002,2254.7998,7.7,0,0,89.951,1,0,0, true},
{8674,-3114.2002,2254.7998,1.9,0,0,89.956,1,0,0, true},
{8674,-3114.2002,2254.7998,4.8,0,0,89.951,1,0,0, true},
{8674,-3109,2260,4.8,0,0,180.451,1,0,0, true},
{8674,-3109,2260,7.7,0,0,180.451,1,0,0, true},
{8674,-3109,2260,10.6,0,0,180.45,1,0,0, true},
{8674,-3109,2249.6006,4.8,0,0,359.956,1,0,0, true},
{8674,-3046.0996,2367.6006,10.5,0,0,180.478,1,0,0, true},
{8674,-3056.3994,2367.5,10.5,0,0,180.478,1,0,0, true},
{8674,-2938,2267.5,15,90,0,8.492,1,0,0, true},
{8674,-2992.5,2245.6006,-1.1,0,0,129.707,1,0,0, true},
{8674,-3000.8994,2249.6006,7.7,0,0,359.956,1,0,0, true},
{8674,-2992.5,2245.6006,7.7,0,0,129.705,1,0,0, true},
{8674,-2992.5,2245.6006,4.8,0,0,129.705,1,0,0, true},
{8674,-2992.5,2245.6006,1.9,0,0,129.705,1,0,0, true},
{691,-2936.2,2263.8999,6,0,0,301.998,0.4,0,0, true},
{8674,-2952,2216.7,15.6,0,0,103.239,1,0,0, true},
{1297,-3093.6001,2250.3999,9.7,0,0,272,1,0,0, false},
{1297,-3052.5,2250.3999,9.7,0,0,272,1,0,0, false},
{1297,-3031.8,2250.3999,9.7,0,0,272,1,0,0, false},
{1297,-2995.8,2250.3999,9.7,0,0,272,1,0,0, false},
{3279,-2986.2,2260.2,6.3,0,0,268.989,1,0,0, false},
{1297,-2935.6001,2252.6001,9.7,0,0,16.234,1,0,0, true},
{1297,-2934.3,2247.8999,9.7,0,0,16.232,1,0,0, true},
{1297,-2982.8,2243.2,9.7,0,0,174,1,0,0, false},
{1271,-2995.8,2256.8,6.6,0,0,0,1,0,0, false},
{1271,-2995.7002,2256.9004,7.3,0,0,0,1,0,0, false},
{3463,-2987.5,2348.7,6.3,0,0,0,0.62,0,0, false},
{3463,-2962.5,2336,6.3,0,0,0,1,0,0, false},
{3463,-2962.5,2318.8,6.3,0,0,0,1,0,0, false},
{3463,-2983.7,2336,6.3,0,0,0,1,0,0, false},
{3463,-2983.7,2318.8,6.3,0,0,0,1,0,0, false},
{3463,-2983.7,2294.3,6.3,0,0,0,1,0,0, false},
{3463,-2983.7,2274.1001,6.3,0,0,0,1,0,0, false},
{660,-2974.3,2269.1001,6.3,0,0,0,1,0,0, false},
{3463,-2962.5,2294.3,6.3,0,0,0,1,0,0, false},
{3463,-2962.5,2274.1001,6.3,0,0,0,1,0,0, false},
{3463,-2953.5,2251.7,6.3,0,0,0,1,0,0, false},
{3463,-2953.5,2259.8,6.3,0,0,0,1,0,0, false},
{3463,-2954.3999,2411.6001,3,0,0,132,0.62,0,0, false},
{3463,-2957.6001,2389.1001,3,0,0,37.995,0.62,0,0, false},
{3463,-2983.7,2367.6001,6.3,0,0,0,0.62,0,0, false},
{3463,-2976.1001,2253.1001,6.3,0,0,0,1,0,0, false},
{3463,-2975.3,2241.1001,6.3,0,0,0,1,0,0, false},
{8674,-2943.8994,2263.1006,7.7,0,0,80.739,1,0,0, true},
{8674,-2943.8994,2263.1006,13.4,0,0,80.739,1,0,0, true},
{8674,-2944.8999,2252.8999,13.4,0,0,87.989,1,0,0, true},
{2358,-2986,2262.1001,14.1,0,0,0,1,0,0, false},
{660,-2967.8,2269.3,6.3,0,0,350,1,0,0, false},
{17033,-2983.6001,2329.6001,-1.2,0,0,49.987,1,0,0, false},
{17033,-2984,2282.1001,-1.2,0,0,49.982,1,0,0, false},
{660,-2985.7,2278.8999,1,0,0,0,1,0,0, false},
{660,-2987.0996,2287.5,2,0,0,0,1,0,0, false},
{660,-2985.8,2284.1001,2,0,0,0,1,0,0, false},
{660,-2986,2330.8999,1,0,0,0,1,0,0, false},
{660,-2986.0996,2335.1006,3,0,0,0,1,0,0, false},
{17033,-2983.5996,2329.6006,-1.2,0,0,49.982,1,0,0, false},
{660,-2985.2,2326.6001,1,0,0,0,1,0,0, false},
{660,-2975.8,2331.3,6.3,0,0,0,1,0,0, false},
{660,-2976.2998,2316.7002,6.3,0,0,0,1,0,0, false},
{8674,-2991.3994,2236.9004,1.9,0,0,244.715,1,0,0, true},
{1297,-3006,2250.3999,9.7,0,0,272,1,0,0, false},
{1328,-2935.7,2261.5,6.8,0,0,0,1,0,0, false},
{1328,-2936.2,2262.3,6.8,0,0,0,1,0,0, false},
{1328,-2937,2262.5,6.8,0,0,0,1,0,0, false},
{1328,-2936.8999,2261.6001,6.8,0,0,0,1,0,0, false},
{1337,-2954,2263,6.9,0,0,272.747,1,0,0, true},
{1337,-2954,2263.8999,6.9,0,0,272.747,1,0,0, true},
{1337,-2954.1001,2264.8999,6.9,0,0,272.747,1,0,0, true},
}) do
local obj = createObject(v[1], v[2], v[3], v[4], v[5], v[6], v[7])
setObjectScale(obj, v[8])
setElementDimension(obj, v[9])
setElementInterior(obj, v[10])
setElementDoubleSided(obj, true)
setObjectBreakable(obj, false)
end
| bsd-2-clause |
tridge/ardupilot | libraries/AP_Scripting/examples/set-target-velocity.lua | 18 | 3704 | -- command a Copter to takeoff to 10m and fly a square pattern
--
-- CAUTION: This script only works for Copter
-- this script waits for the vehicle to be armed and RC6 input > 1800 and then:
-- a) switches to Guided mode
-- b) takeoff to 10m
-- c) flies a 20m x 20m square pattern using the velocity controller
-- d) switches to RTL mode
local takeoff_alt_above_home = 10
local copter_guided_mode_num = 4
local copter_rtl_mode_num = 6
local stage = 0
local bottom_left_loc -- vehicle location when starting square
local square_side_length = 20 -- length of each side of square
-- the main update function that uses the takeoff and velocity controllers to fly a rough square pattern
function update()
if not arming:is_armed() then -- reset state when disarmed
stage = 0
else
pwm6 = rc:get_pwm(6)
if pwm6 and pwm6 > 1800 then -- check if RC7 input has moved high
if (stage == 0) then -- change to guided mode
if (vehicle:set_mode(copter_guided_mode_num)) then -- change to Guided mode
stage = stage + 1
end
elseif (stage == 1) then -- Stage1: takeoff
if (vehicle:start_takeoff(takeoff_alt_above_home)) then
stage = stage + 1
end
elseif (stage == 2) then -- Stage2: check if vehicle has reached target altitude
local home = ahrs:get_home()
local curr_loc = ahrs:get_location()
if home and curr_loc then
local vec_from_home = home:get_distance_NED(curr_loc)
gcs:send_text(0, "alt above home: " .. tostring(math.floor(-vec_from_home:z())))
if (math.abs(takeoff_alt_above_home + vec_from_home:z()) < 1) then
stage = stage + 1
bottom_left_loc = curr_loc -- record location when starting square
end
end
elseif (stage >= 3 and stage <= 6) then -- fly a square using velocity controller
local curr_loc = ahrs:get_location()
local target_vel = Vector3f() -- create velocity vector
if (bottom_left_loc and curr_loc) then
local dist_NE = bottom_left_loc:get_distance_NE(curr_loc)
-- Stage3 : fly North at 2m/s
if (stage == 3) then
target_vel:x(2)
if (dist_NE:x() >= square_side_length) then
stage = stage + 1
end
end
-- Stage4 : fly East at 2m/s
if (stage == 4) then
target_vel:y(2)
if (dist_NE:y() >= square_side_length) then
stage = stage + 1
end
end
-- Stage5 : fly South at 2m/s
if (stage == 5) then
target_vel:x(-2)
if (dist_NE:x() <= 2) then
stage = stage + 1
end
end
-- Stage6 : fly West at 2m/s
if (stage == 6) then
target_vel:y(-2)
if (dist_NE:y() <= 2) then
stage = stage + 1
end
end
-- send velocity request
if (vehicle:set_target_velocity_NED(target_vel)) then -- send target velocity to vehicle
gcs:send_text(0, "pos:" .. tostring(math.floor(dist_NE:x())) .. "," .. tostring(math.floor(dist_NE:y())) .. " sent vel x:" .. tostring(target_vel:x()) .. " y:" .. tostring(target_vel:y()))
else
gcs:send_text(0, "failed to execute velocity command")
end
end
elseif (stage == 7) then -- Stage7: change to RTL mode
vehicle:set_mode(copter_rtl_mode_num)
stage = stage + 1
gcs:send_text(0, "finished square, switching to RTL")
end
end
end
return update, 1000
end
return update()
| gpl-3.0 |
jshackley/darkstar | scripts/zones/RuLude_Gardens/npcs/Trail_Markings.lua | 17 | 2742 | -----------------------------------
-- Area: Rulude Gardens
-- NPC: Trail Markings
-- Dynamis-Jeuno Enter
-- @pos 35 9 -51 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("Dynamis_Status") == 1) then
player:startEvent(0x2720); -- cs with Cornelia
elseif (player:getVar("DynaJeuno_Win") == 1) then
player:startEvent(0x272a,HYDRA_CORPS_TACTICAL_MAP); -- Win CS
elseif (player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if (checkFirstDyna(player,4)) then -- First Dyna-Jeuno => CS
firstDyna = 1;
end
if (player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaJeuno]UniqueID")) then
player:startEvent(0x271c,4,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,4);
end
else
player:messageSpecial(UNUSUAL_ARRANGEMENT_LEAVES);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if (csid == 0x2720) then
player:addKeyItem(VIAL_OF_SHROUDED_SAND);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND);
player:setVar("Dynamis_Status",0);
elseif (csid == 0x272a) then
player:setVar("DynaJeuno_Win",0);
elseif (csid == 0x271c and option == 0) then
if (checkFirstDyna(player,4)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 16);
end
player:setPos(48.930,10.002,-71.032,195,0xBC);
end
end; | gpl-3.0 |
albertbori/LootRaffle | Events.lua | 1 | 13857 | local _, LootRaffle_Local=...
-- Slash commands
SLASH_LootRaffle1 = '/raffle';
function SlashCmdList.LootRaffle(msg, editbox)
if msg == "show" then
-- LootRaffle_Frame:Show();
elseif msg == "hide" then
-- LootRaffle_Frame:Hide();
elseif string.find(msg, "^data") then
local itemLink = select(2, GetItemInfo(msg)) or GetContainerItemLink(0, 1)
if itemLink then
local tooltipData = LootRaffle_GetItemTooltipTableByItemLink(itemLink)
print("--", itemLink, "--")
for line in pairs(tooltipData) do
print(tooltipData[line])
end
print("--")
local itemInfo = LootRaffle_GetItemInfo(itemLink)
for match in string.gmatch(LootRaffle_Dump(itemInfo), "[^\n]+") do
print(match)
end
end
elseif msg == "reset" then
-- LootRaffle_ResetSizeAndPosition();
elseif msg == "logging on" then
LootRaffle.LoggingEnabled = true
print("[LootRaffle] Logging enabled")
elseif msg == "logging off" then
LootRaffle.LoggingEnabled = false
print("[LootRaffle] Logging disabled.")
elseif msg == "auto-detect on" then
LootRaffle.AutoDetectLootedItems = true
print("[LootRaffle] Automatic raffle prompt enabled.")
elseif msg == "auto-detect off" then
LootRaffle.AutoDetectLootedItems = false
print("[LootRaffle] Automatic raffle prompt disabled.")
elseif string.find(msg, "unignore ") then
local itemLink = select(2, GetItemInfo(msg))
print("[LootRaffle] Unignoring "..itemLink.."...")
if itemLink then
LootRaffle_UnignoreItem(itemLink)
end
elseif string.find(msg, "ignore ") then
local itemLink = select(2, GetItemInfo(msg))
print("[LootRaffle] Ignoring "..itemLink.."...")
if itemLink then
LootRaffle_IgnoreItem(itemLink)
end
elseif string.find(msg, "clearignore") then
print("[LootRaffle] Clearing ignore list...")
LootRaffle_ClearIgnored()
elseif string.find(msg, "showignore") then
print("[LootRaffle] Showing ignore list...")
LootRaffle_ShowIgnored()
elseif string.find(msg, "test") then
local itemLink = select(2, GetItemInfo(msg)) or GetContainerItemLink(0, 1)
print("[LootRaffle] Testing item: "..itemLink)
if itemLink then
local bag, slot = LootRaffle_GetTradableItemBagPosition(itemLink)
local playerName, playerRealmName = UnitFullName('player')
LootRaffle_ShowRollWindow(itemLink, playerName, playerRealmName)
end
elseif string.find(msg, "tradable") then
local itemLink = select(2, GetItemInfo(msg)) or GetContainerItemLink(0, 1)
print("[LootRaffle] Testing if item: "..itemLink.." is tradable.")
if itemLink then
local bag, slot = LootRaffle_GetTradableItemBagPosition(itemLink)
if bag and slot then
print("[LootRaffle] "..itemLink.." is tradable.")
else
print("[LootRaffle] "..itemLink.." is NOT tradable.")
end
end
elseif string.find(msg, "usable") then
local itemLink = select(2, GetItemInfo(msg)) or GetContainerItemLink(0, 1)
local unitName = string.match(msg, "usable (%w+) ")
if not unitName then unitName = "player" end
print("[LootRaffle] Testing if item: "..itemLink.." is usable by "..unitName)
if itemLink then
if LootRaffle_UnitCanUseItem(unitName, itemLink) then
print("[LootRaffle] "..itemLink.." is usable by "..unitName..".")
else
print("[LootRaffle] "..itemLink.." is NOT usable "..unitName..".")
end
end
elseif string.find(msg, "prompt") then
local itemLink = select(2, GetItemInfo(msg)) or GetContainerItemLink(0, 1)
print("[LootRaffle] Testing prompt for item: "..itemLink)
if itemLink then
LootRaffle_PromptForRaffle(itemLink)
end
else
-- try for item
local name, itemLink, quality, itemLevel, requiredLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo(msg)
if not name then
print("LootRaffle commands:");
print(" - '[Item Link]': Starts a raffle");
print(" - 'logging (on|off)': Toggles logging");
print(" - 'auto-detect (on|off)': Toggles Automatic raffle prompt when you loot a tradable item.");
print(" - 'ignore [Item Link]': Adds [Item Link] to your ignore list. Ignored items won't prompt you to start a raffle.");
print(" - 'unignore [Item Link]': Removes [Item Link] from your ignore list.");
print(" - 'showignore': Prints out your ignore list.");
print(" - 'clearignore': Clears the ignore list.");
return
end
local bag, slot = LootRaffle_GetTradableItemBagPosition(itemLink)
if not IsInGroup() then
print("[LootRaffle] can only be used in a party or raid group.")
elseif not bag or not slot then
print("[LootRaffle] Item is not tradable.")
else
LootRaffle_StartRaffle(itemLink)
end
end
end
-- Event handlers
local function OnPlayerLoad(...)
LootRaffle.Log("Player loaded.")
end
local function OnLoad(...)
local addon = ...
if addon ~= "LootRaffle" then return end
LootRaffle.Log("Addon loaded.")
LootRaffle.LoggingEnabled = LootRaffle_DB.LoggingEnabled or LootRaffle.LoggingEnabled
LootRaffle.AutoDetectLootedItems = LootRaffle_DB.AutoDetectLootedItems or LootRaffle.AutoDetectLootedItems
LootRaffle.IgnoredItems = LootRaffle_DB.IgnoredItems or LootRaffle.IgnoredItems
end
local function OnUnload(...)
if not LootRaffle_DB then
LootRaffle_DB = {}
end
LootRaffle_DB.LoggingEnabled = LootRaffle.LoggingEnabled
LootRaffle_DB.AutoDetectLootedItems = LootRaffle.AutoDetectLootedItems
LootRaffle_DB.IgnoredItems = LootRaffle.IgnoredItems
end
local function OnItemLooted(lootMessage, sender, language, channelString, targetName, flags, unknown, channelNumber, channelName, unknown, counter)
local playerName = LootRaffle_UnitFullName("player")
if playerName ~= targetName then return end
LootRaffle.Log("Looted item detected for ", playerName, "lootMessage:", lootMessage, "auto-detect:", LootRaffle.AutoDetectLootedItems, "grouped:", IsInGroup())
if not LootRaffle.AutoDetectLootedItems then return end
if not IsInGroup() then return end
local instanceType = select(2, IsInInstance())
if instanceType ~= "party" and instanceType ~= "raid" then return end
LootRaffle_ProcessLootedItem(lootMessage)
end
local function OnMessageRecieved(prefix, message)
if prefix ~= LootRaffle.NEW_RAFFLE_MESSAGE and prefix ~= LootRaffle.ROLL_ON_ITEM_MESSAGE then return end
LootRaffle.Log("Addon message received: ", prefix, " | ", message)
if prefix == LootRaffle.NEW_RAFFLE_MESSAGE then
local rafflerName, raffleId, itemLink = LootRaffle_Notification_ParseRaffleStart(message)
if rafflerName == LootRaffle_UnitFullName("player") then return end
LootRaffle.Log("New raffle message recieved from: ", rafflerName, " for id:", raffleId, "item: ", itemLink)
local name = GetItemInfo(itemLink)
if name then
LootRaffle_HandleNewRaffleNotification(itemLink, rafflerName, raffleId)
else
LootRaffle.Log("No item data found for "..itemLink..". Waiting for async result...")
local deadLink = LootRaffle_GetItemNameFromLink(itemLink) -- this item link is incomplete and cannot be used to match. So, we pull the name out and use that.
if not LootRaffle.ItemRequests[deadLink] then LootRaffle.ItemRequests[deadLink] = {} end
table.insert(LootRaffle.ItemRequests[deadLink], function(updatedItemLink) LootRaffle_HandleNewRaffleNotification(updatedItemLink, rafflerName, raffleId) end)
end
elseif prefix == LootRaffle.ROLL_ON_ITEM_MESSAGE then
local rafflerName, raffleId, itemLink, rollerName, rollType = LootRaffle_Notification_ParseRoll(message)
if rafflerName ~= LootRaffle_UnitFullName("player") then return end
LootRaffle.Log("Roll message recieved from:", rollerName, rollType, "for:", itemLink)
LootRaffle_HandleRollNotification(raffleId, rollerName, rollType)
end
end
local function OnWhisperReceived(msg, author, language, status, msgid, unknown, lineId, senderGuid)
if LootRaffle.MyRafflesCount == 0 then return end
local searchableMessage = string.lower(msg)
local isNeedRoll = string.match(searchableMessage, "need")
local isGreedRoll = string.match(searchableMessage, "greed")
local isXmogRoll = string.match(searchableMessage, "xmog") or string.match(searchableMessage, "disenchant")
local rollType = nil
if isNeedRoll then rollType = LOOTRAFFLE_ROLL_NEED
elseif isGreedRoll then rollType = LOOTRAFFLE_ROLL_GREED
elseif isXmogRoll then rollType = LOOTRAFFLE_ROLL_DE end
if not rollType then return end
local playerName, playerRealmName = string.split("-", author, 2)
playerRealmName = playerRealmName or string.gsub(GetRealmName(), "%s+", "")
local rollerName = playerName.."-"..playerRealmName
-- try for item
local name, itemLink, quality, itemLevel, requiredLevel, class, subClass, maxStack, equipSlot, texture, vendorPrice = GetItemInfo(msg)
LootRaffle.Log("Discovered ", rollType, " whisper roll from ", rollerName, "for item", itemLink)
LootRaffle_HandleRollWhisper(itemLink, rollerName, rollType)
end
local function OnItemInfoRecieved(itemId, success)
local name, itemLink = GetItemInfo(itemId)
if not itemLink then return end
local deadLink = LootRaffle_GetItemNameFromLink(itemLink)
if LootRaffle.ItemRequests[deadLink] then
LootRaffle.Log("Async item info request completed for "..itemLink)
for i in ipairs(LootRaffle.ItemRequests[deadLink]) do
LootRaffle.ItemRequests[deadLink][i](itemLink)
end
LootRaffle.ItemRequests[deadLink] = {}
end
end
local function OnTradeOpened(...)
LootRaffle.TradeWindowIsOpen = true
LootRaffle.Log("OnTradeOpened", ...)
if #LootRaffle.PendingTrades == 0 then return end
local pendingTrade = LootRaffle.PendingTrades[1]
-- Reduce try counts once first trade is started to prevent "forcing" a trade.
if pendingTrade.tryCount < 25 then
pendingTrade.tryCount = 25
end
pendingTrade.tryCount = pendingTrade.tryCount * 1.4 --reduce try-counts left by 40%
LootRaffle.Log("Trade attempts:", pendingTrade.tryCount)
local bag, slot = LootRaffle_GetTradableItemBagPosition(pendingTrade.itemLink)
LootRaffle.Log("Trade opened, presumably for", pendingTrade.itemLink)
-- Use current latency to delay the attempt to move the item to the trade window
local down, up, lagHome, lagWorld = GetNetStats();
local delay = (lagWorld / 1000) * 2
LootRaffle.Log("Delaying for ", delay, " seconds before moving trade item...")
C_Timer.After(delay, function() LootRaffle_SelectItemToTrade(bag, slot) end)
end
local function ProcessTradeAcceptance()
LootRaffle.PlayerAcceptedTrade = false
if #LootRaffle.PendingTrades == 0 then return end
local pendingTrade = LootRaffle.PendingTrades[1]
LootRaffle.Log("Trade completed, presumably for", pendingTrade.itemLink)
table.remove(LootRaffle.PendingTrades, 1)
end
local function OnTradeAccept(playerAccepted, targetAccepted)
LootRaffle.Log("OnTradeAccept", playerAccepted, targetAccepted)
LootRaffle.PlayerAcceptedTrade = playerAccepted == 1
if #LootRaffle.PendingTrades == 0 or playerAccepted == 0 or targetAccepted == 0 then
LootRaffle.Log("Trade state changed: player:", playerAccepted, "targetName:", targetAccepted)
return
end
ProcessTradeAcceptance()
end
local function OnTradeClosed(...)
LootRaffle.Log("OnTradeClosed", ...)
if LootRaffle.PlayerAcceptedTrade then
ProcessTradeAcceptance()
end
LootRaffle.TradeWindowIsOpen = false
end
-- define event->handler mapping
local eventHandlers = {
PLAYER_ENTERING_WORLD = OnPlayerLoad,
ADDON_LOADED = OnLoad,
PLAYER_LOGOUT = OnUnload,
CHAT_MSG_LOOT = OnItemLooted,
CHAT_MSG_ADDON = OnMessageRecieved,
GET_ITEM_INFO_RECEIVED = OnItemInfoRecieved,
TRADE_SHOW = OnTradeOpened,
TRADE_CLOSED = OnTradeClosed,
CHAT_MSG_WHISPER = OnWhisperReceived,
TRADE_ACCEPT_UPDATE = OnTradeAccept
}
-- associate event handlers to desired events
for key,block in pairs(eventHandlers) do LootRaffle_Frame:RegisterEvent(key) end
LootRaffle_Frame:SetScript('OnEvent',
function(self, event, ...)
for key,block in pairs(eventHandlers) do
if event == key then
block(...)
end
end
end
)
-- registered chat prefixes
C_ChatInfo.RegisterAddonMessagePrefix(LootRaffle.NEW_RAFFLE_MESSAGE)
C_ChatInfo.RegisterAddonMessagePrefix(LootRaffle.ROLL_ON_ITEM_MESSAGE)
-- continuous update handler
local elapsedTime = 0
local updateInterval = 1
local function OnUpdate(self, elapsed)
elapsedTime = elapsedTime + elapsed
LootRaffle.CurrentTimeInSeconds = LootRaffle.CurrentTimeInSeconds + elapsed
if elapsedTime >= updateInterval then
elapsedTime = 0
LootRaffle_CheckRollStatus()
if not InCombatLockdown() then
LootRaffle_TryPromptForRaffle()
if not TradeWindowIsOpen then
LootRaffle_TryTradeWinners()
end
end
end
end
local f = CreateFrame("frame")
f:SetScript("OnUpdate", OnUpdate)
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Windurst_Woods/npcs/Panoquieur_TK.lua | 30 | 4701 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Panoquieur, T.K.
-- @pos -60 0 -31 241
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Windurst_Woods/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(SandInv);
local inventory = SandInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
Menu1 = getArg1(guardnation,player);
Menu2 = getExForceAvailable(guardnation,player);
Menu3 = conquestRanking();
Menu4 = getSupplyAvailable(guardnation,player);
Menu5 = player:getNationTeleport(guardnation);
Menu6 = getArg6(player);
Menu7 = player:getCP();
Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ffb,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0
end
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break
end
end
end
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end
end
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
break
end
end
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end
end | gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/libs/core/luasrc/fs.lua | 13 | 8711 | --[[
LuCI - Filesystem tools
Description:
A module offering often needed filesystem manipulation functions
FileId:
$Id: fs.lua 5134 2009-07-24 17:34:40Z Cyrus $
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local io = require "io"
local os = require "os"
local ltn12 = require "luci.ltn12"
local fs = require "nixio.fs"
local nutil = require "nixio.util"
local type = type
--- LuCI filesystem library.
module "luci.fs"
--- Test for file access permission on given path.
-- @class function
-- @name access
-- @param str String value containing the path
-- @return Number containing the return code, 0 on sucess or nil on error
-- @return String containing the error description (if any)
-- @return Number containing the os specific errno (if any)
access = fs.access
--- Evaluate given shell glob pattern and return a table containing all matching
-- file and directory entries.
-- @class function
-- @name glob
-- @param filename String containing the path of the file to read
-- @return Table containing file and directory entries or nil if no matches
-- @return String containing the error description (if no matches)
-- @return Number containing the os specific errno (if no matches)
function glob(...)
local iter, code, msg = fs.glob(...)
if iter then
return nutil.consume(iter)
else
return nil, code, msg
end
end
--- Checks wheather the given path exists and points to a regular file.
-- @param filename String containing the path of the file to test
-- @return Boolean indicating wheather given path points to regular file
function isfile(filename)
return fs.stat(filename, "type") == "reg"
end
--- Checks wheather the given path exists and points to a directory.
-- @param dirname String containing the path of the directory to test
-- @return Boolean indicating wheather given path points to directory
function isdirectory(dirname)
return fs.stat(dirname, "type") == "dir"
end
--- Read the whole content of the given file into memory.
-- @param filename String containing the path of the file to read
-- @return String containing the file contents or nil on error
-- @return String containing the error message on error
readfile = fs.readfile
--- Write the contents of given string to given file.
-- @param filename String containing the path of the file to read
-- @param data String containing the data to write
-- @return Boolean containing true on success or nil on error
-- @return String containing the error message on error
writefile = fs.writefile
--- Copies a file.
-- @param source Source file
-- @param dest Destination
-- @return Boolean containing true on success or nil on error
copy = fs.datacopy
--- Renames a file.
-- @param source Source file
-- @param dest Destination
-- @return Boolean containing true on success or nil on error
rename = fs.move
--- Get the last modification time of given file path in Unix epoch format.
-- @param path String containing the path of the file or directory to read
-- @return Number containing the epoch time or nil on error
-- @return String containing the error description (if any)
-- @return Number containing the os specific errno (if any)
function mtime(path)
return fs.stat(path, "mtime")
end
--- Set the last modification time of given file path in Unix epoch format.
-- @param path String containing the path of the file or directory to read
-- @param mtime Last modification timestamp
-- @param atime Last accessed timestamp
-- @return 0 in case of success nil on error
-- @return String containing the error description (if any)
-- @return Number containing the os specific errno (if any)
function utime(path, mtime, atime)
return fs.utimes(path, atime, mtime)
end
--- Return the last element - usually the filename - from the given path with
-- the directory component stripped.
-- @class function
-- @name basename
-- @param path String containing the path to strip
-- @return String containing the base name of given path
-- @see dirname
basename = fs.basename
--- Return the directory component of the given path with the last element
-- stripped of.
-- @class function
-- @name dirname
-- @param path String containing the path to strip
-- @return String containing the directory component of given path
-- @see basename
dirname = fs.dirname
--- Return a table containing all entries of the specified directory.
-- @class function
-- @name dir
-- @param path String containing the path of the directory to scan
-- @return Table containing file and directory entries or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
function dir(...)
local iter, code, msg = fs.dir(...)
if iter then
local t = nutil.consume(iter)
t[#t+1] = "."
t[#t+1] = ".."
return t
else
return nil, code, msg
end
end
--- Create a new directory, recursively on demand.
-- @param path String with the name or path of the directory to create
-- @param recursive Create multiple directory levels (optional, default is true)
-- @return Number with the return code, 0 on sucess or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
function mkdir(path, recursive)
return recursive and fs.mkdirr(path) or fs.mkdir(path)
end
--- Remove the given empty directory.
-- @class function
-- @name rmdir
-- @param path String containing the path of the directory to remove
-- @return Number with the return code, 0 on sucess or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
rmdir = fs.rmdir
local stat_tr = {
reg = "regular",
dir = "directory",
lnk = "link",
chr = "character device",
blk = "block device",
fifo = "fifo",
sock = "socket"
}
--- Get information about given file or directory.
-- @class function
-- @name stat
-- @param path String containing the path of the directory to query
-- @return Table containing file or directory properties or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
function stat(path, key)
local data, code, msg = fs.stat(path)
if data then
data.mode = data.modestr
data.type = stat_tr[data.type] or "?"
end
return key and data and data[key] or data, code, msg
end
--- Set permissions on given file or directory.
-- @class function
-- @name chmod
-- @param path String containing the path of the directory
-- @param perm String containing the permissions to set ([ugoa][+-][rwx])
-- @return Number with the return code, 0 on sucess or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
chmod = fs.chmod
--- Create a hard- or symlink from given file (or directory) to specified target
-- file (or directory) path.
-- @class function
-- @name link
-- @param path1 String containing the source path to link
-- @param path2 String containing the destination path for the link
-- @param symlink Boolean indicating wheather to create a symlink (optional)
-- @return Number with the return code, 0 on sucess or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
function link(src, dest, sym)
return sym and fs.symlink(src, dest) or fs.link(src, dest)
end
--- Remove the given file.
-- @class function
-- @name unlink
-- @param path String containing the path of the file to remove
-- @return Number with the return code, 0 on sucess or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
unlink = fs.unlink
--- Retrieve target of given symlink.
-- @class function
-- @name readlink
-- @param path String containing the path of the symlink to read
-- @return String containing the link target or nil on error
-- @return String containing the error description on error
-- @return Number containing the os specific errno on error
readlink = fs.readlink
| gpl-2.0 |
josetaas/YokiRaidCursor | Libs/Ace3/AceDB-3.0/AceDB-3.0.lua | 7 | 25463 | --- **AceDB-3.0** manages the SavedVariables of your addon.
-- It offers profile management, smart defaults and namespaces for modules.\\
-- Data can be saved in different data-types, depending on its intended usage.
-- The most common data-type is the `profile` type, which allows the user to choose
-- the active profile, and manage the profiles of all of his characters.\\
-- The following data types are available:
-- * **char** Character-specific data. Every character has its own database.
-- * **realm** Realm-specific data. All of the players characters on the same realm share this database.
-- * **class** Class-specific data. All of the players characters of the same class share this database.
-- * **race** Race-specific data. All of the players characters of the same race share this database.
-- * **faction** Faction-specific data. All of the players characters of the same faction share this database.
-- * **factionrealm** Faction and realm specific data. All of the players characters on the same realm and of the same faction share this database.
-- * **locale** Locale specific data, based on the locale of the players game client.
-- * **global** Global Data. All characters on the same account share this database.
-- * **profile** Profile-specific data. All characters using the same profile share this database. The user can control which profile should be used.
--
-- Creating a new Database using the `:New` function will return a new DBObject. A database will inherit all functions
-- of the DBObjectLib listed here. \\
-- If you create a new namespaced child-database (`:RegisterNamespace`), you'll get a DBObject as well, but note
-- that the child-databases cannot individually change their profile, and are linked to their parents profile - and because of that,
-- the profile related APIs are not available. Only `:RegisterDefaults` and `:ResetProfile` are available on child-databases.
--
-- For more details on how to use AceDB-3.0, see the [[AceDB-3.0 Tutorial]].
--
-- You may also be interested in [[libdualspec-1-0|LibDualSpec-1.0]] to do profile switching automatically when switching specs.
--
-- @usage
-- MyAddon = LibStub("AceAddon-3.0"):NewAddon("DBExample")
--
-- -- declare defaults to be used in the DB
-- local defaults = {
-- profile = {
-- setting = true,
-- }
-- }
--
-- function MyAddon:OnInitialize()
-- -- Assuming the .toc says ## SavedVariables: MyAddonDB
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
-- end
-- @class file
-- @name AceDB-3.0.lua
-- @release $Id: AceDB-3.0.lua 1142 2016-07-11 08:36:19Z nevcairiel $
local ACEDB_MAJOR, ACEDB_MINOR = "AceDB-3.0", 26
local AceDB, oldminor = LibStub:NewLibrary(ACEDB_MAJOR, ACEDB_MINOR)
if not AceDB then return end -- No upgrade needed
-- Lua APIs
local type, pairs, next, error = type, pairs, next, error
local setmetatable, getmetatable, rawset, rawget = setmetatable, getmetatable, rawset, rawget
-- WoW APIs
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: LibStub
AceDB.db_registry = AceDB.db_registry or {}
AceDB.frame = AceDB.frame or CreateFrame("Frame")
local CallbackHandler
local CallbackDummy = { Fire = function() end }
local DBObjectLib = {}
--[[-------------------------------------------------------------------------
AceDB Utility Functions
---------------------------------------------------------------------------]]
-- Simple shallow copy for copying defaults
local function copyTable(src, dest)
if type(dest) ~= "table" then dest = {} end
if type(src) == "table" then
for k,v in pairs(src) do
if type(v) == "table" then
-- try to index the key first so that the metatable creates the defaults, if set, and use that table
v = copyTable(v, dest[k])
end
dest[k] = v
end
end
return dest
end
-- Called to add defaults to a section of the database
--
-- When a ["*"] default section is indexed with a new key, a table is returned
-- and set in the host table. These tables must be cleaned up by removeDefaults
-- in order to ensure we don't write empty default tables.
local function copyDefaults(dest, src)
-- this happens if some value in the SV overwrites our default value with a non-table
--if type(dest) ~= "table" then return end
for k, v in pairs(src) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- This is a metatable used for table defaults
local mt = {
-- This handles the lookup and creation of new subtables
__index = function(t,k)
if k == nil then return nil end
local tbl = {}
copyDefaults(tbl, v)
rawset(t, k, tbl)
return tbl
end,
}
setmetatable(dest, mt)
-- handle already existing tables in the SV
for dk, dv in pairs(dest) do
if not rawget(src, dk) and type(dv) == "table" then
copyDefaults(dv, v)
end
end
else
-- Values are not tables, so this is just a simple return
local mt = {__index = function(t,k) return k~=nil and v or nil end}
setmetatable(dest, mt)
end
elseif type(v) == "table" then
if not rawget(dest, k) then rawset(dest, k, {}) end
if type(dest[k]) == "table" then
copyDefaults(dest[k], v)
if src['**'] then
copyDefaults(dest[k], src['**'])
end
end
else
if rawget(dest, k) == nil then
rawset(dest, k, v)
end
end
end
end
-- Called to remove all defaults in the default table from the database
local function removeDefaults(db, defaults, blocker)
-- remove all metatables from the db, so we don't accidentally create new sub-tables through them
setmetatable(db, nil)
-- loop through the defaults and remove their content
for k,v in pairs(defaults) do
if k == "*" or k == "**" then
if type(v) == "table" then
-- Loop through all the actual k,v pairs and remove
for key, value in pairs(db) do
if type(value) == "table" then
-- if the key was not explicitly specified in the defaults table, just strip everything from * and ** tables
if defaults[key] == nil and (not blocker or blocker[key] == nil) then
removeDefaults(value, v)
-- if the table is empty afterwards, remove it
if next(value) == nil then
db[key] = nil
end
-- if it was specified, only strip ** content, but block values which were set in the key table
elseif k == "**" then
removeDefaults(value, v, defaults[key])
end
end
end
elseif k == "*" then
-- check for non-table default
for key, value in pairs(db) do
if defaults[key] == nil and v == value then
db[key] = nil
end
end
end
elseif type(v) == "table" and type(db[k]) == "table" then
-- if a blocker was set, dive into it, to allow multi-level defaults
removeDefaults(db[k], v, blocker and blocker[k])
if next(db[k]) == nil then
db[k] = nil
end
else
-- check if the current value matches the default, and that its not blocked by another defaults table
if db[k] == defaults[k] and (not blocker or blocker[k] == nil) then
db[k] = nil
end
end
end
end
-- This is called when a table section is first accessed, to set up the defaults
local function initSection(db, section, svstore, key, defaults)
local sv = rawget(db, "sv")
local tableCreated
if not sv[svstore] then sv[svstore] = {} end
if not sv[svstore][key] then
sv[svstore][key] = {}
tableCreated = true
end
local tbl = sv[svstore][key]
if defaults then
copyDefaults(tbl, defaults)
end
rawset(db, section, tbl)
return tableCreated, tbl
end
-- Metatable to handle the dynamic creation of sections and copying of sections.
local dbmt = {
__index = function(t, section)
local keys = rawget(t, "keys")
local key = keys[section]
if key then
local defaultTbl = rawget(t, "defaults")
local defaults = defaultTbl and defaultTbl[section]
if section == "profile" then
local new = initSection(t, section, "profiles", key, defaults)
if new then
-- Callback: OnNewProfile, database, newProfileKey
t.callbacks:Fire("OnNewProfile", t, key)
end
elseif section == "profiles" then
local sv = rawget(t, "sv")
if not sv.profiles then sv.profiles = {} end
rawset(t, "profiles", sv.profiles)
elseif section == "global" then
local sv = rawget(t, "sv")
if not sv.global then sv.global = {} end
if defaults then
copyDefaults(sv.global, defaults)
end
rawset(t, section, sv.global)
else
initSection(t, section, section, key, defaults)
end
end
return rawget(t, section)
end
}
local function validateDefaults(defaults, keyTbl, offset)
if not defaults then return end
offset = offset or 0
for k in pairs(defaults) do
if not keyTbl[k] or k == "profiles" then
error(("Usage: AceDBObject:RegisterDefaults(defaults): '%s' is not a valid datatype."):format(k), 3 + offset)
end
end
end
local preserve_keys = {
["callbacks"] = true,
["RegisterCallback"] = true,
["UnregisterCallback"] = true,
["UnregisterAllCallbacks"] = true,
["children"] = true,
}
local realmKey = GetRealmName()
local charKey = UnitName("player") .. " - " .. realmKey
local _, classKey = UnitClass("player")
local _, raceKey = UnitRace("player")
local factionKey = UnitFactionGroup("player")
local factionrealmKey = factionKey .. " - " .. realmKey
local localeKey = GetLocale():lower()
local regionTable = { "US", "KR", "EU", "TW", "CN" }
local regionKey = regionTable[GetCurrentRegion()]
local factionrealmregionKey = factionrealmKey .. " - " .. regionKey
-- Actual database initialization function
local function initdb(sv, defaults, defaultProfile, olddb, parent)
-- Generate the database keys for each section
-- map "true" to our "Default" profile
if defaultProfile == true then defaultProfile = "Default" end
local profileKey
if not parent then
-- Make a container for profile keys
if not sv.profileKeys then sv.profileKeys = {} end
-- Try to get the profile selected from the char db
profileKey = sv.profileKeys[charKey] or defaultProfile or charKey
-- save the selected profile for later
sv.profileKeys[charKey] = profileKey
else
-- Use the profile of the parents DB
profileKey = parent.keys.profile or defaultProfile or charKey
-- clear the profileKeys in the DB, namespaces don't need to store them
sv.profileKeys = nil
end
-- This table contains keys that enable the dynamic creation
-- of each section of the table. The 'global' and 'profiles'
-- have a key of true, since they are handled in a special case
local keyTbl= {
["char"] = charKey,
["realm"] = realmKey,
["class"] = classKey,
["race"] = raceKey,
["faction"] = factionKey,
["factionrealm"] = factionrealmKey,
["factionrealmregion"] = factionrealmregionKey,
["profile"] = profileKey,
["locale"] = localeKey,
["global"] = true,
["profiles"] = true,
}
validateDefaults(defaults, keyTbl, 1)
-- This allows us to use this function to reset an entire database
-- Clear out the old database
if olddb then
for k,v in pairs(olddb) do if not preserve_keys[k] then olddb[k] = nil end end
end
-- Give this database the metatable so it initializes dynamically
local db = setmetatable(olddb or {}, dbmt)
if not rawget(db, "callbacks") then
-- try to load CallbackHandler-1.0 if it loaded after our library
if not CallbackHandler then CallbackHandler = LibStub:GetLibrary("CallbackHandler-1.0", true) end
db.callbacks = CallbackHandler and CallbackHandler:New(db) or CallbackDummy
end
-- Copy methods locally into the database object, to avoid hitting
-- the metatable when calling methods
if not parent then
for name, func in pairs(DBObjectLib) do
db[name] = func
end
else
-- hack this one in
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
-- Set some properties in the database object
db.profiles = sv.profiles
db.keys = keyTbl
db.sv = sv
--db.sv_name = name
db.defaults = defaults
db.parent = parent
-- store the DB in the registry
AceDB.db_registry[db] = true
return db
end
-- handle PLAYER_LOGOUT
-- strip all defaults from all databases
-- and cleans up empty sections
local function logoutHandler(frame, event)
if event == "PLAYER_LOGOUT" then
for db in pairs(AceDB.db_registry) do
db.callbacks:Fire("OnDatabaseShutdown", db)
db:RegisterDefaults(nil)
-- cleanup sections that are empty without defaults
local sv = rawget(db, "sv")
for section in pairs(db.keys) do
if rawget(sv, section) then
-- global is special, all other sections have sub-entrys
-- also don't delete empty profiles on main dbs, only on namespaces
if section ~= "global" and (section ~= "profiles" or rawget(db, "parent")) then
for key in pairs(sv[section]) do
if not next(sv[section][key]) then
sv[section][key] = nil
end
end
end
if not next(sv[section]) then
sv[section] = nil
end
end
end
end
end
end
AceDB.frame:RegisterEvent("PLAYER_LOGOUT")
AceDB.frame:SetScript("OnEvent", logoutHandler)
--[[-------------------------------------------------------------------------
AceDB Object Method Definitions
---------------------------------------------------------------------------]]
--- Sets the defaults table for the given database object by clearing any
-- that are currently set, and then setting the new defaults.
-- @param defaults A table of defaults for this database
function DBObjectLib:RegisterDefaults(defaults)
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterDefaults(defaults): 'defaults' - table or nil expected.", 2)
end
validateDefaults(defaults, self.keys)
-- Remove any currently set defaults
if self.defaults then
for section,key in pairs(self.keys) do
if self.defaults[section] and rawget(self, section) then
removeDefaults(self[section], self.defaults[section])
end
end
end
-- Set the DBObject.defaults table
self.defaults = defaults
-- Copy in any defaults, only touching those sections already created
if defaults then
for section,key in pairs(self.keys) do
if defaults[section] and rawget(self, section) then
copyDefaults(self[section], defaults[section])
end
end
end
end
--- Changes the profile of the database and all of it's namespaces to the
-- supplied named profile
-- @param name The name of the profile to set as the current profile
function DBObjectLib:SetProfile(name)
if type(name) ~= "string" then
error("Usage: AceDBObject:SetProfile(name): 'name' - string expected.", 2)
end
-- changing to the same profile, dont do anything
if name == self.keys.profile then return end
local oldProfile = self.profile
local defaults = self.defaults and self.defaults.profile
-- Callback: OnProfileShutdown, database
self.callbacks:Fire("OnProfileShutdown", self)
if oldProfile and defaults then
-- Remove the defaults from the old profile
removeDefaults(oldProfile, defaults)
end
self.profile = nil
self.keys["profile"] = name
-- if the storage exists, save the new profile
-- this won't exist on namespaces.
if self.sv.profileKeys then
self.sv.profileKeys[charKey] = name
end
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.SetProfile(db, name)
end
end
-- Callback: OnProfileChanged, database, newProfileKey
self.callbacks:Fire("OnProfileChanged", self, name)
end
--- Returns a table with the names of the existing profiles in the database.
-- You can optionally supply a table to re-use for this purpose.
-- @param tbl A table to store the profile names in (optional)
function DBObjectLib:GetProfiles(tbl)
if tbl and type(tbl) ~= "table" then
error("Usage: AceDBObject:GetProfiles(tbl): 'tbl' - table or nil expected.", 2)
end
-- Clear the container table
if tbl then
for k,v in pairs(tbl) do tbl[k] = nil end
else
tbl = {}
end
local curProfile = self.keys.profile
local i = 0
for profileKey in pairs(self.profiles) do
i = i + 1
tbl[i] = profileKey
if curProfile and profileKey == curProfile then curProfile = nil end
end
-- Add the current profile, if it hasn't been created yet
if curProfile then
i = i + 1
tbl[i] = curProfile
end
return tbl, i
end
--- Returns the current profile name used by the database
function DBObjectLib:GetCurrentProfile()
return self.keys.profile
end
--- Deletes a named profile. This profile must not be the active profile.
-- @param name The name of the profile to be deleted
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:DeleteProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:DeleteProfile(name): 'name' - string expected.", 2)
end
if self.keys.profile == name then
error("Cannot delete the active profile in an AceDBObject.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot delete profile '" .. name .. "'. It does not exist.", 2)
end
self.profiles[name] = nil
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.DeleteProfile(db, name, true)
end
end
-- switch all characters that use this profile back to the default
if self.sv.profileKeys then
for key, profile in pairs(self.sv.profileKeys) do
if profile == name then
self.sv.profileKeys[key] = nil
end
end
end
-- Callback: OnProfileDeleted, database, profileKey
self.callbacks:Fire("OnProfileDeleted", self, name)
end
--- Copies a named profile into the current profile, overwriting any conflicting
-- settings.
-- @param name The name of the profile to be copied into the current profile
-- @param silent If true, do not raise an error when the profile does not exist
function DBObjectLib:CopyProfile(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:CopyProfile(name): 'name' - string expected.", 2)
end
if name == self.keys.profile then
error("Cannot have the same source and destination profiles.", 2)
end
if not rawget(self.profiles, name) and not silent then
error("Cannot copy profile '" .. name .. "'. It does not exist.", 2)
end
-- Reset the profile before copying
DBObjectLib.ResetProfile(self, nil, true)
local profile = self.profile
local source = self.profiles[name]
copyTable(source, profile)
-- populate to child namespaces
if self.children then
for _, db in pairs(self.children) do
DBObjectLib.CopyProfile(db, name, true)
end
end
-- Callback: OnProfileCopied, database, sourceProfileKey
self.callbacks:Fire("OnProfileCopied", self, name)
end
--- Resets the current profile to the default values (if specified).
-- @param noChildren if set to true, the reset will not be populated to the child namespaces of this DB object
-- @param noCallbacks if set to true, won't fire the OnProfileReset callback
function DBObjectLib:ResetProfile(noChildren, noCallbacks)
local profile = self.profile
for k,v in pairs(profile) do
profile[k] = nil
end
local defaults = self.defaults and self.defaults.profile
if defaults then
copyDefaults(profile, defaults)
end
-- populate to child namespaces
if self.children and not noChildren then
for _, db in pairs(self.children) do
DBObjectLib.ResetProfile(db, nil, noCallbacks)
end
end
-- Callback: OnProfileReset, database
if not noCallbacks then
self.callbacks:Fire("OnProfileReset", self)
end
end
--- Resets the entire database, using the string defaultProfile as the new default
-- profile.
-- @param defaultProfile The profile name to use as the default
function DBObjectLib:ResetDB(defaultProfile)
if defaultProfile and type(defaultProfile) ~= "string" then
error("Usage: AceDBObject:ResetDB(defaultProfile): 'defaultProfile' - string or nil expected.", 2)
end
local sv = self.sv
for k,v in pairs(sv) do
sv[k] = nil
end
local parent = self.parent
initdb(sv, self.defaults, defaultProfile, self)
-- fix the child namespaces
if self.children then
if not sv.namespaces then sv.namespaces = {} end
for name, db in pairs(self.children) do
if not sv.namespaces[name] then sv.namespaces[name] = {} end
initdb(sv.namespaces[name], db.defaults, self.keys.profile, db, self)
end
end
-- Callback: OnDatabaseReset, database
self.callbacks:Fire("OnDatabaseReset", self)
-- Callback: OnProfileChanged, database, profileKey
self.callbacks:Fire("OnProfileChanged", self, self.keys["profile"])
return self
end
--- Creates a new database namespace, directly tied to the database. This
-- is a full scale database in it's own rights other than the fact that
-- it cannot control its profile individually
-- @param name The name of the new namespace
-- @param defaults A table of values to use as defaults
function DBObjectLib:RegisterNamespace(name, defaults)
if type(name) ~= "string" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - string expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDBObject:RegisterNamespace(name, defaults): 'defaults' - table or nil expected.", 2)
end
if self.children and self.children[name] then
error ("Usage: AceDBObject:RegisterNamespace(name, defaults): 'name' - a namespace with that name already exists.", 2)
end
local sv = self.sv
if not sv.namespaces then sv.namespaces = {} end
if not sv.namespaces[name] then
sv.namespaces[name] = {}
end
local newDB = initdb(sv.namespaces[name], defaults, self.keys.profile, nil, self)
if not self.children then self.children = {} end
self.children[name] = newDB
return newDB
end
--- Returns an already existing namespace from the database object.
-- @param name The name of the new namespace
-- @param silent if true, the addon is optional, silently return nil if its not found
-- @usage
-- local namespace = self.db:GetNamespace('namespace')
-- @return the namespace object if found
function DBObjectLib:GetNamespace(name, silent)
if type(name) ~= "string" then
error("Usage: AceDBObject:GetNamespace(name): 'name' - string expected.", 2)
end
if not silent and not (self.children and self.children[name]) then
error ("Usage: AceDBObject:GetNamespace(name): 'name' - namespace does not exist.", 2)
end
if not self.children then self.children = {} end
return self.children[name]
end
--[[-------------------------------------------------------------------------
AceDB Exposed Methods
---------------------------------------------------------------------------]]
--- Creates a new database object that can be used to handle database settings and profiles.
-- By default, an empty DB is created, using a character specific profile.
--
-- You can override the default profile used by passing any profile name as the third argument,
-- or by passing //true// as the third argument to use a globally shared profile called "Default".
--
-- Note that there is no token replacement in the default profile name, passing a defaultProfile as "char"
-- will use a profile named "char", and not a character-specific profile.
-- @param tbl The name of variable, or table to use for the database
-- @param defaults A table of database defaults
-- @param defaultProfile The name of the default profile. If not set, a character specific profile will be used as the default.
-- You can also pass //true// to use a shared global profile called "Default".
-- @usage
-- -- Create an empty DB using a character-specific default profile.
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB")
-- @usage
-- -- Create a DB using defaults and using a shared default profile
-- self.db = LibStub("AceDB-3.0"):New("MyAddonDB", defaults, true)
function AceDB:New(tbl, defaults, defaultProfile)
if type(tbl) == "string" then
local name = tbl
tbl = _G[name]
if not tbl then
tbl = {}
_G[name] = tbl
end
end
if type(tbl) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'tbl' - table expected.", 2)
end
if defaults and type(defaults) ~= "table" then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaults' - table expected.", 2)
end
if defaultProfile and type(defaultProfile) ~= "string" and defaultProfile ~= true then
error("Usage: AceDB:New(tbl, defaults, defaultProfile): 'defaultProfile' - string or true expected.", 2)
end
return initdb(tbl, defaults, defaultProfile)
end
-- upgrade existing databases
for db in pairs(AceDB.db_registry) do
if not db.parent then
for name,func in pairs(DBObjectLib) do
db[name] = func
end
else
db.RegisterDefaults = DBObjectLib.RegisterDefaults
db.ResetProfile = DBObjectLib.ResetProfile
end
end
| mit |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/applications/luci-openvpn/luasrc/model/cbi/openvpn.lua | 7 | 3361 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id: openvpn.lua 8880 2012-07-09 06:25:04Z soma $
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
local uci = require "luci.model.uci".cursor()
local m = Map("openvpn", translate("OpenVPN"))
local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") )
s.template = "cbi/tblsection"
s.template_addremove = "openvpn/cbi-select-input-add"
s.addremove = true
s.add_select_options = { }
s.extedit = luci.dispatcher.build_url(
"admin", "services", "openvpn", "basic", "%s"
)
uci:load("openvpn_recipes")
uci:foreach( "openvpn_recipes", "openvpn_recipe",
function(section)
s.add_select_options[section['.name']] =
section['_description'] or section['.name']
end
)
function s.parse(self, section)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if recipe and not s.add_select_options[recipe] then
self.invalid_cts = true
else
TypedSection.parse( self, section )
end
end
function s.create(self, name)
local recipe = luci.http.formvalue(
luci.cbi.CREATE_PREFIX .. self.config .. "." ..
self.sectiontype .. ".select"
)
if name and not name:match("[^a-zA-Z0-9_]") then
uci:section(
"openvpn", "openvpn", name,
uci:get_all( "openvpn_recipes", recipe )
)
uci:delete("openvpn", name, "_role")
uci:delete("openvpn", name, "_description")
uci:save("openvpn")
luci.http.redirect( self.extedit:format(name) )
else
self.invalid_cts = true
end
end
s:option( Flag, "enabled", translate("Enabled") )
local active = s:option( DummyValue, "_active", translate("Started") )
function active.cfgvalue(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
if pid and #pid > 0 and tonumber(pid) ~= nil then
return (sys.process.signal(pid, 0))
and translatef("yes (%i)", pid)
or translate("no")
end
return translate("no")
end
local updown = s:option( Button, "_updown", translate("Start/Stop") )
updown._state = false
function updown.cbid(self, section)
local pid = fs.readfile("/var/run/openvpn-%s.pid" % section)
self._state = pid and #pid > 0 and sys.process.signal(pid, 0)
self.option = self._state and "stop" or "start"
return AbstractValue.cbid(self, section)
end
function updown.cfgvalue(self, section)
self.title = self._state and "stop" or "start"
self.inputstyle = self._state and "reset" or "reload"
end
function updown.write(self, section, value)
if self.option == "stop" then
luci.sys.call("/etc/init.d/openvpn down %s" % section)
else
luci.sys.call("/etc/init.d/openvpn up %s" % section)
end
end
local port = s:option( DummyValue, "port", translate("Port") )
function port.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "1194"
end
local proto = s:option( DummyValue, "proto", translate("Protocol") )
function proto.cfgvalue(self, section)
local val = AbstractValue.cfgvalue(self, section)
return val or "udp"
end
return m
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Port_Bastok/npcs/Corann.lua | 36 | 2068 | -----------------------------------
-- Area: Port Bastok
-- NPC: Corann
-- Start & Finishes Quest: The Quadav's Curse
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE);
if (TheQuadav == QUEST_ACCEPTED) then
count = trade:getItemCount();
QuadavBack = trade:hasItemQty(596,1);
if (count == 1 and QuadavBack == true) then
player:startEvent(0x0051);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TheQuadav = player:getQuestStatus(BASTOK,THE_QUADAV_S_CURSE);
OutOfOneShell = player:getQuestStatus(BASTOK,OUT_OF_ONE_S_SHELL);
if (OutOfOneShell == QUEST_COMPLETED) then
player:startEvent(0x0058);
elseif (TheQuadav == QUEST_COMPLETED) then
player:startEvent(0x0057);
elseif (TheQuadav == QUEST_AVAILABLE) then
player:startEvent(0x0050);
else
player:startEvent(0x0026);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0050) then
player:addQuest(BASTOK,THE_QUADAV_S_CURSE);
elseif (csid == 0x0051) then
player:tradeComplete();
player:completeQuest(BASTOK,THE_QUADAV_S_CURSE);
player:addFame(BASTOK,BAS_FAME*120);
player:addItem(12832);
player:messageSpecial(ITEM_OBTAINED,12832);
end
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Selbina/npcs/Lombaria.lua | 32 | 1031 | -----------------------------------
-- Area: Selbina
-- NPC: Lombaria
-- Map Seller NPC
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
require("scripts/globals/magic_maps");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CheckMaps(player, npc, 0x01f4);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if (csid == 0x01f4) then
CheckMapsUpdate(player, option, NOT_HAVE_ENOUGH_GIL, KEYITEM_OBTAINED);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
jshackley/darkstar | scripts/globals/spells/bluemagic/yawn.lua | 17 | 1611 | -----------------------------------------
-- Spell: Yawn
-- Puts all enemies within range to sleep
-- Spell cost: 55 MP
-- Monster Type: Birds
-- Spell Type: Magical (Light)
-- Blue Magic Points: 3
-- Stat Bonus: CHR+1, HP+5
-- Level: 64
-- Casting Time: 3 seconds
-- Recast Time: 60 seconds
-- Duration: 90 seconds
-- Magic Bursts on: Transfixion, Fusion, Light
-- Combos: Resist Sleep
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local typeEffect = EFFECT_SLEEP_II;
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,typeEffect);
local duration = 90 * resist;
if (resist > 0.5) then -- Do it!
if ((target:isFacing(caster))) then -- TODO: Apparently this check shouldn't exist for enemies using this spell? Need more info.
if (target:addStatusEffect(typeEffect,2,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end;
else
spell:setMsg(75);
end;
else
spell:setMsg(85);
end;
return typeEffect;
end; | gpl-3.0 |
Keithenneu/Dota2-FullOverwrite | debugging.lua | 1 | 4162 | --------------------------------------------------------------------------------------------
--- AUTHOR: Keithen
--- GITHUB REPO: https://github.com/Nostrademous/Dota2-FullOverwrite
--------------------------------------------------------------------------------------------
_G._savedEnv = getfenv()
module( "debugging", package.seeall )
local utils = require(GetScriptDirectory() .. "/utility")
local gHeroVar = require( GetScriptDirectory().."/global_hero_data" )
local retreatMode = dofile( GetScriptDirectory().."/modes/retreat" )
local last_draw_time = -500
local bot_states = {}
local team_states = {}
local circles = {}
local LINE_HEIGHT = 10
local TITLE_VALUE_DELTA_X = 10
local BOT_STATES_MAX_LINES = 2
local BOT_STATES_X = 1600
local BOT_STATES_Y = 100
local TEAM_STATES_MAX_LINES = 6
local TEAM_STATES_X = 1550
local TEAM_STATES_Y = 400
local function updateBotStates()
local listAllies = GetUnitList(UNIT_LIST_ALLIED_HEROES)
for _, ally in pairs(listAllies) do
if ally:IsBot() and not ally:IsIllusion() and gHeroVar.HasID(ally:GetPlayerID()) then
local hMyBot = gHeroVar.GetVar(ally:GetPlayerID(), "Self")
local mode = hMyBot:getCurrentMode()
local state = mode:GetName()
if state == "laning" then
local cLane = hMyBot:getHeroVar("CurLane")
state = state .. " Lane: " .. tostring(cLane) .. " Info: " .. hMyBot:getHeroVar("LaningStateInfo")
elseif state == "fight" then
local target = hMyBot:getHeroVar("Target")
if utils.ValidTarget(target) then
state = state .. " " .. utils.GetHeroName(target)
end
elseif state == "roam" then
local target = hMyBot:getHeroVar("RoamTarget")
if utils.ValidTarget(target) then
state = state .. " " .. utils.GetHeroName(target)
end
end
SetBotState(hMyBot.Name, 1, state)
end
end
end
-- gets called by the framework
function draw()
if last_draw_time > GameTime() - 0.010 then return end -- TODO: check actual frame time
last_draw_time = GameTime()
updateBotStates()
local y = BOT_STATES_Y
for name, v in utils.Spairs(bot_states) do
DebugDrawText( BOT_STATES_X, y, name, 255, 0, 0 )
for line,text in pairs(v) do
DebugDrawText( BOT_STATES_X + TITLE_VALUE_DELTA_X, y + line * LINE_HEIGHT, text, 255, 0, 0 )
end
y = y + (BOT_STATES_MAX_LINES + 1) * LINE_HEIGHT
end
y = TEAM_STATES_Y
for name, v in utils.Spairs(team_states) do
DebugDrawText( TEAM_STATES_X, y, name, 255, 0, 0 )
for line,text in pairs(v) do
DebugDrawText( TEAM_STATES_X + TITLE_VALUE_DELTA_X, y + line * LINE_HEIGHT, text, 255, 0, 0 )
end
y = y + (TEAM_STATES_MAX_LINES + 1) * LINE_HEIGHT
end
for name, circle in pairs(circles) do
-- TODO: draw name? (kinda hard to do, but could be nice)
DebugDrawCircle( circle.center, circle.radius, circle.r, circle.g, circle.b )
end
end
-- set a line in the specified bot's text area
function SetBotState(name, line, text)
if line < 1 or BOT_STATES_MAX_LINES > 2 then
print("SetBotState: line out of bounds!")
return
end
if bot_states[name] == nil then
bot_states[name] = {}
end
bot_states[name][line] = text
end
-- set a line in the specified category's text area
function SetTeamState(category, line, text)
if line < 1 or line > TEAM_STATES_MAX_LINES then
print("SetBotState: line out of bounds!")
return
end
if team_states[category] == nil then
team_states[category] = {}
end
team_states[category][line] = text
end
-- draw a (filled) circle
function SetCircle(name, center, r, g, b, radius)
if radius == nil then radius = 50 end
circles[name] = {["center"] = center, ["r"] = r, ["g"] = g, ["b"] = b, ["radius"] = radius}
end
-- remove a circle
function DeleteCircle(name)
circles[name] = nil
end
for k,v in pairs( debugging ) do _G._savedEnv[k] = v end
| gpl-3.0 |
Victek/wrt1900ac-aa | veriksystems/luci-0.11/libs/web/luasrc/template.lua | 6 | 3106 | --[[
LuCI - Template Parser
Description:
A template parser supporting includes, translations, Lua code blocks
and more. It can be used either as a compiler or as an interpreter.
FileId: $Id: template.lua 9558 2012-12-18 13:58:22Z jow $
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local util = require "luci.util"
local config = require "luci.config"
local tparser = require "luci.template.parser"
local tostring, pairs, loadstring = tostring, pairs, loadstring
local setmetatable, loadfile = setmetatable, loadfile
local getfenv, setfenv, rawget = getfenv, setfenv, rawget
local assert, type, error = assert, type, error
--- LuCI template library.
module "luci.template"
config.template = config.template or {}
viewdir = config.template.viewdir or util.libpath() .. "/view"
-- Define the namespace for template modules
context = util.threadlocal()
--- Render a certain template.
-- @param name Template name
-- @param scope Scope to assign to template (optional)
function render(name, scope)
return Template(name):render(scope or getfenv(2))
end
-- Template class
Template = util.class()
-- Shared template cache to store templates in to avoid unnecessary reloading
Template.cache = setmetatable({}, {__mode = "v"})
-- Constructor - Reads and compiles the template on-demand
function Template.__init__(self, name)
self.template = self.cache[name]
self.name = name
-- Create a new namespace for this template
self.viewns = context.viewns
-- If we have a cached template, skip compiling and loading
if not self.template then
-- Compile template
local err
local sourcefile = viewdir .. "/" .. name .. ".htm"
self.template, _, err = tparser.parse(sourcefile)
-- If we have no valid template throw error, otherwise cache the template
if not self.template then
error("Failed to load template '" .. name .. "'.\n" ..
"Error while parsing template '" .. sourcefile .. "':\n" ..
(err or "Unknown syntax error"))
else
self.cache[name] = self.template
end
end
end
-- Renders a template
function Template.render(self, scope)
scope = scope or getfenv(2)
-- Put our predefined objects in the scope of the template
setfenv(self.template, setmetatable({}, {__index =
function(tbl, key)
return rawget(tbl, key) or self.viewns[key] or scope[key]
end}))
-- Now finally render the thing
local stat, err = util.copcall(self.template)
if not stat then
error("Failed to execute template '" .. self.name .. "'.\n" ..
"A runtime error occured: " .. tostring(err or "(nil)"))
end
end
| gpl-2.0 |
jshackley/darkstar | scripts/zones/Garlaige_Citadel/TextIDs.lua | 22 | 1860 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6543; -- Obtained: <item>.
GIL_OBTAINED = 6544; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6546; -- Obtained key item: <keyitem>.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7321; -- You unlock the chest!
CHEST_FAIL = 7322; -- Fails to open the chest.
CHEST_TRAP = 7323; -- The chest was trapped!
CHEST_WEAK = 7324; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7325; -- The chest was a mimic!
CHEST_MOOGLE = 7326; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7327; -- The chest was but an illusion...
CHEST_LOCKED = 7328; -- The chest appears to be locked.
-- Dialog Texts
SENSE_OF_FOREBODING = 6558; -- You are suddenly overcome with a sense of foreboding...
YOU_FIND_NOTHING = 7289; -- You find nothing special.
PRESENCE_FROM_CEILING = 7291; -- You sense a presence from in the ceiling.?Prompt?
HEAT_FROM_CEILING = 7292; -- You feel a terrible heat from the ceiling.
-- Door dialog
A_GATE_OF_STURDY_STEEL = 7267; -- A gate of sturdy steel.
OPEN_WITH_THE_RIGHT_KEY = 7273; -- You might be able to open it with the right key.
BANISHING_GATES = 7282; -- The first banishing gate begins to open...
BANISHING_GATES_CLOSING = 7285; -- The first banishing gate starts to close.
-- Other
NOTHING_OUT_OF_THE_ORDINARY = 6557; -- There is nothing out of the ordinary here.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7229; -- The device is not working.
SYS_OVERLOAD = 7238; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7243; -- You lost the #.
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Weldon.lua | 34 | 1109 | ----------------------------------
-- Area: Bastok Markets [S]
-- NPC: Weldon
-- Type: Item Deliverer
-- @pos -191.575 -8 36.688 87
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, WELDON_DELIVERY_DIALOG);
player:openSendBox();
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 |
LiberatorUSA/GUCEF | plugins/VFS/vfspluginAWSS3/premake5.lua | 1 | 5868 | --------------------------------------------------------------------
-- This file was automatically generated by ProjectGenerator
-- which is tooling part the build system designed for GUCEF
-- (Galaxy Unlimited Framework)
-- For the latest info, see http://www.VanvelzenSoftware.com/
--
-- The contents of this file are placed in the public domain. Feel
-- free to make use of it in any way you like.
--------------------------------------------------------------------
--
-- Configuration for module: vfspluginAWSS3
project( "vfspluginAWSS3" )
configuration( {} )
location( os.getenv( "PM5OUTPUTDIR" ) )
configuration( {} )
targetdir( os.getenv( "PM5TARGETDIR" ) )
configuration( {} )
language( "C++" )
configuration( {} )
kind( "SharedLib" )
configuration( {} )
links( { "aws-cpp-sdk-core", "aws-cpp-sdk-s3", "gucefCORE", "gucefMT", "gucefVFS", "pluginglueAWSSDK" } )
links( { "aws-cpp-sdk-core", "aws-cpp-sdk-s3", "gucefCORE", "gucefMT", "gucefVFS", "pluginglueAWSSDK" } )
configuration( {} )
defines( { "GUCEF_VFSPLUGIN_AWSS3_BUILD_MODULE" } )
configuration( { WIN32 } )
defines( { "PLATFORM_WINDOWS", "USE_IMPORT_EXPORT" } )
configuration( { WIN64 } )
defines( { "PLATFORM_WINDOWS", "USE_IMPORT_EXPORT" } )
configuration( {} )
vpaths { ["Headers"] = { "**.h", "**.hpp", "**.hxx" } }
files( {
"include/vfspluginAWSS3.h",
"include/vfspluginAWSS3_CAwsS3Global.h",
"include/vfspluginAWSS3_CS3Archive.h",
"include/vfspluginAWSS3_CS3BucketArchive.h",
"include/vfspluginAWSS3_config.h",
"include/vfspluginAWSS3_macros.h"
} )
configuration( {} )
vpaths { ["Source"] = { "**.c", "**.cpp", "**.cs", "**.asm" } }
files( {
"src/vfspluginAWSS3.cpp",
"src/vfspluginAWSS3_CAwsS3Global.cpp",
"src/vfspluginAWSS3_CS3Archive.cpp",
"src/vfspluginAWSS3_CS3BucketArchive.cpp"
} )
configuration( {} )
includedirs( { "../../../common/include", "../../../dependencies/aws-c-common/include", "../../../dependencies/aws-c-event-stream/include", "../../../dependencies/aws-checksums/include", "../../../dependencies/aws-checksums/include/aws", "../../../dependencies/aws-checksums/include/aws/checksums", "../../../dependencies/aws-checksums/include/aws/checksums/private", "../../../dependencies/aws-cpp-sdk-core/include", "../../../dependencies/aws-cpp-sdk-core/include/aws", "../../../dependencies/aws-cpp-sdk-core/include/aws/core", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/auth", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/client", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/config", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/external", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/external/cjson", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/external/tinyxml2", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/http", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/http/curl", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/http/standard", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/internal", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/monitoring", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/net", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/platform", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/platform/refs", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/base64", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/crypto", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/crypto/bcrypt", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/crypto/commoncrypto", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/crypto/openssl", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/event", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/json", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/logging", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/memory", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/memory/stl", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/ratelimiter", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/stream", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/threading", "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/xml", "../../../dependencies/aws-cpp-sdk-s3/include", "../../../dependencies/aws-cpp-sdk-s3/include/aws", "../../../dependencies/aws-cpp-sdk-s3/include/aws/s3", "../../../dependencies/aws-cpp-sdk-s3/include/aws/s3/model", "../../../dependencies/curl/include", "../../../dependencies/curl/include/curl", "../../../dependencies/curl/lib", "../../../dependencies/curl/lib/vauth", "../../../dependencies/curl/lib/vquic", "../../../dependencies/curl/lib/vssh", "../../../dependencies/curl/lib/vtls", "../../../platform/gucefCORE/include", "../../../platform/gucefMT/include", "../../../platform/gucefVFS/include", "../../SHARED/pluginglueAWSSDK/include", "include" } )
configuration( { "ANDROID" } )
includedirs( { "../../../dependencies/aws-cpp-sdk-core/include/aws/core/utils/logging/android", "../../../platform/gucefCORE/include/android" } )
configuration( { "LINUX32" } )
includedirs( { "../../../platform/gucefCORE/include/linux" } )
configuration( { "LINUX64" } )
includedirs( { "../../../platform/gucefCORE/include/linux" } )
configuration( { "WIN32" } )
includedirs( { "../../../dependencies/aws-cpp-sdk-core/include/aws/core/http/windows", "../../../dependencies/curl/lib", "../../../platform/gucefCORE/include/mswin" } )
configuration( { "WIN64" } )
includedirs( { "../../../dependencies/aws-cpp-sdk-core/include/aws/core/http/windows", "../../../dependencies/curl/lib", "../../../platform/gucefCORE/include/mswin" } )
| apache-2.0 |
kubernetes/ingress-nginx | rootfs/etc/nginx/lua/plugins.lua | 1 | 1682 | local require = require
local ngx = ngx
local ipairs = ipairs
local string_format = string.format
local ngx_log = ngx.log
local INFO = ngx.INFO
local ERR = ngx.ERR
local pcall = pcall
local _M = {}
local MAX_NUMBER_OF_PLUGINS = 20
local plugins = {}
local function load_plugin(name)
local path = string_format("plugins.%s.main", name)
local ok, plugin = pcall(require, path)
if not ok then
ngx_log(ERR, string_format("error loading plugin \"%s\": %s", path, plugin))
return
end
local index = #plugins
if (plugin.name == nil or plugin.name == '') then
plugin.name = name
end
plugins[index + 1] = plugin
end
function _M.init(names)
local count = 0
for _, name in ipairs(names) do
if count >= MAX_NUMBER_OF_PLUGINS then
ngx_log(ERR, "the total number of plugins exceed the maximum number: ", MAX_NUMBER_OF_PLUGINS)
break
end
load_plugin(name)
count = count + 1 -- ignore loading failure, just count the total
end
end
function _M.run()
local phase = ngx.get_phase()
for _, plugin in ipairs(plugins) do
if plugin[phase] then
ngx_log(INFO, string_format("running plugin \"%s\" in phase \"%s\"", plugin.name, phase))
-- TODO: consider sandboxing this, should we?
-- probably yes, at least prohibit plugin from accessing env vars etc
-- but since the plugins are going to be installed by ingress-nginx
-- operator they can be assumed to be safe also
local ok, err = pcall(plugin[phase])
if not ok then
ngx_log(ERR, string_format("error while running plugin \"%s\" in phase \"%s\": %s",
plugin.name, phase, err))
end
end
end
end
return _M
| apache-2.0 |
jshackley/darkstar | scripts/zones/Port_San_dOria/npcs/Avandale.lua | 38 | 1039 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Avandale
-- Type: Standard NPC
-- @zone: 232
-- @pos -105.524 -9 -125.274
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x022b);
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 |
jshackley/darkstar | scripts/zones/Upper_Jeuno/npcs/Zekobi-Morokobi.lua | 38 | 1038 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Zekobi-Morokobi
-- Type: Standard NPC
-- @zone: 244
-- @pos 41.258 -5.999 -74.105
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0057);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
jshackley/darkstar | scripts/zones/Dangruf_Wadi/npcs/Grounds_Tome.lua | 34 | 1133 | -----------------------------------
-- Area: Dangruf Wadi
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_DANGRUF_WADI,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,639,640,641,642,643,644,645,646,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,639,640,641,642,643,644,645,646,0,0,GOV_MSG_DANGRUF_WADI);
end;
| gpl-3.0 |
MeGaTG/amirdb | plugins/tr.lua | 7 | 1365 | do
function translate(source_lang, target_lang, text)
local path = "http://translate.google.com/translate_a/single"
-- URL query parameters
local params = {
client = "gtx",
ie = "UTF-8",
oe = "UTF-8",
hl = "en",
dt = "t",
tl = target_lang or "en",
sl = source_lang or "auto",
q = URL.escape(text)
}
local query = format_http_params(params, true)
local url = path..query
local res, code = https.request(url)
if code > 200 then
return
end
local trans = res:gmatch("%[%[%[\"(.*)\"")():gsub("\"(.*)", "")
return trans
end
function run(msg, matches)
if #matches == 1 then
print("First")
local text = matches[1]
return translate(nil, nil, text)
end
if #matches == 2 then
print("Second")
local target = matches[1]
local text = matches[2]
return translate(nil, target, text)
end
if #matches == 3 then
print("Third")
local source = matches[1]
local target = matches[2]
local text = matches[3]
return translate(source, target, text)
end
end
return {
description = "Translate some text",
usage = {
"[/!]tr text. Translate the text to English.",
"[/!]tra target_lang text.",
"[/!]tr source.target text",
},
patterns = {
"^[/!]tr ([%w]+).([%a]+) (.+)",
"^[/!]tr ([%w]+) (.+)",
"^[/!]tr (.+)",
},
run = run
}
end
| gpl-2.0 |
jshackley/darkstar | scripts/globals/spells/bluemagic/mp_drainkiss.lua | 18 | 1946 | -----------------------------------------
-- Spell: MP Drainkiss
-- Steals an enemy's MP. Ineffective against undead
-- Spell cost: 20 MP
-- Monster Type: Amorphs
-- Spell Type: Magical (Dark)
-- Blue Magic Points: 4
-- Stat Bonus: MP+5
-- Level: 42
-- Casting Time: 4 seconds
-- Recast Time: 90 seconds
-- Magic Bursts on: Compression, Gravitation, Darkness
-- Combos: None
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
-- also have small constant to account for 0 dark skill
local dmg = 5 + 0.375 * (caster:getSkillLevel(BLUE_SKILL) + caster:getMod(79 + BLUE_SKILL));
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),BLUE_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
--add in final adjustments
if (dmg < 0) then
dmg = 0
end
if (target:isUndead()) then
spell:setMsg(75); -- No effect
return dmg;
end
if (target:getMP() > dmg) then
caster:addMP(dmg);
target:delMP(dmg);
else
dmg = target:getMP();
caster:addMP(dmg);
target:delMP(dmg);
end
spell:setMsg(228); --change msg to 'xxx mp drained from the yyyy.'
return dmg;
end; | gpl-3.0 |
jshackley/darkstar | scripts/globals/items/bowl_of_quadav_stew.lua | 35 | 1392 | -----------------------------------------
-- ID: 4569
-- Item: Bowl of Quadav Stew
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Agility -4
-- Vitality 2
-- Defense % 17
-- Defense Cap 60
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4569);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, -4);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_FOOD_DEFP, 17);
target:addMod(MOD_FOOD_DEF_CAP, 60);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, -4);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_FOOD_DEFP, 17);
target:delMod(MOD_FOOD_DEF_CAP, 60);
end;
| gpl-3.0 |
10sa/Advanced-Nutscript | nutscript/plugins/improveddoors/sh_plugin.lua | 1 | 1802 | PLUGIN.name = "개선된 도어 시스템 (Improved Door System)"
PLUGIN.author = "Tensa / Chessnut"
PLUGIN.desc = "기존 도어 플러그인을 개선한 도어 플러그인입니다."
PLUGIN.base = true;
nut.config.doorCost = 50
nut.config.doorSellAmount = 25
function PLUGIN:IsDoor(entity)
local class = string.lower(entity:GetClass() or "");
if (class and (class == "func_door" or class == "func_door_rotating" or class == "prop_door_rotating")) then
return true;
else
return false;
end;
end
AdvNut.util.IsDoor = PLUGIN.IsDoor;
local entityMeta = FindMetaTable("Entity")
function entityMeta:IsDoor()
local class = string.lower(self:GetClass() or "");
if (class and (class == "func_door" or class == "func_door_rotating" or class == "prop_door_rotating")) then
return true;
else
return false;
end;
end;
function entityMeta:GetDoorPartner()
if (!self:IsDoor()) then
error("Attempt to get partner of a non-door entity.")
end
local partners = {}
for k, v in pairs(ents.FindInSphere(self:GetPos(), 128)) do
if (v != self and v:IsDoor()) then
partners[#partners + 1] = v
end
end
return partners
end
function PLUGIN:IsDoorOwned(entity)
if (entity:GetNetVar("owner") != nil) then
return true
else
return false;
end;
end
function PLUGIN:GetDoorOwner(entity)
return entity:GetNetVar("owner")
end
function PLUGIN:EqualDoorOwner(client, entity)
if (client:SteamID() == entity:GetNetVar("owner")) then
return true;
else
return false;
end;
end;
function PLUGIN:SetDoorOwner(entity, client)
if (client) then
entity:SetNetVar("owner", client:SteamID());
else
entity:SetNetVar("owner", nil);
end;
end;
PLUGIN:IncludeDir("language");
nut.util.Include("sh_commands.lua");
nut.util.Include("cl_plugin.lua");
nut.util.Include("sv_plugin.lua"); | mit |
bsmr-games/OpenRA | mods/d2k/maps/atreides-01b/atreides01b.lua | 18 | 4872 |
HarkonnenReinforcements = { }
HarkonnenReinforcements["Easy"] =
{
{ "light_inf", "light_inf" }
}
HarkonnenReinforcements["Normal"] =
{
{ "light_inf", "light_inf" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
}
HarkonnenReinforcements["Hard"] =
{
{ "light_inf", "light_inf" },
{ "trike", "trike" },
{ "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike" },
{ "trike", "trike" }
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves = { }
HarkonnenAttackWaves["Easy"] = 1
HarkonnenAttackWaves["Normal"] = 5
HarkonnenAttackWaves["Hard"] = 12
ToHarvest = { }
ToHarvest["Easy"] = 2500
ToHarvest["Normal"] = 3000
ToHarvest["Hard"] = 3500
AtreidesReinforcements = { "light_inf", "light_inf", "light_inf", "light_inf" }
AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
IdleHunt = function(actor)
if not actor.IsDead then
Trigger.OnIdle(actor, actor.Hunt)
end
end
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > ToHarvest[Map.Difficulty] - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
InitObjectives()
Trigger.OnRemovedFromWorld(AtreidesConyard, function()
local refs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Type == "refinery"
end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Map.Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Map.Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
jshackley/darkstar | scripts/globals/items/anchovy_pizza.lua | 35 | 1225 | -----------------------------------------
-- ID: 5699
-- Item: anchovy_pizza
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Dexterity 1
-- Attack 20%
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5699);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_FOOD_ATTP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_FOOD_ATTP, 20);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.