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 |
|---|---|---|---|---|---|
rpetit3/darkstar | scripts/zones/Monarch_Linn/bcnms/ancient_vows.lua | 13 | 1921 | -----------------------------------
-- Area: Monarch Linn
-- Name: Ancient Vows
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/missions");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
--printf("leavecode: %u",leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0);
else
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1);
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)
if (csid == 0x7d01) then
player:addExp(1000);
player:addTitle(TAVNAZIAN_TRAVELER);
if (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 2) then
player:setVar("VowsDone",1);
player:setVar("PromathiaStatus",0);
player:completeMission(COP,ANCIENT_VOWS);
player:addMission(COP,THE_CALL_OF_THE_WYRMKING);
player:setPos(694,-5.5,-619,74,107); -- To South Gustaberg
end
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/globals/spells/blade_madrigal.lua | 27 | 1568 | -----------------------------------------
-- Spell: Blade Madrigal
-- Gives party members accuracy
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 9;
if (sLvl+iLvl > 130) then
power = power + math.floor((sLvl+iLvl-130) / 18);
end
if (power >= 30) then
power = 30;
end
local iBoost = caster:getMod(MOD_MADRIGAL_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*3;
end
power = power + caster:getMerit(MERIT_MADRIGAL_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MADRIGAL,power,0,duration,caster:getID(), 0, 2)) then
spell:setMsg(75);
end
return EFFECT_MADRIGAL;
end; | gpl-3.0 |
yaser1382/BDReborn | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-3.0 |
MHK-BOT/copy | system/libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
dwmw2/luci | applications/luci-app-asterisk/luasrc/model/cbi/asterisk/phone_sip.lua | 68 | 3603 | -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local ast = require("luci.asterisk")
local function find_outgoing_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "dialplan",
function(s)
if not h[s['.name']] then
c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] }
h[s['.name']] = true
end
end)
return c
end
local function find_incoming_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "sip",
function(s)
if s.context and not h[s.context] and
uci:get_bool("asterisk", s['.name'], "provider")
then
c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context }
h[s.context] = true
end
end)
return c
end
--
-- SIP phone info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Phone Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Phone %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "phones")
)
end
return form
--
-- SIP phone configuration
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Client")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "friend",
qualify = "yes",
host = "dynamic",
nat = "no",
canreinvite = "no"
}
back = peer:option(DummyValue, "_overview", "Back to phone overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "phones")
active = peer:option(Flag, "disable", "Account enabled")
active.enabled = "yes"
active.disabled = "no"
function active.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "yes"
end
exten = peer:option(Value, "extension", "Extension Number")
cbimap.uci:foreach("asterisk", "dialplanexten",
function(s)
exten:value(
s.extension,
"%s (via %s/%s)" %{ s.extension, s.type:upper(), s.target }
)
end)
display = peer:option(Value, "callerid", "Display Name")
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
regtimeout = peer:option(Value, "registertimeout", "Registration Time Value")
function regtimeout.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "60"
end
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
linekey = peer:option(ListValue, "_linekey", "Linekey Mode (broken)")
linekey:value("", "Off")
linekey:value("trunk", "Trunk Appearance")
linekey:value("call", "Call Appearance")
dialplan = peer:option(ListValue, "context", "Assign Dialplan")
dialplan.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans")
for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do
dialplan:value(unpack(v))
end
incoming = peer:option(StaticList, "incoming", "Receive incoming calls from")
for _, v in ipairs(find_incoming_contexts(cbimap.uci)) do
incoming:value(unpack(v))
end
--function incoming.cfgvalue(...)
--error(table.concat(MultiValue.cfgvalue(...),"."))
--end
return cbimap
end
| apache-2.0 |
renchunxiao/luajson | tests/lunit-simple-decode.lua | 4 | 3624 | local json = require("json")
local lunit = require("lunit")
-- Test module for handling the simple decoding that behaves more like expected
module("lunit-simple-decode", lunit.testcase, package.seeall)
function test_decode_simple_undefined()
assert_nil(json.decode('undefined', json.decode.simple))
end
function test_decode_default_undefined()
assert_equal(json.util.undefined, json.decode('undefined'))
end
function test_decode_simple_null()
assert_nil(json.decode('null', json.decode.simple))
end
function test_decode_default_null()
assert_equal(json.util.null, json.decode('null'))
end
function test_decode_array_simple_with_only_null()
local result = assert(json.decode('[null]', json.decode.simple))
assert_nil(result[1])
assert_equal(1, result.n)
end
function test_decode_array_default_with_only_null()
local result = assert(json.decode('[null]'))
assert_equal(json.util.null, result[1])
assert_equal(1, #result)
end
function test_decode_array_simple_with_null()
local result = assert(json.decode('[1, null, 3]', json.decode.simple))
assert_equal(1, result[1])
assert_nil(result[2])
assert_equal(3, result[3])
assert_equal(3, result.n)
end
function test_decode_array_default_with_null()
local result = assert(json.decode('[1, null, 3]'))
assert_equal(1, result[1])
assert_equal(json.util.null, result[2])
assert_equal(3, result[3])
assert_equal(3, #result)
end
function test_decode_small_array_simple_with_trailing_null()
local result = assert(json.decode('[1, null]', json.decode.simple))
assert_equal(1, result[1])
assert_nil(result[2])
assert_equal(2, result.n)
end
function test_decode_small_array_default_with_trailing_null()
local result = assert(json.decode('[1, null]'))
assert_equal(1, result[1])
assert_equal(json.util.null, result[2])
assert_equal(2, #result)
end
function test_decode_small_array_simple_with_trailing_null()
local result = assert(json.decode('[1, null]', json.decode.simple))
assert_equal(1, result[1])
assert_nil(result[2])
assert_equal(2, result.n)
end
function test_decode_small_array_default_with_trailing_null()
local result = assert(json.decode('[1, null]'))
assert_equal(1, result[1])
assert_equal(json.util.null, result[2])
assert_equal(2, #result)
end
function test_decode_array_simple_with_trailing_null()
local result = assert(json.decode('[1, null, 3, null]', json.decode.simple))
assert_equal(1, result[1])
assert_nil(result[2])
assert_equal(3, result[3])
assert_nil(result[4])
assert_equal(4, result.n)
end
function test_decode_array_default_with_trailing_null()
local result = assert(json.decode('[1, null, 3, null]'))
assert_equal(1, result[1])
assert_equal(json.util.null, result[2])
assert_equal(3, result[3])
assert_equal(json.util.null, result[4])
assert_equal(4, #result)
end
function test_decode_object_simple_with_null()
local result = assert(json.decode('{x: null}', json.decode.simple))
assert_nil(result.x)
assert_nil(next(result))
end
function test_decode_object_default_with_null()
local result = assert(json.decode('{x: null}'))
assert_equal(json.util.null, result.x)
assert_not_nil(next(result))
end
function test_decode_object_with_stringized_numeric_keys_default()
local result = assert(json.decode('{"1": "one"}'))
assert_equal("one", result["1"])
assert_equal(nil, result[1])
end
function test_decode_object_with_stringized_numeric_keys_force_numeric()
local result = assert(
json.decode(
'{"1": "one"}',
{ object = { setObjectKey = assert(json.decode.util.setObjectKeyForceNumber) } }
)
)
assert_equal(nil, result["1"])
assert_equal("one", result[1])
end
| mit |
opentechinstitute/luci-commotion-linux | libs/web/luasrc/i18n.lua | 77 | 3182 | --[[
LuCI - Internationalisation
Description:
A very minimalistic but yet effective internationalisation module
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
--- LuCI translation library.
module("luci.i18n", package.seeall)
require("luci.util")
local tparser = require "luci.template.parser"
table = {}
i18ndir = luci.util.libpath() .. "/i18n/"
loaded = {}
context = luci.util.threadlocal()
default = "en"
--- Clear the translation table.
function clear()
end
--- Load a translation and copy its data into the translation table.
-- @param file Language file
-- @param lang Two-letter language code
-- @param force Force reload even if already loaded (optional)
-- @return Success status
function load(file, lang, force)
end
--- Load a translation file using the default translation language.
-- Alternatively load the translation of the fallback language.
-- @param file Language file
-- @param force Force reload even if already loaded (optional)
function loadc(file, force)
end
--- Set the context default translation language.
-- @param lang Two-letter language code
function setlanguage(lang)
context.lang = lang:gsub("_", "-")
context.parent = (context.lang:match("^([a-z][a-z])_"))
if not tparser.load_catalog(context.lang, i18ndir) then
if context.parent then
tparser.load_catalog(context.parent, i18ndir)
return context.parent
end
end
return context.lang
end
--- Return the translated value for a specific translation key.
-- @param key Default translation text
-- @return Translated string
function translate(key)
return tparser.translate(key) or key
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function translatef(key, ...)
return tostring(translate(key)):format(...)
end
--- Return the translated value for a specific translation key
-- and ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translate(...))</code>
-- @param key Default translation text
-- @return Translated string
function string(key)
return tostring(translate(key))
end
--- Return the translated value for a specific translation key and use it as sprintf pattern.
-- Ensure that the returned value is a Lua string value.
-- This is the same as calling <code>tostring(translatef(...))</code>
-- @param key Default translation text
-- @param ... Format parameters
-- @return Translated and formatted string
function stringf(key, ...)
return tostring(translate(key)):format(...)
end
| apache-2.0 |
DDTChen/CookieVLC | vlc/share/lua/playlist/liveleak.lua | 91 | 1883 | --[[
$Id$
Copyright © 2012 VideoLAN and AUTHORS
Authors: Ludovic Fauvet <etix@videolan.org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "www.liveleak.com/view" )
end
-- Util function
function find( haystack, needle )
local _,_,r = string.find( haystack, needle )
return r
end
-- Parse function.
function parse()
local p = {}
local title
local art
local video
while true do
line = vlc.readline()
if not line then break end
-- Try to find the title
if string.match( line, '<span class="section_title"' ) then
title = find( line, '<span class="section_title"[^>]*>(.-)<' )
title = string.gsub( title, ' ', ' ' )
end
-- Try to find the art
if string.match( line, 'image:' ) then
art = find( line, 'image: "(.-)"' )
end
-- Try to find the video
if string.match( line, 'file:' ) then
video = find( line, 'file: "(.-)"' )
end
end
if video then
table.insert( p, { path = video; name = title; arturl = art; } )
end
return p
end
| gpl-2.0 |
rpetit3/darkstar | scripts/globals/fieldsofvalor.lua | 12 | 19354 | -------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/conquest");
-- require("scripts/globals/teleports");
require("scripts/globals/status");
require("scripts/globals/regimereward");
require("scripts/globals/regimeinfo");
require("scripts/globals/common");
-- require("scripts/globals/spell_definitions");
-------------------------------------------------
TABS = 12; -- What is this for? Where is it used?
-- key item IDs
ELITE_TRAINING_INTRODUCTION = 1116;
ELITE_TRAINING_CHAPTER_1 = 1117;
ELITE_TRAINING_CHAPTER_2 = 1118;
ELITE_TRAINING_CHAPTER_3 = 1119;
ELITE_TRAINING_CHAPTER_4 = 1120;
ELITE_TRAINING_CHAPTER_5 = 1121;
ELITE_TRAINING_CHAPTER_6 = 1122;
ELITE_TRAINING_CHAPTER_7 = 1123;
-- EVENT PARAM ID CONSTANTS (change these if even seqs displayed break!)
-- onEventUpdate params
FOV_MENU_PAGE_1 = 18;
FOV_MENU_PAGE_2 = 34;
FOV_MENU_PAGE_3 = 50;
FOV_MENU_PAGE_4 = 66;
FOV_MENU_PAGE_5 = 82;
FOV_MENU_VIEW_REGIME = 1;
FOV_MENU_LEVEL_RANGE = 6;
-- onEventFinish params
FOV_MENU_REGEN = 53;
FOV_MENU_REFRESH = 69;
FOV_MENU_PROTECT = 85;
FOV_MENU_SHELL = 101;
FOV_MENU_DRIED_MEAT = 117;
FOV_MENU_SALTED_FISH = 133;
FOV_MENU_HARD_COOKIE = 149;
FOV_MENU_INSTANT_NOODLES = 165;
FOV_MENU_RERAISE = 37;
FOV_MENU_HOME_NATION = 21;
FOV_MENU_CANCEL_REGIME = 3;
FOV_MENU_REPEAT_REGIME1 = -2147483630; -- 2147483666;
FOV_MENU_REPEAT_REGIME2 = -2147483614; -- 2147483682;
FOV_MENU_REPEAT_REGIME3 = -2147483598; -- 2147483698;
FOV_MENU_REPEAT_REGIME4 = -2147483582; -- 2147483714;
FOV_MENU_REPEAT_REGIME5 = -2147483566; -- 2147483730;
FOV_MENU_ELITE_INTRO = 36;
FOV_MENU_ELITE_CHAP1 = 52;
FOV_MENU_ELITE_CHAP2 = 68;
FOV_MENU_ELITE_CHAP3 = 84;
FOV_MENU_ELITE_CHAP4 = 100;
FOV_MENU_ELITE_CHAP5 = 116;
FOV_MENU_ELITE_CHAP6 = 132;
FOV_MENU_ELITE_CHAP7 = 148;
-- Special Message IDs (these usually don't break)
-- Found in Dialog Tables under "Other>System Messages (4)"
FOV_MSG_KILLED_TARGET = 558;
FOV_MSG_COMPLETED_REGIME = 559;
FOV_MSG_GET_GIL = 565;
FOV_MSG_GET_TABS = 566;
FOV_MSG_BEGINS_ANEW = 643;
-- MESSAGE ID CONSTANTS (msg id of "new training regime registered!": change this if msg ids break!)
FOV_MSG_EAST_RONFAURE = 9767;
FOV_MSG_WEST_RONFAURE = 10346;
FOV_MSG_NORTH_GUSTABERG = 10317;
FOV_MSG_SOUTH_GUSTABERG = 9795;
FOV_MSG_WEST_SARUTA = 10126;
FOV_MSG_EAST_SARUTA = 9840;
FOV_MSG_KONSCHTAT = 9701;
FOV_MSG_TAHRONGI = 9720;
FOV_MSG_LA_THEINE = 10039;
FOV_MSG_PASHHOW = 10611;
FOV_MSG_JUGNER = 10757;
FOV_MSG_MERIPH = 10490;
FOV_MSG_BATALLIA = 9921;
FOV_MSG_SAUROMAGUE = 9711;
FOV_MSG_ROLANBERRY = 9672;
FOV_MSG_VALKURM = 10166;
FOV_MSG_BUBURIMU = 10177;
FOV_MSG_QUFIM = 10252;
FOV_MSG_RUAUN_GARDENS = 9672;
FOV_MSG_BEAUCEDINE = 10649;
FOV_MSG_YUHTUNGA = 9971;
FOV_MSG_YHOATOR = 9920;
FOV_MSG_WEST_ALTEPA = 9731;
FOV_MSG_EAST_ALTEPA = 9868;
FOV_MSG_XARCABARD = 10156;
FOV_MSG_BEHEMOTH = 9362;
FOV_MSG_ZITAH = 10188;
FOV_MSG_ROMAEVE = 9537;
FOV_MSG_TERIGGAN = 10031;
FOV_MSG_SORROWS = 9517;
-- Event IDs
FOV_EVENT_RUAUN_GARDENS = 0x0049;
FOV_EVENT_EAST_RONFAURE = 0x003d;
FOV_EVENT_WEST_RONFAURE = 0x003d;
FOV_EVENT_WEST_SARUTA = 0x0034;
FOV_EVENT_EAST_SARUTA = 0x003d;
FOV_EVENT_NORTH_GUSTABERG = 0x010a;
FOV_EVENT_SOUTH_GUSTABERG = 0x003d;
FOV_EVENT_LA_THEINE = 0x003d;
FOV_EVENT_KONSCHTAT = 0x003d;
FOV_EVENT_TAHRONGI = 0x003d;
FOV_EVENT_PASHHOW = 0x001c;
FOV_EVENT_JUGNER = 0x0020;
FOV_EVENT_MERIPH = 0x002e;
FOV_EVENT_BATALLIA = 0x003d;
FOV_EVENT_SAUROMAGUE = 0x003d;
FOV_EVENT_ROLANBERRY = 0x003d;
FOV_EVENT_VALKURM = 0x002f;
FOV_EVENT_BUBURIMU = 0x0033;
FOV_EVENT_QUFIM = 0x0021;
FOV_EVENT_YUHTUNGA = 0x003d;
FOV_EVENT_YHOATOR = 0x003d;
FOV_EVENT_WEST_ALTEPA = 0x003d;
FOV_EVENT_EAST_ALTEPA = 0x003d; -- test
FOV_EVENT_BEAUCEDINE = 0x00da;
FOV_EVENT_XARCABARD = 0x0030;
FOV_EVENT_BEHEMOTH = 0x003d;
FOV_EVENT_ZITAH = 0x003d;
FOV_EVENT_ROMAEVE = 0x003d;
FOV_EVENT_TERIGGAN = 0x003d; -- test
FOV_EVENT_SORROWS = 0x003d;
----------------------------------
-- Start FoV onTrigger
----------------------------------
function startFov(eventid, player)
if (FIELD_MANUALS == 1) then
local hasRegime = player:getVar("fov_regimeid");
local tabs = player:getCurrency("valor_point");
player:startEvent(eventid, 0, 0, 0, 0, 0, 0, tabs, hasRegime);
end;
end
----------------------------------
-- Update FoV onEventUpdate
----------------------------------
function updateFov(player, csid, menuchoice, r1, r2, r3, r4, r5)
if (menuchoice == FOV_MENU_PAGE_1) then
local info = getRegimeInfo(r1);
player:updateEvent(info[1], info[2], info[3], info[4], 0, info[5], info[6], r1);
elseif (menuchoice == FOV_MENU_PAGE_2) then
local info = getRegimeInfo(r2);
player:updateEvent(info[1], info[2], info[3], info[4], 0, info[5], info[6], r2);
elseif (menuchoice == FOV_MENU_PAGE_3) then
local info = getRegimeInfo(r3);
player:updateEvent(info[1], info[2], info[3], info[4], 0, info[5], info[6], r3);
elseif (menuchoice == FOV_MENU_PAGE_4) then
local info = getRegimeInfo(r4);
player:updateEvent(info[1], info[2], info[3], info[4], 0, info[5], info[6], r4);
elseif (menuchoice == FOV_MENU_PAGE_5) then
local info = getRegimeInfo(r5);
player:updateEvent(info[1], info[2], info[3], info[4], 0, info[5], info[6], r5);
elseif (menuchoice == FOV_MENU_VIEW_REGIME) then -- View Regime (this option is only available if they have a regime active!)
-- get regime id and numbers killed...
local regid = player:getVar("fov_regimeid");
local info = getRegimeInfo(regid);
if (info[1] ~= 0) then n1 = player:getVar("fov_numkilled1"); else n1 = 0; end;
if (info[2] ~= 0) then n2 = player:getVar("fov_numkilled2"); else n2 = 0; end;
if (info[3] ~= 0) then n3 = player:getVar("fov_numkilled3"); else n3 = 0; end;
if (info[4] ~= 0) then n4 = player:getVar("fov_numkilled4"); else n4 = 0; end;
player:updateEvent(info[1], info[2], info[3], info[4], n1, n2, n3, n4);
elseif (menuchoice == FOV_MENU_LEVEL_RANGE) then -- Level range and training area on View Regime...
local regid = player:getVar("fov_regimeid");
local info = getRegimeInfo(regid);
player:updateEvent(0, 0, 0, 0, 0, info[5], info[6], 0);
end
end
------------------------------------------
-- Finish FoV onEventFinish
------------------------------------------
function finishFov(player, csid, option, r1, r2, r3, r4, r5, msg_offset)
local msg_accept = msg_offset;
local msg_jobs = msg_offset + 1;
local msg_cancel = msg_offset +2;
local tabs = player:getCurrency("valor_point");
local HAS_FOOD = player:hasStatusEffect(EFFECT_FOOD);
local HAS_SUPPORT_FOOD = player:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD);
local fov_repeat = bit.band(option, 0x80000000);
if (fov_repeat ~= 0) then
fov_repeat = 1;
end
option = bit.band(option, 0x7FFFFFFF);
-- ================= FIELD SUPPORT ===============================================
if (option == FOV_MENU_REGEN) then -- Chose Regen. Regen from FoV removes all forms of regen.
-- Decrease tabs
if (tabs >= 20) then
player:delCurrency("valor_point", 20);
-- Removes regen if on player
player:delStatusEffect(EFFECT_REGEN);
-- Adds regen
player:addStatusEffect(EFFECT_REGEN, 1, 3, 3600);
end
elseif (option == FOV_MENU_REFRESH) then -- Chose Refresh, removes all other refresh.
-- Decrease tabs
if (tabs >= 20) then
player:delCurrency("valor_point", 20);
-- Removes refresh if on player
player:delStatusEffect(EFFECT_REFRESH);
player:delStatusEffect(EFFECT_SUBLIMATION_COMPLETE);
player:delStatusEffect(EFFECT_SUBLIMATION_ACTIVATED);
-- Add refresh
player:addStatusEffect(EFFECT_REFRESH, 1, 3, 3600, 0, 3);
end
elseif (option == FOV_MENU_PROTECT) then -- Chose Protect, removes all other protect.
-- Decrease tabs
if (tabs >= 15) then
player:delCurrency("valor_point", 15);
-- Removes protect if on player
player:delStatusEffect(EFFECT_PROTECT);
-- Work out how much def to give (highest tier dependant on level)
local def = 0;
if (player:getMainLvl() < 27) then -- before protect 2, give protect 1
def = 15;
elseif (player:getMainLvl() < 47) then -- after p2, before p3
def = 40;
elseif (player:getMainLvl() < 63) then -- after p3, before p4
def = 75;
else -- after p4
def = 120;
end
-- Add protect
player:addStatusEffect(EFFECT_PROTECT, def, 0, 1800);
end
elseif (option == FOV_MENU_SHELL) then -- Chose Shell, removes all other shell.
-- Decrease tabs
if (tabs >= 15) then
player:delCurrency("valor_point", 15);
-- Removes shell if on player
player:delStatusEffect(EFFECT_SHELL);
-- Work out how much mdef to give (highest tier dependant on level)
-- values taken from Shell scripts by Tenjou.
local def = 0;
if (player:getMainLvl() < 37) then -- before shell 2, give shell 1
def = 9;
elseif (player:getMainLvl() < 57) then -- after s2, before s3
def = 14;
elseif (player:getMainLvl() < 68) then -- after s3, before s4
def = 19;
else -- after s4
def = 22;
end
-- Add shell
player:addStatusEffect(EFFECT_SHELL, def, 0, 1800);
end
elseif (option == FOV_MENU_RERAISE) then -- Reraise chosen.
-- Decrease tabs
if (tabs >= 10) then
player:delCurrency("valor_point", 10);
-- Remove any other RR
player:delStatusEffect(EFFECT_RERAISE);
-- apply RR1, 2 hour duration.
player:addStatusEffect(EFFECT_RERAISE, 1, 0, 7200);
end
elseif (option == FOV_MENU_HOME_NATION) then -- Return to home nation.
-- Decrease tabs
if (tabs >= 50) then
player:delCurrency("valor_point", 50);
toHomeNation(player); -- Needs an entry in scripts/globals/teleports.lua?
end
elseif (option == FOV_MENU_DRIED_MEAT) then -- Dried Meat: STR+4, Attack +22% (caps at 63)
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 1, 0, 1800);
end
end
elseif (option == FOV_MENU_SALTED_FISH) then -- Salted Fish: VIT+2 DEF+30% (Caps at 86)
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 2, 0, 1800);
end
end
elseif (option == FOV_MENU_HARD_COOKIE) then --- Hard Cookie: INT+4, MaxMP+30
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 3, 0, 1800);
end
end
elseif (option == FOV_MENU_INSTANT_NOODLES) then -- Instant Noodles: VIT+1, Max HP+27% (caps at 75), StoreTP+5
if (tabs >= 50) then
if (HAS_FOOD == true or HAS_SUPPORT_FOOD == true) then
player:messageBasic(246);
else
player:delCurrency("valor_point", 50);
player:addStatusEffectEx(EFFECT_FIELD_SUPPORT_FOOD, 251, 4, 0, 1800);
end
end
elseif (option == FOV_MENU_CANCEL_REGIME) then -- Cancelled Regime.
player:setVar("fov_regimeid" , 0);
player:setVar("fov_numkilled1", 0);
player:setVar("fov_numkilled2", 0);
player:setVar("fov_numkilled3", 0);
player:setVar("fov_numkilled4", 0);
player:showText(player, msg_cancel);
elseif (option == FOV_MENU_PAGE_1) then -- Page 1
writeRegime(player, r1, msg_accept, msg_jobs, fov_repeat);
elseif (option == FOV_MENU_PAGE_2) then -- Page 2
writeRegime(player, r2, msg_accept, msg_jobs, fov_repeat);
elseif (option == FOV_MENU_PAGE_3) then -- Page 3
writeRegime(player, r3, msg_accept, msg_jobs, fov_repeat);
elseif (option == FOV_MENU_PAGE_4) then -- Page 4
writeRegime(player, r4, msg_accept, msg_jobs, fov_repeat);
elseif (option == FOV_MENU_PAGE_5) then -- Page 5
writeRegime(player, r5, msg_accept, msg_jobs, fov_repeat);
elseif (option == FOV_MENU_ELITE_INTRO) then -- Want elite, 100tabs
-- giveEliteRegime(player, ELITE_TRAINING_CHAPTER_7, 100);
elseif (option == FOV_MENU_ELITE_CHAP1) then -- Want elite, 150tabs
-- local tabs = player:getVar("tabs");
-- local newtabs = tabs-150;
-- player:setVar("tabs", newtabs);
elseif (option == FOV_MENU_ELITE_CHAP2) then -- Want elite, 200tabs
-- local tabs = player:getVar("tabs");
-- local newtabs = tabs-200;
-- player:setVar("tabs", newtabs);
elseif (option == FOV_MENU_ELITE_CHAP3) then -- Want elite, 250tabs
elseif (option == FOV_MENU_ELITE_CHAP4) then -- Want elite, 300tabs
elseif (option == FOV_MENU_ELITE_CHAP5) then -- Want elite, 350tabs
elseif (option == FOV_MENU_ELITE_CHAP6) then -- Want elite, 400tabs
elseif (option == FOV_MENU_ELITE_CHAP7) then -- Want elite, 450tabs
else
-- print("opt is "..option);
end
end
function giveEliteRegime(player, keyitem, cost)
if (player:hasKeyItem(keyitem)) then
-- print("has");
-- player:messageBasic(98, keyitem);
else
player:delCurrency("valor_point", cost);
player:addKeyItem(keyitem);
end
end
-----------------------------------
-- Writes the chosen Regime to the SQL database
-----------------------------------
function writeRegime(player, rid, msg_accept, msg_jobs, regrepeat)
local info = getRegimeInfo(rid);
player:setVar("fov_regimeid", rid);
player:setVar("fov_repeat", regrepeat);
for i = 1, 4 do
player:setVar("fov_numkilled"..i, 0);
player:setVar("fov_numneeded"..i, info[i]);
end;
player:showText(player, msg_accept);
player:showText(player, msg_jobs);
end
-----------------------------------
-- player, mob, regime ID, index in the list of mobs to kill that this mob corresponds to (1-4)
-----------------------------------
function checkRegime(player, mob, rid, index)
-- dead people get no point
if (player == nil or player:getHP() == 0) then
return;
end
local partyType = player:checkSoloPartyAlliance();
if (player:checkFovAllianceAllowed() == 1) then
partyType = 1;
end
if (player:getVar("fov_regimeid") == rid) then -- player is doing this regime
-- Need to add difference because a lvl1 can xp with a level 75 at ro'maeve
local difference = math.abs(mob:getMainLvl() - player:getMainLvl());
if (partyType < 2 and (mob:getBaseExp() > 0 or LOW_LEVEL_REGIME == 1) and difference <= 15 and (player:checkDistance(mob) < 100 or player:checkFovDistancePenalty() == 0)) then
-- get the number of mobs needed/killed
local needed = player:getVar("fov_numneeded"..index);
local killed = player:getVar("fov_numkilled"..index);
if (killed < needed) then -- increment killed number and save.
killed = killed + 1;
player:messageBasic(FOV_MSG_KILLED_TARGET, killed, needed);
player:setVar("fov_numkilled"..index, killed);
if (killed == needed) then
local fov_info = getRegimeInfo(rid);
local k1 = player:getVar("fov_numkilled1");
local k2 = player:getVar("fov_numkilled2");
local k3 = player:getVar("fov_numkilled3");
local k4 = player:getVar("fov_numkilled4");
if (k1 == fov_info[1] and k2 == fov_info[2] and k3 == fov_info[3] and k4 == fov_info[4]) then
-- complete regime
player:messageBasic(FOV_MSG_COMPLETED_REGIME);
local reward = getFoVregimeReward(rid);
local tabs = (math.floor(reward / 10) * TABS_RATE);
local VanadielEpoch = vanaDay();
-- Award gil and tabs once per day.
if (player:getVar("fov_LastReward") < VanadielEpoch) then
player:messageBasic(FOV_MSG_GET_GIL, reward);
player:addGil(reward);
player:addCurrency("valor_point", tabs);
player:messageBasic(FOV_MSG_GET_TABS, tabs, player:getCurrency("valor_point")); -- Careful about order.
if (REGIME_WAIT == 1) then
player:setVar("fov_LastReward", VanadielEpoch);
end
end
-- TODO: display msgs (based on zone annoyingly, so will need player:getZoneID() then a lookup)
player:addExp(reward);
if (k1 ~= 0) then player:setVar("fov_numkilled1", 0); end
if (k2 ~= 0) then player:setVar("fov_numkilled2", 0); end
if (k3 ~= 0) then player:setVar("fov_numkilled3", 0); end
if (k4 ~= 0) then player:setVar("fov_numkilled4", 0); end
if (player:getVar("fov_repeat") ~= 1) then
player:setVar("fov_regimeid", 0);
player:setVar("fov_numneeded1", 0);
player:setVar("fov_numneeded2", 0);
player:setVar("fov_numneeded3", 0);
player:setVar("fov_numneeded4", 0);
else
player:messageBasic(FOV_MSG_BEGINS_ANEW);
end
end
end
end
end
end
end
| gpl-3.0 |
vlapsley/outback | mods/plantlife/vines/functions.lua | 1 | 4309 | -- support for i18n
local S = plantlife_i18n.gettext
vines.register_vine = function( name, defs, biome )
local groups = { vines=1, snappy=3, flammable=2 }
local vine_name_end = 'vines:'..name..'_end'
local vine_name_middle = 'vines:'..name..'_middle'
local vine_image_end = "vines_"..name.."_end.png"
local vine_image_middle = "vines_"..name.."_middle.png"
local drop_node = vine_name_end
biome.spawn_plants = { vine_name_end }
local vine_group = 'group:'..name..'_vines'
biome.spawn_surfaces[ #biome.spawn_surfaces + 1 ] = vine_group
local selection_box = { type = "wallmounted", }
local drawtype = 'signlike'
if ( not biome.spawn_on_side ) then
--different properties for bottom and side vines.
selection_box = { type = "fixed", fixed = { -0.4, -1/2, -0.4, 0.4, 1/2, 0.4 }, }
drawtype = 'plantlike'
end
minetest.register_node( vine_name_end, {
description = defs.description,
walkable = false,
climbable = true,
wield_image = vine_image_end,
drop = "",
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "wallmounted",
buildable_to = false,
tiles = { vine_image_end },
drawtype = drawtype,
inventory_image = vine_image_end,
groups = groups,
sounds = default.node_sound_leaves_defaults(),
selection_box = selection_box,
on_construct = function( pos )
local timer = minetest.get_node_timer( pos )
timer:start( math.random(5, 10) )
end,
on_timer = function( pos )
local node = minetest.get_node( pos )
local bottom = {x=pos.x, y=pos.y-1, z=pos.z}
local bottom_node = minetest.get_node( bottom )
if bottom_node.name == "air" then
if not ( math.random( defs.average_length ) == 1 ) then
minetest.set_node( pos, { name = vine_name_middle, param2 = node.param2 } )
minetest.set_node( bottom, { name = node.name, param2 = node.param2 } )
local timer = minetest.get_node_timer( bottom_node )
timer:start( math.random(5, 10) )
end
end
end,
after_dig_node = function(pos, node, oldmetadata, user)
vines.dig_vine( pos, drop_node, user )
end
})
minetest.register_node( vine_name_middle, {
description = S("Matured").." "..defs.description,
walkable = false,
climbable = true,
drop = "",
sunlight_propagates = true,
paramtype = "light",
paramtype2 = "wallmounted",
buildable_to = false,
tiles = { vine_image_middle },
wield_image = vine_image_middle,
drawtype = drawtype,
inventory_image = vine_image_middle,
groups = groups,
sounds = default.node_sound_leaves_defaults(),
selection_box = selection_box,
on_destruct = function( pos )
local bottom = {x=pos.x, y=pos.y-1, z=pos.z}
local bottom_node = minetest.get_node( bottom )
if minetest.get_item_group( bottom_node.name, "vines") > 0 then
minetest.after( 0, minetest.remove_node, bottom )
end
end,
after_dig_node = function( pos, node, oldmetadata, user )
vines.dig_vine( pos, drop_node, user )
end
})
biome_lib:spawn_on_surfaces( biome )
local override_nodes = function( nodes, def )
local function override( index, registered )
local node = nodes[ index ]
if index > #nodes then return registered end
if minetest.registered_nodes[node] then
minetest.override_item( node, def )
registered[#registered+1] = node
end
override( index+1, registered )
end
override( 1, {} )
end
override_nodes( biome.spawn_surfaces,{
on_destruct = function( pos )
local pos_min = { x = pos.x -1, y = pos.y - 1, z = pos.z - 1 }
local pos_max = { x = pos.x +1, y = pos.y + 1, z = pos.z + 1 }
local positions = minetest.find_nodes_in_area( pos_min, pos_max, "group:vines" )
for index, position in pairs(positions) do
minetest.remove_node( position )
end
end
})
end
vines.dig_vine = function( pos, node_name, user )
--only dig give the vine if shears are used
if not user then return false end
local wielded = user:get_wielded_item()
if 'vines:shears' == wielded:get_name() then
local inv = user:get_inventory()
if inv then
inv:add_item("main", ItemStack( node_name ))
end
end
end
| lgpl-2.1 |
tommo/gii | template/game/lib/mock/component/Audio.lua | 1 | 5245 | module 'mock'
--------------------------------------------------------------------
--SOUND Listener
--------------------------------------------------------------------
--TODO: add multiple listener support (need host works) ?
CLASS: SoundListener ()
:MODEL{
Field 'forward' :type('vec3') :getset('VectorForward');
Field 'up' :type('vec3') :getset('VectorUp') ;
}
wrapWithMoaiTransformMethods( SoundListener, '_listener' )
function SoundListener:__init()
local listener = MOAIFmodEventMgr.getMicrophone()
self._listener = listener
self:setVectorForward( 0,0,-1 )
self:setVectorUp( 0,1,0 )
self.transformHookNode = MOAIScriptNode.new()
end
function SoundListener:onAttach( entity )
entity:_attachTransform( self._listener )
end
function SoundListener:onDetach( entity )
-- do nothing...
end
function SoundListener:getVectorForward()
return unpack( self.forward )
end
function SoundListener:setVectorForward( x,y,z )
self.forward = { x,y,z }
self._listener:setVectorForward( x,y,z )
end
function SoundListener:getVectorUp()
return unpack( self.up )
end
function SoundListener:setVectorUp( x,y,z )
self.up = { x,y,z }
self._listener:setVectorUp( x,y,z )
end
registerComponent( 'SoundListener', SoundListener )
--------------------------------------------------------------------
--SOUND SOURCE
--------------------------------------------------------------------
CLASS: SoundSource ()
:MODEL{
Field 'defaultClip' :asset('fmod_event') :getset('DefaultClip');
Field 'autoPlay' :boolean();
Field 'is3D' :boolean();
}
function SoundSource:__init()
self.eventInstances = {}
self.eventNamePrefix = false
self.is3D = true
self.loopSound = true
end
function SoundSource:onAttach( entity )
end
function SoundSource:onDetach( entity )
for evt, k in pairs( self.eventInstances ) do
evt:stop()
end
self.eventInstances = nil
end
function SoundSource:setDefaultClip( path )
self.defaultClipPath = path
end
function SoundSource:getDefaultClip()
return self.defaultClipPath
end
function SoundSource:onStart()
if self.autoPlay then self:start() end
end
function SoundSource:setEventPrefix( prefix )
self.eventNamePrefix = prefix or false
end
function SoundSource:start()
if self.defaultClipPath then
if self.is3D then
return self:playEvent3D( self.defaultClipPath )
else
return self:playEvent2D( self.defaultClipPath )
end
end
end
--------------------------------------------------------------------
local inheritLoc = inheritLoc
function SoundSource:_addInstance( evt, follow )
self:clearInstances()
self.eventInstances[ evt ] = true
if follow then
self._entity:_attachTransform( evt )
evt:forceUpdate()
end
return evt
end
local function _affirmFmodEvent( event )
if not event then return nil end
if type( event ) == 'string' then
event, node = loadAsset( event )
if node and node.type == 'fmod_event' then return event:getFullName() end
else
return event:getFullName()
end
_error( 'unknown sound event type:', event )
return nil
end
function SoundSource:_playEvent3DAt( event, x,y,z, follow, looped )
local eventId = _affirmFmodEvent( event )
if not eventId then return false end
local evt
evt = MOAIFmodEventMgr.playEvent3D( eventId, x,y,z )
if evt then
return self:_addInstance( evt, follow~=false )
else
_error( 'sound event not found:', eventId )
end
end
function SoundSource:_playEvent2D( event, looped )
local eventId = _affirmFmodEvent( event )
if not eventId then return false end
local evt = MOAIFmodEventMgr.playEvent2D( eventId, looped )
if evt then
return self:_addInstance( evt, false )
else
_error( 'sound event not found:', eventId )
end
end
--------------------------------------------------------------------
function SoundSource:playEvent3DAt( event, x,y,z, follow )
return self:_playEvent3DAt( event, x,y,z, follow, nil )
end
function SoundSource:playEvent3D( event, follow )
local x,y,z
self._entity:forceUpdate()
x,y,z = self._entity:getWorldLoc()
return self:playEvent3DAt( event, x,y,z, follow )
end
function SoundSource:playEvent2D( event )
return self:_playEvent2D( event, nil )
end
function SoundSource:loopEvent3DAt( event, x,y,z, follow )
return self:_playEvent3DAt( event, x,y,z, follow, true )
end
function SoundSource:loopEvent3D( event, follow )
local x,y,z
x,y,z = self._entity:getWorldLoc()
return self:loopEvent3DAt( event, x,y,z, follow )
end
function SoundSource:loopEvent2D( event )
return self:_playEvent2D( event, true )
end
--------------------------------------------------------------------
function SoundSource:isBusy()
self:clearInstances()
return next(self.eventInstances) ~= nil
end
function SoundSource:clearInstances()
if not self.eventInstances then return end
local t1 = {}
for evt, k in pairs( self.eventInstances ) do
if evt:isValid() then
t1[ evt ] = k
end
end
self.eventInstances = t1
end
--------------------------------------------------------------------
function SoundSource:onBuildGizmo()
local giz = mock_edit.IconGizmo()
giz:setIcon( 'sound.png' )
giz:setTransform( self._entity:getProp() )
return giz
end
registerComponent( 'SoundSource', SoundSource )
--------------------------------------------------------------------
| mit |
ddouglascarr/rooset | lffrontend/app/main/index/_sidebar_units.lua | 1 | 3993 | local member = param.get ( "member", "table" )
local unit = app.unit
ui.sidebar ( "tab-whatcanido units", function ()
local areas_selector = Area:new_selector()
:reset_fields()
:add_field("area.id", nil, { "grouped" })
:add_field("area.unit_id", nil, { "grouped" })
:add_field("area.name", nil, { "grouped" })
:add_where{ "area.unit_id = ?", unit.id }
:add_where{ "area.active" }
:add_order_by("area.name")
if member then
areas_selector:left_join (
"membership", nil,
{ "membership.area_id = area.id AND membership.member_id = ?", member.id }
)
areas_selector:add_field("membership.member_id NOTNULL", "subscribed", { "grouped" })
end
local areas = areas_selector:exec()
if member then
areas:load_delegation_info_once_for_member_id(member.id)
end
if #areas > 0 then
ui.container {
attr = { class = "sidebarHead" },
content = function ()
ui.heading { level = 2, content = function ()
ui.link {
attr = { class = "unit" },
module = "unit", view = "show", id = unit.id,
content = unit.name
}
if member then
local delegation = Delegation:by_pk(member.id, unit.id, nil, nil)
if delegation then
ui.link {
module = "delegation", view = "show", params = {
unit_id = unit.id
},
attr = { class = "delegation_info" },
content = function ()
ui.delegation(delegation.trustee_id, delegation.trustee.name)
end
}
end
end
end }
end
}
ui.tag { tag = "div", attr = { class = "areas areas-" .. unit.id }, content = function ()
local any_subscribed = false
local subscribed_count = 0
for i, area in ipairs(areas) do
local class = "sidebarRow"
class = class .. (not area.subscribed and " disabled" or "")
ui.tag { tag = "div", attr = { class = class }, content = function ()
if area.subscribed then
local text = _"subscribed"
ui.image { attr = { class = "icon16 star", alt = text, title = text }, static = "icons/48/star.png" }
any_subscribed = true
subscribed_count = subscribed_count +1
end
if member then
local delegation = Delegation:by_pk(member.id, nil, area.id, nil)
if delegation then
ui.link {
module = "delegation", view = "show", params = {
area_id = area.id
},
attr = { class = "delegation_info" },
content = function ()
ui.delegation(delegation.trustee_id, delegation.trustee_id and delegation.trustee.name)
end
}
end
end
slot.put ( " " )
ui.link {
attr = { class = "area" },
module = "area", view = "show", id = area.id,
content = area.name
}
end }
end
if subscribed_count < #areas then
local text
if any_subscribed then
text = _"show other subject areas"
else
text = _"show subject areas"
end
ui.script{ script = "$('.areas-" .. unit.id .. "').addClass('folded');" }
ui.tag { tag = "div", attr = { class = "sidebarRow moreLink whenfolded" }, content = function ()
ui.link {
attr = {
onclick = "$('.areas-" .. unit.id .. "').removeClass('folded'); return false;"
},
text = text
}
end }
ui.tag { tag = "div", attr = { class = "sidebarRow moreLink whenunfolded" }, content = function ()
ui.link {
attr = {
onclick = "$('.areas-" .. unit.id .. "').addClass('folded'); return false;"
},
text = _"collapse subject areas"
}
end }
end
end }
end
end )
| mit |
rpetit3/darkstar | scripts/zones/Port_San_dOria/npcs/HomePoint#3.lua | 27 | 1266 | -----------------------------------
-- Area: Port San dOria
-- NPC: HomePoint#3
-- @pos -6 -13 -150 232
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fe, 8);
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 == 0x21fe) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/globals/items/slice_of_dragon_meat.lua | 18 | 1345 | -----------------------------------------
-- ID: 4272
-- Item: slice_of_dragon_meat
-- Food Effect: 5Min, Galka only
-----------------------------------------
-- Strength 6
-- Intelligence -8
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_MEAT) == 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,4272);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 6);
target:addMod(MOD_INT, -8);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 6);
target:delMod(MOD_INT, -8);
end;
| gpl-3.0 |
vseledkin/april-ann | packages/imaging/interest_points/test/testAreaPixel.lua | 3 | 1224 | imgFile = "sample_iam.png"
pointsFile = "sample_iam.txt"
img = ImageIO.read(imgFile):to_grayscale()
points = {{},{},{},{},{}}
-- Open the interest points list
for line in io.open(pointsFile, "r"):lines() do
point = map(tonumber, ipairs(string.tokenize(line)))
if point[3] <= 5 then
table.insert(points[point[3]], point)
end
end
for i,v in ipairs(points) do
print (i, #v)
end
result = interest_points.classify_pixel(img, points[1],
points[2],points[4], points[5])
ImageIO.write(result,"classified.png", "png")
-- Load The dataset image
local m_indexes = interest_points.get_indexes_from_colored(result)
local num_classes = 3;
w,h = result:geometry()
print(w, h)
local dsIndex = dataset.identity(num_classes)
local dsPositions = dataset.matrix(m_indexes,{
patternSize = {1,1},
offset = {0,0},
numSteps = {m_indexes:dim(1),1},
})
local dsTags = dataset.matrix(m_indexes,{
patternSize = {1,1},
offset = {0,1},
numSteps = {m_indexes:dim(1),1},
})
local dsSoftmax = dataset.indexed(dsTags, {dsIndex})
local computed = interest_points.get_image_area_from_dataset(dsSoftmax, dsPositions, w, h)
ImageIO.write(computed,"computed.png", "png")
| gpl-3.0 |
askore/LootSecretary | src/lua/Libs/AceGUI-3.0/widgets/AceGUIWidget-ColorPicker.lua | 3 | 5744 | --[[-----------------------------------------------------------------------------
ColorPicker Widget
-------------------------------------------------------------------------------]]
local Type, Version = "ColorPicker", 23
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
local IsLegion = select(4, GetBuildInfo()) >= 70000
-- Lua APIs
local pairs = pairs
-- WoW APIs
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: ShowUIPanel, HideUIPanel, ColorPickerFrame, OpacitySliderFrame
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
local function ColorCallback(self, r, g, b, a, isAlpha)
if not self.HasAlpha then
a = 1
end
self:SetColor(r, g, b, a)
if ColorPickerFrame:IsVisible() then
--colorpicker is still open
self:Fire("OnValueChanged", r, g, b, a)
else
--colorpicker is closed, color callback is first, ignore it,
--alpha callback is the final call after it closes so confirm now
if isAlpha then
self:Fire("OnValueConfirmed", r, g, b, a)
end
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 ColorSwatch_OnClick(frame)
HideUIPanel(ColorPickerFrame)
local self = frame.obj
if not self.disabled then
ColorPickerFrame:SetFrameStrata("FULLSCREEN_DIALOG")
ColorPickerFrame:SetFrameLevel(frame:GetFrameLevel() + 10)
ColorPickerFrame:SetClampedToScreen(true)
ColorPickerFrame.func = function()
local r, g, b = ColorPickerFrame:GetColorRGB()
local a = 1 - OpacitySliderFrame:GetValue()
ColorCallback(self, r, g, b, a)
end
ColorPickerFrame.hasOpacity = self.HasAlpha
ColorPickerFrame.opacityFunc = function()
local r, g, b = ColorPickerFrame:GetColorRGB()
local a = 1 - OpacitySliderFrame:GetValue()
ColorCallback(self, r, g, b, a, true)
end
local r, g, b, a = self.r, self.g, self.b, self.a
if self.HasAlpha then
ColorPickerFrame.opacity = 1 - (a or 0)
end
ColorPickerFrame:SetColorRGB(r, g, b)
ColorPickerFrame.cancelFunc = function()
ColorCallback(self, r, g, b, a, true)
end
ShowUIPanel(ColorPickerFrame)
end
AceGUI:ClearFocus()
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetHeight(24)
self:SetWidth(200)
self:SetHasAlpha(false)
self:SetColor(0, 0, 0, 1)
self:SetDisabled(nil)
self:SetLabel(nil)
end,
-- ["OnRelease"] = nil,
["SetLabel"] = function(self, text)
self.text:SetText(text)
end,
["SetColor"] = function(self, r, g, b, a)
self.r = r
self.g = g
self.b = b
self.a = a or 1
self.colorSwatch:SetVertexColor(r, g, b, a)
end,
["SetHasAlpha"] = function(self, HasAlpha)
self.HasAlpha = HasAlpha
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if self.disabled then
self.frame:Disable()
self.text:SetTextColor(0.5, 0.5, 0.5)
else
self.frame:Enable()
self.text:SetTextColor(1, 1, 1)
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Button", nil, UIParent)
frame:Hide()
frame:EnableMouse(true)
frame:SetScript("OnEnter", Control_OnEnter)
frame:SetScript("OnLeave", Control_OnLeave)
frame:SetScript("OnClick", ColorSwatch_OnClick)
local colorSwatch = frame:CreateTexture(nil, "OVERLAY")
colorSwatch:SetWidth(19)
colorSwatch:SetHeight(19)
colorSwatch:SetTexture("Interface\\ChatFrame\\ChatFrameColorSwatch")
colorSwatch:SetPoint("LEFT")
local texture = frame:CreateTexture(nil, "BACKGROUND")
texture:SetWidth(16)
texture:SetHeight(16)
if IsLegion then
texture:SetColorTexture(1, 1, 1)
else
texture:SetTexture(1, 1, 1)
end
texture:SetPoint("CENTER", colorSwatch)
texture:Show()
local checkers = frame:CreateTexture(nil, "BACKGROUND")
checkers:SetWidth(14)
checkers:SetHeight(14)
checkers:SetTexture("Tileset\\Generic\\Checkers")
checkers:SetTexCoord(.25, 0, 0.5, .25)
checkers:SetDesaturated(true)
checkers:SetVertexColor(1, 1, 1, 0.75)
checkers:SetPoint("CENTER", colorSwatch)
checkers:Show()
local text = frame:CreateFontString(nil,"OVERLAY","GameFontHighlight")
text:SetHeight(24)
text:SetJustifyH("LEFT")
text:SetTextColor(1, 1, 1)
text:SetPoint("LEFT", colorSwatch, "RIGHT", 2, 0)
text:SetPoint("RIGHT")
--local highlight = frame:CreateTexture(nil, "HIGHLIGHT")
--highlight:SetTexture("Interface\\QuestFrame\\UI-QuestTitleHighlight")
--highlight:SetBlendMode("ADD")
--highlight:SetAllPoints(frame)
local widget = {
colorSwatch = colorSwatch,
text = text,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| apache-2.0 |
atkinson137/lootmasterplus | Libs/AceGUI-3.0/widgets/AceGUIWidget-Heading.lua | 68 | 2216 | --[[-----------------------------------------------------------------------------
Heading Widget
-------------------------------------------------------------------------------]]
local Type, Version = "Heading", 20
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 pairs = pairs
-- WoW APIs
local CreateFrame, UIParent = CreateFrame, UIParent
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
self:SetText()
self:SetFullWidth()
self:SetHeight(18)
end,
-- ["OnRelease"] = nil,
["SetText"] = function(self, text)
self.label:SetText(text or "")
if text and text ~= "" then
self.left:SetPoint("RIGHT", self.label, "LEFT", -5, 0)
self.right:Show()
else
self.left:SetPoint("RIGHT", -3, 0)
self.right:Hide()
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local label = frame:CreateFontString(nil, "BACKGROUND", "GameFontNormal")
label:SetPoint("TOP")
label:SetPoint("BOTTOM")
label:SetJustifyH("CENTER")
local left = frame:CreateTexture(nil, "BACKGROUND")
left:SetHeight(8)
left:SetPoint("LEFT", 3, 0)
left:SetPoint("RIGHT", label, "LEFT", -5, 0)
left:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
left:SetTexCoord(0.81, 0.94, 0.5, 1)
local right = frame:CreateTexture(nil, "BACKGROUND")
right:SetHeight(8)
right:SetPoint("RIGHT", -3, 0)
right:SetPoint("LEFT", label, "RIGHT", 5, 0)
right:SetTexture("Interface\\Tooltips\\UI-Tooltip-Border")
right:SetTexCoord(0.81, 0.94, 0.5, 1)
local widget = {
label = label,
left = left,
right = right,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| mit |
rpetit3/darkstar | scripts/zones/West_Sarutabaruta_[S]/mobs/Ramponneau.lua | 2 | 1919 | -----------------------------------
-- Area: West Sarutabaruta (S)
-- NM: Ramponneau
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:setMobMod(MOBMOD_ADD_EFFECT, mob:getShortID());
mob:addStatusEffect(EFFECT_SHOCK_SPIKES, 10, 0, 0);
mob:getStatusEffect(EFFECT_SHOCK_SPIKES):setFlag(32);
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
mob:SetMobAbilityEnabled(false);
end;
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(mob,target,damage)
local power = math.random(4,15);
local params = {};
params.bonusmab = 0;
params.includemab = false;
power = addBonusesAbility(mob, ELE_ICE, target, power, params);
power = power * applyResistanceAddEffect(mob, target, ELE_ICE, 0);
power = adjustForTarget(target, power, ELE_ICE);
power = finalMagicNonSpellAdjustments(mob, target, ELE_ICE, power);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (power < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_ICE_DAMAGE, message, power;
end;
-----------------------------------
-- onMobDespawn
-----------------------------------
function onMobDespawn(mob)
-- Set Ramponneau's Window Open Time
local wait = 5400 -- 90 minutes
SetServerVariable("[POP]Ramponneau", os.time(t) + wait );
DeterMob(mob:getID(), true);
-- Set PH back to normal, then set to respawn spawn
local PH = GetServerVariable("[PH]Ramponneau");
SetServerVariable("[PH]Ramponneau", 0);
DeterMob(PH, false);
GetMobByID(PH):setRespawnTime(GetMobRespawnTime(PH));
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Bastok_Markets/npcs/Zaira.lua | 17 | 1868 | -----------------------------------
-- Area: Batok Markets
-- NPC: Zaira
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ZAIRA_SHOP_DIALOG);
stock = {
0x12FE, 111,1, --Scroll of Blind
0x12E6, 360,2, --Scroll of Bio
0x12DC, 82,2, --Scroll of Poison
0x12FD, 2250,2, --Scroll of Sleep
0x129F, 61,3, --Scroll of Stone
0x12A9, 140,3, --Scroll of Water
0x129A, 324,3, --Scroll of Aero
0x1290, 837,3, --Scroll of Fire
0x1295, 1584,3, --Scroll of Blizzard
0x12A4, 3261,3, --Scroll of Thunder
0x12EF, 1363,3, --Scroll of Shock
0x12EE, 1827,3, --Scroll of Rasp
0x12ED, 2250,3, --Scroll of Choke
0x12EC, 3688,3, --Scroll of Frost
0x12EB, 4644,3, --Scroll of Burn
0x12F0, 6366,3, --Scroll of Drown
}
showNationShop(player, BASTOK, 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 |
i32ropie/telegram-bot | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
Maxsteam/BBBBKKKK | plugins/rss.lua | 700 | 5434 | local function get_base_redis(id, option, extra)
local ex = ''
if option ~= nil then
ex = ex .. ':' .. option
if extra ~= nil then
ex = ex .. ':' .. extra
end
end
return 'rss:' .. id .. ex
end
local function prot_url(url)
local url, h = string.gsub(url, "http://", "")
local url, hs = string.gsub(url, "https://", "")
local protocol = "http"
if hs == 1 then
protocol = "https"
end
return url, protocol
end
local function get_rss(url, prot)
local res, code = nil, 0
if prot == "http" then
res, code = http.request(url)
elseif prot == "https" then
res, code = https.request(url)
end
if code ~= 200 then
return nil, "Error while doing the petition to " .. url
end
local parsed = feedparser.parse(res)
if parsed == nil then
return nil, "Error decoding the RSS.\nAre you sure that " .. url .. " it's a RSS?"
end
return parsed, nil
end
local function get_new_entries(last, nentries)
local entries = {}
for k,v in pairs(nentries) do
if v.id == last then
return entries
else
table.insert(entries, v)
end
end
return entries
end
local function print_subs(id)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
local text = id .. ' are subscribed to:\n---------\n'
for k,v in pairs(subs) do
text = text .. k .. ") " .. v .. '\n'
end
return text
end
local function subscribe(id, url)
local baseurl, protocol = prot_url(url)
local prothash = get_base_redis(baseurl, "protocol")
local lasthash = get_base_redis(baseurl, "last_entry")
local lhash = get_base_redis(baseurl, "subs")
local uhash = get_base_redis(id)
if redis:sismember(uhash, baseurl) then
return "You are already subscribed to " .. url
end
local parsed, err = get_rss(url, protocol)
if err ~= nil then
return err
end
local last_entry = ""
if #parsed.entries > 0 then
last_entry = parsed.entries[1].id
end
local name = parsed.feed.title
redis:set(prothash, protocol)
redis:set(lasthash, last_entry)
redis:sadd(lhash, id)
redis:sadd(uhash, baseurl)
return "You had been subscribed to " .. name
end
local function unsubscribe(id, n)
if #n > 3 then
return "I don't think that you have that many subscriptions."
end
n = tonumber(n)
local uhash = get_base_redis(id)
local subs = redis:smembers(uhash)
if n < 1 or n > #subs then
return "Subscription id out of range!"
end
local sub = subs[n]
local lhash = get_base_redis(sub, "subs")
redis:srem(uhash, sub)
redis:srem(lhash, id)
local left = redis:smembers(lhash)
if #left < 1 then -- no one subscribed, remove it
local prothash = get_base_redis(sub, "protocol")
local lasthash = get_base_redis(sub, "last_entry")
redis:del(prothash)
redis:del(lasthash)
end
return "You had been unsubscribed from " .. sub
end
local function cron()
-- sync every 15 mins?
local keys = redis:keys(get_base_redis("*", "subs"))
for k,v in pairs(keys) do
local base = string.match(v, "rss:(.+):subs") -- Get the URL base
local prot = redis:get(get_base_redis(base, "protocol"))
local last = redis:get(get_base_redis(base, "last_entry"))
local url = prot .. "://" .. base
local parsed, err = get_rss(url, prot)
if err ~= nil then
return
end
local newentr = get_new_entries(last, parsed.entries)
local subscribers = {}
local text = '' -- Send only one message with all updates
for k2, v2 in pairs(newentr) do
local title = v2.title or 'No title'
local link = v2.link or v2.id or 'No Link'
text = text .. "[rss](" .. link .. ") - " .. title .. '\n'
end
if text ~= '' then
local newlast = newentr[1].id
redis:set(get_base_redis(base, "last_entry"), newlast)
for k2, receiver in pairs(redis:smembers(v)) do
send_msg(receiver, text, ok_cb, false)
end
end
end
end
local function run(msg, matches)
local id = "user#id" .. msg.from.id
if is_chat_msg(msg) then
id = "chat#id" .. msg.to.id
end
if matches[1] == "!rss"then
return print_subs(id)
end
if matches[1] == "sync" then
if not is_sudo(msg) then
return "Only sudo users can sync the RSS."
end
cron()
end
if matches[1] == "subscribe" or matches[1] == "sub" then
return subscribe(id, matches[2])
end
if matches[1] == "unsubscribe" or matches[1] == "uns" then
return unsubscribe(id, matches[2])
end
end
return {
description = "Manage User/Chat RSS subscriptions. If you are in a chat group, the RSS subscriptions will be of that chat. If you are in an one-to-one talk with the bot, the RSS subscriptions will be yours.",
usage = {
"!rss: Get your rss (or chat rss) subscriptions",
"!rss subscribe (url): Subscribe to that url",
"!rss unsubscribe (id): Unsubscribe of that id",
"!rss sync: Download now the updates and send it. Only sudo users can use this option."
},
patterns = {
"^!rss$",
"^!rss (subscribe) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (sub) (https?://[%w-_%.%?%.:/%+=&]+)$",
"^!rss (unsubscribe) (%d+)$",
"^!rss (uns) (%d+)$",
"^!rss (sync)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
nokizorque/ucd | UCDaviator/server.lua | 1 | 3860 | --[[
-- Distances
LS --> LV = 4000
LS --> VM = 5000
LS --> SF = 3500
LV --> SF = 3300
LV --> VM = 1500
SF --> VM = 3000
--]]
local sml = {[511] = true, [593] = true, [513] = true} -- Beagle, Dodo, Stuntplane
local lrg = {[592] = true, [577] = true, [553] = true} -- Nevada, AT-400, Andromada
local mid = {[519] = true} -- Shamal
addEventHandler("onResourceStart", resourceRoot,
function ()
ranks = exports.UCDjobsTable:getJobRanks("Aviator")
end
)
function processFlight(flightData, vehicle)
if (client and flightData and vehicle) then
local model = vehicle.model
local playerRank = exports.UCDjobs:getPlayerJobRank(client, "Aviator") or 0
local base, bonus, distance
local start, finish
if (vehicle.vehicleType == "Plane") then
start = destinations["Plane"][airports[flightData[3]]][flightData[4]]
finish = destinations["Plane"][airports[flightData[1]]][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
if (sml[model]) then
base = math.random((distance * 1.2) - 250, (distance * 1.2) + 250)
elseif (lrg[model]) then
base = math.random((distance * 2) - 250, (distance * 2) + 250)
elseif (mid[model]) then
base = math.random((distance * 1.6) - 250, (distance * 1.7) + 250)
else
outputDebugString("Unknown type given")
return
end
else
start = destinations["Helicopter"][flightData[1]]
finish = destinations["Helicopter"][flightData[2]]
local x1, y1, z1 = start[1], start[2], start[3]
local x2, y2, z2 = finish[1], finish[2], finish[3]
distance = getDistanceBetweenPoints3D(x1, y1, z1, x2, y2, z2)
--outputDebugString("Distance: "..distance)
-- You should earn slightly more with a helicopter
base = math.random(distance * 1.5, (distance * 1.5) + 350)
end
bonus = ranks[playerRank].bonus
local newAmount = math.floor((base * (bonus / 100)) + base)
local formattedAmount = exports.UCDutil:tocomma(newAmount)
outputDebugString("Base = "..base)
outputDebugString("Bonus = "..bonus.."%")
outputDebugString("New amount = "..newAmount)
local roundedDist = exports.UCDutil:mathround(distance / 1000, 2)
if (vehicle.vehicleType == "Plane") then
local fA = airports[flightData[1]]
local sA = airports[flightData[3]]
exports.UCDdx:new(client, "ATC: Flight from "..sA.." to "..fA.." complete ("..tostring(roundedDist).." km). You have been paid $"..formattedAmount..".", 255, 215, 0)
else
exports.UCDdx:new(client, "ATC: Flight complete ("..tostring(roundedDist).."km). You have been paid $"..formattedAmount..".", 255, 215, 0)
end
exports.UCDaccounts:SAD(client.account.name, "aviator", exports.UCDaccounts:GAD(client.account.name, "aviator") + roundedDist)
if (client.vehicle) then
--client.vehicle.frozen = false
local health = math.floor(client.vehicle.health / 10)
if (health >= 95) then
exports.UCDdx:new(client, "ATC: 5% bonus for minimal damage to the "..tostring(vehicle.vehicleType == "Plane" and "plane" or "helicopter").." and its cargo", 255, 215, 0)
newAmount = newAmount + (newAmount * 0.5)
elseif (health <= 60) then
exports.UCDdx:new(client, "ATC: Your "..tostring(vehicle.vehicleType == "Plane" and "plane" or "helicopter").." suffered considerable damage and 10% of your earnings were taxed for repairs", 255, 215, 0)
newAmount = newAmount - (newAmount * 0.1)
end
Timer(
function (plr)
triggerClientEvent(plr, "UCDaviator.startItinerary", plr, plr.vehicle, plr.vehicleSeat)
end, 2000, 1, client
)
end
client.money = client.money + newAmount
end
end
addEvent("UCDaviator.processFlight", true)
addEventHandler("UCDaviator.processFlight", root, processFlight)
| mit |
schidler/ionic-luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/netlink.lua | 68 | 2502 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
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
| apache-2.0 |
rpetit3/darkstar | scripts/zones/Port_Bastok/npcs/Belka.lua | 16 | 1547 | -----------------------------------
-- Area: Port Bastok
-- NPC: Belka
-- Only sells when Bastok controlls Derfland Region
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(DERFLAND);
if (RegionOwner ~= BASTOK) then
player:showText(npc,BELKA_CLOSED_DIALOG);
else
player:showText(npc,BELKA_OPEN_DIALOG);
stock = {
0x1100, 128, --Derfland Pear
0x0269, 142, --Ginger
0x11C1, 62, --Gysahl Greens
0x0584, 1656, --Olive Flower
0x0279, 14, --Olive Oil
0x03B7, 110 --Wijnruit
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Endika/Algorithm-Implementations | Dijkstra_Search/Lua/Yonaba/dijkstra.lua | 26 | 3785 | -- Generic Dijkstra graph search algorithm implementation
-- See : http://en.wikipedia.org/wiki/Dijkstra%27s_algorithm
-- Notes : this is a generic implementation of Dijkstra graph search algorithm.
-- It is devised to be used on any type of graph (point-graph, tile-graph,
-- or whatever. It expects to be initialized with a handler, which acts as
-- an interface between the search algorithm and the search space.
-- This implementation uses internally a binary heap to handle fast retrieval
-- of the lowest-cost node.
-- The Dijkstra class expects a handler to be initialized. Roughly said, the handler
-- is an interface between your search space and the generic search algorithm.
-- This model ensures flexibility, so that this generic implementation can be
-- adapted to search on any kind of space.
-- The passed-in handler should implement those functions.
-- handler.getNode(...) -> returns a Node (instance of node.lua)
-- handler.getAllNodes() -> returns an array list of all nodes in graph
-- handler.distance(a, b) -> heuristic function which returns the distance
-- between node a and node b
-- handler.getNeighbors(n) -> returns an array of all nodes that can be reached
-- via node n (also called successors of node n)
-- The generic Node class provided (see node.lua) should also be implemented
-- through the handler. Basically, it should describe how nodes are labelled
-- and tested for equality for a custom search space.
-- The following functions should be implemented:
-- function Node:initialize(...) -> creates a Node with custom attributes
-- function Node:isEqualTo(n) -> returns if self is equal to node n
-- function Node:toString() -> returns a unique string representation of
-- the node, for debug purposes
-- See custom handlers for reference (*_hander.lua).
-- Dependencies
local class = require 'utils.class'
local bheap = require 'utils.bheap'
-- Clears nodes data between consecutive path requests.
local function resetForNextSearch(dijkstra)
for node in pairs(dijkstra.visited) do
node.previous = nil
node.distance = math.huge
end
dijkstra.Q:clear()
dijkstra.visited = {}
end
-- Builds and returns the path to the goal node
local function backtrace(node)
local path = {}
repeat
table.insert(path, 1, node)
node = node.previous
until not node
return path
end
-- Initializes Dijkstra search with a custom handler
local Dijkstra = class()
function Dijkstra:initialize(handler)
self.handler = handler
self.Q = bheap()
self.visited = {}
end
-- Processes the graph for shortest paths
-- source : the starting node from which the search will spread
-- target : the goal location. If passed, returns the shortest path from
-- source to this target. If not given, will evaluate all the shortest
-- paths length from to source to all nodes in the graph. This length can
-- be retrieved by indexing in each node after the search (node.distance)
-- Returns : an array of nodes (if target supplied)
function Dijkstra:process(source, target)
resetForNextSearch(self)
source.distance = 0
self.visited[source] = true
local nodes = self.handler.getAllNodes()
for _, node in ipairs(nodes) do self.Q:push(node) end
while not self.Q:isEmpty() do
local u = self.Q:pop()
if u == target then return backtrace(u) end
if u.distance == math.huge then break end
local neighbors = self.handler.getNeighbors(u)
for _, v in ipairs(neighbors) do
local alt = u.distance + self.handler.distance(u, v)
if alt < v.distance then
v.distance = alt
v.previous = u
self.visited[v] = true
self.Q:sort(v)
end
end
end
end
return Dijkstra
| mit |
gligneul/FastLua | luatests/tpack.lua | 1 | 10563 | -- $Id: tpack.lua,v 1.12 2016/05/18 18:22:45 roberto Exp $
local pack = string.pack
local packsize = string.packsize
local unpack = string.unpack
print "testing pack/unpack"
-- maximum size for integers
local NB = 16
local sizeshort = packsize("h")
local sizeint = packsize("i")
local sizelong = packsize("l")
local sizesize_t = packsize("T")
local sizeLI = packsize("j")
local sizefloat = packsize("f")
local sizedouble = packsize("d")
local sizenumber = packsize("n")
local little = (pack("i2", 1) == "\1\0")
local align = packsize("!xXi16")
assert(1 <= sizeshort and sizeshort <= sizeint and sizeint <= sizelong and
sizefloat <= sizedouble)
print("platform:")
print(string.format(
"\tshort %d, int %d, long %d, size_t %d, float %d, double %d,\n\z
\tlua Integer %d, lua Number %d",
sizeshort, sizeint, sizelong, sizesize_t, sizefloat, sizedouble,
sizeLI, sizenumber))
print("\t" .. (little and "little" or "big") .. " endian")
print("\talignment: " .. align)
-- check errors in arguments
function checkerror (msg, f, ...)
local status, err = pcall(f, ...)
-- print(status, err, msg)
assert(not status and string.find(err, msg))
end
-- minimum behavior for integer formats
assert(unpack("B", pack("B", 0xff)) == 0xff)
assert(unpack("b", pack("b", 0x7f)) == 0x7f)
assert(unpack("b", pack("b", -0x80)) == -0x80)
assert(unpack("H", pack("H", 0xffff)) == 0xffff)
assert(unpack("h", pack("h", 0x7fff)) == 0x7fff)
assert(unpack("h", pack("h", -0x8000)) == -0x8000)
assert(unpack("L", pack("L", 0xffffffff)) == 0xffffffff)
assert(unpack("l", pack("l", 0x7fffffff)) == 0x7fffffff)
assert(unpack("l", pack("l", -0x80000000)) == -0x80000000)
for i = 1, NB do
-- small numbers with signal extension ("\xFF...")
local s = string.rep("\xff", i)
assert(pack("i" .. i, -1) == s)
assert(packsize("i" .. i) == #s)
assert(unpack("i" .. i, s) == -1)
-- small unsigned number ("\0...\xAA")
s = "\xAA" .. string.rep("\0", i - 1)
assert(pack("<I" .. i, 0xAA) == s)
assert(unpack("<I" .. i, s) == 0xAA)
assert(pack(">I" .. i, 0xAA) == s:reverse())
assert(unpack(">I" .. i, s:reverse()) == 0xAA)
end
do
local lnum = 0x13121110090807060504030201
local s = pack("<j", lnum)
assert(unpack("<j", s) == lnum)
assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
assert(unpack("<i" .. sizeLI + 1, s .. "\0") == lnum)
for i = sizeLI + 1, NB do
local s = pack("<j", -lnum)
assert(unpack("<j", s) == -lnum)
-- strings with (correct) extra bytes
assert(unpack("<i" .. i, s .. ("\xFF"):rep(i - sizeLI)) == -lnum)
assert(unpack(">i" .. i, ("\xFF"):rep(i - sizeLI) .. s:reverse()) == -lnum)
assert(unpack("<I" .. i, s .. ("\0"):rep(i - sizeLI)) == -lnum)
-- overflows
checkerror("does not fit", unpack, "<I" .. i, ("\x00"):rep(i - 1) .. "\1")
checkerror("does not fit", unpack, ">i" .. i, "\1" .. ("\x00"):rep(i - 1))
end
end
for i = 1, sizeLI do
local lstr = "\1\2\3\4\5\6\7\8\9\10\11\12\13"
local lnum = 0x13121110090807060504030201
local n = lnum & (~(-1 << (i * 8)))
local s = string.sub(lstr, 1, i)
assert(pack("<i" .. i, n) == s)
assert(pack(">i" .. i, n) == s:reverse())
assert(unpack(">i" .. i, s:reverse()) == n)
end
-- sign extension
do
local u = 0xf0
for i = 1, sizeLI - 1 do
assert(unpack("<i"..i, "\xf0"..("\xff"):rep(i - 1)) == -16)
assert(unpack(">I"..i, "\xf0"..("\xff"):rep(i - 1)) == u)
u = u * 256 + 0xff
end
end
-- mixed endianness
do
assert(pack(">i2 <i2", 10, 20) == "\0\10\20\0")
local a, b = unpack("<i2 >i2", "\10\0\0\20")
assert(a == 10 and b == 20)
assert(pack("=i4", 2001) == pack("i4", 2001))
end
print("testing invalid formats")
checkerror("out of limits", pack, "i0", 0)
checkerror("out of limits", pack, "i" .. NB + 1, 0)
checkerror("out of limits", pack, "!" .. NB + 1, 0)
checkerror("%(17%) out of limits %[1,16%]", pack, "Xi" .. NB + 1)
checkerror("invalid format option 'r'", pack, "i3r", 0)
checkerror("16%-byte integer", unpack, "i16", string.rep('\3', 16))
checkerror("not power of 2", pack, "!4i3", 0);
checkerror("missing size", pack, "c", "")
checkerror("variable%-length format", packsize, "s")
checkerror("variable%-length format", packsize, "z")
-- overflow in option size (error will be in digit after limit)
checkerror("invalid format", packsize, "c1" .. string.rep("0", 40))
if packsize("i") == 4 then
-- result would be 2^31 (2^3 repetitions of 2^28 strings)
local s = string.rep("c268435456", 2^3)
checkerror("too large", packsize, s)
-- one less is OK
s = string.rep("c268435456", 2^3 - 1) .. "c268435455"
assert(packsize(s) == 0x7fffffff)
end
-- overflow in packing
for i = 1, sizeLI - 1 do
local umax = (1 << (i * 8)) - 1
local max = umax >> 1
local min = ~max
checkerror("overflow", pack, "<I" .. i, -1)
checkerror("overflow", pack, "<I" .. i, min)
checkerror("overflow", pack, ">I" .. i, umax + 1)
checkerror("overflow", pack, ">i" .. i, umax)
checkerror("overflow", pack, ">i" .. i, max + 1)
checkerror("overflow", pack, "<i" .. i, min - 1)
assert(unpack(">i" .. i, pack(">i" .. i, max)) == max)
assert(unpack("<i" .. i, pack("<i" .. i, min)) == min)
assert(unpack(">I" .. i, pack(">I" .. i, umax)) == umax)
end
-- Lua integer size
assert(unpack(">j", pack(">j", math.maxinteger)) == math.maxinteger)
assert(unpack("<j", pack("<j", math.mininteger)) == math.mininteger)
assert(unpack("<J", pack("<j", -1)) == -1) -- maximum unsigned integer
if little then
assert(pack("f", 24) == pack("<f", 24))
else
assert(pack("f", 24) == pack(">f", 24))
end
print "testing pack/unpack of floating-point numbers"
for _, n in ipairs{0, -1.1, 1.9, 1/0, -1/0, 1e20, -1e20, 0.1, 2000.7} do
assert(unpack("n", pack("n", n)) == n)
assert(unpack("<n", pack("<n", n)) == n)
assert(unpack(">n", pack(">n", n)) == n)
assert(pack("<f", n) == pack(">f", n):reverse())
assert(pack(">d", n) == pack("<d", n):reverse())
end
-- for non-native precisions, test only with "round" numbers
for _, n in ipairs{0, -1.5, 1/0, -1/0, 1e10, -1e9, 0.5, 2000.25} do
assert(unpack("<f", pack("<f", n)) == n)
assert(unpack(">f", pack(">f", n)) == n)
assert(unpack("<d", pack("<d", n)) == n)
assert(unpack(">d", pack(">d", n)) == n)
end
print "testing pack/unpack of strings"
do
local s = string.rep("abc", 1000)
assert(pack("zB", s, 247) == s .. "\0\xF7")
local s1, b = unpack("zB", s .. "\0\xF9")
assert(b == 249 and s1 == s)
s1 = pack("s", s)
assert(unpack("s", s1) == s)
checkerror("does not fit", pack, "s1", s)
checkerror("contains zeros", pack, "z", "alo\0");
for i = 2, NB do
local s1 = pack("s" .. i, s)
assert(unpack("s" .. i, s1) == s and #s1 == #s + i)
end
end
do
local x = pack("s", "alo")
checkerror("too short", unpack, "s", x:sub(1, -2))
checkerror("too short", unpack, "c5", "abcd")
checkerror("out of limits", pack, "s100", "alo")
end
do
assert(pack("c0", "") == "")
assert(packsize("c0") == 0)
assert(unpack("c0", "") == "")
assert(pack("<! c3", "abc") == "abc")
assert(packsize("<! c3") == 3)
assert(pack(">!4 c6", "abcdef") == "abcdef")
assert(pack("c3", "123") == "123")
assert(pack("c0", "") == "")
assert(pack("c8", "123456") == "123456\0\0")
assert(pack("c88", "") == string.rep("\0", 88))
assert(pack("c188", "ab") == "ab" .. string.rep("\0", 188 - 2))
local a, b, c = unpack("!4 z c3", "abcdefghi\0xyz")
assert(a == "abcdefghi" and b == "xyz" and c == 14)
checkerror("longer than", pack, "c3", "1234")
end
-- testing multiple types and sequence
do
local x = pack("<b h b f d f n i", 1, 2, 3, 4, 5, 6, 7, 8)
assert(#x == packsize("<b h b f d f n i"))
local a, b, c, d, e, f, g, h = unpack("<b h b f d f n i", x)
assert(a == 1 and b == 2 and c == 3 and d == 4 and e == 5 and f == 6 and
g == 7 and h == 8)
end
print "testing alignment"
do
assert(pack(" < i1 i2 ", 2, 3) == "\2\3\0") -- no alignment by default
local x = pack(">!8 b Xh i4 i8 c1 Xi8", -12, 100, 200, "\xEC")
assert(#x == packsize(">!8 b Xh i4 i8 c1 Xi8"))
assert(x == "\xf4" .. "\0\0\0" ..
"\0\0\0\100" ..
"\0\0\0\0\0\0\0\xC8" ..
"\xEC" .. "\0\0\0\0\0\0\0")
local a, b, c, d, pos = unpack(">!8 c1 Xh i4 i8 b Xi8 XI XH", x)
assert(a == "\xF4" and b == 100 and c == 200 and d == -20 and (pos - 1) == #x)
x = pack(">!4 c3 c4 c2 z i4 c5 c2 Xi4",
"abc", "abcd", "xz", "hello", 5, "world", "xy")
assert(x == "abcabcdxzhello\0\0\0\0\0\5worldxy\0")
local a, b, c, d, e, f, g, pos = unpack(">!4 c3 c4 c2 z i4 c5 c2 Xh Xi4", x)
assert(a == "abc" and b == "abcd" and c == "xz" and d == "hello" and
e == 5 and f == "world" and g == "xy" and (pos - 1) % 4 == 0)
x = pack(" b b Xd b Xb x", 1, 2, 3)
assert(packsize(" b b Xd b Xb x") == 4)
assert(x == "\1\2\3\0")
a, b, c, pos = unpack("bbXdb", x)
assert(a == 1 and b == 2 and c == 3 and pos == #x)
-- only alignment
assert(packsize("!8 xXi8") == 8)
local pos = unpack("!8 xXi8", "0123456701234567"); assert(pos == 9)
assert(packsize("!8 xXi2") == 2)
local pos = unpack("!8 xXi2", "0123456701234567"); assert(pos == 3)
assert(packsize("!2 xXi2") == 2)
local pos = unpack("!2 xXi2", "0123456701234567"); assert(pos == 3)
assert(packsize("!2 xXi8") == 2)
local pos = unpack("!2 xXi8", "0123456701234567"); assert(pos == 3)
assert(packsize("!16 xXi16") == 16)
local pos = unpack("!16 xXi16", "0123456701234567"); assert(pos == 17)
checkerror("invalid next option", pack, "X")
checkerror("invalid next option", unpack, "XXi", "")
checkerror("invalid next option", unpack, "X i", "")
checkerror("invalid next option", pack, "Xc1")
end
do -- testing initial position
local x = pack("i4i4i4i4", 1, 2, 3, 4)
for pos = 1, 16, 4 do
local i, p = unpack("i4", x, pos)
assert(i == pos//4 + 1 and p == pos + 4)
end
-- with alignment
for pos = 0, 12 do -- will always round position to power of 2
local i, p = unpack("!4 i4", x, pos + 1)
assert(i == (pos + 3)//4 + 1 and p == i*4 + 1)
end
-- negative indices
local i, p = unpack("!4 i4", x, -4)
assert(i == 4 and p == 17)
local i, p = unpack("!4 i4", x, -7)
assert(i == 4 and p == 17)
local i, p = unpack("!4 i4", x, -#x)
assert(i == 1 and p == 5)
-- limits
for i = 1, #x + 1 do
assert(unpack("c0", x, i) == "")
end
checkerror("out of string", unpack, "c0", x, 0)
checkerror("out of string", unpack, "c0", x, #x + 2)
checkerror("out of string", unpack, "c0", x, -(#x + 1))
end
print "OK"
| mit |
rpetit3/darkstar | scripts/zones/Promyvion-Vahzl/mobs/Memory_Receptacle.lua | 6 | 6906 | -----------------------------------
-- Area: Promyvion-Vahzl
-- MOB: Memory Receptacle
-- Todo: clean up disgustingly bad formatting
-----------------------------------
package.loaded["scripts/zones/Promyvion-Vahzl/TextIDs"] = nil;
-----------------------------------
require( "scripts/zones/Promyvion-Vahzl/TextIDs" );
require("scripts/globals/status");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
mob:addMod(MOD_REGAIN, 100); -- 10% Regain for now
mob:SetAutoAttackEnabled(false); -- Recepticles only use TP moves.
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob, target)
local Mem_Recep = mob:getID();
-- This will serve as a ghetto Regain (not damage dependent) based on kjlotus's testing. Caps at 100
if (mob:getTP() < 900) then
mob:addTP(100);
end
if (Mem_Recep == 16867382 or Mem_Recep == 16867387) then -- Floor 1
for i = Mem_Recep+1, Mem_Recep+3 do -- Keep pets linked
if (GetMobAction(i) == 16) then
GetMobByID(i):updateEnmity(target);
end
end
elseif (Mem_Recep == 16867429 or Mem_Recep == 16867436 or Mem_Recep == 16867494 or Mem_Recep == 16867501 or Mem_Recep == 16867508 or -- Floor 2/3
Mem_Recep == 16867515) then
for i = Mem_Recep+1, Mem_Recep+5 do
if (GetMobAction(i) == 16) then
GetMobByID(i):updateEnmity(target);
end
end
elseif (Mem_Recep == 16867586 or Mem_Recep == 16867595 or Mem_Recep == 16867604) then -- Floor 4
for i = Mem_Recep+1, Mem_Recep+7 do
if (GetMobAction(i) == 16) then
GetMobByID(i):updateEnmity(target);
end
end
end
-- Summons a single stray every 30 seconds.
if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867382 or Mem_Recep == 16867387) and mob:AnimationSub() == 2) then -- Floor 1
for i = Mem_Recep+1, Mem_Recep+3 do
if (GetMobAction(i) == 0) then -- My Stray is deeaaaaaad!
mob:AnimationSub(1);
SpawnMob(i):updateEnmity(target);
GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle
return;
end
end
elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867429 or Mem_Recep == 16867436 or Mem_Recep == 16867494 or -- Floor 2/3
Mem_Recep == 16867501 or Mem_Recep == 16867508 or Mem_Recep == 16867515) and mob:AnimationSub() == 2) then
for i = Mem_Recep+1, Mem_Recep+5 do
if (GetMobAction(i) == 0) then
mob:AnimationSub(1);
SpawnMob(i):updateEnmity(target);
GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1); -- Set stray x and z position +1 from Recepticle
return;
end
end
elseif (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3 and (Mem_Recep == 16867586 or Mem_Recep == 16867595 or Mem_Recep == 16867604) and -- Floor 4
mob:AnimationSub() == 2) then
for i = Mem_Recep+1, Mem_Recep+7 do
if (GetMobAction(i) == 0) then
mob:AnimationSub(1);
SpawnMob(i):updateEnmity(target);
GetMobByID(i):setPos(mob:getXPos()+1, mob:getYPos(), mob:getZPos()+1);
return;
end
end
else
mob:AnimationSub(2);
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, player, isKiller)
local mobID = mob:getID();
local difX = player:getXPos()-mob:getXPos();
local difY = player:getYPos()-mob:getYPos();
local difZ = player:getZPos()-mob:getZPos();
local killeranimation = player:getAnimation();
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difY,2) + math.pow(difZ,2) ); --calcul de la distance entre les "killer" et le memory receptacle
mob:AnimationSub(0); -- Set ani. sub to default or the recepticles wont work properly
switch (mob:getID()) : caseof {
[16867387] = function (x)
GetNPCByID(16867700):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(32);
end
end,
[16867382] = function (x)
GetNPCByID(16867699):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(33);
end
end,
[16867429] = function (x)
GetNPCByID(16867697):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(30);
end
end,
[16867436] = function (x)
GetNPCByID(16867698):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(31);
end
end,
[16867501] = function (x)
GetNPCByID(16867703):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(35);
end
end,
[16867515] = function (x)
GetNPCByID(16867705):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(36);
end
end,
[16867494] = function (x)
GetNPCByID(16867702):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(37);
end
end,
[16867508] = function (x)
GetNPCByID(16867704):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(38);
end
end,
[16867604] = function (x)
GetNPCByID(16867707):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(34);
end
end,
[16867586] = function (x)
GetNPCByID(16867701):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(39);
end
end,
[16867595] = function (x)
GetNPCByID(16867706):openDoor(180);
if (Distance <4 and killeranimation == 0) then
player:startEvent(40);
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 |
rpetit3/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Moogle.lua | 13 | 1170 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Moogle
-- @zone 80
-- @pos <many>
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/moghouse")
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
moogleTrade(player,npc,trade);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (not moogleTrigger(player,npc)) then
player:startEvent(0x003D);
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 == 0x7530) then
player:setVar("MoghouseExplication",0);
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Qulun_Dome/npcs/Magicite.lua | 13 | 1659 | -----------------------------------
-- Area: Qulun Dome
-- NPC: Magicite
-- Involved in Mission: Magicite
-- @pos 11 25 -81 148
-----------------------------------
package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Qulun_Dome/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_AURASTONE) == false) then
if (player:getVar("MissionStatus") < 4) then
player:startEvent(0x0000,1); -- play Lion part of the CS (this is first magicite)
else
player:startEvent(0x0000); -- don't play Lion part of the CS
end
else
player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0000) then
player:setVar("MissionStatus",4);
player:addKeyItem(MAGICITE_AURASTONE);
player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_AURASTONE);
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/zones/Eastern_Adoulin/Zone.lua | 16 | 1192 | -----------------------------------
--
-- Zone: Eastern Adoulin
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Eastern_Adoulin/TextIDs"] = nil;
require("scripts/zones/Eastern_Adoulin/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-155,0,-19,250);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
DDDBTG/DDBTG | libs/dateparser.lua | 114 | 6213 | local difftime, time, date = os.difftime, os.time, os.date
local format = string.format
local tremove, tinsert = table.remove, table.insert
local pcall, pairs, ipairs, tostring, tonumber, type, setmetatable = pcall, pairs, ipairs, tostring, tonumber, type, setmetatable
local dateparser={}
--we shall use the host OS's time conversion facilities. Dealing with all those leap seconds by hand can be such a bore.
local unix_timestamp
do
local now = time()
local local_UTC_offset_sec = difftime(time(date("!*t", now)), time(date("*t", now)))
unix_timestamp = function(t, offset_sec)
local success, improper_time = pcall(time, t)
if not success or not improper_time then return nil, "invalid date. os.time says: " .. (improper_time or "nothing") end
return improper_time - local_UTC_offset_sec - offset_sec
end
end
local formats = {} -- format names
local format_func = setmetatable({}, {__mode='v'}) --format functions
---register a date format parsing function
function dateparser.register_format(format_name, format_function)
if type(format_name)~="string" or type(format_function)~='function' then return nil, "improper arguments, can't register format handler" end
local found
for i, f in ipairs(format_func) do --for ordering
if f==format_function then
found=true
break
end
end
if not found then
tinsert(format_func, format_function)
end
formats[format_name] = format_function
return true
end
---register a date format parsing function
function dateparser.unregister_format(format_name)
if type(format_name)~="string" then return nil, "format name must be a string" end
formats[format_name]=nil
end
---return the function responsible for handling format_name date strings
function dateparser.get_format_function(format_name)
return formats[format_name] or nil, ("format %s not registered"):format(format_name)
end
---try to parse date string
--@param str date string
--@param date_format optional date format name, if known
--@return unix timestamp if str can be parsed; nil, error otherwise.
function dateparser.parse(str, date_format)
local success, res, err
if date_format then
if not formats[date_format] then return 'unknown date format: ' .. tostring(date_format) end
success, res = pcall(formats[date_format], str)
else
for i, func in ipairs(format_func) do
success, res = pcall(func, str)
if success and res then return res end
end
end
return success and res
end
dateparser.register_format('W3CDTF', function(rest)
local year, day_of_year, month, day, week
local hour, minute, second, second_fraction, offset_hours
local alt_rest
year, rest = rest:match("^(%d%d%d%d)%-?(.*)$")
day_of_year, alt_rest = rest:match("^(%d%d%d)%-?(.*)$")
if day_of_year then rest=alt_rest end
month, rest = rest:match("^(%d%d)%-?(.*)$")
day, rest = rest:match("^(%d%d)(.*)$")
if #rest>0 then
rest = rest:match("^T(.*)$")
hour, rest = rest:match("^([0-2][0-9]):?(.*)$")
minute, rest = rest:match("^([0-6][0-9]):?(.*)$")
second, rest = rest:match("^([0-6][0-9])(.*)$")
second_fraction, alt_rest = rest:match("^%.(%d+)(.*)$")
if second_fraction then
rest=alt_rest
end
if rest=="Z" then
rest=""
offset_hours=0
else
local sign, offset_h, offset_m
sign, offset_h, rest = rest:match("^([+-])(%d%d)%:?(.*)$")
local offset_m, alt_rest = rest:match("^(%d%d)(.*)$")
if offset_m then rest=alt_rest end
offset_hours = tonumber(sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 then return nil end
end
year = tonumber(year)
local d = {
year = year and (year > 100 and year or (year < 50 and (year + 2000) or (year + 1900))),
month = tonumber(month) or 1,
day = tonumber(day) or 1,
hour = tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
local t = unix_timestamp(d, (offset_hours or 0) * 3600)
if second_fraction then
return t + tonumber("0."..second_fraction)
else
return t
end
end)
do
local tz_table = { --taken from http://www.timeanddate.com/library/abbreviations/timezones/
A = 1, B = 2, C = 3, D = 4, E=5, F = 6, G = 7, H = 8, I = 9,
K = 10, L = 11, M = 12, N = -1, O = -2, P = -3, Q = -4, R = -5,
S = -6, T = -7, U = -8, V = -9, W = -10, X = -11, Y = -12,
Z = 0,
EST = -5, EDT = -4, CST = -6, CDT = -5,
MST = -7, MDT = -6, PST = -8, PDT = -7,
GMT = 0, UT = 0, UTC = 0
}
local month_val = {Jan=1, Feb=2, Mar=3, Apr=4, May=5, Jun=6, Jul=7, Aug=8, Sep=9, Oct=10, Nov=11, Dec=12}
dateparser.register_format('RFC2822', function(rest)
local year, month, day, day_of_year, week_of_year, weekday
local hour, minute, second, second_fraction, offset_hours
local alt_rest
weekday, alt_rest = rest:match("^(%w%w%w),%s+(.*)$")
if weekday then rest=alt_rest end
day, rest=rest:match("^(%d%d?)%s+(.*)$")
month, rest=rest:match("^(%w%w%w)%s+(.*)$")
month = month_val[month]
year, rest = rest:match("^(%d%d%d?%d?)%s+(.*)$")
hour, rest = rest:match("^(%d%d?):(.*)$")
minute, rest = rest:match("^(%d%d?)(.*)$")
second, alt_rest = rest:match("^:(%d%d)(.*)$")
if second then rest = alt_rest end
local tz, offset_sign, offset_h, offset_m
tz, alt_rest = rest:match("^%s+(%u+)(.*)$")
if tz then
rest = alt_rest
offset_hours = tz_table[tz]
else
offset_sign, offset_h, offset_m, rest = rest:match("^%s+([+-])(%d%d)(%d%d)%s*(.*)$")
offset_hours = tonumber(offset_sign .. offset_h) + (tonumber(offset_m) or 0)/60
end
if #rest>0 or not (year and day and month and hour and minute) then
return nil
end
year = tonumber(year)
local d = {
year = year and ((year > 100) and year or (year < 50 and (year + 2000) or (year + 1900))),
month = month,
day = tonumber(day),
hour= tonumber(hour) or 0,
min = tonumber(minute) or 0,
sec = tonumber(second) or 0,
isdst = false
}
return unix_timestamp(d, offset_hours * 3600)
end)
end
dateparser.register_format('RFC822', formats.RFC2822) --2822 supercedes 822, but is not a strict superset. For our intents and purposes though, it's perfectly good enough
dateparser.register_format('RFC3339', formats.W3CDTF) --RFC3339 is a subset of W3CDTF
return dateparser
| gpl-2.0 |
tommo/gii | template/game/lib/mock/component/FSMController.lua | 1 | 3716 | module 'mock'
--------------------------------------------------------------------
local stateCollectorMT
local setmetatable=setmetatable
local insert, remove = table.insert, table.remove
local rawget,rawset=rawget,rawset
local pairs=pairs
stateCollectorMT = {
__index = function( t, k )
local __state = t.__state
local __id = t.__id
return setmetatable({
__state = __state and __state..'.'..k or k,
__id = __id and __id..'_'..k or '_FSM_'..k,
__class = t.__class
} ,stateCollectorMT)
end,
--got state method
__newindex =function( t, action, func )
local name = t.__state
local id = t.__id
local class = t.__class
if
action ~= 'jumpin' and action ~= 'jumpout'
and action~='step' and action~='enter' and action~='exit'
then
return error('unsupported state action:'..action)
end
--NOTE:validation will be done after setting scheme to controller
--save under fullname
local methodName = id..'__'..action
rawset ( class, methodName, func )
end
}
local function newStateMethodCollector( class )
return setmetatable({
__state = false,
__id = false,
__class = class
} ,stateCollectorMT )
end
--------------------------------------------------------------------
CLASS: FSMController ( Behaviour )
:MODEL{
Field 'state' :string() :readonly() :get('getState');
Field 'scheme' :asset('fsm_scheme') :getset('Scheme');
}
-----fsm state method collector
FSMController.fsm = newStateMethodCollector( FSMController )
function FSMController:__initclass( subclass )
subclass.fsm = newStateMethodCollector( subclass )
end
function FSMController:__init()
self.msgBox = {}
local msgFilter = false
self.msgBoxListener = function( msg, data, source )
if msgFilter and msgFilter( msg,data,source ) == false then return end
return insert( self.msgBox, { msg, data, source } )
end
self._msgFilterSetter = function( f ) msgFilter = f end
end
function FSMController:setMsgFilter( func )
return self._msgFilterSetter( func )
end
function FSMController:onAttach( entity )
Behaviour.onAttach( self, entity )
entity:addMsgListener( self.msgBoxListener )
end
function FSMController:onStart( entity )
self.threadFSMUpdate = self:addCoroutine( 'onThreadFSMUpdate' )
Behaviour.onStart( self, entity )
end
function FSMController:onDetach( ent )
Behaviour.onDetach( self, ent )
ent:removeMsgListener( self.msgBoxListener )
end
function FSMController:getState()
local ent = self._entity
return ent and ent:getState()
end
function FSMController:clearMsgBox()
self.msgBox = {}
end
function FSMController:pushTopMsg( msg, data, source )
insert( self.msgBox, 1, { msg, data, source } )
end
function FSMController:pollMsg()
local m = remove( self.msgBox, 1 )
if m then return m[1],m[2],m[3] end
return nil
end
function FSMController:peekMsg( id )
id = id or 1
local m = self.msgBox[ id ]
if m then return m[1],m[2],m[3] end
return nil
end
function FSMController:hasMsgInBox( msg )
for i, m in ipairs( self.msgBox ) do
if m[1] == msg then return true end
end
return false
end
function FSMController:updateFSM( dt )
local func = self.currentStateFunc
if func then
return func( self, dt, 0 )
end
end
function FSMController:setScheme( schemePath )
self.schemePath = schemePath
local scheme = loadAsset( schemePath )
self.scheme = scheme
if scheme then
self.currentStateFunc = scheme[0]
self:validateStateMethods()
else
self.currentStateFunc = nil
end
end
function FSMController:validateStateMethods()
--todo
end
function FSMController:getScheme()
return self.schemePath
end
function FSMController:onThreadFSMUpdate()
local dt = 0
while true do
self:updateFSM( dt )
dt = coroutine.yield()
end
end
| mit |
rpetit3/darkstar | scripts/zones/La_Theine_Plateau/npcs/Telepoint.lua | 13 | 1675 | -----------------------------------
-- Area: La Theine Plateau
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/La_Theine_Plateau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local item = trade:getItem();
if (trade:getItemCount() == 1 and item > 4095 and item < 4104) then
if (player:getFreeSlotsCount() > 0 and player:hasItem(613) == false) then
player:tradeComplete();
player:addItem(613);
player:messageSpecial(ITEM_OBTAINED,613); -- Faded Crystal
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,613); -- Faded Crystal
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(HOLLA_GATE_CRYSTAL) == false) then
player:addKeyItem(HOLLA_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,HOLLA_GATE_CRYSTAL);
else
player:messageSpecial(ALREADY_OBTAINED_TELE);
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 |
rpetit3/darkstar | scripts/zones/Sacrificial_Chamber/npcs/_4j2.lua | 13 | 1421 | -----------------------------------
-- Area: Sacrificial Chamber
-- NPC: Mahogany Door
-- @pos -260 -33 274 163
-------------------------------------
package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/zones/Sacrificial_Chamber/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (TradeBCNM(player,player:getZoneID(),trade,npc)) then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (EventTriggerBCNM(player,npc)) then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if (EventUpdateBCNM(player,csid,option)) then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
Endika/Algorithm-Implementations | Shell_Sort/Lua/Yonaba/shell_sort_test.lua | 27 | 1367 | -- Tests for shell_sort.lua
local shell_sort = require 'shell_sort'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Comparison functions
local function le(a,b) return a <= b end
local function ge(a,b) return a >= b end
-- Checks if list is sorted
function is_sorted(list, comp)
comp = comp or le
for i = 2, #list do
if not comp(list[i-1],list[i]) then return false end
end
return true
end
-- Generates a table of n random values
local function gen(n)
local t = {}
for i = 1, n do t[i] = math.random(n) end
return t
end
math.randomseed(os.time())
run('Empty arrays', function()
local t = {}
assert(is_sorted(shell_sort({})))
end)
run('Already sorted array', function()
local t = {1, 2, 3, 4, 5}
assert(is_sorted(shell_sort(t)))
end)
run('Sorting a large array (1e3 values)', function()
local t = gen(1e3)
assert(is_sorted(shell_sort(t)))
assert(is_sorted(shell_sort(t, ge), ge))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
tenvick/hugula | Client/build/luajit-2.1.0b3/src/host/genlibbc.lua | 37 | 4965 | ----------------------------------------------------------------------------
-- Lua script to dump the bytecode of the library functions written in Lua.
-- The resulting 'buildvm_libbc.h' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local ffi = require("ffi")
local bit = require("bit")
local vmdef = require("jit.vmdef")
local bcnames = vmdef.bcnames
local format = string.format
local isbe = (string.byte(string.dump(function() end), 5) % 2 == 1)
local function usage(arg)
io.stderr:write("Usage: ", arg and arg[0] or "genlibbc",
" [-o buildvm_libbc.h] lib_*.c\n")
os.exit(1)
end
local function parse_arg(arg)
local outfile = "-"
if not (arg and arg[1]) then
usage(arg)
end
if arg[1] == "-o" then
outfile = arg[2]
if not outfile then usage(arg) end
table.remove(arg, 1)
table.remove(arg, 1)
end
return outfile
end
local function read_files(names)
local src = ""
for _,name in ipairs(names) do
local fp = assert(io.open(name))
src = src .. fp:read("*a")
fp:close()
end
return src
end
local function transform_lua(code)
local fixup = {}
local n = -30000
code = string.gsub(code, "CHECK_(%w*)%((.-)%)", function(tp, var)
n = n + 1
fixup[n] = { "CHECK", tp }
return format("%s=%d", var, n)
end)
code = string.gsub(code, "PAIRS%((.-)%)", function(var)
fixup.PAIRS = true
return format("nil, %s, 0", var)
end)
return "return "..code, fixup
end
local function read_uleb128(p)
local v = p[0]; p = p + 1
if v >= 128 then
local sh = 7; v = v - 128
repeat
local r = p[0]
v = v + bit.lshift(bit.band(r, 127), sh)
sh = sh + 7
p = p + 1
until r < 128
end
return p, v
end
-- ORDER LJ_T
local name2itype = {
str = 5, func = 9, tab = 12, int = 14, num = 15
}
local BC = {}
for i=0,#bcnames/6-1 do
BC[string.gsub(string.sub(bcnames, i*6+1, i*6+6), " ", "")] = i
end
local xop, xra = isbe and 3 or 0, isbe and 2 or 1
local xrc, xrb = isbe and 1 or 2, isbe and 0 or 3
local function fixup_dump(dump, fixup)
local buf = ffi.new("uint8_t[?]", #dump+1, dump)
local p = buf+5
local n, sizebc
p, n = read_uleb128(p)
local start = p
p = p + 4
p = read_uleb128(p)
p = read_uleb128(p)
p, sizebc = read_uleb128(p)
local rawtab = {}
for i=0,sizebc-1 do
local op = p[xop]
if op == BC.KSHORT then
local rd = p[xrc] + 256*p[xrb]
rd = bit.arshift(bit.lshift(rd, 16), 16)
local f = fixup[rd]
if f then
if f[1] == "CHECK" then
local tp = f[2]
if tp == "tab" then rawtab[p[xra]] = true end
p[xop] = tp == "num" and BC.ISNUM or BC.ISTYPE
p[xrb] = 0
p[xrc] = name2itype[tp]
else
error("unhandled fixup type: "..f[1])
end
end
elseif op == BC.TGETV then
if rawtab[p[xrb]] then
p[xop] = BC.TGETR
end
elseif op == BC.TSETV then
if rawtab[p[xrb]] then
p[xop] = BC.TSETR
end
elseif op == BC.ITERC then
if fixup.PAIRS then
p[xop] = BC.ITERN
end
end
p = p + 4
end
return ffi.string(start, n)
end
local function find_defs(src)
local defs = {}
for name, code in string.gmatch(src, "LJLIB_LUA%(([^)]*)%)%s*/%*(.-)%*/") do
local env = {}
local tcode, fixup = transform_lua(code)
local func = assert(load(tcode, "", nil, env))()
defs[name] = fixup_dump(string.dump(func, true), fixup)
defs[#defs+1] = name
end
return defs
end
local function gen_header(defs)
local t = {}
local function w(x) t[#t+1] = x end
w("/* This is a generated file. DO NOT EDIT! */\n\n")
w("static const int libbc_endian = ") w(isbe and 1 or 0) w(";\n\n")
local s = ""
for _,name in ipairs(defs) do
s = s .. defs[name]
end
w("static const uint8_t libbc_code[] = {\n")
local n = 0
for i=1,#s do
local x = string.byte(s, i)
w(x); w(",")
n = n + (x < 10 and 2 or (x < 100 and 3 or 4))
if n >= 75 then n = 0; w("\n") end
end
w("0\n};\n\n")
w("static const struct { const char *name; int ofs; } libbc_map[] = {\n")
local m = 0
for _,name in ipairs(defs) do
w('{"'); w(name); w('",'); w(m) w('},\n')
m = m + #defs[name]
end
w("{NULL,"); w(m); w("}\n};\n\n")
return table.concat(t)
end
local function write_file(name, data)
if name == "-" then
assert(io.write(data))
assert(io.flush())
else
local fp = io.open(name)
if fp then
local old = fp:read("*a")
fp:close()
if data == old then return end
end
fp = assert(io.open(name, "w"))
assert(fp:write(data))
assert(fp:close())
end
end
local outfile = parse_arg(arg)
local src = read_files(arg)
local defs = find_defs(src)
local hdr = gen_header(defs)
write_file(outfile, hdr)
| mit |
peterbarker/ardupilot | libraries/AP_Scripting/examples/copter-deadreckon-home.lua | 8 | 17148 | -- Copter attempts to fly home using dead reckoning if the GPS quality deteriorates or an EKF failsafe triggers
--
-- CAUTION: This script only works for Copter 4.3 (and higher)
-- this script checks for low GPS quality and/or an EKF failsafe and if either occurs, flies in the last known direction towards home
--
-- DR_ENABLE : 1 = enabled, 0 = disabled
-- DR_ENABLE_DIST : distance from home (in meters) beyond which the dead reckoning will be enabled
-- DR_GPS_SACC_MAX : GPS speed accuracy maximum, above which deadreckoning home will begin (default is 0.8). Lower values trigger with good GPS quality, higher values will allow poorer GPS before triggering. Set to 0 to disable use of GPS speed accuracy.
-- DR_GPS_SAT_MIN : GPS satellite count threshold below which deadreckoning home will begin (default is 6). Higher values trigger with good GPS quality, Lower values trigger with worse GPS quality. Set to 0 to disable use of GPS satellite count.
-- DR_GPS_TRIGG_SEC : GPS checks must fail for this many seconds before dead reckoning will be triggered.
-- DR_FLY_ANGLE : lean angle (in degrees) during deadreckoning. Most vehicles reach maximum speed at 22deg
-- DR_FLY_ALT_MIN : min alt (above home in meters) during deadreckoning. zero to return at current alt
-- DR_FLY_TIMEOUT : timeout (in seconds). Vehicle will attempt to switch to NEXT_MODE after this many seconds of deadreckoning. If it cannot switch modes it will continue in Guided_NoGPS. Set to 0 to disable timeout
-- DR_NEXT_MODE : flight mode vehicle will change to when GPS / EKF recovers or DR_FLY_TIMEOUT expires. Default is 6=RTL, see FLTMODE1 parameter description for list of flight mode number. Set to -1 to return to mode used before deadreckoning was triggered
-- How to use:
-- 1. set SCR_ENABLE = 1 to enable scripting (and reboot the autopilot)
-- 2. set SCR_HEAP_SIZE to 80000 or higher to allocate enough memory for this script
-- 3. set DR_ENABLE = 1 to enable dead reckoning
-- 4. optionally set DR_GPS_SACC_MAX and/or DR_GPS_SAT_MIN parameters to adjust how bad the GPS quality must be before triggering
-- 5. confirm "DR: waiting for dist (Xm < 50m)" message is displayed on ground station (so you know script is working)
-- 6. arm and takeoff to a safe altitude
-- 7. fly at least DR_ENABLE_DIST meters from home and confirm "DR: activated!" is displayed on ground station
--
-- If this script senses low GPS quality or an EKF failsafe triggers:
-- - vehicle will change to Guided_NoGPS mode
-- - vehicle will lean in the last known direction of home (see DR_FLY_ANGLE)
-- - if GPS recovers or EKF failsafe is cleared the vehicle will switch to DR_NEXT_MODE (if -1 then it will switch back to the mode in use before the GPS/EKF failure)
-- - if the timeout is surpassed (see DR_FLY_TIMEOUT) the vehicle will try to switch to DR_NEXT_MODE. If it fails to change it will continue in Guided_NoGPS but keep trying to change mode
-- - the pilot can retake control by switching to an "unprotected" mode like AltHold, Loiter (see "protected_mode_array" below)
--
-- Testing in SITL:
-- a. set map setshowsimpos 1 (to allow seeing where vehicle really is in simulator even with GPS disabled)
-- b. set SIM_GPS_DISABLE = 1 to disable GPS (confirm dead reckoning begins)
-- c. set SIM_GPS_DISABLE = 0 to re-enable GPS
-- d. set SIM_GPS_NUMSAT = 3 to lower simulated satellite count to confirm script triggers
-- e. set DR_GPS_SACC_MAX = 0.01 to lower the threshold and trigger below the simulator value which is 0.04 (remember to set this back after testing!)
--
-- Test on a real vehicle:
-- A. set DR_FLY_TIMEOUT to a low value (e.g. 5 seconds)
-- B. fly the vehicle at least DR_DIST_MIN meters from home and confirm the "DR: activated!" message is displayed
-- C. set GPS_TYPE = 0 to disable GPS and confirm the vehicle begins deadreckoning after a few seconds
-- D. restore GPS_TYPE to its original value (normally 1) and confirm the vehicle switches to DR_NEXT_MODE
-- E. restore DR_FLY_TIMEOUT to a higher value for real-world use
-- Note: Instaed of setting GPS_TYPE, an auxiliary function switch can be setup to disable the GPS (e.g. RC9_OPTION = 65/"Disable GPS")
--
-- Testing that it does not require RC (in SITL):
-- a. set FS_OPTIONS's "Continue if in Guided on RC failsafe" bit
-- b. set FS_GCS_ENABLE = 1 (to enable GCS failsafe otherwise RC failsafe will trigger anyway)
-- c. optionally set SYSID_MYGCS = 77 (or almost any other unused system id) to trick the above check so that GCS failsafe can really be disabled
-- d. set SIM_RC_FAIL = 1 (to simulate RC failure, note vehicle keeps flying)
-- e. set SIM_RC_FAIL = 0 (to simulate RC recovery)
--
-- Test with wind (in SITL)
-- a. SIM_WIND_DIR <-- sets direction wind is coming from
-- b. SIM_WIND_SPD <-- sets wind speed in m/s
--
-- create and initialise parameters
local PARAM_TABLE_KEY = 86 -- parameter table key must be used by only one script on a particular flight controller
assert(param:add_table(PARAM_TABLE_KEY, "DR_", 9), 'could not add param table')
assert(param:add_param(PARAM_TABLE_KEY, 1, 'ENABLE', 1), 'could not add DR_ENABLE param') -- 1 = enabled, 0 = disabled
assert(param:add_param(PARAM_TABLE_KEY, 2, 'ENABLE_DIST', 50), 'could not add DR_ENABLE_DIST param') -- distance from home (in meters) beyond which the dead reckoning will be enabled
assert(param:add_param(PARAM_TABLE_KEY, 3, 'GPS_SACC_MAX', 0.8), 'could not add DR_GPS_SACC_MAX param') -- GPS speed accuracy max threshold
assert(param:add_param(PARAM_TABLE_KEY, 4, 'GPS_SAT_MIN', 6), 'could not add DR_GPS_SAT_MIN param') -- GPS satellite count min threshold
assert(param:add_param(PARAM_TABLE_KEY, 5, 'GPS_TRIGG_SEC', 3), 'could not add DR_GPS_TRIGG_SEC parameter') -- GPS checks must fail for this many seconds before dead reckoning will be triggered
assert(param:add_param(PARAM_TABLE_KEY, 6, 'FLY_ANGLE', 10), 'could not add DR_FLY_ANGLE param') -- lean angle (in degrees) during deadreckoning
assert(param:add_param(PARAM_TABLE_KEY, 7, 'FLY_ALT_MIN', 0), 'could not add DR_FLY_ALT_MIN param') -- min alt above home (in meters) during deadreckoning. zero to return at current alt
assert(param:add_param(PARAM_TABLE_KEY, 8, 'FLY_TIMEOUT', 30), 'could not add DR_FLY_TIMEOUT param')-- deadreckoning timeout (in seconds)
assert(param:add_param(PARAM_TABLE_KEY, 9, 'NEXT_MODE', 6), 'could not add DR_NEXT_MODE param') -- mode to switch to after GPS recovers or timeout elapses
-- bind parameters to variables
local enable = Parameter("DR_ENABLE") -- 1 = enabled, 0 = disabled
local enable_dist = Parameter("DR_ENABLE_DIST") -- distance from home (in meters) beyond which the dead reckoning will be enabled
local gps_speed_acc_max = Parameter("DR_GPS_SACC_MAX") -- GPS speed accuracy max threshold
local gps_sat_count_min = Parameter("DR_GPS_SAT_MIN") -- GPS satellite count min threshold
local gps_trigger_sec = Parameter("DR_GPS_TRIGG_SEC") -- GPS checks must fail for this many seconds before dead reckoning will be triggered
local fly_angle = Parameter("DR_FLY_ANGLE") -- lean angle (in degrees) during deadreckoning
local fly_alt_min = Parameter("DR_FLY_ALT_MIN") -- min alt above home (in meters) during deadreckoning
local fly_timeoout = Parameter("DR_FLY_TIMEOUT") -- deadreckoning timeout (in seconds)
local next_mode = Parameter("DR_NEXT_MODE") -- mode to switch to after GPS recovers or timeout elapses
local wpnav_speedup = Parameter("WPNAV_SPEED_UP") -- maximum climb rate from WPNAV_SPEED_UP
local wpnav_accel_z = Parameter("WPNAV_ACCEL_Z") -- maximum vertical acceleration from WPNAV_ACCEL_Z
-- modes deadreckoning may be activated from
-- comment out lines below to remove protection from these modes
local protected_mode_array = {
3, -- AUTO
4, -- GUIDED
--5, -- LOITER
6, -- RTL
7, -- CIRCLE
9, -- LAND
--11, -- DRIFT
--16, -- POSHOLD
17, -- BRAKE
21, -- SMART_RTL
27, -- AUTO_RTL
}
function is_protected_mode()
local curr_mode = vehicle:get_mode()
for i = 1, #protected_mode_array do
if curr_mode == protected_mode_array[i] then
return true
end
end
return false
end
local copter_guided_nogps_mode = 20 -- Guided_NoGPS is mode 20 on Copter
local copter_RTL_mode = 6 -- RTL is mode 6 on Copter
local recovery_delay_ms = 3000 -- switch to NEXT_MODE happens this many milliseconds after GPS and EKF failsafe recover
local gps_bad = false -- true if GPS is failing checks
local ekf_bad = false -- true if EKF failsafe has triggered
local gps_or_ekf_bad = true -- true if GPS and/or EKF is bad, true once both have recovered
local flight_stage = 0 -- 0. wait for good-gps and dist-from-home, 1=wait for bad gps or ekf, 2=level vehicle, 3=deadreckon home
local gps_bad_start_time_ms = 0 -- system time GPS quality went bad (0 if not bad)
local recovery_start_time_ms = 0-- system time GPS quality and EKF failsafe recovered (0 if not recovered)
local fly_start_time_ms = 0 -- system time fly using deadreckoning started
local home_dist = 0 -- distance to home in meters
local home_yaw = 0 -- direction to home in degrees
local target_yaw = 0 -- deg
local climb_rate = 0 -- m/s
local stage1_flight_mode = nil -- flight mode vehicle was in during stage1 (may be used during recovery)
local stage2_start_time_ms -- system time stage2 started (level vehicle)
local stage3_start_time_ms -- system time stage3 started (deadreckon home)
local last_print_ms = 0 -- pilot update timer
local interval_ms = 100 -- update at 10hz
function update()
-- exit immediately if not enabled
if (enable:get() < 1) then
return update, 1000
end
-- determine if progress update should be sent to user
local now_ms = millis()
local update_user = false
if (now_ms - last_print_ms > 5000) then
last_print_ms = now_ms
update_user = true
end
-- check GPS
local gps_primary = gps:primary_sensor()
local gps_speed_acc = gps:speed_accuracy(gps:primary_sensor())
if gps_speed_acc == nil then
gps_speed_acc = 99
end
local gps_speed_acc_bad = ((gps_speed_acc_max:get() > 0) and (gps_speed_acc > gps_speed_acc_max:get()))
local gps_num_sat = gps:num_sats(gps:primary_sensor())
local gps_num_sat_bad = (gps_sat_count_min:get() > 0) and ((gps_num_sat == nil) or (gps:num_sats(gps:primary_sensor()) < gps_sat_count_min:get()))
if gps_bad then
-- GPS is bad, check for recovery
if (not gps_speed_acc_bad and not gps_num_sat_bad) then
gps_bad = false
end
else
-- GPS is good, check for GPS going bad
if (gps_speed_acc_bad or gps_num_sat_bad) then
if (gps_bad_start_time_ms == 0) then
-- start gps bad timer
gps_bad_start_time_ms = now_ms
elseif (now_ms - gps_bad_start_time_ms > gps_trigger_sec:get()) then
gps_bad = true
end
end
end
-- check EKF failsafe
local fs_ekf = vehicle:has_ekf_failsafed()
if not (ekf_bad == fs_ekf) then
ekf_bad = fs_ekf
end
-- check for GPS and/or EKF going bad
if not gps_or_ekf_bad and (gps_bad or ekf_bad) then
gps_or_ekf_bad = true
gcs:send_text(0, "DR: GPS or EKF bad")
end
-- check for GPS and/or EKF recovery
if (gps_or_ekf_bad and (not gps_bad and not ekf_bad)) then
-- start recovery timer
if recovery_start_time_ms == 0 then
recovery_start_time_ms = now_ms
end
if (now_ms - recovery_start_time_ms > recovery_delay_ms) then
gps_or_ekf_bad = false
recovery_start_time_ms = 0
gcs:send_text(0, "DR: GPS and EKF recovered")
end
end
-- update distance and direction home while GPS and EKF are good
if (not gps_or_ekf_bad) then
local home = ahrs:get_home()
local curr_loc = ahrs:get_location()
if home and curr_loc then
home_dist = curr_loc:get_distance(home)
home_yaw = math.deg(curr_loc:get_bearing(home))
elseif (update_user) then
-- warn user of unexpected failure
gcs:send_text(0, "DR: could not get home or vehicle location")
end
end
-- reset flight_stage when disarmed
if not arming:is_armed() then
flight_stage = 0
fly_start_time_ms = 0
transition_start_time_ms = 0
return update, interval_ms
end
-- flight_stage 0: wait for good gps and dist-from-home
if (flight_stage == 0) then
-- wait for GPS and EKF to be good
if (gps_or_ekf_bad) then
return update, interval_ms
end
-- wait for distance from home to pass DR_ENABLE_DIST
if ((home_dist > 0) and (home_dist >= enable_dist:get())) then
gcs:send_text(5, "DR: enabled")
flight_stage = 1
elseif (update_user) then
gcs:send_text(5, "DR: waiting for dist:" .. tostring(math.floor(home_dist)) .. " need:" .. tostring(math.floor(enable_dist:get())))
end
return update, interval_ms
end
-- flight_stage 1: wait for bad gps or ekf
if (flight_stage == 1) then
if (gps_or_ekf_bad and is_protected_mode()) then
-- change to Guided_NoGPS and initialise stage2
if (vehicle:set_mode(copter_guided_nogps_mode)) then
flight_stage = 2
target_yaw = math.deg(ahrs:get_yaw())
stage2_start_time_ms = now_ms
else
-- warn user of unexpected failure
if (update_user) then
gcs:send_text(5, "DR: failed to change to Guided_NoGPS mode")
end
end
else
-- store flight mode (may be used during recovery)
stage1_flight_mode = vehicle:get_mode()
end
return update, interval_ms
end
-- flight_stage 2: level vehicle for 5 seconds
if (flight_stage == 2) then
-- allow pilot to retake control
if (vehicle:get_mode() ~= copter_guided_nogps_mode) then
gcs:send_text(5, "DR: pilot retook control")
flight_stage = 1
return update, interval_ms
end
-- level vehicle for 5 seconds
climb_rate = 0
vehicle:set_target_angle_and_climbrate(0, 0, target_yaw, climb_rate, false, 0)
if ((now_ms - stage2_start_time_ms) >= 5000) then
flight_stage = 3
stage3_start_time_ms = now_ms
gcs:send_text(5, "DR: flying home")
end
if (update_user) then
gcs:send_text(5, "DR: leveling vehicle")
end
return update, interval_ms
end
-- flight_stage 3: deadreckon towards home
if (flight_stage == 3) then
-- allow pilot to retake control
if (vehicle:get_mode() ~= copter_guided_nogps_mode) then
gcs:send_text(5, "DR: pilot retook control")
flight_stage = 1
return update, interval_ms
end
-- check for timeout
local time_elapsed_ms = now_ms - stage3_start_time_ms
local timeout = (fly_timeoout:get() > 0) and (time_elapsed_ms >= (fly_timeoout:get() * 1000))
-- calculate climb rate in m/s
if (fly_alt_min:get() > 0) then
local curr_alt_below_home = ahrs:get_relative_position_D_home()
if curr_alt_below_home then
local target_alt_above_vehicle = fly_alt_min:get() + curr_alt_below_home
if target_alt_above_vehicle > 0 then
-- climb at up to 1m/s towards target above vehicle. climb rate change is limited by WPNAV_ACCEL_Z
local climb_rate_chg_max = interval_ms * 0.001 * (wpnav_accel_z:get() * 0.01)
climb_rate = math.min(target_alt_above_vehicle * 0.1, wpnav_speedup:get() * 0.01, climb_rate + climb_rate_chg_max)
end
end
end
-- set angle target to roll 0, pitch to lean angle (note: negative is forward), yaw towards home
if (vehicle:set_target_angle_and_climbrate(0, -math.abs(fly_angle:get()), home_yaw, climb_rate, false, 0)) then
if (update_user) then
local time_left_str = ""
if (not timeout and (fly_timeoout:get() > 0)) then
time_left_str = " t:" .. tostring(math.max(0, ((fly_timeoout:get() * 1000) - time_elapsed_ms) / 1000))
end
gcs:send_text(5, "DR: fly home yaw:" .. tostring(math.floor(home_yaw)) .. " pit:" .. tostring(math.floor(fly_angle:get())) .. " cr:" .. tostring(math.floor(climb_rate*10)/10) .. time_left_str)
end
elseif (update_user) then
gcs:send_text(0, "DR: failed to set attitude target")
end
-- if GPS and EKF recover or timeout switch to next mode
if (not gps_or_ekf_bad) or timeout then
local recovery_mode = stage1_flight_mode
if (next_mode:get() >= 0) then
recovery_mode = next_mode:get()
end
if (recovery_mode == nil) then
recovery_mode = copter_RTL_mode
gcs:send_text(0, "DR: NEXT_MODE=-1 but fallingback to RTL")
end
-- change to DR_NEXT_MODE
if (vehicle:set_mode(recovery_mode)) then
flight_stage = 0
elseif (update_user) then
-- warn user of unexpected failure
gcs:send_text(0, "DR: failed to change to mode " .. tostring(recovery_mode))
end
end
return update, interval_ms
end
-- we should never get here but just in case
return update, interval_ms
end
return update()
| gpl-3.0 |
NightWitch/Clever | redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| agpl-3.0 |
esguk811/DarkRP | gamemode/modules/fadmin/fadmin/playeractions/freeze/cl_init.lua | 10 | 1858 | FAdmin.StartHooks["Freeze"] = function()
FAdmin.Messages.RegisterNotification{
name = "freeze",
hasTarget = true,
message = {"instigator", " froze ", "targets", " ", "extraInfo.1"},
readExtraInfo = function()
local time = net.ReadUInt(16)
return {time == 0 and FAdmin.PlayerActions.commonTimes[time] or string.format("for %s", FAdmin.PlayerActions.commonTimes[time] or (time .. " seconds"))}
end
}
FAdmin.Messages.RegisterNotification{
name = "unfreeze",
hasTarget = true,
message = {"instigator", " unfroze ", "targets"},
}
FAdmin.Access.AddPrivilege("Freeze", 2)
FAdmin.Commands.AddCommand("freeze", nil, "<Player>")
FAdmin.Commands.AddCommand("unfreeze", nil, "<Player>")
FAdmin.ScoreBoard.Player:AddActionButton(function(ply)
if ply:FAdmin_GetGlobal("FAdmin_frozen") then return "Unfreeze" end
return "Freeze"
end, function(ply)
if ply:FAdmin_GetGlobal("FAdmin_frozen") then return "fadmin/icons/freeze", "fadmin/icons/disable" end
return "fadmin/icons/freeze"
end, Color(255, 130, 0, 255),
function(ply) return FAdmin.Access.PlayerHasPrivilege(LocalPlayer(), "Freeze", ply) end, function(ply, button)
if not ply:FAdmin_GetGlobal("FAdmin_frozen") then
FAdmin.PlayerActions.addTimeMenu(function(secs)
RunConsoleCommand("_FAdmin", "freeze", ply:UserID(), secs)
button:SetImage2("fadmin/icons/disable")
button:SetText("Unfreeze")
button:GetParent():InvalidateLayout()
end)
else
RunConsoleCommand("_FAdmin", "unfreeze", ply:UserID())
end
button:SetImage2("null")
button:SetText("Freeze")
button:GetParent():InvalidateLayout()
end)
end
| mit |
sys4-fr/server-minetestforfun | mods/nalc/maptools.lua | 1 | 4538 | -- Nodes
minetest.register_node(
"nalc:stone_with_coin",
{ description = "Stone with Coin",
tiles = {"default_stone.png^maptools_gold_coin.png"},
is_ground_content = true,
groups = {cracky = 3},
drop = {
items = {
{items = {"maptools:gold_coin"}},
},
},
sounds = default.node_sound_stone_defaults(),
})
minetest.register_alias("default:stone_with_coin", "nalc:stone_with_coin")
-- Ores
minetest.register_ore(
{ ore_type = "scatter",
ore = "nalc:stone_with_coin",
wherein = "default:stone",
clust_scarcity = 26 * 26 * 26,
clust_num_ores = 1,
clust_size = 1,
y_min = -30000,
y_max = 0,
flags = "absheight",
})
-- Super Apples
minetest.register_ore({
ore_type = "scatter",
ore = "maptools:superapple",
wherein = "default:apple",
clust_scarcity = 6 * 6 * 6,
clust_num_ores = 5,
clust_size = 2,
y_min = 0,
y_max = 64,
})
minetest.register_ore({
ore_type = "scatter",
ore = "maptools:superapple",
wherein = "default:jungleleaves",
clust_scarcity = 16 * 16 * 16,
clust_num_ores = 5,
clust_size = 2,
y_min = 0,
y_max = 64,
})
-- Override items
minetest.override_item(
"default:desert_stone",
{
drop = {
items = {
{items = {"default:desert_cobble"}},
{items = {"maptools:copper_coin"}, rarity = 20}
}
}
})
local drop = minetest.registered_items["default:dirt"].drop
if drop then
table.insert(drop.items, 1, {items = {"maptools:copper_coin", "default:dirt"}, rarity = 32})
else
minetest.override_item(
"default:dirt",
{
drop = {
items = {
{items = {"default:dirt"}},
{items = {"maptools:copper_coin"}, rarity = 32}
}
}
})
end
minetest.override_item(
"default:stone_with_coal",
{
drop = {
items = {
{items = {"default:coal_lump"}},
{items = {"maptools:copper_coin"}}
}
}
})
minetest.override_item(
"nalc:desert_stone_with_coal",
{
drop = {
items = {
{items = {"default:coal_lump"}},
{items = {"maptools:copper_coin"}}
}
}
})
minetest.override_item(
"default:stone_with_iron",
{
drop = {
items = {
{items = {"default:iron_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
minetest.override_item(
"nalc:desert_stone_with_iron",
{
drop = {
items = {
{items = {"default:iron_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
minetest.override_item(
"default:stone_with_copper",
{
drop = {
items = {
{items = {"default:copper_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
minetest.override_item(
"nalc:desert_stone_with_copper",
{
drop = {
items = {
{items = {"default:copper_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
if minetest.registered_items["default:stone_with_tin"] then
minetest.override_item(
"default:stone_with_tin",
{
drop = {
items = {
{items = {"default:tin_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
end
minetest.override_item(
"nalc:desert_stone_with_tin",
{
drop = {
items = {
{items = {"default:tin_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
minetest.override_item(
"default:stone_with_mese",
{
drop = {
items = {
{items = {"default:mese_crystal"}},
{items = {"maptools:silver_coin 2", rarity = 75}},
}
}
})
minetest.override_item(
"default:stone_with_gold",
{
drop = {
items = {
{items = {"default:gold_lump"}},
{items = {"maptools:silver_coin", rarity = 80}},
}
}
})
minetest.override_item(
"default:stone_with_diamond",
{
drop = {
items = {
{items = {"default:diamond"}},
{items = {"maptools:silver_coin"}},
}
}
})
if minetest.get_modpath("moreores") then
minetest.override_item(
"moreores:mineral_silver",
{
drop = {
items = {
{items = {"moreores:silver_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
minetest.override_item(
"moreores:mineral_mithril",
{
drop = {
items = {
{items = {"moreores:mithril_lump"}},
{items = {"maptools:silver_coin 3"}},
}
}
})
minetest.override_item(
"nalc:desert_stone_with_silver",
{
drop = {
items = {
{items = {"moreores:silver_lump"}},
{items = {"maptools:copper_coin 3"}}
}
}
})
end
| unlicense |
esguk811/DarkRP | entities/entities/drug/init.lua | 3 | 2731 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
local function UnDrugPlayer(ply)
if not IsValid(ply) then return end
ply.isDrugged = false
local IDSteam = ply:SteamID64()
timer.Remove(IDSteam .. "DruggedHealth")
SendUserMessage("DrugEffects", ply, false)
end
hook.Add("PlayerDeath", "UndrugPlayers", function(ply) if ply.isDrugged then UnDrugPlayer(ply) end end)
local function DrugPlayer(ply)
if not IsValid(ply) then return end
SendUserMessage("DrugEffects", ply, true)
ply.isDrugged = true
local IDSteam = ply:SteamID64()
if not timer.Exists(IDSteam .. "DruggedHealth") then
ply:SetHealth(ply:Health() + 100)
timer.Create(IDSteam .. "DruggedHealth", 60 / (100 + 5), 100 + 5, function()
if not IsValid(ply) then return end
ply:SetHealth(ply:Health() - 1)
if ply:Health() <= 0 then
ply:Kill()
end
if timer.RepsLeft(IDSteam .. "DruggedHealth") == 0 then
UnDrugPlayer(ply)
end
end)
end
end
function ENT:Initialize()
self:SetModel("models/props_lab/jar01a.mdl")
self:PhysicsInit(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self.CanUse = true
local phys = self:GetPhysicsObject()
phys:Wake()
self.damage = 10
self:Setprice(self:Getprice() or 100)
self.SeizeReward = GAMEMODE.Config.pricemin or 35
end
function ENT:OnTakeDamage(dmg)
self:TakePhysicsDamage(dmg)
self.damage = self.damage - dmg:GetDamage()
if self.damage <= 0 then
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos())
effectdata:SetMagnitude(2)
effectdata:SetScale(2)
effectdata:SetRadius(3)
util.Effect("Sparks", effectdata)
self:Remove()
end
end
function ENT:Use(activator,caller)
if not self.CanUse then return end
local Owner = self:Getowning_ent()
if not IsValid(Owner) then return end
if activator ~= Owner then
if not activator:canAfford(self:Getprice()) then return end
DarkRP.payPlayer(activator, Owner, self:Getprice())
DarkRP.notify(activator, 0, 4, DarkRP.getPhrase("you_bought", string.lower(DarkRP.getPhrase("drugs")), DarkRP.formatMoney(self:Getprice()), ""))
DarkRP.notify(Owner, 0, 4, DarkRP.getPhrase("you_received_x", DarkRP.formatMoney(self:Getprice()), string.lower(DarkRP.getPhrase("drugs"))))
end
DrugPlayer(caller)
self.CanUse = false
self:Remove()
end
function ENT:OnRemove()
local ply = self:Getowning_ent()
if not IsValid(ply) then return end
ply.maxDrugs = ply.maxDrugs - 1
end
| mit |
Marnador/OpenRA-Marn-TS-Edition | lua/sandbox.lua | 84 | 5098 | local sandbox = {
_VERSION = "sandbox 0.5",
_DESCRIPTION = "A pure-lua solution for running untrusted Lua code.",
_URL = "https://github.com/kikito/sandbox.lua",
_LICENSE = [[
MIT LICENSE
Copyright (c) 2013 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
-- The base environment is merged with the given env option (or an empty table, if no env provided)
--
local BASE_ENV = {}
-- List of non-safe packages/functions:
--
-- * string.rep: can be used to allocate millions of bytes in 1 operation
-- * {set|get}metatable: can be used to modify the metatable of global objects (strings, integers)
-- * collectgarbage: can affect performance of other systems
-- * dofile: can access the server filesystem
-- * _G: It has access to everything. It can be mocked to other things though.
-- * load{file|string}: All unsafe because they can grant acces to global env
-- * raw{get|set|equal}: Potentially unsafe
-- * module|require|module: Can modify the host settings
-- * string.dump: Can display confidential server info (implementation of functions)
-- * string.rep: Can allocate millions of bytes in one go
-- * math.randomseed: Can affect the host sytem
-- * io.*, os.*: Most stuff there is non-save
-- Safe packages/functions below
([[
_VERSION assert error ipairs next pairs
pcall select tonumber tostring type unpack xpcall
coroutine.create coroutine.resume coroutine.running coroutine.status
coroutine.wrap coroutine.yield
math.abs math.acos math.asin math.atan math.atan2 math.ceil
math.cos math.cosh math.deg math.exp math.fmod math.floor
math.frexp math.huge math.ldexp math.log math.log10 math.max
math.min math.modf math.pi math.pow math.rad
math.sin math.sinh math.sqrt math.tan math.tanh
os.clock os.difftime os.time
string.byte string.char string.find string.format string.gmatch
string.gsub string.len string.lower string.match string.reverse
string.sub string.upper
table.insert table.maxn table.remove table.sort
]]):gsub('%S+', function(id)
local module, method = id:match('([^%.]+)%.([^%.]+)')
if module then
BASE_ENV[module] = BASE_ENV[module] or {}
BASE_ENV[module][method] = _G[module][method]
else
BASE_ENV[id] = _G[id]
end
end)
local function protect_module(module, module_name)
return setmetatable({}, {
__index = module,
__newindex = function(_, attr_name, _)
error('Can not modify ' .. module_name .. '.' .. attr_name .. '. Protected by the sandbox.')
end
})
end
('coroutine math os string table'):gsub('%S+', function(module_name)
BASE_ENV[module_name] = protect_module(BASE_ENV[module_name], module_name)
end)
-- auxiliary functions/variables
local string_rep = string.rep
local function merge(dest, source)
for k,v in pairs(source) do
dest[k] = dest[k] or v
end
return dest
end
local function sethook(f, key, quota)
if type(debug) ~= 'table' or type(debug.sethook) ~= 'function' then return end
debug.sethook(f, key, quota)
end
local function cleanup()
sethook()
string.rep = string_rep
end
-- Public interface: sandbox.protect
function sandbox.protect(f, options)
if type(f) == 'string' then f = assert(loadstring(f)) end
options = options or {}
local quota = false
if options.quota ~= false then
quota = options.quota or 500000
end
local env = merge(options.env or {}, BASE_ENV)
env._G = env._G or env
setfenv(f, env)
return function(...)
if quota then
local timeout = function()
cleanup()
error('Quota exceeded: ' .. tostring(quota))
end
sethook(timeout, "", quota)
end
string.rep = nil
local ok, result = pcall(f, ...)
cleanup()
if not ok then error(result) end
return result
end
end
-- Public interface: sandbox.run
function sandbox.run(f, options, ...)
return sandbox.protect(f, options)(...)
end
-- make sandbox(f) == sandbox.protect(f)
setmetatable(sandbox, {__call = function(_,f,o) return sandbox.protect(f,o) end})
return sandbox
| gpl-3.0 |
42wim/wptvscraper | weepeetv.lua | 1 | 1319 | --SD_Description=WeePee TV
--[[
Copyright (C) 2013 <wim at 42 dot be>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
require "simplexml"
function descriptor()
return { title="WeePee TV" }
end
function main()
local tree = simplexml.parse_url("http://yourserver.url/wptv.xml")
for _, items in ipairs( tree.children ) do
simplexml.add_name_maps(items)
local url = vlc.strings.resolve_xml_special_chars( items.children_map['h264'][1].children[1] )
local title = vlc.strings.resolve_xml_special_chars( items.children_map['title'][1].children[1] )
local arturl = vlc.strings.resolve_xml_special_chars( items.children_map['thumb'][1].children[1] )
vlc.sd.add_item( { path = url, title = title , arturl = arturl } )
end
end
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Kazham/npcs/Rauteinot.lua | 26 | 3159 | -----------------------------------
-- Area: Kazham
-- NPC: Rauteinot
-- Starts and Finishes Quest: Missionary Man
-- @zone 250
-- @pos -42 -10 -89
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getVar("MissionaryManVar") == 1 and trade:hasItemQty(1146,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x008b); -- Trading elshimo marble
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MissionaryMan = player:getQuestStatus(OUTLANDS,MISSIONARY_MAN);
MissionaryManVar = player:getVar("MissionaryManVar");
if (MissionaryMan == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 3) then
player:startEvent(0x0089,0,1146); -- Start quest "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 1) then
player:startEvent(0x008a,0,1146); -- During quest (before trade marble) "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and (MissionaryManVar == 2 or MissionaryManVar == 3)) then
player:startEvent(0x008c); -- During quest (after trade marble) "Missionary Man"
elseif (MissionaryMan == QUEST_ACCEPTED and MissionaryManVar == 4) then
player:startEvent(0x008d); -- Finish quest "Missionary Man"
elseif (MissionaryMan == QUEST_COMPLETED) then
player:startEvent(0x008e); -- New standard dialog
else
player:startEvent(0x0088); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0089 and option == 1) then
player:addQuest(OUTLANDS,MISSIONARY_MAN);
player:setVar("MissionaryManVar",1);
elseif (csid == 0x008b) then
player:setVar("MissionaryManVar",2);
player:addKeyItem(RAUTEINOTS_PARCEL);
player:messageSpecial(KEYITEM_OBTAINED,RAUTEINOTS_PARCEL);
player:tradeComplete();
elseif (csid == 0x008d) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,4728);
else
player:setVar("MissionaryManVar",0);
player:delKeyItem(SUBLIME_STATUE_OF_THE_GODDESS);
player:addItem(4728);
player:messageSpecial(ITEM_OBTAINED,4728);
player:addFame(WINDURST,30);
player:completeQuest(OUTLANDS,MISSIONARY_MAN);
end
end
end; | gpl-3.0 |
rpetit3/darkstar | scripts/globals/weaponskills/heavy_swing.lua | 25 | 1367 | -----------------------------------
-- Heavy Swing
-- Staff weapon skill
-- Skill Level: 5
-- Deacription:Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 2.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 2.25;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, tp, primary, action, taChar, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
rpetit3/darkstar | scripts/globals/spells/bluemagic/foot_kick.lua | 35 | 1687 | -----------------------------------------
-- Spell: Foot Kick
-- Deals critical damage. Chance of critical hit varies with TP
-- Spell cost: 5 MP
-- Monster Type: Beasts
-- Spell Type: Physical (Slashing)
-- Blue Magic Points: 2
-- Stat Bonus: AGI+1
-- Level: 1
-- Casting Time: 0.5 seconds
-- Recast Time: 6.5 seconds
-- Skillchain Property: Detonation (can open Scission or Gravitation)
-- Combos: Lizard 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_CRITICAL;
params.dmgtype = DMGTYPE_SLASH;
params.scattr = SC_DETONATION;
params.numhits = 1;
params.multiplier = 1.0;
params.tp150 = 1.0;
params.tp300 = 1.0;
params.azuretp = 1.0;
params.duppercap = 9;
params.str_wsc = 0.1;
params.dex_wsc = 0.1;
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;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
MinetestForFun/server-minetestforfun-creative | minetestforfun_game/mods/farming/tomato.lua | 12 | 2097 |
--[[
Textures edited from:
http://www.minecraftforum.net/forums/mapping-and-modding/minecraft-mods/1288375-food-plus-mod-more-food-than-you-can-imagine-v2-9)
]]
local S = farming.intllib
-- tomato
minetest.register_craftitem("farming:tomato", {
description = S("Tomato"),
inventory_image = "farming_tomato.png",
on_place = function(itemstack, placer, pointed_thing)
return farming.place_seed(itemstack, placer, pointed_thing, "farming:tomato_1")
end,
on_use = minetest.item_eat(4),
})
-- tomato definition
local crop_def = {
drawtype = "plantlike",
tiles = {"farming_tomato_1.png"},
paramtype = "light",
sunlight_propagates = true,
walkable = false,
buildable_to = true,
drop = "",
selection_box = farming.select,
groups = {
snappy = 3, flammable = 2, plant = 1, attached_node = 1,
not_in_creative_inventory = 1, growing = 1
},
sounds = default.node_sound_leaves_defaults()
}
-- stage 1
minetest.register_node("farming:tomato_1", table.copy(crop_def))
-- stage2
crop_def.tiles = {"farming_tomato_2.png"}
minetest.register_node("farming:tomato_2", table.copy(crop_def))
-- stage 3
crop_def.tiles = {"farming_tomato_3.png"}
minetest.register_node("farming:tomato_3", table.copy(crop_def))
-- stage 4
crop_def.tiles = {"farming_tomato_4.png"}
minetest.register_node("farming:tomato_4", table.copy(crop_def))
-- stage 5
crop_def.tiles = {"farming_tomato_5.png"}
minetest.register_node("farming:tomato_5", table.copy(crop_def))
-- stage 6
crop_def.tiles = {"farming_tomato_6.png"}
minetest.register_node("farming:tomato_6", table.copy(crop_def))
-- stage 7
crop_def.tiles = {"farming_tomato_7.png"}
crop_def.drop = {
items = {
{items = {'farming:tomato'}, rarity = 1},
{items = {'farming:tomato'}, rarity = 3},
}
}
minetest.register_node("farming:tomato_7", table.copy(crop_def))
-- stage 8 (final)
crop_def.tiles = {"farming_tomato_8.png"}
crop_def.groups.growing = 0
crop_def.drop = {
items = {
{items = {'farming:tomato 3'}, rarity = 1},
{items = {'farming:tomato 3'}, rarity = 2},
}
}
minetest.register_node("farming:tomato_8", table.copy(crop_def))
| unlicense |
rpetit3/darkstar | scripts/zones/East_Sarutabaruta/npcs/Sama_Gohjima.lua | 13 | 1487 | -----------------------------------
-- Area: East Sarutabaruta
-- NPC: Sama Gohjima
-- Involved in Mission: The Horutoto Ruins Experiment (optional)
-- @pos 377 -13 98 116
-----------------------------------
package.loaded["scripts/zones/East_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/East_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 1) then
player:showText(npc,SAMA_GOHJIMA_PREDIALOG);
elseif (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") ~= 1) then
player:messageSpecial(SAMA_GOHJIMA_POSTDIALOG);
else
player:startEvent(0x002b);
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 |
rpetit3/darkstar | scripts/zones/Abyssea-Misareaux/npcs/qm13.lua | 17 | 1523 | -----------------------------------
-- Zone: Abyssea-Misereaux
-- NPC: ???
-- Spawns: Cirein-Croin
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17662481) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(GLISTENING_OROBON_LIVER) and player:hasKeyItem(DOFFED_POROGGO_HAT)) then
player:startEvent(1021, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Ask if player wants to use KIs
else
player:startEvent(1020, GLISTENING_OROBON_LIVER, DOFFED_POROGGO_HAT); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1021 and option == 1) then
SpawnMob(17662481):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(GLISTENING_OROBON_LIVER);
player:delKeyItem(DOFFED_POROGGO_HAT);
end
end; | gpl-3.0 |
libretro/lutro-pong | Background.lua | 1 | 1420 | local ColoredEntity = require("Lutron/Entity/ColoredEntity")
local Background
do
local _class_0
local _parent_0 = ColoredEntity
local _base_0 = {
load = function(self)
self.padding = 10
self.length = 10
self.lineSpacing = 20
self.position.x = self.game.width / 2
end,
draw = function(self)
_class_0.__parent.__base.draw(self)
for i = self.padding, self.game.height - self.padding, self.length + self.lineSpacing do
lutro.graphics.line(self.position.x, i, self.position.x, i + self.length)
end
end
}
_base_0.__index = _base_0
setmetatable(_base_0, _parent_0.__base)
_class_0 = setmetatable({
__init = function(self, game)
_class_0.__parent.__init(self)
self.game = game
end,
__base = _base_0,
__name = "Background",
__parent = _parent_0
}, {
__index = function(cls, name)
local val = rawget(_base_0, name)
if val == nil then
local parent = rawget(cls, "__parent")
if parent then
return parent[name]
end
else
return val
end
end,
__call = function(cls, ...)
local _self_0 = setmetatable({}, _base_0)
cls.__init(_self_0, ...)
return _self_0
end
})
_base_0.__class = _class_0
if _parent_0.__inherited then
_parent_0.__inherited(_parent_0, _class_0)
end
Background = _class_0
return _class_0
end
| mit |
Marnador/OpenRA-Marn-TS-Edition | mods/ra/maps/survival02/survival02.lua | 10 | 13010 | FrenchSquad = { "2tnk", "2tnk", "mcv" }
TimerTicks = DateTime.Minutes(10)
AttackTicks = DateTime.Seconds(52)
AttackAtFrame = DateTime.Seconds(18)
AttackAtFrameIncrement = DateTime.Seconds(18)
Producing = true
SpawningInfantry = true
ProduceAtFrame = DateTime.Seconds(12)
ProduceAtFrameIncrement = DateTime.Seconds(12)
SovietGroupSize = 4
SovietAttackGroupSize = 7
InfantryGuards = { }
HarvGuards = { HarvGuard1, HarvGuard2, HarvGuard3 }
SovietPlatoonUnits = { "e1", "e1", "e2", "e4", "e4", "e1", "e1", "e2", "e4", "e4" }
SovietTanks = { "3tnk", "3tnk", "3tnk" }
SovietVehicles = { "3tnk", "3tnk", "v2rl" }
SovietInfantry = { "e1", "e4", "e2" }
SovietEntryPoints = { SovietEntry1, SovietEntry2, SovietEntry3 }
SovietRallyPoints = { SovietRally2, SovietRally4, SovietRally5, SovietRally6 }
NewSovietEntryPoints = { SovietParaDropEntry, SovietEntry3 }
NewSovietRallyPoints = { SovietRally3, SovietRally4, SovietRally8 }
ParaWaves =
{
{ delay = AttackTicks, type = "SovietSquad", target = SovietRally5 },
{ delay = 0, type = "SovietSquad", target = SovietRally6 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop3 },
{ delay = 0, type = "SovietPlatoonUnits", target = SovietRally5 },
{ delay = 0, type = "SovietPlatoonUnits", target = SovietRally6 },
{ delay = 0, type = "SovietSquad", target = SovietRally2 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop2 },
{ delay = AttackTicks * 2, type = "SovietSquad", target = SovietParaDrop1 },
{ delay = AttackTicks * 3, type = "SovietSquad", target = SovietParaDrop1 }
}
IdleHunt = function(unit)
Trigger.OnIdle(unit, function(a)
if a.IsInWorld then
a.Hunt()
end
end)
end
GuardHarvester = function(unit, harvester)
if not unit.IsDead then
unit.Stop()
local start = unit.Location
if not harvester.IsDead then
unit.AttackMove(harvester.Location)
else
unit.Hunt()
end
Trigger.OnIdle(unit, function()
if unit.Location == start then
Trigger.ClearAll(unit)
else
unit.AttackMove(start)
end
end)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end
end
ticked = TimerTicks
Tick = function()
if soviets.HasNoRequiredUnits() then
if DestroyObj then
allies.MarkCompletedObjective(DestroyObj)
else
DestroyObj = allies.AddPrimaryObjective("Destroy all Soviet forces in the area.")
allies.MarkCompletedObjective(DestroyObj)
end
end
if allies.HasNoRequiredUnits() then
soviets.MarkCompletedObjective(SovietObj)
end
if soviets.Resources > soviets.ResourceCapacity / 2 then
soviets.Resources = soviets.ResourceCapacity / 2
end
if DateTime.GameTime == ProduceAtFrame then
if SpawningInfantry then
ProduceAtFrame = ProduceAtFrame + ProduceAtFrameIncrement
ProduceAtFrameIncrement = ProduceAtFrameIncrement * 2 - 5
SpawnSovietInfantry()
end
end
if DateTime.GameTime == AttackAtFrame then
AttackAtFrame = AttackAtFrame + AttackAtFrameIncrement
AttackAtFrameIncrement = AttackAtFrameIncrement * 2 - 5
if Producing then
SpawnSovietVehicle(SovietEntryPoints, SovietRallyPoints)
else
SpawnSovietVehicle(NewSovietEntryPoints, NewSovietRallyPoints)
end
end
if DateTime.Minutes(5) == ticked then
Media.PlaySpeechNotification(allies, "WarningFiveMinutesRemaining")
InitCountDown()
end
if ticked > 0 then
UserInterface.SetMissionText("Soviet reinforcements arrive in " .. Utils.FormatTime(ticked), TimerColor)
ticked = ticked - 1
elseif ticked == 0 then
FinishTimer()
ticked = ticked - 1
end
end
SendSovietParadrops = function(table)
local paraproxy = Actor.Create(table.type, false, { Owner = soviets })
units = paraproxy.SendParatroopers(table.target.CenterPosition)
Utils.Do(units, function(unit) IdleHunt(unit) end)
paraproxy.Destroy()
end
SpawnSovietInfantry = function()
soviets.Build({ Utils.Random(SovietInfantry) }, function(units)
IdleHunt(units[1])
end)
end
SpawnSovietVehicle = function(spawnpoints, rallypoints)
local route = Utils.RandomInteger(1, #spawnpoints + 1)
local rally = Utils.RandomInteger(1, #rallypoints + 1)
local unit = Reinforcements.Reinforce(soviets, { Utils.Random(SovietVehicles) }, { spawnpoints[route].Location })[1]
unit.AttackMove(rallypoints[rally].Location)
IdleHunt(unit)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end
SpawnAndAttack = function(types, entry)
local units = Reinforcements.Reinforce(soviets, types, { entry })
Utils.Do(units, function(unit)
IdleHunt(unit)
Trigger.OnCapture(unit, function()
Trigger.ClearAll(unit)
end)
end)
return units
end
SendFrenchReinforcements = function()
local camera = Actor.Create("camera", true, { Owner = allies, Location = SovietRally1.Location })
Beacon.New(allies, FranceEntry.CenterPosition - WVec.New(0, 3 * 1024, 0))
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, FrenchSquad, { FranceEntry.Location, FranceRally.Location })
Trigger.AfterDelay(DateTime.Seconds(3), function() camera.Destroy() end)
end
FrenchReinforcements = function()
Camera.Position = SovietRally1.CenterPosition
if drum1.IsDead or drum2.IsDead or drum3.IsDead then
SendFrenchReinforcements()
return
end
powerproxy = Actor.Create("powerproxy.parabombs", false, { Owner = allies })
powerproxy.SendAirstrike(drum1.CenterPosition, false, Facing.NorthEast + 4)
powerproxy.SendAirstrike(drum2.CenterPosition, false, Facing.NorthEast)
powerproxy.SendAirstrike(drum3.CenterPosition, false, Facing.NorthEast - 4)
powerproxy.Destroy()
Trigger.AfterDelay(DateTime.Seconds(3), function()
SendFrenchReinforcements()
end)
end
FinalAttack = function()
local units1 = SpawnAndAttack(SovietTanks, SovietEntry1.Location)
local units2 = SpawnAndAttack(SovietTanks, SovietEntry1.Location)
local units3 = SpawnAndAttack(SovietTanks, SovietEntry2.Location)
local units4 = SpawnAndAttack(SovietPlatoonUnits, SovietEntry1.Location)
local units5 = SpawnAndAttack(SovietPlatoonUnits, SovietEntry2.Location)
local units = { }
local insert = function(table)
local count = #units
Utils.Do(table, function(unit)
units[count] = unit
count = count + 1
end)
end
insert(units1)
insert(units2)
insert(units3)
insert(units4)
insert(units5)
Trigger.OnAllKilledOrCaptured(units, function()
if not DestroyObj then
Media.DisplayMessage("Excellent work Commander! We have reinforced our position enough to initiate a counter-attack.", "Incoming Report")
DestroyObj = allies.AddPrimaryObjective("Destroy the remaining Soviet forces in the area.")
end
allies.MarkCompletedObjective(SurviveObj)
end)
end
FinishTimer = function()
for i = 0, 9, 1 do
local c = TimerColor
if i % 2 == 0 then
c = HSLColor.White
end
Trigger.AfterDelay(DateTime.Seconds(i), function() UserInterface.SetMissionText("Soviet reinforcements have arrived!", c) end)
end
Trigger.AfterDelay(DateTime.Seconds(10), function() UserInterface.SetMissionText("") end)
end
wave = 1
SendParadrops = function()
SendSovietParadrops(ParaWaves[wave])
wave = wave + 1
if wave > #ParaWaves then
Trigger.AfterDelay(AttackTicks, FrenchReinforcements)
else
Trigger.AfterDelay(ParaWaves[wave].delay, SendParadrops)
end
end
SetupBridges = function()
local count = 0
local counter = function()
count = count + 1
if count == 2 then
allies.MarkCompletedObjective(RepairBridges)
end
end
Media.DisplayMessage("Commander! The Soviets destroyed the bridges to disable our reinforcements. Repair them for additional reinforcements.", "Incoming Report")
RepairBridges = allies.AddSecondaryObjective("Repair the two southern bridges.")
local bridgeA = Map.ActorsInCircle(BrokenBridge1.CenterPosition, WDist.FromCells(1), function(self) return self.Type == "bridge1" end)
local bridgeB = Map.ActorsInCircle(BrokenBridge2.CenterPosition, WDist.FromCells(1), function(self) return self.Type == "bridge1" end)
Utils.Do(bridgeA, function(bridge)
Trigger.OnDamaged(bridge, function()
Utils.Do(bridgeA, function(self) Trigger.ClearAll(self) end)
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, { "1tnk", "2tnk", "2tnk" }, { ReinforcementsEntry1.Location, ReinforcementsRally1.Location })
counter()
end)
end)
Utils.Do(bridgeB, function(bridge)
Trigger.OnDamaged(bridge, function()
Utils.Do(bridgeB, function(self) Trigger.ClearAll(self) end)
Media.PlaySpeechNotification(allies, "AlliedReinforcementsArrived")
Reinforcements.Reinforce(allies, { "jeep", "1tnk", "1tnk" }, { ReinforcementsEntry2.Location, ReinforcementsRally2.Location })
counter()
end)
end)
end
InitCountDown = function()
Trigger.AfterDelay(DateTime.Minutes(1), function() Media.PlaySpeechNotification(allies, "WarningFourMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(2), function() Media.PlaySpeechNotification(allies, "WarningThreeMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(3), function() Media.PlaySpeechNotification(allies, "WarningTwoMinutesRemaining") end)
Trigger.AfterDelay(DateTime.Minutes(4), function() Media.PlaySpeechNotification(allies, "WarningOneMinuteRemaining") end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
SurviveObj = allies.AddPrimaryObjective("Enforce your position and hold-out the onslaught.")
SovietObj = soviets.AddPrimaryObjective("Eliminate all Allied forces.")
Trigger.AfterDelay(DateTime.Seconds(15), function()
SetupBridges()
end)
Trigger.OnObjectiveCompleted(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(allies, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(allies, function()
Media.PlaySpeechNotification(allies, "Lose")
end)
Trigger.OnPlayerWon(allies, function()
Media.PlaySpeechNotification(allies, "Win")
Media.DisplayMessage("We have destroyed the remaining Soviet presence!", "Incoming Report")
end)
end
InitMission = function()
Camera.Position = AlliesBase.CenterPosition
TimerColor = HSLColor.Red
Trigger.AfterDelay(DateTime.Seconds(1), function() Media.PlaySpeechNotification(allies, "MissionTimerInitialised") end)
Trigger.AfterDelay(TimerTicks, function()
Media.DisplayMessage("The Soviet reinforcements are approaching!", "Incoming Report")
Media.PlaySpeechNotification(allies, "SovietReinforcementsArrived")
SpawnSovietVehicle(NewSovietEntryPoints, NewSovietRallyPoints)
FinalAttack()
Producing = false
end)
Trigger.AfterDelay(AttackTicks, SendParadrops)
Trigger.OnKilled(drum1, function() --Kill the remaining stuff from FrenchReinforcements
if not boom2.IsDead then boom2.Kill() end
if not boom4.IsDead then boom4.Kill() end
if not drum2.IsDead then drum2.Kill() end
if not drum3.IsDead then drum3.Kill() end
end)
Trigger.OnKilled(drum2, function()
if not boom1.IsDead then boom1.Kill() end
if not boom5.IsDead then boom5.Kill() end
Trigger.AfterDelay(DateTime.Seconds(1), function() if not drum1.IsDead then drum1.Kill() end end)
end)
Trigger.OnKilled(drum3, function()
if not boom1.IsDead then boom1.Kill() end
if not boom3.IsDead then boom3.Kill() end
Trigger.AfterDelay(DateTime.Seconds(1), function() if not drum1.IsDead then drum1.Kill() end end)
end)
end
SetupSoviets = function()
Barrack1.IsPrimaryBuilding = true
Barrack1.RallyPoint = SovietRally.Location
Trigger.OnKilledOrCaptured(Barrack1, function()
SpawningInfantry = false
end)
Harvester1.FindResources()
Trigger.OnDamaged(Harvester1, function()
Utils.Do(HarvGuards, function(unit)
GuardHarvester(unit, Harvester1)
end)
end)
Trigger.OnCapture(Harvester1, function()
Trigger.ClearAll(Harvester1)
end)
Harvester2.FindResources()
Trigger.OnDamaged(Harvester2, function()
Utils.Do(InfantryGuards, function(unit) GuardHarvester(unit, Harvester2) end)
local toBuild = { }
for i = 1, 6, 1 do
toBuild[i] = Utils.Random(SovietInfantry)
end
soviets.Build(toBuild, function(units)
Utils.Do(units, function(unit)
InfantryGuards[#InfantryGuards + 1] = unit
GuardHarvester(unit, Harvester2)
end)
end)
end)
Trigger.OnCapture(Harvester2, function()
Trigger.ClearAll(Harvester2)
end)
Trigger.AfterDelay(0, function()
local buildings = Utils.Where(Map.ActorsInWorld, function(self) return self.Owner == soviets and self.HasProperty("StartBuildingRepairs") end)
Utils.Do(buildings, function(actor)
Trigger.OnDamaged(actor, function(building)
if building.Owner == soviets and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
end)
end)
end
WorldLoaded = function()
allies = Player.GetPlayer("Allies")
soviets = Player.GetPlayer("Soviets")
InitObjectives()
InitMission()
SetupSoviets()
end
| gpl-3.0 |
Endika/Algorithm-Implementations | Levenshtein_distance/Lua/Yonaba/levenshtein_test.lua | 27 | 1499 | -- Tests for levenshtein.lua
local lev_iter = (require 'levenshtein').lev_iter
local lev_recursive = (require 'levenshtein').lev_recursive
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
run('Fails on running with no arg', function()
assert(not pcall(lev_iter))
assert(not pcall(lev_recursive))
end)
run('Fails if only one string is passed', function()
assert(not pcall( lev_iter, 'astring'))
assert(not pcall(lev_recursive, 'astring'))
end)
run('Otherwise, returns the levenshtein distance', function()
assert(lev_iter('Godfather', 'Godfather') == 0)
assert(lev_iter('Godfather', 'Godfathe') == 1)
assert(lev_iter('Godfather', 'odfather') == 1)
assert(lev_iter('Godfather', 'Gdfthr') == 3)
assert(lev_iter( 'seven', 'eight') == 5)
assert(lev_recursive('Godfather', 'Godfather') == 0)
assert(lev_recursive('Godfather', 'Godfathe') == 1)
assert(lev_recursive('Godfather', 'odfather') == 1)
assert(lev_recursive('Godfather', 'Gdfthr') == 3)
assert(lev_recursive( 'seven', 'eight') == 5)
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
tommo/gii | template/game/lib/character/EventYaka.lua | 2 | 1204 | module 'character'
EnumYakaFightProjectileMessages = _ENUM_V {
'projectile.launch',
}
CLASS: YakaEventMessageProjectile ( EventMessage )
:MODEL{
Field 'loc' :type('vec3') :getset('Loc');
Field 'message' :enum( EnumYakaFightProjectileMessages );
}
function YakaEventMessageProjectile:__init()
self.name = 'projectile'
self.transform = MOAITransform.new()
self.message = 'projectile.launch'
end
function YakaEventMessageProjectile:setLoc( x,y,z )
return self.transform:setLoc( x,y,z )
end
function YakaEventMessageProjectile:getLoc()
return self.transform:getLoc()
end
function YakaEventMessageProjectile:onBuildGizmo()
local giz = mock_edit.SimpleBoundGizmo()
giz:setTarget( self )
linkLoc( giz:getProp(), self.transform )
return giz
end
function YakaEventMessageProjectile:drawBounds()
MOAIDraw.drawCircle( 0,0, 20 )
end
registerActionMessageEventType( 'projectile', YakaEventMessageProjectile )
-- --------------------------------------------------------------------
-- EnumYakaFightCommonMessages = _ENUM_V {
-- 'attack.prepare',
-- 'attack.execute',
-- 'attack.start',
-- 'attack.stop',
-- }
-- CLASS: YakaEventMessageCommon ( EventMessage )
-- :MODEL{
-- }
| mit |
rpetit3/darkstar | scripts/zones/Windurst_Waters/npcs/Kipo-Opo.lua | 53 | 1913 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Kipo-Opo
-- Type: Cooking Adv. Image Support
-- @pos -119.750 -5.239 64.500 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,4);
local SkillLevel = player:getSkillLevel(SKILL_COOKING);
local Cost = getAdvImageSupportCost(player,SKILL_COOKING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_COOKING_IMAGERY) == false) then
player:startEvent(0x271F,Cost,SkillLevel,0,495,player:getGil(),0,0,0); -- p1 = skill level
else
player:startEvent(0x271F,Cost,SkillLevel,0,495,player:getGil(),28589,0,0);
end
else
player:startEvent(0x271F); -- Standard Dialogue
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local Cost = getAdvImageSupportCost(player,SKILL_COOKING);
if (csid == 0x271F and option == 1) then
player:delGil(Cost);
player:messageSpecial(COOKING_SUPPORT,0,8,0);
player:addStatusEffect(EFFECT_COOKING_IMAGERY,3,0,480);
end
end; | gpl-3.0 |
schidler/ionic-luci | modules/luci-mod-admin-full/luasrc/model/cbi/admin_status/processes.lua | 75 | 1236 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
f = SimpleForm("processes", translate("Processes"), translate("This list gives an overview over currently running system processes and their status."))
f.reset = false
f.submit = false
t = f:section(Table, luci.sys.process.list())
t:option(DummyValue, "PID", translate("PID"))
t:option(DummyValue, "USER", translate("Owner"))
t:option(DummyValue, "COMMAND", translate("Command"))
t:option(DummyValue, "%CPU", translate("CPU usage (%)"))
t:option(DummyValue, "%MEM", translate("Memory usage (%)"))
hup = t:option(Button, "_hup", translate("Hang Up"))
hup.inputstyle = "reload"
function hup.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 1)
end
term = t:option(Button, "_term", translate("Terminate"))
term.inputstyle = "remove"
function term.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 15)
end
kill = t:option(Button, "_kill", translate("Kill"))
kill.inputstyle = "reset"
function kill.write(self, section)
null, self.tag_error[section] = luci.sys.process.signal(section, 9)
end
return f | apache-2.0 |
rpetit3/darkstar | scripts/zones/Tahrongi_Canyon/npcs/Shattered_Telepoint.lua | 27 | 2330 | -----------------------------------
-- Area: Tahrongi_Canyon
-- NPC: Shattered Telepoint
-- @pos 179 35 255 117
-----------------------------------
package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Tahrongi_Canyon/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x0391,0,0,1); -- first time in promy -> have you made your preparations cs
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and (player:hasKeyItem(LIGHT_OF_HOLLA) or player:hasKeyItem(LIGHT_OF_DEM))) then
if (player:getVar("cspromy2") == 1) then
player:startEvent(0x0390); -- cs you get nearing second promyvion
else
player:startEvent(0x391)
end
elseif (player:getCurrentMission(COP) > THE_MOTHERCRYSTALS or player:hasCompletedMission(COP,THE_LAST_VERSE) or (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") > 1)) then
player:startEvent(0x0391); -- normal cs (third promyvion and each entrance after having that promyvion visited or mission completed)
else
player:messageSpecial(TELEPOINT_HAS_BEEN_SHATTERED);
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 == 0x0390) then
player:setVar("cspromy2",0);
player:setVar("cs2ndpromy",1);
player:setPos(280.066, -80.635, -67.096, 191, 14); -- To Hall of Transference {R}
elseif (csid == 0x0391 and option == 0) then
player:setPos(280.066, -80.635, -67.096, 191, 14); -- To Hall of Transference {R}
end
end; | gpl-3.0 |
vseledkin/april-ann | packages/imaging/image_cleaning/package.lua | 3 | 1128 | package{ name = "image_cleaning",
version = "1.0",
depends = { "dataset", "Image" },
keywords = { "image", "cleaning", "tools" },
description = "some util classes and functions to measure image enhancement, cleaning or binarization",
-- targets como en ant
target{
name = "init",
mkdir{ dir = "build" },
mkdir{ dir = "include" },
},
target{ name = "clean",
delete{ dir = "build" },
delete{ dir = "include" },
},
target{
name = "provide",
depends = "init",
copy{ file= "c_src/*.h", dest_dir = "include" },
provide_bind{ file = "binding/bind_image_cleaning.lua.cc", dest_dir = "include" },
},
target{
name = "build",
depends = "provide",
use_timestamp=true,
object{
file = "c_src/*.cc",
include_dirs = "${include_dirs}",
dest_dir = "build",
},
luac{
orig_dir = "lua_src",
dest_dir = "build",
},
build_bind{ file = "binding/bind_image_cleaning.lua.cc", dest_dir = "build" },
},
target{
name = "document",
document_src{},
document_bind{},
},
}
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Selbina/npcs/Wenzel.lua | 13 | 1052 | ----------------------------------
-- Area: Selbina
-- NPC: Wenzel
-- Type: Item Deliverer
-- @pos 31.961 -14.661 57.997 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, WENZEL_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 |
rpetit3/darkstar | scripts/globals/abilities/corsairs_roll.lua | 19 | 2648 | -----------------------------------
-- Ability: Corsair's Roll
-- Increases the amount of experience points earned by party members within area of effect
-- Optimal Job: Corsair
-- Lucky Number: 5
-- Unlucky Number: 9
-- Level: 5
--
-- Die Roll |Exp Bonus%
-- -------- -----------
-- 1 |10%
-- 2 |11%
-- 3 |11%
-- 4 |12%
-- 5 |20%
-- 6 |13%
-- 7 |15%
-- 8 |16%
-- 9 |8%
-- 10 |17%
-- 11 |24%
-- 12+ |-6%
--
-- Bust for Corsair set as subjob is also -6%.
-- Corsair set as subjob is 7% on Lucky roll (5) and 1% on Unlucky roll (9).
-- The EXP bonus afforded by Corsair's Roll does not apply within Abyssea.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/ability");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = EFFECT_CORSAIRS_ROLL;
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
elseif atMaxCorsairBusts(player) then
return MSGBASIC_CANNOT_PERFORM,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, EFFECT_CORSAIRS_ROLL, JOBS.COR);
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end;
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {10, 11, 11, 12, 20, 13, 15, 16, 8, 17, 24, 6};
local effectpower = effectpowers[total];
if (caster:getMainJob() == JOBS.COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOBS.COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_CORSAIRS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_EXP_BONUS) == false) then
ability:setMsg(422);
elseif total > 11 then
ability:setMsg(426);
end
return total;
end
| gpl-3.0 |
rpetit3/darkstar | scripts/zones/Windurst_Waters/npcs/Upih_Khachla.lua | 12 | 2150 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Upih Khachla
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
onHalloweenTrade(player,trade,npc);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,UPIHKHACHLA_SHOP_DIALOG);
stock = {
0x43A1, 1107,1, --Grenade
0x1010, 837,1, --Potion
0x03B7, 108,1, --Wijnruit
0x027C, 119,2, --Chamomile
0x1037, 736,2, --Echo Drops
0x1020, 4445,2, --Ether
0x1034, 290,3, --Antidote
0x0764, 3960,3, --Desalinator
0x026E, 44,3, --Dried Marjoram
0x1036, 2387,3, --Eye Drops
0x025D, 180,3, --Pickaxe
0x0765, 3960,3, --Salinator
0x03FC, 276,3, --Sickle
0x04D9, 354,3 --Twinkle Powder
}
rank = getNationRank(WINDURST);
if (rank ~= 1) then
table.insert(stock,0x03fe); --Thief's Tools
table.insert(stock,3643);
table.insert(stock,3);
end
if (rank == 3) then
table.insert(stock,0x03ff); --Living Key
table.insert(stock,5520);
table.insert(stock,3);
end
showNationShop(player, WINDURST, 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 |
rpetit3/darkstar | scripts/globals/items/bowl_of_riverfin_soup.lua | 18 | 1891 | -----------------------------------------
-- ID: 6069
-- Item: Bowl of Riverfin Soup
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- Accuracy % 14 Cap 90
-- Ranged Accuracy % 14 Cap 90
-- Attack % 18 Cap 80
-- Ranged Attack % 18 Cap 80
-- Amorph Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,6069);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 90);
target:addMod(MOD_FOOD_RACCP, 14);
target:addMod(MOD_FOOD_RACC_CAP, 90);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_AMORPH_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 90);
target:delMod(MOD_FOOD_RACCP, 14);
target:delMod(MOD_FOOD_RACC_CAP, 90);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_AMORPH_KILLER, 5);
end;
| gpl-3.0 |
vseledkin/april-ann | packages/trainable/lua_src/qlearning.lua | 3 | 11581 | local trainable_qlearning_trainer,trainable_qlearning_trainer_methods =
class("trainable.qlearning_trainer")
trainable = trainable or {} -- global environment
trainable.qlearning_trainer = trainable_qlearning_trainer -- global environment
local md = matrix.dict
-----------------------------
-- QLEARNING TRAINER CLASS --
-----------------------------
function trainable_qlearning_trainer:constructor(t)
local params = get_table_fields(
{
sup_trainer = { isa_match=trainable.supervised_trainer, mandatory=true },
discount = { type_match="number", mandatory=true, default=0.6 },
lambda = { type_match="number", mandatory=true, default=0.6 },
gradients = { mandatory=false, default={} },
traces = { mandatory=false, default={} },
noise = { mandatory=false, default=ann.components.base() },
clampQ = { mandatory=false },
nactions = { mandatory=false, type_match="number" },
}, t)
local tr = params.sup_trainer
local thenet = tr:get_component()
local weights = tr:get_weights_table()
local optimizer = tr:get_optimizer()
self.tr = tr
self.thenet = thenet
self.weights = weights
self.optimizer = optimizer
self.gradients = params.gradients
self.traces = params.traces
self.discount = params.discount
self.lambda = params.lambda
self.noise = params.noise
self.nactions = params.nactions or thenet:get_output_size()
self.clampQ = params.clampQ
assert(self.nactions > 0, "nactions must be > 0")
end
-- PRIVATE METHOD
-- updates the weights given the previous state, the action, the current state
-- and the observed reward
local function trainable_qlearning_trainer_train(self, prev_state, prev_action, state, reward)
local noise = self.noise
local weights = self.weights
local thenet = self.thenet
local optimizer = self.optimizer
local gradients = self.gradients
local traces = self.traces
local nactions = self.nactions
local discount = self.discount
local lambda = self.lambda
local clampQ = self.clampQ
-- add random noise if given
noise:reset(1)
local prev_state = noise:forward(prev_state, true)
noise:reset(0)
local state = noise:forward(state, true)
local error_grad = matrix(1, nactions):zeros()
local needs_gradient = optimizer:needs_property("gradient")
local loss,Qsp,Qs
loss,gradients,Qsp,Qs,expected_Qsa =
optimizer:execute(function(weights, it)
assert(not it or it == 0)
if weights ~= self.weights then
thenet:build{ weights = weights }
end
thenet:reset(it)
local Qsp = thenet:forward(state)
local Qs = thenet:forward(prev_state,true)
local Qsa = Qs:get(1, prev_action)
local delta = reward + discount * Qsp:max() - Qsa
local diff = delta
local loss = 0.5 * diff * diff
if needs_gradient then
error_grad:set(1, prev_action, -diff)
thenet:backprop(error_grad)
gradients:zeros()
gradients = thenet:compute_gradients(gradients)
if traces:size() == 0 then
for name,g in pairs(gradients) do
traces[name] = matrix.as(g):zeros()
end
end
md.scal( traces, lambda*discount )
md.axpy( traces, 1.0, gradients )
return loss,traces,Qsp,Qs,expected_Qsa
else
return loss,nil,Qsp,Qs,expected_Qsa
end
end,
weights)
self.gradients = gradients
return loss,Qsp,Qs,expected_Qsa
end
-- takes the previos action, the current state (ANN input) and the reward,
-- updates the ANN weights and returns the current output Q(state,a);
-- this method updates on-line, using eligibility traces
function trainable_qlearning_trainer_methods:one_step(action, state, reward)
local Qsp
if self.prev_state then
local loss,Qs,expected_Qsa
loss,Qsp,Qs,expected_Qsa = trainable_qlearning_trainer_train(self,
self.prev_state,
action,
state,
reward)
self.Qprob = (self.Qprob or 0) + math.log(Qs:get(1,action))
-- printf("%8.2f Q(s): %8.2f %8.2f %8.2f E(Q(s)): %8.2f ACTION: %d REWARD: %6.2f LOSS: %8.4f MP: %.4f %.4f\n",
-- -self.Qprob,
-- Qs:get(1,1), Qs:get(1,2), Qs:get(1,3),
-- expected_Qsa,
-- action, reward, loss,
-- self.tr:norm2("w."), self.tr:norm2("b."))
else
self.noise:reset(0)
local state = self.noise:forward(state,true)
Qsp = self.thenet:forward(state)
end
self.prev_state = state
return Qsp
end
-- returns an object where you can add several (state, action, next_state,
-- reward) batches, and at the end, build a pair of input/output datasets for
-- supervised training
function trainable_qlearning_trainer_methods:get_batch_builder()
return trainable.qlearning_trainer.batch_builder(self)
end
-- begins a new sequence of training
function trainable_qlearning_trainer_methods:reset()
self.prev_state = nil
self.traces:zeros()
self.Qprob = 0
end
function trainable_qlearning_trainer_methods:calculate(...)
return self.tr:calculate(...)
end
function trainable_qlearning_trainer_methods:randomize_weights(...)
return self.tr:randomize_weights(...)
end
function trainable_qlearning_trainer_methods:set_option(...)
return self.tr:set_option(...)
end
function trainable_qlearning_trainer_methods:set_layerwise_option(...)
return self.tr:set_layerwise_option(...)
end
function trainable_qlearning_trainer_methods:get_option(...)
return self.tr:get_option(...)
end
function trainable_qlearning_trainer_methods:has_option(...)
return self.tr:has_option(...)
end
function trainable.qlearning_trainer.load(filename)
return util.deserialize(filename)
end
function trainable_qlearning_trainer_methods:save(filename,format)
util.serialize(self, filename, format)
end
function trainable_qlearning_trainer_methods:ctor_name()
return "trainable.qlearning_trainer"
end
function trainable_qlearning_trainer_methods:ctor_params()
return { sup_trainer = self.tr,
noise = self.noise,
discount = self.discount,
lambda = self.lambda,
traces = self.traces,
gradients = self.gradients,
clampQ = self.clampQ, }
end
------------------------------------------------------------------------------
-- the batch object helps to implement NFQ algorithm:
--
-- http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.72.1193&rep=rep1&type=pdf
--
-- Martin Riedmiller, Neural Fitted Q Iteration - First Experiences
-- with a Data Efficient Neural Reinforcement Learning Method, ECML 2005
local trainable_batch_builder,trainable_batch_builder_methods =
class("trainable.qlearning_trainer.batch_builder")
trainable = trainable or {} -- global environment
trainable.qlearning_trainer = trainable.qlearning_trainer or {} -- global environment
trainable.qlearning_trainer.batch_builder = trainable_batch_builder -- global environment
function trainable_batch_builder:constructor(qlearner)
self.qlearner = qlearner
self.batch = {}
end
function trainable_batch_builder_methods:add(prev_state, output, action, reward)
assert(isa(prev_state, matrix), "Needs a matrix as 1st argument")
assert(isa(prev_state, matrix), "Needs a matrix as 2nd argument")
assert(type(action) == "number", "Needs a number as 3rd argument")
assert(type(reward) == "number", "Needs a matrix as 4th argument")
table.insert(self.batch,
{
prev_state:clone():rewrap(prev_state:size()),
action,
reward,
output:clone():rewrap(output:size()),
})
if self.state_size then
assert(self.state_size == prev_state:size(), "Found different state sizes")
end
self.state_size = prev_state:size()
end
function trainable_batch_builder_methods:compute_dataset_pair()
assert(self.state_size and self.state_size>0,
"Several number of adds is needed")
local discount = self.qlearner.discount
local inputs = matrix(#self.batch, self.state_size)
local outputs = matrix(#self.batch, self.qlearner.nactions):zeros()
local mask = outputs:clone()
local mask_row
local Qs
local state
local acc_reward = 0
for i=#self.batch,1,-1 do
local prev_state,action,reward,output = table.unpack(self.batch[i])
--
acc_reward = reward + discount * acc_reward
Qs = outputs:select(1,i,Qs):set(action,acc_reward)
mask_row = mask:select(1,i,mask_row):set(action,1)
--
state = inputs:select(1,i):copy(prev_state)
end
if self.qlearner.clampQ then outputs:map(self.qlearner.clampQ) end
return dataset.matrix(inputs),dataset.matrix(outputs),dataset.matrix(mask)
end
function trainable_batch_builder_methods:size()
return #self.batch
end
-------------------------------------------------------------------------------
trainable.qlearning_trainer.strategies = {}
trainable.qlearning_trainer.strategies.make_epsilon_greedy = function(actions,
epsilon,
rnd)
assert(type(actions) == "table", "Needs an actions table as 1st argument")
assert(#actions > 1, "#actions must be > 1")
local epsilon = epsilon or 0.1
local rnd = rnd or random()
local ambiguous_rel_diff = 0.1
return function(output)
local coin = rnd:rand()
local max,action = output:max()
local min = output:min()
local diff = max - min
local rel_diff = diff / max
if coin < epsilon or rel_diff < ambiguous_rel_diff then
action = rnd:choose(actions)
end
return action
end
end
trainable.qlearning_trainer.strategies.make_epsilon_decresing = function(actions,
epsilon,
decay,
rnd)
assert(type(actions) == "table", "Needs an actions table as 1st argument")
local epsilon = epsilon or 0.1
local decay = decay or 0.9
local rnd = rnd or random()
return function(output)
local coin = rnd:rand()
local max,action = output:max()
local min = output:min()
local diff = max - min
local rel_diff = diff / (max + min)
if coin < epsilon or rel_diff < 0.01 then
action = rnd:choose(actions)
end
epsilon = epsilon * decay
return action
end
end
trainable.qlearning_trainer.strategies.make_softmax = function(actions,rnd)
assert(type(actions) == "table", "Needs an actions table as 1st argument")
local rnd = rnd or random()
return function(output)
assert(math.abs(1-output:sum()) < 1e-03,
"Softmax strategy needs normalized outputs")
local dice = random.dice(output:toTable())
local action = dice:thrown(rnd)
return action
end
end
| gpl-3.0 |
ali-iraqi-bot/devil3_bot | plugins/jjj.lua | 2 | 3336 | local function addword(msg, name)
local hash = 'chat:'..msg.to.id..':badword'
redis:hset(hash, name, 'newword')
local text = "تـ्م رفُـعٌ😕 : "..name.. "ڪـ ژمـٱڵـ ﭜٱڵـمـچمـوعـة☹ ️ 💔😹 "
return reply_msg(msg.id, text, ok_cb, false)
end
local function get_variables_hash(msg)
return 'chat:'..msg.to.id..':badword'
end
local function list_variablesbad(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'ﻗﺂ̣̐ئمـة ﺂ̣̐ﻟ̣̣زْﻣـﺂ̣̐ۑل😻 : :\n\n'
for i=1, #names do
text = text..'- '..names[i]..'\n'
end
return text
else
return
end
end
function clear_commandbad(msg, var_name)
-- Save on redis
local hash = get_variables_hash(msg)
redis:del(hash, var_name)
local text = 'تٌـمً مًسِـحً جّـمًيِعٌ ألَزمًأيِلَ مًنِ ألَقُأئمًة😞💔️'
return reply_msg(msg.id, text, ok_cb, false)
end
local function list_variables2(msg, value)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
if string.match(value, names[i]) and not is_momod(msg) then
if msg.to.type == 'channel' then
return ""
end
return
end
-- text = text..names[i]..'\n'
end
end
end
local function get_valuebad(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return
else
return value
end
end
end
function clear_commandsbad(msg, cmd_name)
-- Save on redis
local hash = get_variables_hash(msg)
redis:hdel(hash, cmd_name)
local text = 'تـ्م تٌـنِزيِلَ ☹️'..cmd_nae..' مـٍنـً قـْأئمـٍة ألِزِمـٍأيًلِ😮🎈 '
return reply_msg(msg.id, text, ok_cb, false)
end
local function run(msg, matches)
if matches[2] == 'رفع زمال' then
if not is_momod(msg) then
return 'يْآ لْوڪْيْ بْسْ آلْادمن يْرْفْعْ زْمْآيْلْ بْڪْيْفْة 😒🎈 لتْلْعْبْ تْرْة تْنْرْفْعْ رْئيْسْ آلْزْمْآيْلْ 😑🎈🐾'
end
local name = string.sub(matches[3], 1, 50)
local text = addword(msg, name)
return text
end
if matches[2] == 'قائمه الزمايل' then
return list_variablesbad(msg)
elseif matches[2] == 'تنزيل الزمايل' then
if not is_momod(msg) then return 'للادمنيه فقط' end
local asd = '1'
return clear_commandbad(msg, asd)
elseif matches[2] == 'تنزيل زمال' or matches[2] == 'rw' then
if not is_momod(msg) then return 'يْآ لْوڪْيْ بْسْ آلْادمن يْرْفْعْ زْمْآيْلْ بْڪْيْفْة 😒🎈 لتْلْعْبْ تْرْة تْنْرْفْعْ رْئيْسْ آلْزْمْآيْلْ 😑🎈🐾🐾' end
return clear_commandsbad(msg, matches[3])
else
local name = user_print_name(msg.from)
return list_variables2(msg, matches[1])
end
end
return {
patterns = {
"^()(rw) (.*)$",
"^()(رفع زمال) (.*)$",
"^()(تنزيل زمال) (.*)$",
"^()(قائمه الزمايل)$",
"^()(تنزيل الزمايل)$",
"^(.+)$",
},
run = run
} | agpl-3.0 |
destdev/ygopro-scripts | c25524823.lua | 2 | 4806 | --墓守の審神者
function c25524823.initial_effect(c)
--summon with 3 tribute
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(25524823,0))
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SUMMON_PROC)
e1:SetCondition(c25524823.ttcon)
e1:SetOperation(c25524823.ttop)
e1:SetValue(SUMMON_TYPE_ADVANCE)
c:RegisterEffect(e1)
--summon with 1 tribute
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(25524823,1))
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SUMMON_PROC)
e2:SetCondition(c25524823.otcon)
e2:SetOperation(c25524823.otop)
e2:SetValue(SUMMON_TYPE_ADVANCE)
c:RegisterEffect(e2)
--summon success
local e3=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(25524823,6))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_SUMMON_SUCCESS)
e3:SetCondition(c25524823.condition)
e3:SetTarget(c25524823.target)
e3:SetOperation(c25524823.operation)
c:RegisterEffect(e3)
--tribute check
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_MATERIAL_CHECK)
e4:SetValue(c25524823.valcheck)
c:RegisterEffect(e4)
e3:SetLabelObject(e4)
e4:SetLabelObject(e3)
end
function c25524823.ttcon(e,c,minc)
if c==nil then return true end
return minc<=3 and Duel.CheckTribute(c,3)
end
function c25524823.ttop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RELEASE)
local g=Duel.SelectTribute(tp,c,3,3)
c:SetMaterial(g)
Duel.Release(g,REASON_SUMMON+REASON_MATERIAL)
end
function c25524823.otfilter(c,tp)
return c:IsSetCard(0x2e) and (c:IsControler(tp) or c:IsFaceup())
end
function c25524823.otcon(e,c,minc)
if c==nil then return true end
local tp=c:GetControler()
local mg=Duel.GetMatchingGroup(c25524823.otfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,tp)
return c:IsLevelAbove(7) and minc<=1 and Duel.CheckTribute(c,1,1,mg)
end
function c25524823.otop(e,tp,eg,ep,ev,re,r,rp,c)
local mg=Duel.GetMatchingGroup(c25524823.otfilter,tp,LOCATION_MZONE,LOCATION_MZONE,nil,tp)
local sg=Duel.SelectTribute(tp,c,1,1,mg)
c:SetMaterial(sg)
Duel.Release(sg,REASON_SUMMON+REASON_MATERIAL)
end
function c25524823.valcheck(e,c)
local g=c:GetMaterial()
local ct=g:FilterCount(Card.IsSetCard,nil,0x2e)
local lv=0
local tc=g:GetFirst()
while tc do
lv=lv+tc:GetLevel()
tc=g:GetNext()
end
e:SetLabel(lv)
e:GetLabelObject():SetLabel(ct)
end
function c25524823.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsSummonType(SUMMON_TYPE_ADVANCE)
end
function c25524823.filter(c)
return c:IsFacedown()
end
function c25524823.target(e,tp,eg,ep,ev,re,r,rp,chk)
local ct=e:GetLabel()
local b1=e:GetLabelObject():GetLabel()>0
local b2=Duel.IsExistingMatchingCard(c25524823.filter,tp,0,LOCATION_MZONE,1,nil)
local b3=Duel.IsExistingMatchingCard(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil)
if chk==0 then return ct>0 and (b1 or b2 or b3) end
local sel=0
local off=0
repeat
local ops={}
local opval={}
off=1
if b1 then
ops[off]=aux.Stringid(25524823,2)
opval[off-1]=1
off=off+1
end
if b2 then
ops[off]=aux.Stringid(25524823,3)
opval[off-1]=2
off=off+1
end
if b3 then
ops[off]=aux.Stringid(25524823,4)
opval[off-1]=3
off=off+1
end
local op=Duel.SelectOption(tp,table.unpack(ops))
if opval[op]==1 then
sel=sel+1
b1=false
elseif opval[op]==2 then
sel=sel+2
b2=false
else
sel=sel+4
b3=false
end
ct=ct-1
until ct==0 or off<3 or not Duel.SelectYesNo(tp,aux.Stringid(25524823,5))
e:SetLabel(sel)
if bit.band(sel,2)~=0 then
local g=Duel.GetMatchingGroup(c25524823.filter,tp,0,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
end
function c25524823.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local sel=e:GetLabel()
if bit.band(sel,1)~=0 and c:IsFaceup() and c:IsRelateToEffect(e) then
local lv=e:GetLabelObject():GetLabel()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(lv*100)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_DISABLE)
c:RegisterEffect(e1)
end
if bit.band(sel,2)~=0 then
local g=Duel.GetMatchingGroup(c25524823.filter,tp,0,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
if bit.band(sel,4)~=0 then
local g=Duel.GetMatchingGroup(Card.IsFaceup,tp,0,LOCATION_MZONE,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(-2000)
tc:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_DEFENSE)
tc:RegisterEffect(e2)
tc=g:GetNext()
end
end
end
| gpl-2.0 |
WohlSoft/LunaLUA | LuaScriptsLibExt/smb3goalcard.lua | 3 | 12080 | local __title = "SMB3 Goal Cards";
local __version = "1.0.1.1";
local __description = "Make the SMB3 Goal Card act as it did in SMB3.";
local __author = "XNBlank";
local __url = "https://github.com/XNBlank";
--[[
HOW TO USE
1 . Make a new file in your worlds folder called LunaWorld.lua.
2 . Add " smb3card = loadAPI("smb3goalcard"); " to the file.
3 . In your onLoad function, you can toggle the card function on/off with " smb3card.usesCard(TRUE/FALSE); "
4 . If you want to have a certain level not use the card function, or if it doesn't have a card, add the above line, set it to false, and put it into a LunaDll.lua file in that levels graphic folder.
]]
local smbGoalCard_API = {} --instance
local card1 = -1; -- basically a bool. Checks if card is used
local card2 = -1;
local card3 = -1;
local cards = 0;
local goalcard = NPC(11);
local getframe = 0;
local postWinFrameCounter = 0;
local endLevelTimer = 0;
local gotcard = false;
local addCard = false;
local doesUseCard = true;
local playOnce = false;
local resPath = getSMBXPath() .. "\\LuaScriptsLib\\smb3goalcard"; --res path
local uicard = Graphics.loadImage(resPath .. "\\smb3card.png");
local mushroomcard = Graphics.loadImage(resPath .. "\\mushroom.png");
local flowercard = Graphics.loadImage(resPath .. "\\flower.png");
local starcard = Graphics.loadImage(resPath .. "\\star.png");
local oneup = Graphics.loadImage(resPath .. "\\1up.png");
local twoup = Graphics.loadImage(resPath .. "\\2up.png");
local threeup = Graphics.loadImage(resPath .. "\\3up.png");
local fiveup = Graphics.loadImage(resPath .. "\\5up.png");
local curLivesCount = mem(0x00B2C5AC, FIELD_FLOAT);
local dataInstance = Data(Data.DATA_WORLD,"SMB3 Cards", true);
local levelFinished = false;
local firstRun = true
smbGoalCard_API.GUIPosition1 = {x = 650, y = 550}
smbGoalCard_API.GUIPosition2 = {x = 698, y = 550}
smbGoalCard_API.GUIPosition3 = {x = 746, y = 550}
function smbGoalCard_API.onInitAPI()
gotcard = false;
addCard = false;
registerEvent(smbGoalCard_API, "onLoop", "onLoopOverride");
registerEvent(smbGoalCard_API, "onLoad", "onLoadOverride");
cards = tonumber(dataInstance:get("cards"));
card1 = tonumber(dataInstance:get("card1"));
card2 = tonumber(dataInstance:get("card2"));
card3 = tonumber(dataInstance:get("card3"));
--Defines.smb3RouletteScoreValueStar = 4;
--Defines.smb3RouletteScoreValueMushroom = 2;
--Defines.smb3RouletteScoreValueFlower = 3;
end
function smbGoalCard_API.onLoadOverride()
end
function smbGoalCard_API.onLoopOverride()
if(firstRun)then
Graphics.placeSprite(1,uicard,smbGoalCard_API.GUIPosition1.x,smbGoalCard_API.GUIPosition1.y);
Graphics.placeSprite(1,uicard,smbGoalCard_API.GUIPosition2.x,smbGoalCard_API.GUIPosition2.y);
Graphics.placeSprite(1,uicard,smbGoalCard_API.GUIPosition3.x,smbGoalCard_API.GUIPosition3.y);
if(card1 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
elseif(card1 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
elseif(card1 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
end
if(card2 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
elseif(card2 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
elseif(card2 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
end
if(card3 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
elseif(card3 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
elseif(card3 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
end
firstRun = false
end
temp = NPC.get(11, -1);
if(temp == nil) then
elseif(temp[1] ~= nil) then
thiscard = (temp[1]:mem(0xE4, FIELD_WORD));
-- Text.print(tostring(temp[1]:mem(0xE4, FIELD_WORD)), 0, 0);
end
--temp[0]:mem(0xE4, FIELD_WORD);
smbGoalCard_API.debugDraw();
if(Level.winState() > 0) then
smbGoalCard_API.endLevel();
end
end
function smbGoalCard_API.debugDraw()
--[[
Text.print("Card 1 = " .. dataInstance:get("card1"), 0, 100);
Text.print("Card 2 = " .. dataInstance:get("card2"), 0, 115);
Text.print("Card 3 = " .. dataInstance:get("card3"), 0, 130);
Text.print("Timer = " .. tostring(endLevelTimer), 0, 160);
Text.print("Current Card = " .. tostring(thiscard), 0, 160);
Text.print("Cards = " .. tostring(cards), 0, 75);
Text.print("Win state: " .. Level.winState(), 0, 200)
]]
end
function smbGoalCard_API.endLevel()
levelFinished = true;
if(doesUseCard == true) then
if(Level.winState() == 1) then
postWinFrameCounter = postWinFrameCounter + 1;
local endLevelTimer = round(postWinFrameCounter / 60, 0);
if (addCard == false) then
if(cards == nil) then
cards = 0;
end
if(cards >= 4) then
cards = 0;
addCard = true;
elseif(cards < 3) then
local newcard = 1;
cards = cards + newcard;
addCard = true;
end
end
gotcard = true;
if (card1 == nil) then
card1 = -1;
end
if (card2 == nil) then
card2 = -1;
end
if (card3 == nil) then
card3 = -1;
end
if(cards == 1) then
if(card1 < 0) then
card1 = tonumber(thiscard);
dCard1 = card1;
dataInstance:set("card1", tostring(card1));
end
if(card1 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
elseif(card1 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
elseif(card1 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition1.x, smbGoalCard_API.GUIPosition1.y);
end
end
if(cards == 2) then
if(card2 < 0) then
card2 = tonumber(thiscard);
dCard2 = card2;
dataInstance:set("card2", tostring(card2));
end
if(card2 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
elseif(card2 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
elseif(card2 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition2.x, smbGoalCard_API.GUIPosition2.y);
end
end
if(cards == 3) then
if(card3 < 0) then
card3 = tonumber(thiscard);
dCard3 = card3;
dataInstance:set("card3", tostring(card3));
end
if(card3 == 0) then
Graphics.placeSprite(1, starcard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
elseif(card3 == 1) then
Graphics.placeSprite(1, mushroomcard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
elseif(card3 == 2) then
Graphics.placeSprite(1, flowercard, smbGoalCard_API.GUIPosition3.x, smbGoalCard_API.GUIPosition3.y);
end
end
Text.print("Got Card!", 280, 115)
if(thiscard == 1) then
Graphics.placeSprite(1,mushroomcard,450,96, "", 2);
local dCard1 = tonumber(dataInstance:get("card1 "));
elseif(thiscard == 2) then
Graphics.placeSprite(1,flowercard,450,96, "", 2);
local dCard2 = tonumber(dataInstance:get("card2 "));
elseif(thiscard == 0) then
Graphics.placeSprite(1,starcard,450,96, "", 2);
local dCard3 = tonumber(dataInstance:get("card3 "));
end
if(cards == 1) then
--Text.print("set card1 to " .. tostring(card1), 0, 45);
elseif(cards == 2) then
--Text.print("set card2 to " .. tostring(card2), 0, 45);
elseif(cards == 3) then
--Text.print("set card3 to " .. tostring(card3), 0, 45);
if(card1 == 0) and (card2 == 0) and (card3 == 0) then
mem(0x00B2C5AC, FIELD_FLOAT, (curLivesCount + 5));
if(playOnce == false) then
playSFXSDL(resPath .. "\\1up.wav");
playOnce = true;
end
Graphics.placeSprite(1,fiveup,500,110);
elseif(card1 == 1) and (card2 == 1) and (card3 == 1) then
mem(0x00B2C5AC, FIELD_FLOAT, (curLivesCount + 2));
if(playOnce == false) then
playSFXSDL(resPath .. "\\1up.wav");
playOnce = true;
end
Graphics.placeSprite(1,twoup,500,110);
elseif(card1 == 2) and (card2 == 2) and (card3 == 2) then
mem(0x00B2C5AC, FIELD_FLOAT, (curLivesCount + 3));
if(playOnce == false) then
playSFXSDL(resPath .. "\\1up.wav");
playOnce = true;
end
Graphics.placeSprite(1,threeup,500,110);
else
mem(0x00B2C5AC, FIELD_FLOAT, (curLivesCount + 1));
if(playOnce == false) then
playSFXSDL(resPath .. "\\1up.wav");
playOnce = true;
end
Graphics.placeSprite(1,oneup,500,110);
end
if(endLevelTimer >= 1) then
card1 = -1;
card2 = -1;
card3 = -1;
cards = 0;
dataInstance:set("card1", tostring(card1));
dataInstance:set("card2", tostring(card2));
dataInstance:set("card3", tostring(card3));
end
end
dataInstance:set("cards", tostring(cards));
dataInstance:save();
end
end
end
function smbGoalCard_API.usesCard(me)
doesUseCard = me;
end
return smbGoalCard_API; | gpl-3.0 |
ffxijuggalo/darkstar | scripts/commands/addquest.lua | 11 | 1570 | ---------------------------------------------------------------------------------------------------
-- func: addquest <logID> <questID> <player>
-- desc: Adds a quest to the given targets log.
---------------------------------------------------------------------------------------------------
require("scripts/globals/quests");
cmdprops =
{
permission = 1,
parameters = "sss"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!addquest <logID> <questID> {player}");
end;
function onTrigger(player, logId, questId, target)
-- validate logId
local questLog = GetQuestLogInfo(logId);
if (questLog == nil) then
error(player, "Invalid logID.");
return;
end
local logName = questLog.full_name;
logId = questLog.quest_log;
-- validate questId
local areaQuestIds = dsp.quest.id[dsp.quest.area[logId]];
if (questId ~= nil) then
questId = tonumber(questId) or areaQuestIds[string.upper(questId)];
end
if (questId == nil or questId < 0) then
error(player, "Invalid questID.");
return;
end
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- add quest
targ:addQuest(logId, questId);
player:PrintToPlayer(string.format("Added %s quest %i to %s.", logName, questId, targ:getName()));
end; | gpl-3.0 |
destdev/ygopro-scripts | c5220687.lua | 4 | 1235 | --素早いビッグハムスター
function c5220687.initial_effect(c)
--flip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(5220687,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_FLIP+EFFECT_TYPE_TRIGGER_O)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetTarget(c5220687.target)
e1:SetOperation(c5220687.operation)
c:RegisterEffect(e1)
end
function c5220687.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c5220687.filter,tp,LOCATION_DECK,0,1,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c5220687.filter(c,e,tp)
return c:IsLevelBelow(3) and c:IsRace(RACE_BEAST) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEDOWN_DEFENSE)
end
function c5220687.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local g=Duel.GetMatchingGroup(c5220687.filter,tp,LOCATION_DECK,0,nil,e,tp)
if g:GetCount()>0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,1,1,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEDOWN_DEFENSE)
Duel.ConfirmCards(1-tp,sg)
end
end
| gpl-2.0 |
Kong/kong | spec/03-plugins/05-syslog/01-log_spec.lua | 1 | 8046 | local helpers = require "spec.helpers"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
local pl_stringx = require "pl.stringx"
for _, strategy in helpers.each_strategy() do
describe("Plugin: syslog (log) [#" .. strategy .. "]", function()
local proxy_client
local proxy_client_grpc
local platform
lazy_setup(function()
local bp = helpers.get_db_utils(strategy, {
"routes",
"services",
"plugins",
})
local route1 = bp.routes:insert {
hosts = { "logging.com" },
}
local route2 = bp.routes:insert {
hosts = { "logging2.com" },
}
local route3 = bp.routes:insert {
hosts = { "logging3.com" },
}
local route4 = bp.routes:insert {
hosts = { "logging4.com" },
}
bp.plugins:insert {
route = { id = route1.id },
name = "syslog",
config = {
log_level = "info",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
bp.plugins:insert {
route = { id = route2.id },
name = "syslog",
config = {
log_level = "err",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
bp.plugins:insert {
route = { id = route3.id },
name = "syslog",
config = {
log_level = "warning",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
bp.plugins:insert {
route = { id = route4.id },
name = "syslog",
config = {
log_level = "warning",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
custom_fields_by_lua = {
new_field = "return 123",
route = "return nil", -- unset route field
},
},
}
-- grpc [[
local grpc_service = bp.services:insert {
name = "grpc-service",
url = helpers.grpcbin_url,
}
local grpc_route1 = bp.routes:insert {
service = grpc_service,
hosts = { "grpc_logging.com" },
}
local grpc_route2 = bp.routes:insert {
service = grpc_service,
hosts = { "grpc_logging2.com" },
}
local grpc_route3 = bp.routes:insert {
service = grpc_service,
hosts = { "grpc_logging3.com" },
}
bp.plugins:insert {
route = { id = grpc_route1.id },
name = "syslog",
config = {
log_level = "info",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
bp.plugins:insert {
route = { id = grpc_route2.id },
name = "syslog",
config = {
log_level = "err",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
bp.plugins:insert {
route = { id = grpc_route3.id },
name = "syslog",
config = {
log_level = "warning",
successful_severity = "warning",
client_errors_severity = "warning",
server_errors_severity = "warning",
},
}
-- grpc ]]
local ok, _, stdout = helpers.execute("uname")
assert(ok, "failed to retrieve platform name")
platform = pl_stringx.strip(stdout)
assert(helpers.start_kong({
database = strategy,
nginx_conf = "spec/fixtures/custom_nginx.template",
}))
proxy_client_grpc = helpers.proxy_client_grpc()
end)
lazy_teardown(function()
helpers.stop_kong()
end)
before_each(function()
proxy_client = assert(helpers.proxy_client())
end)
after_each(function()
if proxy_client then proxy_client:close() end
end)
local function do_test(host, expecting_same, grpc)
local uuid = utils.uuid()
local ok, resp
if not grpc then
local response = assert(proxy_client:send {
method = "GET",
path = "/request",
headers = {
host = host,
sys_log_uuid = uuid,
}
})
assert.res_status(200, response)
else
ok, resp = proxy_client_grpc({
service = "hello.HelloService.SayHello",
body = {
greeting = "world!"
},
opts = {
[" -H"] = "'Content-Type: text/plain'",
["-H"] = "'sys_log_uuid: " .. uuid .. "'",
["-authority"] = ("%s"):format(host),
}
})
assert.truthy(ok, resp)
assert.truthy(resp)
end
if platform == "Darwin" then
local _, _, stdout = assert(helpers.execute("syslog -k Sender kong | tail -1"))
local msg = string.match(stdout, "{.*}")
local json = cjson.decode(msg)
if expecting_same then
assert.equal(uuid, json.request.headers["sys-log-uuid"])
else
assert.not_equal(uuid, json.request.headers["sys-log-uuid"])
end
resp = stdout
elseif expecting_same then
-- wait for file writing
helpers.pwait_until(function()
local _, _, stdout = assert(helpers.execute("sudo find /var/log -type f -mmin -5 | grep syslog"))
assert.True(#stdout > 0)
local files = pl_stringx.split(stdout, "\n")
assert.True(#files > 0)
if files[#files] == "" then
table.remove(files)
end
local tmp = {}
-- filter out suspicious files
for _, file in ipairs(files) do
local _, stderr, stdout = assert(helpers.execute("file " .. file))
assert(stdout, stderr)
assert.True(#stdout > 0, stderr)
--[[
to avoid file like syslog.2.gz
because syslog must be a text file
--]]
if stdout:find("text", 1, true) then
table.insert(tmp, file)
end
end
files = tmp
local matched = false
for _, file in ipairs(files) do
--[[
we have to run grep with sudo on Github Action
because of the `Permission denied` error
-- ]]
local cmd = string.format("sudo grep '\"sys_log_uuid\":\"%s\"' %s", uuid, file)
local ok, _, stdout = helpers.execute(cmd)
if ok then
matched = true
resp = stdout
break
end
end
assert(matched, "uuid not found in syslog")
end, 5)
end
return resp
end
it("logs to syslog if log_level is lower", function()
do_test("logging.com", true)
end)
it("does not log to syslog if log_level is higher", function()
do_test("logging2.com", false)
end)
it("logs to syslog if log_level is the same", function()
do_test("logging3.com", true)
end)
it("logs custom values", function()
local resp = do_test("logging4.com", true)
assert.matches("\"new_field\".*123", resp)
assert.not_matches("\"route\"", resp)
end)
it("logs to syslog if log_level is lower #grpc", function()
do_test("grpc_logging.com", true, true)
end)
it("does not log to syslog if log_level is higher #grpc", function()
do_test("grpc_logging2.com", false, true)
end)
it("logs to syslog if log_level is the same #grpc", function()
do_test("grpc_logging3.com", true, true)
end)
end)
end
| apache-2.0 |
Deadwing888/darkstar | scripts/zones/Quicksand_Caves/npcs/_5sc.lua | 13 | 1253 | -----------------------------------
-- Area: Quicksand Caves
-- NPC: Ornate Door
-- Door blocked by Weight system
-- @pos -410 0 662 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local difX = player:getXPos()-(-410);
local difZ = player:getZPos()-(654);
local Distance = math.sqrt( math.pow(difX,2) + math.pow(difZ,2) );
if (Distance < 3) then
return -1;
end
player:messageSpecial(DOOR_FIRMLY_SHUT);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
destdev/ygopro-scripts | c55794644.lua | 1 | 2951 | --マスター・ヒュペリオン
function c55794644.initial_effect(c)
--spsummon proc
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c55794644.hspcon)
e1:SetOperation(c55794644.hspop)
c:RegisterEffect(e1)
--destroy
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(55794644,0))
e2:SetCategory(CATEGORY_DESTROY)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetCondition(c55794644.condition)
e2:SetCost(c55794644.cost)
e2:SetTarget(c55794644.target)
e2:SetOperation(c55794644.operation)
c:RegisterEffect(e2)
end
function c55794644.spfilter(c)
return c:IsSetCard(0x44) and c:IsAbleToRemoveAsCost() and (not c:IsLocation(LOCATION_MZONE) or c:IsFaceup())
end
function c55794644.hspcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=-1 then return false end
if ft<=0 then
return Duel.IsExistingMatchingCard(c55794644.spfilter,tp,LOCATION_MZONE,0,1,nil)
else return Duel.IsExistingMatchingCard(c55794644.spfilter,tp,0x16,0,1,nil) end
end
function c55794644.hspop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then
local g=Duel.SelectMatchingCard(tp,c55794644.spfilter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
else
local g=Duel.SelectMatchingCard(tp,c55794644.spfilter,tp,0x16,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
end
function c55794644.condition(e,tp,eg,ep,ev,re,r,rp)
if Duel.IsEnvironment(56433456) then return e:GetHandler():GetFlagEffect(55794644)<2
else return e:GetHandler():GetFlagEffect(55794644)<1 end
end
function c55794644.costfilter(c)
return c:IsAttribute(ATTRIBUTE_LIGHT) and c:IsRace(RACE_FAIRY) and c:IsAbleToRemoveAsCost()
end
function c55794644.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c55794644.costfilter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c55794644.costfilter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.Remove(g,POS_FACEUP,REASON_COST)
end
function c55794644.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() end
if chk==0 then return Duel.IsExistingTarget(aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,aux.TRUE,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
e:GetHandler():RegisterFlagEffect(55794644,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,0,1)
end
function c55794644.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
RwNigma/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/Treasure_Chest.lua | 19 | 2590 | -----------------------------------
-- Area: Horutoto Ruins
-- NPC: Treasure Chest
-- @zone 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/treasure");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
local TreasureType = "Chest";
local TreasureLvL = 43;
local TreasureMinLvL = 33;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
--trade:hasItemQty(1029,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(1029,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,1029);
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 |
Kong/kong | kong/plugins/proxy-cache/handler.lua | 1 | 11210 | local require = require
local cache_key = require "kong.plugins.proxy-cache.cache_key"
local utils = require "kong.tools.utils"
local kong_meta = require "kong.meta"
local ngx = ngx
local kong = kong
local type = type
local pairs = pairs
local tostring = tostring
local tonumber = tonumber
local max = math.max
local floor = math.floor
local lower = string.lower
local concat = table.concat
local time = ngx.time
local resp_get_headers = ngx.resp and ngx.resp.get_headers
local ngx_re_gmatch = ngx.re.gmatch
local ngx_re_sub = ngx.re.gsub
local ngx_re_match = ngx.re.match
local parse_http_time = ngx.parse_http_time
local tab_new = require("table.new")
local STRATEGY_PATH = "kong.plugins.proxy-cache.strategies"
local CACHE_VERSION = 1
local EMPTY = {}
-- http://www.w3.org/Protocols/rfc2616/rfc2616-sec13.html#sec13.5.1
-- note content-length is not strictly hop-by-hop but we will be
-- adjusting it here anyhow
local hop_by_hop_headers = {
["connection"] = true,
["keep-alive"] = true,
["proxy-authenticate"] = true,
["proxy-authorization"] = true,
["te"] = true,
["trailers"] = true,
["transfer-encoding"] = true,
["upgrade"] = true,
["content-length"] = true,
}
local function overwritable_header(header)
local n_header = lower(header)
return not hop_by_hop_headers[n_header]
and not ngx_re_match(n_header, "ratelimit-remaining")
end
local function parse_directive_header(h)
if not h then
return EMPTY
end
if type(h) == "table" then
h = concat(h, ", ")
end
local t = {}
local res = tab_new(3, 0)
local iter = ngx_re_gmatch(h, "([^,]+)", "oj")
local m = iter()
while m do
local _, err = ngx_re_match(m[0], [[^\s*([^=]+)(?:=(.+))?]],
"oj", nil, res)
if err then
kong.log.err(err)
end
-- store the directive token as a numeric value if it looks like a number;
-- otherwise, store the string value. for directives without token, we just
-- set the key to true
t[lower(res[1])] = tonumber(res[2]) or res[2] or true
m = iter()
end
return t
end
local function req_cc()
return parse_directive_header(ngx.var.http_cache_control)
end
local function res_cc()
return parse_directive_header(ngx.var.sent_http_cache_control)
end
local function resource_ttl(res_cc)
local max_age = res_cc["s-maxage"] or res_cc["max-age"]
if not max_age then
local expires = ngx.var.sent_http_expires
-- if multiple Expires headers are present, last one wins
if type(expires) == "table" then
expires = expires[#expires]
end
local exp_time = parse_http_time(tostring(expires))
if exp_time then
max_age = exp_time - time()
end
end
return max_age and max(max_age, 0) or 0
end
local function cacheable_request(conf, cc)
-- TODO refactor these searches to O(1)
do
local method = kong.request.get_method()
local method_match = false
for i = 1, #conf.request_method do
if conf.request_method[i] == method then
method_match = true
break
end
end
if not method_match then
return false
end
end
-- check for explicit disallow directives
-- TODO note that no-cache isnt quite accurate here
if conf.cache_control and (cc["no-store"] or cc["no-cache"] or
ngx.var.authorization) then
return false
end
return true
end
local function cacheable_response(conf, cc)
-- TODO refactor these searches to O(1)
do
local status = kong.response.get_status()
local status_match = false
for i = 1, #conf.response_code do
if conf.response_code[i] == status then
status_match = true
break
end
end
if not status_match then
return false
end
end
do
local content_type = ngx.var.sent_http_content_type
-- bail if we cannot examine this content type
if not content_type or type(content_type) == "table" or
content_type == "" then
return false
end
local content_match = false
for i = 1, #conf.content_type do
if conf.content_type[i] == content_type then
content_match = true
break
end
end
if not content_match then
return false
end
end
if conf.cache_control and (cc["private"] or cc["no-store"] or cc["no-cache"])
then
return false
end
if conf.cache_control and resource_ttl(cc) <= 0 then
return false
end
return true
end
-- indicate that we should attempt to cache the response to this request
local function signal_cache_req(ctx, cache_key, cache_status)
ctx.proxy_cache = {
cache_key = cache_key,
}
kong.response.set_header("X-Cache-Status", cache_status or "Miss")
end
local ProxyCacheHandler = {
VERSION = kong_meta.version,
PRIORITY = 100,
}
function ProxyCacheHandler:init_worker()
-- catch notifications from other nodes that we purged a cache entry
-- only need one worker to handle purges like this
-- if/when we introduce inline LRU caching this needs to involve
-- worker events as well
local unpack = unpack
kong.cluster_events:subscribe("proxy-cache:purge", function(data)
kong.log.err("handling purge of '", data, "'")
local plugin_id, cache_key = unpack(utils.split(data, ":"))
local plugin, err = kong.db.plugins:select({
id = plugin_id,
})
if err then
kong.log.err("error in retrieving plugins: ", err)
return
end
local strategy = require(STRATEGY_PATH)({
strategy_name = plugin.config.strategy,
strategy_opts = plugin.config[plugin.config.strategy],
})
if cache_key ~= "nil" then
local ok, err = strategy:purge(cache_key)
if not ok then
kong.log.err("failed to purge cache key '", cache_key, "': ", err)
return
end
else
local ok, err = strategy:flush(true)
if not ok then
kong.log.err("error in flushing cache data: ", err)
end
end
end)
end
function ProxyCacheHandler:access(conf)
local cc = req_cc()
-- if we know this request isnt cacheable, bail out
if not cacheable_request(conf, cc) then
kong.response.set_header("X-Cache-Status", "Bypass")
return
end
local consumer = kong.client.get_consumer()
local route = kong.router.get_route()
local uri = ngx_re_sub(ngx.var.request, "\\?.*", "", "oj")
local cache_key, err = cache_key.build_cache_key(consumer and consumer.id,
route and route.id,
kong.request.get_method(),
uri,
kong.request.get_query(),
kong.request.get_headers(),
conf)
if err then
kong.log.err(err)
return
end
kong.response.set_header("X-Cache-Key", cache_key)
-- try to fetch the cached object from the computed cache key
local strategy = require(STRATEGY_PATH)({
strategy_name = conf.strategy,
strategy_opts = conf[conf.strategy],
})
local ctx = kong.ctx.plugin
local res, err = strategy:fetch(cache_key)
if err == "request object not in cache" then -- TODO make this a utils enum err
-- this request wasn't found in the data store, but the client only wanted
-- cache data. see https://tools.ietf.org/html/rfc7234#section-5.2.1.7
if conf.cache_control and cc["only-if-cached"] then
return kong.response.exit(ngx.HTTP_GATEWAY_TIMEOUT)
end
ctx.req_body = kong.request.get_raw_body()
-- this request is cacheable but wasn't found in the data store
-- make a note that we should store it in cache later,
-- and pass the request upstream
return signal_cache_req(ctx, cache_key)
elseif err then
kong.log.err(err)
return
end
if res.version ~= CACHE_VERSION then
kong.log.notice("cache format mismatch, purging ", cache_key)
strategy:purge(cache_key)
return signal_cache_req(ctx, cache_key, "Bypass")
end
-- figure out if the client will accept our cache value
if conf.cache_control then
if cc["max-age"] and time() - res.timestamp > cc["max-age"] then
return signal_cache_req(ctx, cache_key, "Refresh")
end
if cc["max-stale"] and time() - res.timestamp - res.ttl > cc["max-stale"]
then
return signal_cache_req(ctx, cache_key, "Refresh")
end
if cc["min-fresh"] and res.ttl - (time() - res.timestamp) < cc["min-fresh"]
then
return signal_cache_req(ctx, cache_key, "Refresh")
end
else
-- don't serve stale data; res may be stored for up to `conf.storage_ttl` secs
if time() - res.timestamp > conf.cache_ttl then
return signal_cache_req(ctx, cache_key, "Refresh")
end
end
-- we have cache data yo!
-- expose response data for logging plugins
local response_data = {
res = res,
req = {
body = res.req_body,
},
server_addr = ngx.var.server_addr,
}
kong.ctx.shared.proxy_cache_hit = response_data
local nctx = ngx.ctx
nctx.KONG_PROXIED = true
for k in pairs(res.headers) do
if not overwritable_header(k) then
res.headers[k] = nil
end
end
res.headers["Age"] = floor(time() - res.timestamp)
res.headers["X-Cache-Status"] = "Hit"
return kong.response.exit(res.status, res.body, res.headers)
end
function ProxyCacheHandler:header_filter(conf)
local ctx = kong.ctx.plugin
local proxy_cache = ctx.proxy_cache
-- don't look at our headers if
-- a) the request wasn't cacheable, or
-- b) the request was served from cache
if not proxy_cache then
return
end
local cc = res_cc()
-- if this is a cacheable request, gather the headers and mark it so
if cacheable_response(conf, cc) then
proxy_cache.res_headers = resp_get_headers(0, true)
proxy_cache.res_ttl = conf.cache_control and resource_ttl(cc) or conf.cache_ttl
else
kong.response.set_header("X-Cache-Status", "Bypass")
ctx.proxy_cache = nil
end
-- TODO handle Vary header
end
function ProxyCacheHandler:body_filter(conf)
local ctx = kong.ctx.plugin
local proxy_cache = ctx.proxy_cache
if not proxy_cache then
return
end
local body = kong.response.get_raw_body()
if body then
local strategy = require(STRATEGY_PATH)({
strategy_name = conf.strategy,
strategy_opts = conf[conf.strategy],
})
local res = {
status = kong.response.get_status(),
headers = proxy_cache.res_headers,
body = body,
body_len = #body,
timestamp = time(),
ttl = proxy_cache.res_ttl,
version = CACHE_VERSION,
req_body = ctx.req_body,
}
local ttl = conf.storage_ttl or conf.cache_control and proxy_cache.res_ttl or
conf.cache_ttl
local ok, err = strategy:store(proxy_cache.cache_key, res, ttl)
if not ok then
kong.log(err)
end
end
end
return ProxyCacheHandler
| apache-2.0 |
Kong/kong | spec/01-unit/19-hybrid/05-wrpc/queue_spec.lua | 1 | 1560 | local wrpc_queue = require "kong.tools.wrpc.queue"
local semaphore = require "ngx.semaphore"
describe("kong.tools.wrpc.queue", function()
local queue
before_each(function()
queue = wrpc_queue.new()
end)
it("simple", function()
assert.same({ nil, "timeout" }, { queue:pop(0) })
queue:push("test0")
queue:push("test1")
queue:push("test2")
assert.same("test0", queue:pop())
assert.same("test1", queue:pop())
assert.same("test2", queue:pop(0.5))
assert.same({ nil, "timeout" }, { queue:pop(0) })
end)
it("simple2", function()
queue:push("test0")
queue:push("test1")
assert.same("test0", queue:pop())
queue:push("test2")
assert.same("test1", queue:pop())
assert.same("test2", queue:pop())
assert.same({ nil, "timeout" }, { queue:pop(0) })
end)
it("thread", function()
local smph = semaphore.new()
ngx.thread.spawn(function()
-- wait for no time so it will timed out
assert.same({ nil, "timeout" }, { queue:pop(0) })
assert.same({}, queue:pop())
assert.same({1}, queue:pop())
assert.same({2}, queue:pop())
assert.same({ nil, "timeout" }, { queue:pop(0) })
smph:post()
end)
-- yield
ngx.sleep(0)
queue:push({})
queue:push({1})
queue:push({2})
-- yield to allow thread to finish
ngx.sleep(0)
-- should be empty again
assert.same({ nil, "timeout" }, { queue:pop(0) })
queue:push({2, {}})
assert.same({2, {}}, queue:pop())
assert(smph:wait(0), "thread is not resumed")
end)
end)
| apache-2.0 |
Deadwing888/darkstar | scripts/globals/spells/knights_minne_v.lua | 27 | 1498 | -----------------------------------------
-- Spell: Knight's Minne V
-- Grants Defense bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 50 + math.floor((sLvl + iLvl)/10);
if (power >= 120) then
power = 120;
end
local iBoost = caster:getMod(MOD_MINNE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINNE_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINNE,power,0,duration,caster:getID(), 0, 5)) then
spell:setMsg(75);
end
return EFFECT_MINNE;
end; | gpl-3.0 |
Deadwing888/darkstar | scripts/commands/togglegm.lua | 50 | 1876 | ---------------------------------------------------------------------------------------------------
-- func: togglegm
-- desc: Toggles a GMs nameflags/icon.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = ""
};
function onTrigger(player)
-- GM Flag Definitions
local FLAG_GM = 0x04000000;
local FLAG_GM_SENIOR = 0x05000000;
local FLAG_GM_LEAD = 0x06000000;
local FLAG_GM_PRODUCER = 0x07000000;
local FLAG_SENIOR = 0x01000000; -- Do NOT set these flags. These are here to
local FLAG_LEAD = 0x02000000; -- ensure all GM status is removed.
-- Configurable Options
local MINLVL_GM = 1; -- For "whitelisting" players to have some commands, but not GM tier commands.
local MINLVL_GM_SENIOR = 2; -- These are configurable so that commands may be restricted
local MINLVL_GM_LEAD = 3; -- between different levels of GM's with the same icon.
local MINLVL_GM_PRODUCER = 4;
if (player:checkNameFlags(FLAG_GM)) then
if (player:checkNameFlags(FLAG_GM)) then
player:setFlag(FLAG_GM);
end
if (player:checkNameFlags(FLAG_SENIOR)) then
player:setFlag(FLAG_SENIOR);
end
if (player:checkNameFlags(FLAG_LEAD)) then
player:setFlag(FLAG_LEAD);
end
else
local gmlvl = player:getGMLevel();
if (gmlvl >= MINLVL_GM_PRODUCER) then
player:setFlag(FLAG_GM_PRODUCER);
elseif (gmlvl >= MINLVL_GM_LEAD) then
player:setFlag(FLAG_GM_LEAD);
elseif (gmlvl >= MINLVL_GM_SENIOR) then
player:setFlag(FLAG_GM_SENIOR);
elseif (gmlvl >= MINLVL_GM) then
player:setFlag(FLAG_GM);
end
end
end | gpl-3.0 |
RwNigma/darkstar | scripts/globals/items/silken_sash.lua | 36 | 1212 | -----------------------------------------
-- ID: 5632
-- Item: Silken Sash
-- Food Effect: 4 Hrs, All Races
-----------------------------------------
-- TODO: Group Effect
-- HP Recovered while healing +3
-- MP Recovered while healing +5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5632);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HPHEAL, 3);
target:addMod(MOD_MPHEAL, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HPHEAL, 3);
target:delMod(MOD_MPHEAL, 5);
end;
| gpl-3.0 |
LGCaerwyn/QSanguosha-Para-tangjs520-LGCaerwyn | lang/zh_CN/Audio/SPPackageLines.lua | 2 | 5083 | -- lines for SP Package
return {
-- 杨修
["$jilei1"] = "食之无肉,弃之有味。",
["$jilei2"] = "曹公之意我已了然。",
["$danlao2"] = "来来,一人一口。",
["$danlao1"] = "我喜欢。",
["~yangxiu"] = "我固自以死之晚也。",
-- 公孙瓒
["$yicong1"] = "冲啊!", -- +1 -> -1
["$yicong2"] = "众将听令,摆好阵势,御敌!", -- -1 -> +1
["~gongsunzan"] = "我军将败,我已无颜苟活于世……",
-- 袁术
["$yongsi1"] = "玉玺在手,天下我有!",
["$yongsi2"] = "大汉天下,已半入我手!",
["$weidi1"] = "我才是皇帝!",
["$weidi2"] = "你们都得听我的号令!",
["~yuanshu"] = "可恶,就差一步了!",
-- SP关羽
["cv:sp_guanyu"] = "喵小林,官方",
["$danji"] = "吾兄待我甚厚,誓以共死,今往投之,望曹公见谅。",
-- 曹洪
["cv:caohong"] = "喵小林",
["$yuanhu1"] = "将军,这件兵器可还趁手!", --武器
["$yuanhu2"] = "刀剑无眼,须得小心防护。", --防具
["$yuanhu3"] = "宝马配英雄!哈哈哈哈……", --坐骑
["$yuanhu4"] = "天下可无洪,不可无公。", --曹操
["$yuanhu5"] = "持戈整兵,列阵御敌!", --自己
["~caohong"] = "福兮祸所伏…",
-- 关银屏
["cv:guanyinping"] = "蒲小猫",
["$xueji1"] = "这炙热的鲜血父亲你可感受的到!",
["$xueji2"] = "取你首级祭先父之灵!",
["$huxiao1"] = "大仇未报还不能放弃",
["$huxiao2"] = "虎父无犬女!",
["$huxiao3"] = "孜然老贼还吾父命来",
["$wuji1"] = "我感受到了父亲的力量!",
["$wuji2"] = "我也要像父亲那样坚强!",
["~guanyinping"] = "父亲,你来救我了吗……",
-- 夏侯霸
["cv:xiahouba"] = "裤衩,官方",
["$baobian1"] = "跪下受降,饶你不死!", -- 3体力
["$baobian2"] = "黄口小儿,可听过将军名号?", -- 2体力
["$baobian3"] = "受死吧!", -- 1体力
["$tiaoxin3"] = "跪下受降,饶你不死!",
["$tiaoxin4"] = "黄口小儿,可听过将军名号?",
["$paoxiao3"] = "喝啊~~~",
["$paoxiao4"] = "受死吧!",
["$shensu3"] = "冲杀敌阵,来去如电!",
["$shensu4"] = "今日有恙在身,须得速战速决!",
["~xiahouba"] = "弃魏投蜀,死而无憾……",
-- 陈琳
["cv:chenlin"] = "官方",
["$bifa1"] = "笔墨纸砚皆兵器也!", -- 发动
["$bifa2"] = "汝德行败坏,人所不齿也!", -- 给牌
["$bifa3"] = "行文如刀,笔墨诛心!", -- 失去体力
["$songci1"] = "将军德才兼备,大汉之栋梁也。", -- 摸牌
["$songci2"] = "汝窃国奸贼,人人得而诛之。", -- 弃牌
["~chenlin"] = "来人,我的笔呢?",
-- 大乔小乔
["$xingwu1"] = "哼,不要小瞧女孩子哦!", -- 放置牌
["$xingwu2"] = "姐妹齐心,其利断金!", -- 造成伤害
["~erqiao"] = "伯符、公瑾,请一定守护着我们的江东哦……",
-- 张宝
["$zhoufu"] = "违吾咒者,倾死灭亡!",
["$yingbing"] = "朱雀玄武,侍卫我真!",
["~zhangbao"] = "黄天!为何……" ,
-- 诸葛恪
["$aocai1"] = "吾主圣明,泽被臣属!",
["$aocai2"] = "哼,易如反掌!",
["$duwu1"] = "破曹大功,正在今朝!",
["$duwu2"] = "全力攻城,言退者,斩!",
["~zhugeke"] = "重权镇主,是我疏忽了……",
-- 虎牢关吕布
["cv:shenlvbu2"] = "官方,风叹息",
["$shenwei1"] = "我不会输给任何人!",
["$shenwei2"] = "萤烛之火,也敢与日月争辉!",
["$shenji1"] = "竟想赢我,痴人说梦!",
["$shenji2"] = "杂鱼们,都去死吧!",
["$xiuluo1"] = "鼠辈,螳臂当车!",
["$xiuluo2"] = "准备受死吧!",
["~shenlvbu2"] = "虎牢关失守了…",
-- 张宝
["$zhoufu1"] = "违吾咒者,倾死灭亡。",
["$zhoufu2"] = "咒宝符命,速显威灵!",
["$yingbing1"] = "所呼立至,所召立前。",
["$yingbing2"] = "朱雀玄武,侍卫我真。",
["~zhangbao"] = "黄天……为何……",
-- 曹昂
["$kangkai1"] = "父亲快走,孩儿断后。",
["$kangkai2"] = "典将军,比比看谁杀敌更多!",
["~caoang"] = "典将军………还是你赢了…",
-- 诸葛瑾
["$hongyuan1"] = "自舍其身,失于天下。",
["$hongyuan2"] = "诸将莫慌,粮草已到。",
["$huanshi1"] = "尽此生之力,保友邦之安。",
["$huanshi2"] = "患乐之危机释兵之困顿。",
["$mingzhe1"] = "塞翁失马,焉知非福。",
["$mingzhe2"] = "名义洞察,哲以保身。",
-- 星彩
["$shenxian1"] = "抚慰君兮,以安国事。",
["$shenxian2"] = "愿尽己力,为君分忧!",
["$qiangwu1"] = "咆哮沙场,万夫不敌!",
["$qiangwu2"] = "父亲未尽之业由我继续!",
["~xingcai"] = "复兴汉室之路………臣妾再也不能陪伴左右…",
-- 祖茂
["$yingbing1"] = "将军走此小道,追兵交我应付。",
["$yingbing2"] = "追兵凶猛,末将断后!",
["$juedi1"] = "提起武器,最后一搏!",
["$juedi2"] = "困兽之斗,以全忠义!",
["~zumao"] = "孙将军………已经安全了吧…",
} | lgpl-3.0 |
RwNigma/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tsih_Kolgimih.lua | 38 | 1045 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tsih Kolgimih
-- Type: Event Scene Replayer
-- @pos -143.000 0.999 11.000 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0327);
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 |
ffxijuggalo/darkstar | scripts/zones/Throne_Room/IDs.lua | 8 | 1338 | -----------------------------------
-- Area: Throne_Room
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.THRONE_ROOM] =
{
text =
{
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
CONQUEST_BASE = 7049, -- Tallying conquest results...
NO_HIDE_AWAY = 7698, -- I have not been hiding away from my troubles!
FEEL_MY_PAIN = 7699, -- Feel my twenty years of pain!
YOUR_ANSWER = 7700, -- Is that your answer!?
RETURN_TO_THE_DARKNESS = 7701, -- Return with your soul to the darkness you came from!
CANT_UNDERSTAND = 7702, -- You--a man who has never lived bound by the chains of his country--how can you understand my pain!?
BLADE_ANSWER = 7703, -- Let my blade be the answer!
},
mob =
{
SHADOW_LORD_STAGE_2_OFFSET = 17453060,
ZEID_BCNM_OFFSET = 17453064,
},
npc =
{
},
}
return zones[dsp.zone.THRONE_ROOM] | gpl-3.0 |
ffxijuggalo/darkstar | scripts/zones/Cloister_of_Flames/npcs/Fire_Protocrystal.lua | 9 | 1333 | -----------------------------------
-- Area: Cloister of Flames
-- NPC: Fire Protocrystal
-- Involved in Quests: Trial by Fire, Trial Size Trial by Fire
-- !pos -721 0 -598 207
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/bcnm");
local ID = require("scripts/zones/Cloister_of_Flames/IDs");
function onTrade(player,npc,trade)
TradeBCNM(player,npc,trade);
end;
function onTrigger(player,npc)
if (player:getCurrentMission(ASA) == dsp.mission.id.asa.SUGAR_COATED_DIRECTIVE and player:getCharVar("ASA4_Scarlet") == 1) then
player:startEvent(2);
elseif (EventTriggerBCNM(player,npc)) then
return;
else
player:messageSpecial(ID.text.PROTOCRYSTAL);
end
end;
function onEventUpdate(player,csid,option,extras)
EventUpdateBCNM(player,csid,option,extras);
end;
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid==2) then
player:delKeyItem(dsp.ki.DOMINAS_SCARLET_SEAL);
player:addKeyItem(dsp.ki.SCARLET_COUNTERSEAL);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SCARLET_COUNTERSEAL);
player:setCharVar("ASA4_Scarlet","2");
elseif (EventFinishBCNM(player,csid,option)) then
return;
end
end; | gpl-3.0 |
destdev/ygopro-scripts | c57288708.lua | 1 | 3589 | --星遺物-『星杯』
function c57288708.initial_effect(c)
--send to grave
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(57288708,0))
e1:SetCategory(CATEGORY_TOGRAVE)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetProperty(EFFECT_FLAG_DELAY)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c57288708.tgcon)
e1:SetCost(c57288708.tgcost)
e1:SetTarget(c57288708.tgtg)
e1:SetOperation(c57288708.tgop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(57288708,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e2:SetCountLimit(1,57288708)
e2:SetCondition(c57288708.spcon)
e2:SetTarget(c57288708.sptg)
e2:SetOperation(c57288708.spop)
c:RegisterEffect(e2)
--tohand
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(57288708,2))
e3:SetCategory(CATEGORY_SEARCH)
e3:SetType(EFFECT_TYPE_IGNITION)
e3:SetRange(LOCATION_GRAVE)
e3:SetCountLimit(1,57288709)
e3:SetCondition(aux.exccon)
e3:SetCost(aux.bfgcost)
e3:SetTarget(c57288708.thtg)
e3:SetOperation(c57288708.thop)
c:RegisterEffect(e3)
end
function c57288708.tgfilter(c)
return bit.band(c:GetSummonLocation(),LOCATION_EXTRA)==LOCATION_EXTRA
end
function c57288708.tgcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c57288708.tgfilter,1,nil)
end
function c57288708.tgcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c57288708.tgtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=eg:Filter(c57288708.tgfilter,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,g,g:GetCount(),0,0)
end
function c57288708.tgop(e,tp,eg,ep,ev,re,r,rp)
local g=eg:Filter(c57288708.tgfilter,nil)
if g:GetCount()>0 then
Duel.SendtoGrave(g,REASON_EFFECT)
end
end
function c57288708.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsPreviousPosition(POS_FACEUP) and not c:IsSummonType(SUMMON_TYPE_SPECIAL)
end
function c57288708.spfilter(c,e,tp)
return c:IsSetCard(0xfd) and not c:IsCode(57288708) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c57288708.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return not Duel.IsPlayerAffectedByEffect(tp,59822133)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>1
and Duel.IsExistingMatchingCard(c57288708.spfilter,tp,LOCATION_DECK,0,2,nil,e,tp) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,2,tp,LOCATION_DECK)
end
function c57288708.spop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<2 or Duel.IsPlayerAffectedByEffect(tp,59822133) then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c57288708.spfilter,tp,LOCATION_DECK,0,2,2,nil,e,tp)
if g:GetCount()==2 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
function c57288708.thfilter(c)
return c:IsSetCard(0xfe) and c:IsAbleToHand()
end
function c57288708.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c57288708.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c57288708.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c57288708.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
riking/marvin | vendor/github.com/yuin/gopher-lua/_lua5.1-tests/gc.lua | 19 | 7014 | print('testing garbage collection')
collectgarbage()
_G["while"] = 234
limit = 5000
contCreate = 0
print('tables')
while contCreate <= limit do
local a = {}; a = nil
contCreate = contCreate+1
end
a = "a"
contCreate = 0
print('strings')
while contCreate <= limit do
a = contCreate .. "b";
a = string.gsub(a, '(%d%d*)', string.upper)
a = "a"
contCreate = contCreate+1
end
contCreate = 0
a = {}
print('functions')
function a:test ()
while contCreate <= limit do
loadstring(string.format("function temp(a) return 'a%d' end", contCreate))()
assert(temp() == string.format('a%d', contCreate))
contCreate = contCreate+1
end
end
a:test()
-- collection of functions without locals, globals, etc.
do local f = function () end end
print("functions with errors")
prog = [[
do
a = 10;
function foo(x,y)
a = sin(a+0.456-0.23e-12);
return function (z) return sin(%x+z) end
end
local x = function (w) a=a+w; end
end
]]
do
local step = 1
if rawget(_G, "_soft") then step = 13 end
for i=1, string.len(prog), step do
for j=i, string.len(prog), step do
pcall(loadstring(string.sub(prog, i, j)))
end
end
end
print('long strings')
x = "01234567890123456789012345678901234567890123456789012345678901234567890123456789"
assert(string.len(x)==80)
s = ''
n = 0
k = 300
while n < k do s = s..x; n=n+1; j=tostring(n) end
assert(string.len(s) == k*80)
s = string.sub(s, 1, 20000)
s, i = string.gsub(s, '(%d%d%d%d)', math.sin)
assert(i==20000/4)
s = nil
x = nil
assert(_G["while"] == 234)
local bytes = gcinfo()
while 1 do
local nbytes = gcinfo()
if nbytes < bytes then break end -- run until gc
bytes = nbytes
a = {}
end
local function dosteps (siz)
collectgarbage()
collectgarbage"stop"
local a = {}
for i=1,100 do a[i] = {{}}; local b = {} end
local x = gcinfo()
local i = 0
repeat
i = i+1
until collectgarbage("step", siz)
assert(gcinfo() < x)
return i
end
assert(dosteps(0) > 10)
assert(dosteps(6) < dosteps(2))
assert(dosteps(10000) == 1)
assert(collectgarbage("step", 1000000) == true)
assert(collectgarbage("step", 1000000))
do
local x = gcinfo()
collectgarbage()
collectgarbage"stop"
repeat
local a = {}
until gcinfo() > 1000
collectgarbage"restart"
repeat
local a = {}
until gcinfo() < 1000
end
lim = 15
a = {}
-- fill a with `collectable' indices
for i=1,lim do a[{}] = i end
b = {}
for k,v in pairs(a) do b[k]=v end
-- remove all indices and collect them
for n in pairs(b) do
a[n] = nil
assert(type(n) == 'table' and next(n) == nil)
collectgarbage()
end
b = nil
collectgarbage()
for n in pairs(a) do error'cannot be here' end
for i=1,lim do a[i] = i end
for i=1,lim do assert(a[i] == i) end
print('weak tables')
a = {}; setmetatable(a, {__mode = 'k'});
-- fill a with some `collectable' indices
for i=1,lim do a[{}] = i end
-- and some non-collectable ones
for i=1,lim do local t={}; a[t]=t end
for i=1,lim do a[i] = i end
for i=1,lim do local s=string.rep('@', i); a[s] = s..'#' end
collectgarbage()
local i = 0
for k,v in pairs(a) do assert(k==v or k..'#'==v); i=i+1 end
assert(i == 3*lim)
a = {}; setmetatable(a, {__mode = 'v'});
a[1] = string.rep('b', 21)
collectgarbage()
assert(a[1]) -- strings are *values*
a[1] = nil
-- fill a with some `collectable' values (in both parts of the table)
for i=1,lim do a[i] = {} end
for i=1,lim do a[i..'x'] = {} end
-- and some non-collectable ones
for i=1,lim do local t={}; a[t]=t end
for i=1,lim do a[i+lim]=i..'x' end
collectgarbage()
local i = 0
for k,v in pairs(a) do assert(k==v or k-lim..'x' == v); i=i+1 end
assert(i == 2*lim)
a = {}; setmetatable(a, {__mode = 'vk'});
local x, y, z = {}, {}, {}
-- keep only some items
a[1], a[2], a[3] = x, y, z
a[string.rep('$', 11)] = string.rep('$', 11)
-- fill a with some `collectable' values
for i=4,lim do a[i] = {} end
for i=1,lim do a[{}] = i end
for i=1,lim do local t={}; a[t]=t end
collectgarbage()
assert(next(a) ~= nil)
local i = 0
for k,v in pairs(a) do
assert((k == 1 and v == x) or
(k == 2 and v == y) or
(k == 3 and v == z) or k==v);
i = i+1
end
assert(i == 4)
x,y,z=nil
collectgarbage()
assert(next(a) == string.rep('$', 11))
-- testing userdata
collectgarbage("stop") -- stop collection
local u = newproxy(true)
local s = 0
local a = {[u] = 0}; setmetatable(a, {__mode = 'vk'})
for i=1,10 do a[newproxy(u)] = i end
for k in pairs(a) do assert(getmetatable(k) == getmetatable(u)) end
local a1 = {}; for k,v in pairs(a) do a1[k] = v end
for k,v in pairs(a1) do a[v] = k end
for i =1,10 do assert(a[i]) end
getmetatable(u).a = a1
getmetatable(u).u = u
do
local u = u
getmetatable(u).__gc = function (o)
assert(a[o] == 10-s)
assert(a[10-s] == nil) -- udata already removed from weak table
assert(getmetatable(o) == getmetatable(u))
assert(getmetatable(o).a[o] == 10-s)
s=s+1
end
end
a1, u = nil
assert(next(a) ~= nil)
collectgarbage()
assert(s==11)
collectgarbage()
assert(next(a) == nil) -- finalized keys are removed in two cycles
-- __gc x weak tables
local u = newproxy(true)
setmetatable(getmetatable(u), {__mode = "v"})
getmetatable(u).__gc = function (o) os.exit(1) end -- cannot happen
collectgarbage()
local u = newproxy(true)
local m = getmetatable(u)
m.x = {[{0}] = 1; [0] = {1}}; setmetatable(m.x, {__mode = "kv"});
m.__gc = function (o)
assert(next(getmetatable(o).x) == nil)
m = 10
end
u, m = nil
collectgarbage()
assert(m==10)
-- errors during collection
u = newproxy(true)
getmetatable(u).__gc = function () error "!!!" end
u = nil
assert(not pcall(collectgarbage))
if not rawget(_G, "_soft") then
print("deep structures")
local a = {}
for i = 1,200000 do
a = {next = a}
end
collectgarbage()
end
-- create many threads with self-references and open upvalues
local thread_id = 0
local threads = {}
function fn(thread)
local x = {}
threads[thread_id] = function()
thread = x
end
coroutine.yield()
end
while thread_id < 1000 do
local thread = coroutine.create(fn)
coroutine.resume(thread, thread)
thread_id = thread_id + 1
end
-- create a userdata to be collected when state is closed
do
local newproxy,assert,type,print,getmetatable =
newproxy,assert,type,print,getmetatable
local u = newproxy(true)
local tt = getmetatable(u)
___Glob = {u} -- avoid udata being collected before program end
tt.__gc = function (o)
assert(getmetatable(o) == tt)
-- create new objects during GC
local a = 'xuxu'..(10+3)..'joao', {}
___Glob = o -- ressurect object!
newproxy(o) -- creates a new one with same metatable
print(">>> closing state " .. "<<<\n")
end
end
-- create several udata to raise errors when collected while closing state
do
local u = newproxy(true)
getmetatable(u).__gc = function (o) return o + 1 end
table.insert(___Glob, u) -- preserve udata until the end
for i = 1,10 do table.insert(___Glob, newproxy(u)) end
end
print('OK')
| gpl-3.0 |
destdev/ygopro-scripts | c52370835.lua | 9 | 1409 | --H・C ソード・シールド
function c52370835.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(52370835,0))
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c52370835.condition)
e1:SetCost(c52370835.cost)
e1:SetOperation(c52370835.operation)
c:RegisterEffect(e1)
end
function c52370835.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0x6f)
end
function c52370835.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c52370835.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c52370835.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c52370835.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(1)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c52370835.filter)
e2:SetReset(RESET_PHASE+PHASE_END)
e2:SetValue(1)
Duel.RegisterEffect(e2,tp)
end
function c52370835.filter(e,c)
return c:IsSetCard(0x6f)
end
| gpl-2.0 |
destdev/ygopro-scripts | c18865703.lua | 1 | 3268 | --ZW-玄武絶対聖盾
function c18865703.initial_effect(c)
c:SetUniqueOnField(1,0,18865703)
--equip
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(18865703,0))
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetRange(LOCATION_MZONE)
e1:SetCondition(c18865703.eqcon)
e1:SetTarget(c18865703.eqtg)
e1:SetOperation(c18865703.eqop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(18865703,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetTarget(c18865703.sptg)
e2:SetOperation(c18865703.spop)
c:RegisterEffect(e2)
local e3=e2:Clone()
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
c:RegisterEffect(e3)
end
function c18865703.eqcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():CheckUniqueOnField(tp)
end
function c18865703.filter(c)
return c:IsFaceup() and c:IsSetCard(0x107f)
end
function c18865703.eqtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c18865703.filter(chkc) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_SZONE)>0
and Duel.IsExistingTarget(c18865703.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c18865703.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
function c18865703.eqop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) or c:IsFacedown() then return end
local tc=Duel.GetFirstTarget()
if Duel.GetLocationCount(tp,LOCATION_SZONE)<=0 or tc:GetControler()~=tp or tc:IsFacedown() or not tc:IsRelateToEffect(e) or not c:CheckUniqueOnField(tp) then
Duel.SendtoGrave(c,REASON_EFFECT)
return
end
Duel.Equip(tp,c,tc,true)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_EQUIP_LIMIT)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
e1:SetValue(c18865703.eqlimit)
e1:SetLabelObject(tc)
c:RegisterEffect(e1)
--atkup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_DEFENSE)
e2:SetValue(2000)
e2:SetReset(RESET_EVENT+RESETS_STANDARD)
c:RegisterEffect(e2)
end
function c18865703.eqlimit(e,c)
return c==e:GetLabelObject()
end
function c18865703.spfilter(c,e,tp)
return c:IsFaceup() and c:IsType(TYPE_XYZ) and c:IsCanBeSpecialSummoned(e,0,tp,false,false,POS_FACEUP_DEFENSE)
end
function c18865703.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c18865703.spfilter(chkc,e,tp) end
if chk==0 then return Duel.IsExistingTarget(c18865703.spfilter,tp,LOCATION_REMOVED,0,1,nil,e,tp)
and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c18865703.spfilter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c18865703.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP_DEFENSE)
end
end
| gpl-2.0 |
RwNigma/darkstar | scripts/globals/weaponskills/heavy_swing.lua | 30 | 1339 | -----------------------------------
-- Heavy Swing
-- Staff weapon skill
-- Skill Level: 5
-- Deacription:Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.25 2.25
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1.25; params.ftp300 = 2.25;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
RwNigma/darkstar | scripts/zones/Crawlers_Nest/npcs/qm12.lua | 57 | 2120 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: qm12 (??? - Exoray Mold Crumbs)
-- Involved in Quest: In Defiant Challenge
-- @pos 99.326 -0.126 -188.869 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Crawlers_Nest/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1089) == false and player:hasKeyItem(EXORAY_MOLD_CRUMB3) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(EXORAY_MOLD_CRUMB3);
player:messageSpecial(KEYITEM_OBTAINED,EXORAY_MOLD_CRUMB3);
end
if (player:hasKeyItem(EXORAY_MOLD_CRUMB1) and player:hasKeyItem(EXORAY_MOLD_CRUMB2) and player:hasKeyItem(EXORAY_MOLD_CRUMB3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1089, 1);
player:messageSpecial(ITEM_OBTAINED, 1089);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1089);
end
end
if (player:hasItem(1089)) then
player:delKeyItem(EXORAY_MOLD_CRUMB1);
player:delKeyItem(EXORAY_MOLD_CRUMB2);
player:delKeyItem(EXORAY_MOLD_CRUMB3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
destdev/ygopro-scripts | c8978197.lua | 1 | 1623 | --ロード・オブ・ドラゴン-ドラゴンの統制者-
function c8978197.initial_effect(c)
--change name
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetCode(EFFECT_CHANGE_CODE)
e1:SetRange(LOCATION_MZONE)
e1:SetValue(17985575)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(8978197,0))
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetCost(c8978197.thcost)
e2:SetTarget(c8978197.thtg)
e2:SetOperation(c8978197.thop)
c:RegisterEffect(e2)
end
function c8978197.cfilter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDiscardable()
end
function c8978197.thcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c8978197.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,c8978197.cfilter,1,1,REASON_COST+REASON_DISCARD)
end
function c8978197.thfilter(c)
return c:IsCode(71867500,43973174,48800175) and c:IsAbleToHand()
end
function c8978197.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c8978197.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c8978197.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c8978197.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
destdev/ygopro-scripts | c20838380.lua | 6 | 1401 | --シャーク・サッカー
function c20838380.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(20838380,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e1:SetRange(LOCATION_HAND)
e1:SetCode(EVENT_SPSUMMON_SUCCESS)
e1:SetCondition(c20838380.spcon)
e1:SetTarget(c20838380.sptg)
e1:SetOperation(c20838380.spop)
c:RegisterEffect(e1)
local e2=e1:Clone()
e2:SetCode(EVENT_SUMMON_SUCCESS)
c:RegisterEffect(e2)
--
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e3:SetValue(1)
c:RegisterEffect(e3)
end
function c20838380.cfilter(c,tp)
return c:IsFaceup() and c:IsControler(tp) and c:IsRace(RACE_FISH+RACE_SEASERPENT+RACE_AQUA)
end
function c20838380.spcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c20838380.cfilter,1,nil,tp)
end
function c20838380.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c20838380.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
| gpl-2.0 |
ffxijuggalo/darkstar | scripts/globals/items/lungfish.lua | 11 | 1043 | -----------------------------------------
-- ID: 4315
-- Item: Lungfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -2
-- Mind 4
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if (target:getRace() ~= dsp.race.MITHRA) then
result = dsp.msg.basic.CANNOT_EAT
elseif target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then
result = 0
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,300,4315)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.DEX, -2)
target:addMod(dsp.mod.MND, 4)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.DEX, -2)
target:delMod(dsp.mod.MND, 4)
end
| gpl-3.0 |
RwNigma/darkstar | scripts/zones/Spire_of_Dem/bcnms/ancient_flames_beckon.lua | 17 | 3853 | -----------------------------------
-- Area: Spire_of_Dem
-- Name: ancient_flames_backon
-- KSNM30
-----------------------------------
package.loaded["scripts/zones/Spire_of_Dem/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/globals/teleports");
require("scripts/zones/Spire_of_Dem/TextIDs");
-----------------------------------
-- EXAMPLE SCRIPT
--
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
print("instance code ");
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)
-- printf("leavecode: %u",leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then
if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_HOLLA)) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,3);
elseif (player:hasKeyItem(LIGHT_OF_MEA) or player:hasKeyItem(LIGHT_OF_HOLLA)) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,2);
end
elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,0,1);
else
player:startEvent(0x7d01,0,0,0,instance:getTimeInside(),0,0,1); -- can't tell which cs is playing when you're doing it again to help
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7D01) then
if (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then
if (player:hasKeyItem(LIGHT_OF_MEA) and player:hasKeyItem(LIGHT_OF_HOLLA)) then
player:addExp(1500);
player:addKeyItem(LIGHT_OF_DEM);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM);
player:completeMission(COP,THE_MOTHERCRYSTALS);
player:setVar("PromathiaStatus",0)
player:addMission(COP,AN_INVITATION_WEST);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_LUFAISE,0,1);
elseif (not(player:hasKeyItem(LIGHT_OF_DEM))) then
player:setVar("cspromy3",1)
player:addKeyItem(LIGHT_OF_DEM);
player:addExp(1500);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1);
end
elseif (player:getCurrentMission(COP) == BELOW_THE_ARKS) then
player:addExp(1500);
player:completeMission(COP,BELOW_THE_ARKS);
player:addMission(COP,THE_MOTHERCRYSTALS)
player:setVar("cspromy2",1)
player:setVar("PromathiaStatus",0)
player:addKeyItem(LIGHT_OF_DEM);
player:messageSpecial(CANT_REMEMBER,LIGHT_OF_DEM);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1);
else
player:addExp(1500);
player:addStatusEffectEx(EFFECT_TELEPORT,0,TELEPORT_EXITPROMDEM,0,1);
end
end
end; | gpl-3.0 |
your-gatsby/skynet | examples/login/gated.lua | 57 | 2201 | local msgserver = require "snax.msgserver"
local crypt = require "crypt"
local skynet = require "skynet"
local loginservice = tonumber(...)
local server = {}
local users = {}
local username_map = {}
local internal_id = 0
-- login server disallow multi login, so login_handler never be reentry
-- call by login server
function server.login_handler(uid, secret)
if users[uid] then
error(string.format("%s is already login", uid))
end
internal_id = internal_id + 1
local id = internal_id -- don't use internal_id directly
local username = msgserver.username(uid, id, servername)
-- you can use a pool to alloc new agent
local agent = skynet.newservice "msgagent"
local u = {
username = username,
agent = agent,
uid = uid,
subid = id,
}
-- trash subid (no used)
skynet.call(agent, "lua", "login", uid, id, secret)
users[uid] = u
username_map[username] = u
msgserver.login(username, secret)
-- you should return unique subid
return id
end
-- call by agent
function server.logout_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
msgserver.logout(u.username)
users[uid] = nil
username_map[u.username] = nil
skynet.call(loginservice, "lua", "logout",uid, subid)
end
end
-- call by login server
function server.kick_handler(uid, subid)
local u = users[uid]
if u then
local username = msgserver.username(uid, subid, servername)
assert(u.username == username)
-- NOTICE: logout may call skynet.exit, so you should use pcall.
pcall(skynet.call, u.agent, "lua", "logout")
end
end
-- call by self (when socket disconnect)
function server.disconnect_handler(username)
local u = username_map[username]
if u then
skynet.call(u.agent, "lua", "afk")
end
end
-- call by self (when recv a request from client)
function server.request_handler(username, msg)
local u = username_map[username]
return skynet.tostring(skynet.rawcall(u.agent, "client", msg))
end
-- call by self (when gate open)
function server.register_handler(name)
servername = name
skynet.call(loginservice, "lua", "register_gate", servername, skynet.self())
end
msgserver.start(server)
| mit |
Deadwing888/darkstar | scripts/zones/Dynamis-Jeuno/npcs/qm1.lua | 13 | 1216 | -----------------------------------
-- Area: Dynamis Jeuno
-- NPC: ??? (Spawn when mega is defeated)
-----------------------------------
package.loaded["scripts/zones/Dynamis-Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Dynamis-Jeuno/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(HYDRA_CORPS_TACTICAL_MAP) == false) then
player:setVar("DynaJeuno_Win",1);
player:addKeyItem(HYDRA_CORPS_TACTICAL_MAP);
player:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_TACTICAL_MAP);
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 |
ffxijuggalo/darkstar | scripts/globals/items/dish_of_hydra_kofte_+1.lua | 11 | 1613 | -----------------------------------------
-- ID: 5603
-- Item: dish_of_hydra_kofte_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength 8
-- Intelligence -4
-- Attack % 20
-- Attack Cap 160
-- Defense % 25
-- Defense Cap 75
-- Ranged ATT % 20
-- Ranged ATT Cap 160
-- Poison Resist 5
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,14400,5603)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.STR, 8)
target:addMod(dsp.mod.INT, -4)
target:addMod(dsp.mod.FOOD_ATTP, 20)
target:addMod(dsp.mod.FOOD_ATT_CAP, 160)
target:addMod(dsp.mod.FOOD_DEFP, 25)
target:addMod(dsp.mod.FOOD_DEF_CAP, 75)
target:addMod(dsp.mod.FOOD_RATTP, 20)
target:addMod(dsp.mod.FOOD_RATT_CAP, 160)
target:addMod(dsp.mod.POISONRES, 5)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, 8)
target:delMod(dsp.mod.INT, -4)
target:delMod(dsp.mod.FOOD_ATTP, 20)
target:delMod(dsp.mod.FOOD_ATT_CAP, 160)
target:delMod(dsp.mod.FOOD_DEFP, 25)
target:delMod(dsp.mod.FOOD_DEF_CAP, 75)
target:delMod(dsp.mod.FOOD_RATTP, 20)
target:delMod(dsp.mod.FOOD_RATT_CAP, 160)
target:delMod(dsp.mod.POISONRES, 5)
end
| gpl-3.0 |
RwNigma/darkstar | scripts/zones/La_Theine_Plateau/npcs/Narvecaint.lua | 17 | 1702 | -----------------------------------
-- Area: La Theine Plateau
-- NPC: Narvecaint
-- Involved in Mission: The Rescue Drill
-- @pos -263 22 129 102
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/La_Theine_Plateau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(SANDORIA) == THE_RESCUE_DRILL) then
local MissionStatus = player:getVar("MissionStatus");
if (MissionStatus == 6) then
player:startEvent(0x006b);
elseif (MissionStatus == 7) then
player:showText(npc, RESCUE_DRILL + 14);
elseif (MissionStatus == 8) then
player:showText(npc, RESCUE_DRILL + 21);
elseif (MissionStatus >= 9) then
player:showText(npc, RESCUE_DRILL + 26);
else
player:showText(npc, RESCUE_DRILL);
end
else
player:showText(npc, RESCUE_DRILL);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x006b) then
player:setVar("MissionStatus",7);
end
end; | gpl-3.0 |
destdev/ygopro-scripts | c98494543.lua | 4 | 1299 | --魔法石の採掘
function c98494543.initial_effect(c)
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c98494543.cost)
e1:SetTarget(c98494543.target)
e1:SetOperation(c98494543.operation)
c:RegisterEffect(e1)
end
function c98494543.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(Card.IsDiscardable,tp,LOCATION_HAND,0,2,e:GetHandler()) end
Duel.DiscardHand(tp,Card.IsDiscardable,2,2,REASON_COST+REASON_DISCARD)
end
function c98494543.filter(c)
return c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c98494543.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:GetLocation()==LOCATION_GRAVE and chkc:GetControler()==tp and c98494543.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c98494543.filter,tp,LOCATION_GRAVE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectTarget(tp,c98494543.filter,tp,LOCATION_GRAVE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOHAND,g,g:GetCount(),0,0)
end
function c98494543.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc and tc:IsRelateToEffect(e) then
Duel.SendtoHand(tc,nil,REASON_EFFECT)
end
end
| gpl-2.0 |
destdev/ygopro-scripts | c43664494.lua | 2 | 3736 | --プランキッズ・プランク
function c43664494.initial_effect(c)
--activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--token
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(43664494,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON+CATEGORY_TOKEN)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1,43664494)
e2:SetCost(c43664494.tkcost)
e2:SetTarget(c43664494.tktg)
e2:SetOperation(c43664494.tkop)
c:RegisterEffect(e2)
--shuffle & draw
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(43664494,1))
e3:SetCategory(CATEGORY_TODECK+CATEGORY_DRAW)
e3:SetProperty(EFFECT_FLAG_CARD_TARGET)
e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O)
e3:SetCode(EVENT_PHASE+PHASE_END)
e3:SetRange(LOCATION_SZONE)
e3:SetCountLimit(1,43664495)
e3:SetCondition(c43664494.drcon)
e3:SetTarget(c43664494.drtg)
e3:SetOperation(c43664494.drop)
c:RegisterEffect(e3)
end
function c43664494.cfilter(c)
return c:IsSetCard(0x120) and c:IsDiscardable()
end
function c43664494.tkcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c43664494.cfilter,tp,LOCATION_HAND,0,1,nil) end
Duel.DiscardHand(tp,c43664494.cfilter,1,1,REASON_COST+REASON_DISCARD)
end
function c43664494.tktg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,43664495,0x120,0x4011,0,0,1,RACE_PYRO,ATTRIBUTE_FIRE,POS_FACEUP) end
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,0)
end
function c43664494.tkop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if not c:IsRelateToEffect(e) then return end
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0
or not Duel.IsPlayerCanSpecialSummonMonster(tp,43664495,0x120,0x4011,0,0,1,RACE_PYRO,ATTRIBUTE_FIRE,POS_FACEUP) then return end
local token=Duel.CreateToken(tp,43664495)
Duel.SpecialSummonStep(token,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UNRELEASABLE_SUM)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
token:RegisterEffect(e1,true)
local e2=e1:Clone()
e2:SetCode(EFFECT_UNRELEASABLE_NONSUM)
token:RegisterEffect(e2,true)
Duel.SpecialSummonComplete()
end
function c43664494.drcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c43664494.tdfilter(c)
return c:IsSetCard(0x120) and not c:IsCode(43664494) and c:IsAbleToDeck()
end
function c43664494.drtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c43664494.tdfilter(chkc) end
if chk==0 then return Duel.IsPlayerCanDraw(tp,1)
and Duel.IsExistingTarget(c43664494.tdfilter,tp,LOCATION_GRAVE,0,3,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectTarget(tp,c43664494.tdfilter,tp,LOCATION_GRAVE,0,3,3,nil)
Duel.SetOperationInfo(0,CATEGORY_TODECK,g,g:GetCount(),0,0)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c43664494.drop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tg=Duel.GetChainInfo(0,CHAININFO_TARGET_CARDS):Filter(Card.IsRelateToEffect,nil,e)
if not tg or tg:FilterCount(Card.IsRelateToEffect,nil,e)~=3 then return end
Duel.SendtoDeck(tg,nil,0,REASON_EFFECT)
local g=Duel.GetOperatedGroup()
if g:IsExists(Card.IsLocation,1,nil,LOCATION_DECK) then Duel.ShuffleDeck(tp) end
local ct=g:FilterCount(Card.IsLocation,nil,LOCATION_DECK+LOCATION_EXTRA)
if ct>0 then
Duel.BreakEffect()
Duel.Draw(tp,1,REASON_EFFECT)
end
end
| gpl-2.0 |
destdev/ygopro-scripts | c49959355.lua | 1 | 3512 | --ユニゾンビ
function c49959355.initial_effect(c)
--level
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(49959355,0))
e1:SetCategory(CATEGORY_HANDES)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCountLimit(1,49959355)
e1:SetCost(c49959355.lvcost)
e1:SetTarget(c49959355.lvtg1)
e1:SetOperation(c49959355.lvop1)
c:RegisterEffect(e1)
--level
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(49959355,1))
e2:SetCategory(CATEGORY_TOGRAVE)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_MZONE)
e2:SetProperty(EFFECT_FLAG_CARD_TARGET)
e2:SetCountLimit(1,49959356)
e2:SetCost(c49959355.lvcost)
e2:SetTarget(c49959355.lvtg2)
e2:SetOperation(c49959355.lvop2)
c:RegisterEffect(e2)
end
function c49959355.lvcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
end
function c49959355.filter(c)
return c:IsFaceup() and c:GetLevel()>0
end
function c49959355.lvtg1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c49959355.filter(chkc) end
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>0
and Duel.IsExistingTarget(c49959355.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c49959355.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_HANDES,nil,0,tp,1)
end
function c49959355.lvop1(e,tp,eg,ep,ev,re,r,rp)
if Duel.DiscardHand(tp,nil,1,1,REASON_EFFECT+REASON_DISCARD)==0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
end
function c49959355.tgfilter(c)
return c:IsRace(RACE_ZOMBIE) and c:IsAbleToGrave()
end
function c49959355.lvtg2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c49959355.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c49959355.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil)
and Duel.IsExistingMatchingCard(c49959355.tgfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c49959355.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_TOGRAVE,nil,1,tp,LOCATION_DECK)
end
function c49959355.lvop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,c49959355.tgfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()==0 or Duel.SendtoGrave(g,REASON_EFFECT)==0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) and g:GetFirst():IsLocation(LOCATION_GRAVE) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_LEVEL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD)
tc:RegisterEffect(e1)
end
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_ATTACK)
e2:SetTargetRange(LOCATION_MZONE,0)
e2:SetTarget(c49959355.atktg)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c49959355.atktg(e,c)
return not c:IsRace(RACE_ZOMBIE)
end
| gpl-2.0 |
destdev/ygopro-scripts | c67511500.lua | 4 | 1260 | --ドラゴン・ウィッチ-ドラゴンの守護者-
function c67511500.initial_effect(c)
--cannot be battle target
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetTargetRange(0,LOCATION_MZONE)
e1:SetValue(c67511500.atlimit)
c:RegisterEffect(e1)
--destroy replace
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_DESTROY_REPLACE)
e2:SetTarget(c67511500.desreptg)
c:RegisterEffect(e2)
end
function c67511500.atlimit(e,c)
return c:IsFaceup() and c:IsRace(RACE_DRAGON)
end
function c67511500.desreptg(e,tp,eg,ep,ev,re,r,rp,chk)
local c=e:GetHandler()
if chk==0 then return c:IsReason(REASON_BATTLE+REASON_EFFECT) and not c:IsReason(REASON_REPLACE)
and Duel.IsExistingMatchingCard(Card.IsRace,tp,LOCATION_HAND,0,1,nil,RACE_DRAGON) end
if Duel.SelectEffectYesNo(tp,e:GetHandler(),96) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TOGRAVE)
local g=Duel.SelectMatchingCard(tp,Card.IsRace,tp,LOCATION_HAND,0,1,1,nil,RACE_DRAGON)
Duel.SendtoGrave(g,REASON_EFFECT+REASON_REPLACE)
return true
else return false end
end
| gpl-2.0 |
destdev/ygopro-scripts | c44236692.lua | 4 | 1688 | --ネクロ・リンカー
function c44236692.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(44236692,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c44236692.spcost)
e1:SetTarget(c44236692.sptg)
e1:SetOperation(c44236692.spop)
c:RegisterEffect(e1)
end
function c44236692.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c44236692.filter(c,e,tp)
return c:IsSetCard(0x1017) and c:IsType(TYPE_TUNER) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c44236692.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(tp) and chkc:IsLocation(LOCATION_GRAVE) and c44236692.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
and Duel.IsExistingTarget(c44236692.filter,tp,LOCATION_GRAVE,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c44236692.filter,tp,LOCATION_GRAVE,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c44236692.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) and Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)~=0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CANNOT_BE_SYNCHRO_MATERIAL)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e1:SetValue(1)
e1:SetReset(RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
RwNigma/darkstar | scripts/globals/items/naval_rice_ball.lua | 21 | 1526 | -----------------------------------------
-- ID: 4605
-- Item: Naval Rice Ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP +26
-- Dex +3
-- Vit +4
-- hHP +2
-- Effect with enhancing equipment (Note: these are latents on gear with the effect)
-- Atk +40
-- Def +40
-- Arcana Killer (guesstimated 5%)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,4605);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 26);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 26);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 2);
end; | gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.