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 |
|---|---|---|---|---|---|
UnfortunateFruit/darkstar | scripts/zones/Port_Windurst/npcs/Sachetan_IM.lua | 30 | 4748 | -----------------------------------
-- Area: Port Windurst
-- NPC: Sachetan, I.M.
-- @pos -82 -5 165 z 240
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Port_Windurst/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(BastInv);
local inventory = BastInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff9,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break
end
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end
end
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
break
end
end
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end
end | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Upper_Jeuno/npcs/HomePoint#2.lua | 12 | 1240 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: HomePoint#2
-- @pos 32 -1 -44 244
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Upper_Jeuno/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 33);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
hamed9898/maxbot | plugins/yoda.lua | 642 | 1199 | local ltn12 = require "ltn12"
local https = require "ssl.https"
-- Edit data/mashape.lua with your Mashape API key
-- http://docs.mashape.com/api-keys
local mashape = load_from_file('data/mashape.lua', {
api_key = ''
})
local function request(text)
local api = "https://yoda.p.mashape.com/yoda?"
text = string.gsub(text, " ", "+")
local parameters = "sentence="..(text or "")
local url = api..parameters
local api_key = mashape.api_key
if api_key:isempty() then
return 'Configure your Mashape API Key'
end
local headers = {
["X-Mashape-Key"] = api_key,
["Accept"] = "text/plain"
}
local respbody = {}
local body, code = https.request{
url = url,
method = "GET",
headers = headers,
sink = ltn12.sink.table(respbody),
protocol = "tlsv1"
}
if code ~= 200 then return code end
local body = table.concat(respbody)
return body
end
local function run(msg, matches)
return request(matches[1])
end
return {
description = "Listen to Yoda and learn from his words!",
usage = "!yoda You will learn how to speak like me someday.",
patterns = {
"^![y|Y]oda (.*)$"
},
run = run
}
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Ulycille.lua | 53 | 1947 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Ulycille
-- Type: Woodworking Adv. Synthesis Image Support
-- @pos -183.320 9.999 269.651 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/crafting");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local guildMember = isGuildMember(player,9);
local SkillLevel = player:getSkillLevel(SKILL_WOODWORKING);
local Cost = getAdvImageSupportCost(player,SKILL_WOODWORKING);
if (guildMember == 1) then
if (player:hasStatusEffect(EFFECT_WOODWORKING_IMAGERY) == false) then
player:startEvent(0x026F,Cost,SkillLevel,0,207,player:getGil(),0,4095,0);
else
player:startEvent(0x026F,Cost,SkillLevel,0,207,player:getGil(),28482,4095,0);
end
else
player:startEvent(0x026F); -- 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_WOODWORKING);
if (csid == 0x026F and option == 1) then
player:delGil(Cost);
player:messageSpecial(IMAGE_SUPPORT,0,1,0);
player:addStatusEffect(EFFECT_WOODWORKING_IMAGERY,3,0,480);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Cloister_of_Storms/bcnms/carbuncle_debacle.lua | 13 | 1478 | -----------------------------------
-- Area: Cloister of Storms
-- BCNM: Carbuncle Debacle
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/Cloister_of_Storms/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- 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)
-- print("leave code "..leavecode);
if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0,0);
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
player:setVar("CarbuncleDebacleProgress",4);
end;
end;
| gpl-3.0 |
waitwaitforget/torch7 | test/test_qr.lua | 46 | 9128 | -- This file contains tests for the QR decomposition functions in torch:
-- torch.qr(), torch.geqrf() and torch.orgqr().
local torch = require 'torch'
local tester = torch.Tester()
local tests = {}
-- torch.qr() with result tensors given.
local function qrInPlace(tensorFunc)
return function(x)
local q, r = tensorFunc(), tensorFunc()
torch.qr(q, r, x:clone())
return q, r
end
end
-- torch.qr() without result tensors given.
local function qrReturned(tensorFunc)
return function(x)
return torch.qr(x:clone())
end
end
-- torch.geqrf() with result tensors given.
local function geqrfInPlace(tensorFunc)
return function(x)
local result = tensorFunc()
local tau = tensorFunc()
local result_, tau_ = torch.geqrf(result, tau, x)
assert(torch.pointer(result) == torch.pointer(result_),
'expected result, result_ same tensor')
assert(torch.pointer(tau) == torch.pointer(tau_),
'expected tau, tau_ same tensor')
return result_, tau_
end
end
-- torch.orgqr() with result tensors given.
local function orgqrInPlace(tensorFunc)
return function(result, tau)
local q = tensorFunc()
local q_ = torch.orgqr(q, result, tau)
assert(torch.pointer(q) == torch.pointer(q_), 'expected q, q_ same tensor')
return q
end
end
-- Test a custom QR routine that calls the LAPACK functions manually.
local function qrManual(geqrfFunc, orgqrFunc)
return function(x)
local m = x:size(1)
local n = x:size(2)
local k = math.min(m, n)
local result, tau = geqrfFunc(x)
assert(result:size(1) == m)
assert(result:size(2) == n)
assert(tau:size(1) == k)
local r = torch.triu(result:narrow(1, 1, k))
local q = orgqrFunc(result, tau)
return q:narrow(2, 1, k), r
end
end
-- Check that the given `q`, `r` matrices are a valid QR decomposition of `a`.
local function checkQR(testOpts, a, q, r)
local qrFunc = testOpts.qr
if not q then
q, r = qrFunc(a)
end
local k = math.min(a:size(1), a:size(2))
tester:asserteq(q:size(1), a:size(1), "Bad size for q first dimension.")
tester:asserteq(q:size(2), k, "Bad size for q second dimension.")
tester:asserteq(r:size(1), k, "Bad size for r first dimension.")
tester:asserteq(r:size(2), a:size(2), "Bad size for r second dimension.")
tester:assertTensorEq(q:t() * q,
torch.eye(q:size(2)):typeAs(testOpts.tensorFunc()),
testOpts.precision,
"Q was not orthogonal")
tester:assertTensorEq(r, r:triu(), testOpts.precision,
"R was not upper triangular")
tester:assertTensorEq(q * r, a, testOpts.precision, "QR = A")
end
-- Do a QR decomposition of `a` and check that the result is valid and matches
-- the given expected `q` and `r`.
local function checkQRWithExpected(testOpts, a, expected_q, expected_r)
local qrFunc = testOpts.qr
-- Since the QR decomposition is unique only up to the signs of the rows of
-- R, we must ensure these are positive before doing the comparison.
local function canonicalize(q, r)
local d = r:diag():sign():diag()
return q * d, d * r
end
local q, r = qrFunc(a)
local q_canon, r_canon = canonicalize(q, r)
local expected_q_canon, expected_r_canon
= canonicalize(expected_q, expected_r)
tester:assertTensorEq(q_canon, expected_q_canon, testOpts.precision,
"Q did not match expected")
tester:assertTensorEq(r_canon, expected_r_canon, testOpts.precision,
"R did not match expected")
checkQR(testOpts, a, q, r)
end
-- Generate a separate test based on `func` for each of the possible
-- combinations of tensor type (double or float) and QR function (torch.qr
-- in-place, torch.qr, and manually calling the geqrf and orgqr from Lua
-- (both in-place and not).
--
-- The tests are added to the given `tests` table, with names generated by
-- appending a unique string for the specific combination to `name`.
--
-- If opts.doubleTensorOnly is true, then the FloatTensor versions of the test
-- will be skipped.
local function addTestVariations(tests, name, func, opts)
opts = opts or {}
local tensorTypes = {
[torch.DoubleTensor] = 1e-12,
[torch.FloatTensor] = 1e-5,
}
for tensorFunc, requiredPrecision in pairs(tensorTypes) do
local qrFuncs = {
['inPlace'] = qrInPlace(tensorFunc),
['returned'] = qrReturned(tensorFunc),
['manualInPlace'] = qrManual(geqrfInPlace(tensorFunc),
orgqrInPlace(tensorFunc)),
['manualReturned'] = qrManual(torch.geqrf, torch.orgqr)
}
for qrName, qrFunc in pairs(qrFuncs) do
local testOpts = {
tensorFunc=tensorFunc,
precision=requiredPrecision,
qr=qrFunc,
}
local tensorType = tensorFunc():type()
local fullName = name .. "_" .. qrName .. "_" .. tensorType
assert(not tests[fullName])
if tensorType == 'torch.DoubleTensor' or not opts.doubleTensorOnly then
tests[fullName] = function()
local state = torch.getRNGState()
torch.manualSeed(1)
func(testOpts)
torch.setRNGState(state)
end
end
end
end
end
-- Decomposing a specific square matrix.
addTestVariations(tests, 'qrSquare', function(testOpts)
return function(testOpts)
local tensorFunc = testOpts.tensorFunc
local a = tensorFunc{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
local expected_q = tensorFunc{
{-1.230914909793328e-01, 9.045340337332914e-01,
4.082482904638621e-01},
{-4.923659639173310e-01, 3.015113445777629e-01,
-8.164965809277264e-01},
{-8.616404368553292e-01, -3.015113445777631e-01,
4.082482904638634e-01},
}
local expected_r = tensorFunc{
{-8.124038404635959e+00, -9.601136296387955e+00,
-1.107823418813995e+01},
{ 0.000000000000000e+00, 9.045340337332926e-01,
1.809068067466585e+00},
{ 0.000000000000000e+00, 0.000000000000000e+00,
-8.881784197001252e-16},
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end
end, {doubleTensorOnly=true})
-- Decomposing a specific (wide) rectangular matrix.
addTestVariations(tests, 'qrRectFat', function(testOpts)
-- The matrix is chosen to be full-rank.
local a = testOpts.tensorFunc{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 13}
}
local expected_q = testOpts.tensorFunc{
{-0.0966736489045663, 0.907737593658436 , 0.4082482904638653},
{-0.4833682445228317, 0.3157348151855452, -0.8164965809277254},
{-0.870062840141097 , -0.2762679632873518, 0.4082482904638621}
}
local expected_r = testOpts.tensorFunc{
{ -1.0344080432788603e+01, -1.1794185166357092e+01,
-1.3244289899925587e+01, -1.5564457473635180e+01},
{ 0.0000000000000000e+00, 9.4720444555662542e-01,
1.8944088911132546e+00, 2.5653453733825331e+00},
{ 0.0000000000000000e+00, 0.0000000000000000e+00,
1.5543122344752192e-15, 4.0824829046386757e-01}
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end, {doubleTensorOnly=true})
-- Decomposing a specific (thin) rectangular matrix.
addTestVariations(tests, 'qrRectThin', function(testOpts)
-- The matrix is chosen to be full-rank.
local a = testOpts.tensorFunc{
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
{10, 11, 13},
}
local expected_q = testOpts.tensorFunc{
{-0.0776150525706334, -0.833052161400748 , 0.3651483716701106},
{-0.3104602102825332, -0.4512365874254053, -0.1825741858350556},
{-0.5433053679944331, -0.0694210134500621, -0.7302967433402217},
{-0.7761505257063329, 0.3123945605252804, 0.5477225575051663}
}
local expected_r = testOpts.tensorFunc{
{-12.8840987267251261, -14.5916298832790581, -17.0753115655393231},
{ 0, -1.0413152017509357, -1.770235842976589 },
{ 0, 0, 0.5477225575051664}
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end, {doubleTensorOnly=true})
-- Decomposing a sequence of medium-sized random matrices.
addTestVariations(tests, 'randomMediumQR', function(testOpts)
for x = 0, 10 do
for y = 0, 10 do
local m = math.pow(2, x)
local n = math.pow(2, y)
local x = torch.rand(m, n)
checkQR(testOpts, x:typeAs(testOpts.tensorFunc()))
end
end
end)
-- Decomposing a sequence of small random matrices.
addTestVariations(tests, 'randomSmallQR', function(testOpts)
for m = 1, 40 do
for n = 1, 40 do
checkQR(testOpts, torch.rand(m, n):typeAs(testOpts.tensorFunc()))
end
end
end)
-- Decomposing a sequence of small matrices that are not contiguous in memory.
addTestVariations(tests, 'randomNonContiguous', function(testOpts)
for m = 2, 40 do
for n = 2, 40 do
local x = torch.rand(m, n):t()
tester:assert(not x:isContiguous(), "x should not be contiguous")
checkQR(testOpts, x:typeAs(testOpts.tensorFunc()))
end
end
end)
tester:add(tests)
tester:run()
| bsd-3-clause |
kirangonella/torch7 | test/test_qr.lua | 46 | 9128 | -- This file contains tests for the QR decomposition functions in torch:
-- torch.qr(), torch.geqrf() and torch.orgqr().
local torch = require 'torch'
local tester = torch.Tester()
local tests = {}
-- torch.qr() with result tensors given.
local function qrInPlace(tensorFunc)
return function(x)
local q, r = tensorFunc(), tensorFunc()
torch.qr(q, r, x:clone())
return q, r
end
end
-- torch.qr() without result tensors given.
local function qrReturned(tensorFunc)
return function(x)
return torch.qr(x:clone())
end
end
-- torch.geqrf() with result tensors given.
local function geqrfInPlace(tensorFunc)
return function(x)
local result = tensorFunc()
local tau = tensorFunc()
local result_, tau_ = torch.geqrf(result, tau, x)
assert(torch.pointer(result) == torch.pointer(result_),
'expected result, result_ same tensor')
assert(torch.pointer(tau) == torch.pointer(tau_),
'expected tau, tau_ same tensor')
return result_, tau_
end
end
-- torch.orgqr() with result tensors given.
local function orgqrInPlace(tensorFunc)
return function(result, tau)
local q = tensorFunc()
local q_ = torch.orgqr(q, result, tau)
assert(torch.pointer(q) == torch.pointer(q_), 'expected q, q_ same tensor')
return q
end
end
-- Test a custom QR routine that calls the LAPACK functions manually.
local function qrManual(geqrfFunc, orgqrFunc)
return function(x)
local m = x:size(1)
local n = x:size(2)
local k = math.min(m, n)
local result, tau = geqrfFunc(x)
assert(result:size(1) == m)
assert(result:size(2) == n)
assert(tau:size(1) == k)
local r = torch.triu(result:narrow(1, 1, k))
local q = orgqrFunc(result, tau)
return q:narrow(2, 1, k), r
end
end
-- Check that the given `q`, `r` matrices are a valid QR decomposition of `a`.
local function checkQR(testOpts, a, q, r)
local qrFunc = testOpts.qr
if not q then
q, r = qrFunc(a)
end
local k = math.min(a:size(1), a:size(2))
tester:asserteq(q:size(1), a:size(1), "Bad size for q first dimension.")
tester:asserteq(q:size(2), k, "Bad size for q second dimension.")
tester:asserteq(r:size(1), k, "Bad size for r first dimension.")
tester:asserteq(r:size(2), a:size(2), "Bad size for r second dimension.")
tester:assertTensorEq(q:t() * q,
torch.eye(q:size(2)):typeAs(testOpts.tensorFunc()),
testOpts.precision,
"Q was not orthogonal")
tester:assertTensorEq(r, r:triu(), testOpts.precision,
"R was not upper triangular")
tester:assertTensorEq(q * r, a, testOpts.precision, "QR = A")
end
-- Do a QR decomposition of `a` and check that the result is valid and matches
-- the given expected `q` and `r`.
local function checkQRWithExpected(testOpts, a, expected_q, expected_r)
local qrFunc = testOpts.qr
-- Since the QR decomposition is unique only up to the signs of the rows of
-- R, we must ensure these are positive before doing the comparison.
local function canonicalize(q, r)
local d = r:diag():sign():diag()
return q * d, d * r
end
local q, r = qrFunc(a)
local q_canon, r_canon = canonicalize(q, r)
local expected_q_canon, expected_r_canon
= canonicalize(expected_q, expected_r)
tester:assertTensorEq(q_canon, expected_q_canon, testOpts.precision,
"Q did not match expected")
tester:assertTensorEq(r_canon, expected_r_canon, testOpts.precision,
"R did not match expected")
checkQR(testOpts, a, q, r)
end
-- Generate a separate test based on `func` for each of the possible
-- combinations of tensor type (double or float) and QR function (torch.qr
-- in-place, torch.qr, and manually calling the geqrf and orgqr from Lua
-- (both in-place and not).
--
-- The tests are added to the given `tests` table, with names generated by
-- appending a unique string for the specific combination to `name`.
--
-- If opts.doubleTensorOnly is true, then the FloatTensor versions of the test
-- will be skipped.
local function addTestVariations(tests, name, func, opts)
opts = opts or {}
local tensorTypes = {
[torch.DoubleTensor] = 1e-12,
[torch.FloatTensor] = 1e-5,
}
for tensorFunc, requiredPrecision in pairs(tensorTypes) do
local qrFuncs = {
['inPlace'] = qrInPlace(tensorFunc),
['returned'] = qrReturned(tensorFunc),
['manualInPlace'] = qrManual(geqrfInPlace(tensorFunc),
orgqrInPlace(tensorFunc)),
['manualReturned'] = qrManual(torch.geqrf, torch.orgqr)
}
for qrName, qrFunc in pairs(qrFuncs) do
local testOpts = {
tensorFunc=tensorFunc,
precision=requiredPrecision,
qr=qrFunc,
}
local tensorType = tensorFunc():type()
local fullName = name .. "_" .. qrName .. "_" .. tensorType
assert(not tests[fullName])
if tensorType == 'torch.DoubleTensor' or not opts.doubleTensorOnly then
tests[fullName] = function()
local state = torch.getRNGState()
torch.manualSeed(1)
func(testOpts)
torch.setRNGState(state)
end
end
end
end
end
-- Decomposing a specific square matrix.
addTestVariations(tests, 'qrSquare', function(testOpts)
return function(testOpts)
local tensorFunc = testOpts.tensorFunc
local a = tensorFunc{{1, 2, 3}, {4, 5, 6}, {7, 8, 9}}
local expected_q = tensorFunc{
{-1.230914909793328e-01, 9.045340337332914e-01,
4.082482904638621e-01},
{-4.923659639173310e-01, 3.015113445777629e-01,
-8.164965809277264e-01},
{-8.616404368553292e-01, -3.015113445777631e-01,
4.082482904638634e-01},
}
local expected_r = tensorFunc{
{-8.124038404635959e+00, -9.601136296387955e+00,
-1.107823418813995e+01},
{ 0.000000000000000e+00, 9.045340337332926e-01,
1.809068067466585e+00},
{ 0.000000000000000e+00, 0.000000000000000e+00,
-8.881784197001252e-16},
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end
end, {doubleTensorOnly=true})
-- Decomposing a specific (wide) rectangular matrix.
addTestVariations(tests, 'qrRectFat', function(testOpts)
-- The matrix is chosen to be full-rank.
local a = testOpts.tensorFunc{
{1, 2, 3, 4},
{5, 6, 7, 8},
{9, 10, 11, 13}
}
local expected_q = testOpts.tensorFunc{
{-0.0966736489045663, 0.907737593658436 , 0.4082482904638653},
{-0.4833682445228317, 0.3157348151855452, -0.8164965809277254},
{-0.870062840141097 , -0.2762679632873518, 0.4082482904638621}
}
local expected_r = testOpts.tensorFunc{
{ -1.0344080432788603e+01, -1.1794185166357092e+01,
-1.3244289899925587e+01, -1.5564457473635180e+01},
{ 0.0000000000000000e+00, 9.4720444555662542e-01,
1.8944088911132546e+00, 2.5653453733825331e+00},
{ 0.0000000000000000e+00, 0.0000000000000000e+00,
1.5543122344752192e-15, 4.0824829046386757e-01}
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end, {doubleTensorOnly=true})
-- Decomposing a specific (thin) rectangular matrix.
addTestVariations(tests, 'qrRectThin', function(testOpts)
-- The matrix is chosen to be full-rank.
local a = testOpts.tensorFunc{
{ 1, 2, 3},
{ 4, 5, 6},
{ 7, 8, 9},
{10, 11, 13},
}
local expected_q = testOpts.tensorFunc{
{-0.0776150525706334, -0.833052161400748 , 0.3651483716701106},
{-0.3104602102825332, -0.4512365874254053, -0.1825741858350556},
{-0.5433053679944331, -0.0694210134500621, -0.7302967433402217},
{-0.7761505257063329, 0.3123945605252804, 0.5477225575051663}
}
local expected_r = testOpts.tensorFunc{
{-12.8840987267251261, -14.5916298832790581, -17.0753115655393231},
{ 0, -1.0413152017509357, -1.770235842976589 },
{ 0, 0, 0.5477225575051664}
}
checkQRWithExpected(testOpts, a, expected_q, expected_r)
end, {doubleTensorOnly=true})
-- Decomposing a sequence of medium-sized random matrices.
addTestVariations(tests, 'randomMediumQR', function(testOpts)
for x = 0, 10 do
for y = 0, 10 do
local m = math.pow(2, x)
local n = math.pow(2, y)
local x = torch.rand(m, n)
checkQR(testOpts, x:typeAs(testOpts.tensorFunc()))
end
end
end)
-- Decomposing a sequence of small random matrices.
addTestVariations(tests, 'randomSmallQR', function(testOpts)
for m = 1, 40 do
for n = 1, 40 do
checkQR(testOpts, torch.rand(m, n):typeAs(testOpts.tensorFunc()))
end
end
end)
-- Decomposing a sequence of small matrices that are not contiguous in memory.
addTestVariations(tests, 'randomNonContiguous', function(testOpts)
for m = 2, 40 do
for n = 2, 40 do
local x = torch.rand(m, n):t()
tester:assert(not x:isContiguous(), "x should not be contiguous")
checkQR(testOpts, x:typeAs(testOpts.tensorFunc()))
end
end
end)
tester:add(tests)
tester:run()
| bsd-3-clause |
UnfortunateFruit/darkstar | scripts/zones/Eastern_Altepa_Desert/Zone.lua | 27 | 4256 | -----------------------------------
--
-- Zone: Eastern_Altepa_Desert (114)
--
-----------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
package.loaded["scripts/globals/chocobo_digging"] = nil;
-----------------------------------
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
require( "scripts/globals/icanheararainbow");
require("scripts/globals/zone");
require("scripts/globals/conquest");
require("scripts/globals/chocobo_digging");
-----------------------------------
-- Chocobo Digging vars
-----------------------------------
local itemMap = {
-- itemid, abundance, requirement
{ 880, 167, DIGREQ_NONE },
{ 893, 88, DIGREQ_NONE },
{ 17296, 135, DIGREQ_NONE },
{ 736, 52, DIGREQ_NONE },
{ 644, 22, DIGREQ_NONE },
{ 942, 4, DIGREQ_NONE },
{ 738, 12, DIGREQ_NONE },
{ 866, 36, DIGREQ_NONE },
{ 642, 58, DIGREQ_NONE },
{ 4096, 100, DIGREQ_NONE }, -- all crystals
{ 574, 33, DIGREQ_BURROW },
{ 575, 74, DIGREQ_BURROW },
{ 572, 59, DIGREQ_BURROW },
{ 1237, 19, DIGREQ_BURROW },
{ 573, 44, DIGREQ_BURROW },
{ 2235, 41, DIGREQ_BURROW },
{ 646, 3, DIGREQ_BORE },
{ 678, 18, DIGREQ_BORE },
{ 645, 9, DIGREQ_BORE },
{ 768, 129, DIGREQ_BORE },
{ 737, 3, DIGREQ_BORE },
{ 739, 3, DIGREQ_BORE },
{ 4570, 10, DIGREQ_MODIFIER },
{ 4487, 11, DIGREQ_MODIFIER },
{ 4409, 12, DIGREQ_MODIFIER },
{ 1188, 10, DIGREQ_MODIFIER },
{ 4532, 12, DIGREQ_MODIFIER },
};
local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED };
-----------------------------------
-- onChocoboDig
-----------------------------------
function onChocoboDig(player, precheck)
return chocoboDig(player, itemMap, precheck, messageArray);
end;
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17244653,17244654,17244655};
SetFieldManual(manuals);
-- Cactrot Rapido
SetRespawnTime(17244539, 900, 10800);
-- Centurio XII-I
SetRespawnTime(17244372, 900, 10800);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( 260.09, 6.013, 320.454, 76);
end
if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0002;
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter( player, region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0002) then
lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/bluemagic/temporal_shift.lua | 4 | 1468 | -----------------------------------------
-- Spell: Temporal Shift
-- Enemies within range are temporarily prevented from acting
-- Spell cost: 48 MP
-- Monster Type: Luminians
-- Spell Type: Magical (Lightning)
-- Blue Magic Points: 5
-- Stat Bonus: HP+10, MP+15
-- Level: 73
-- Casting Time: 0.5 seconds
-- Recast Time: 120 seconds
-- Magic Bursts on: Impaction, Fragmentation, and Light
-- Combos: Attack Bonus
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local duration = 5;
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local resist = applyResistanceEffect(caster,spell,target,dINT,BLUE_SKILL,0,EFFECT_STUN);
if(resist <= (1/16)) then
-- resisted!
spell:setMsg(85);
return 0;
end
if(target:hasStatusEffect(EFFECT_STUN)) then
-- no effect
spell:setMsg(75);
else
target:addStatusEffect(EFFECT_STUN,2,0,duration*resist);
spell:setMsg(236);
end
return EFFECT_STUN;
end;
| gpl-3.0 |
abasshacker/extreme | plugins/info.lua | 10 | 8374 | --[[
#
# Show users information in groups
#
# author: Arian < @Dragon_Born >
# our channel: @GPMod
# Version: 2016-04-02
#
# Features added:
# -- setrank on reply
# -- get users info with their IDs and @username
#
]]
do
local Arian = 99530862 --put your id here(BOT OWNER ID)
local function setrank(msg, name, value) -- setrank function
local hash = nil
if msg.to.type == 'chat' then
hash = 'rank:'..msg.to.id..':variables'
end
if hash then
redis:hset(hash, name, value)
return send_msg('chat#id'..msg.to.id, 'set Rank for ('..name..') To : '..value, ok_cb, true)
end
end
local function res_user_callback(extra, success, result) -- /info <username> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'User name: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == 179983320 then
text = text..'Rank : sudo🌟🌟🌟🌟🌟 \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin⭐️⭐️⭐️⭐️ \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner⭐️⭐️⭐ \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator⭐️⭐️ \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@extreme Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, ' Username not found.', ok_cb, false)
end
end
local function action_by_id(extra, success, result) -- /info <ID> function
if success == 1 then
if result.username then
Username = '@'..result.username
else
Username = '----'
end
local text = 'Full name : '..(result.first_name or '')..' '..(result.last_name or '')..'\n'
..'Username: '..Username..'\n'
..'ID : '..result.id..'\n\n'
local hash = 'rank:'..extra.chat2..':variables'
local value = redis:hget(hash, result.id)
if not value then
if result.id == 179983320 then
text = text..'Rank : sudo🌟🌟🌟🌟🌟 \n\n'
elseif is_admin2(result.id) then
text = text..'Rank : Admin⭐️⭐️⭐️⭐ \n\n'
elseif is_owner2(result.id, extra.chat2) then
text = text..'Rank : Owner⭐️⭐️ \n\n'
elseif is_momod2(result.id, extra.chat2) then
text = text..'Rank : Moderator⭐️ \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local uhash = 'user:'..result.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.id..':'..extra.chat2
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@extreme Team'
send_msg(extra.receiver, text, ok_cb, true)
else
send_msg(extra.receiver, 'id not found.\nuse : /info @username', ok_cb, false)
end
end
local function action_by_reply(extra, success, result)-- (reply) /info function
if result.from.username then
Username = '@'..result.from.username
else
Username = '----'
end
local text = 'Full name : '..(result.from.first_name or '')..' '..(result.from.last_name or '')..'\n'
..'Username : '..Username..'\n'
..'ID : '..result.from.id..'\n\n'
local hash = 'rank:'..result.to.id..':variables'
local value = redis:hget(hash, result.from.id)
if not value then
if result.from.id == 179983320 then
text = text..'Rank : sudo🌟🌟🌟🌟🌟 \n\n'
elseif is_admin2(result.from.id) then
text = text..'Rank : Admin⭐️⭐️⭐️⭐ \n\n'
elseif is_owner2(result.from.id, result.to.id) then
text = text..'Rank : Owner⭐️⭐ \n\n'
elseif is_momod2(result.from.id, result.to.id) then
text = text..'Rank : Moderator⭐️ \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n\n'
end
local user_info = {}
local uhash = 'user:'..result.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..result.from.id..':'..result.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
text = text..'@extreme Team'
send_msg(extra.receiver, text, ok_cb, true)
end
local function action_by_reply2(extra, success, result)
local value = extra.value
setrank(result, result.from.id, value)
end
local function run(msg, matches)
if matches[1]:lower() == 'setrank' then
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if not is_sudo(msg) then
return "Only for Sudo"
end
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
local value = string.sub(matches[2], 1, 1000)
msgr = get_message(msg.reply_id, action_by_reply2, {receiver=receiver, Reply=Reply, value=value})
else
local name = string.sub(matches[2], 1, 50)
local value = string.sub(matches[3], 1, 1000)
local text = setrank(msg, name, value)
return text
end
end
if matches[1]:lower() == 'info' and not matches[2] then
local receiver = get_receiver(msg)
local Reply = msg.reply_id
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {receiver=receiver, Reply=Reply})
else
if msg.from.username then
Username = '@'..msg.from.username
else
Username = '----'
end
local text = 'First name : '..(msg.from.first_name or '----')..'\n'
local text = text..'Last name : '..(msg.from.last_name or '----')..'\n'
local text = text..'Username : '..Username..'\n'
local text = text..'ID : '..msg.from.id..'\n\n'
local hash = 'rank:'..msg.to.id..':variables'
if hash then
local value = redis:hget(hash, msg.from.id)
if not value then
if msg.from.id == 179983320 then
text = text..'Rank : sudo🌟🌟🌟🌟🌟 \n\n'
elseif is_sudo(msg) then
text = text..'Rank : Admin⭐️⭐️⭐️⭐ \n\n'
elseif is_owner(msg) then
text = text..'Rank : Owner⭐️⭐️ \n\n'
elseif is_momod(msg) then
text = text..'Rank : Moderator⭐️ \n\n'
else
text = text..'Rank : Member \n\n'
end
else
text = text..'Rank : '..value..'\n'
end
end
local uhash = 'user:'..msg.from.id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..msg.from.id..':'..msg.to.id
user_info_msgs = tonumber(redis:get(um_hash) or 0)
text = text..'Total messages : '..user_info_msgs..'\n\n'
if msg.to.type == 'chat' then
text = text..'Group name : '..msg.to.title..'\n'
text = text..'Group ID : '..msg.to.id
end
text = text..'\n\n@GPMod Team'
return send_msg(receiver, text, ok_cb, true)
end
end
if matches[1]:lower() == 'info' and matches[2] then
local user = matches[2]
local chat2 = msg.to.id
local receiver = get_receiver(msg)
if string.match(user, '^%d+$') then
user_info('user#id'..user, action_by_id, {receiver=receiver, user=user, text=text, chat2=chat2})
elseif string.match(user, '^@.+$') then
username = string.gsub(user, '@', '')
msgr = res_user(username, res_user_callback, {receiver=receiver, user=user, text=text, chat2=chat2})
end
end
end
return {
description = 'Know your information or the info of a chat members.',
usage = {
'!info: Return your info and the chat info if you are in one.',
'(Reply)!info: Return info of replied user if used by reply.',
'!info <id>: Return the info\'s of the <id>.',
'!info @<user_name>: Return the member @<user_name> information from the current chat.',
'!setrank <userid> <rank>: change members rank.',
'(Reply)!setrank <rank>: change members rank.',
},
patterns = {
"^[/!]([Ii][Nn][Ff][Oo])$",
"^[/!]([Ii][Nn][Ff][Oo]) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (%d+) (.*)$",
"^[/!]([Ss][Ee][Tt][Rr][Aa][Nn][Kk]) (.*)$",
},
run = run
}
end
-- By Arian
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Abyssea-Vunkerl/npcs/qm19.lua | 17 | 1524 | -----------------------------------
-- Zone: Abyssea-Vunkeral
-- NPC: ???
-- Spawns: Karkadann
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(17666502) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(MALODOROUS_MARID_FUR) and player:hasKeyItem(WARPED_SMILODON_CHOKER)) then
player:startEvent(1015, MALODOROUS_MARID_FUR, WARPED_SMILODON_CHOKER); -- Ask if player wants to use KIs
else
player:startEvent(1120, MALODOROUS_MARID_FUR, WARPED_SMILODON_CHOKER); -- 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 == 1015 and option == 1) then
SpawnMob(17666502):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(MALODOROUS_MARID_FUR);
player:delKeyItem(WARPED_SMILODON_CHOKER);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fn.lua | 34 | 2569 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: North Plate
-- @pos 180 -34 71 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 22; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
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 |
UnfortunateFruit/darkstar | scripts/globals/weaponskills/shining_blade.lua | 30 | 1336 | -----------------------------------
-- Shining Blade
-- Sword weapon skill
-- Skill Level: 100
-- Deals light elemental damage to enemy. Damage varies with TP.
-- Aligned with the Soil Gorget.
-- Aligned with the Soil Belt.
-- Element: Light
-- Modifiers: STR:40% ; MND:40%
-- 100%TP 200%TP 300%TP
-- 1.125 2.222 3.523
-----------------------------------
require("scripts/globals/magic");
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 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.2; params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_SWD;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 1.125; params.ftp200 = 2.222; params.ftp300 = 3.523;
params.str_wsc = 0.4; params.mnd_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
longhf/torch7 | File.lua | 3 | 11933 | local File = torch.getmetatable('torch.File')
function File:writeBool(value)
if value then
self:writeInt(1)
else
self:writeInt(0)
end
end
function File:readBool()
return (self:readInt() == 1)
end
local TYPE_NIL = 0
local TYPE_NUMBER = 1
local TYPE_STRING = 2
local TYPE_TABLE = 3
local TYPE_TORCH = 4
local TYPE_BOOLEAN = 5
local TYPE_FUNCTION = 6
local TYPE_RECUR_FUNCTION = 8
local LEGACY_TYPE_RECUR_FUNCTION = 7
-- Lua 5.2 compatibility
local loadstring = loadstring or load
function File:isWritableObject(object)
local typename = type(object)
local typeidx
if type(object) ~= 'boolean' and not object then
typeidx = TYPE_NIL
elseif torch.typename(object) and torch.factory(torch.typename(object)) then
typeidx = TYPE_TORCH
elseif typename == 'table' then
typeidx = TYPE_TABLE
elseif typename == 'number' then
typeidx = TYPE_NUMBER
elseif typename == 'string' then
typeidx = TYPE_STRING
elseif typename == 'boolean' then
typeidx = TYPE_BOOLEAN
elseif typename == 'function' and pcall(string.dump, object) then
typeidx = TYPE_RECUR_FUNCTION
end
return typeidx
end
function File:referenced(ref)
-- we use an environment to keep a record of written objects
if not torch.getenv(self).writeObjects then
torch.setenv(self, {writeObjects={}, writeObjectsRef={}, readObjects={}})
end
local env = torch.getenv(self)
env.force = not ref
torch.setenv(self,env)
return self
end
function File:isReferenced()
-- if no environment, then no forcing setup yet
if not torch.getenv(self).writeObjects then
return true
end
local env = torch.getenv(self)
return not env.force
end
local function getmetamethod(obj, name)
local func
local status
-- check getmetatable(obj).__name or
-- check getmetatable(obj).name
status, func = pcall(
function()
-- note that sometimes the metatable is hidden
-- we get it for sure through the torch type system
local mt = torch.getmetatable(torch.typename(obj))
if mt then
return mt['__' .. name] or mt[name]
end
end
)
if status and type(func) == 'function' then
return func
end
end
function File:writeObject(object)
-- we use an environment to keep a record of written objects
if not torch.getenv(self).writeObjects then
torch.setenv(self, {writeObjects={}, writeObjectsRef={}, readObjects={}})
end
local force = torch.getenv(self).force
-- if nil object, only write the type and return
if type(object) ~= 'boolean' and not object then
self:writeInt(TYPE_NIL)
return
end
-- check the type we are dealing with
local typeidx = self:isWritableObject(object)
if not typeidx then
error(string.format('Unwritable object <%s>', type(object)))
end
self:writeInt(typeidx)
if typeidx == TYPE_NUMBER then
self:writeDouble(object)
elseif typeidx == TYPE_BOOLEAN then
self:writeBool(object)
elseif typeidx == TYPE_STRING then
local stringStorage = torch.CharStorage():string(object)
self:writeInt(#stringStorage)
self:writeChar(stringStorage)
elseif typeidx == TYPE_TORCH or typeidx == TYPE_TABLE or typeidx == TYPE_RECUR_FUNCTION then
-- check it exists already (we look at the pointer!)
local objects = torch.getenv(self).writeObjects
local objectsRef = torch.getenv(self).writeObjectsRef
local index = objects[torch.pointer(object)]
if index and (not force) then
-- if already exists, write only its index
self:writeInt(index)
else
-- else write the object itself
index = objects.nWriteObject or 0
index = index + 1
if not force then
objects[torch.pointer(object)] = index
objectsRef[object] = index -- we make sure the object is not going to disappear
end
self:writeInt(index)
objects.nWriteObject = index
if typeidx == TYPE_RECUR_FUNCTION then
local upvalues = {}
local counter = 0
while true do
counter = counter + 1
local name,value = debug.getupvalue(object, counter)
if not name then break end
if name == '_ENV' then value = nil end
table.insert(upvalues, {name=name, value=value})
end
local dumped = string.dump(object)
local stringStorage = torch.CharStorage():string(dumped)
self:writeInt(#stringStorage)
self:writeChar(stringStorage)
self:writeObject(upvalues)
elseif typeidx == TYPE_TORCH then
local version = torch.CharStorage():string('V ' .. torch.version(object))
local className = torch.CharStorage():string(torch.typename(object))
self:writeInt(#version)
self:writeChar(version)
self:writeInt(#className)
self:writeChar(className)
local write = getmetamethod(object, 'write')
if write then
write(object, self)
elseif type(object) == 'table' then
local var = {}
for k,v in pairs(object) do
if self:isWritableObject(v) then
var[k] = v
else
print(string.format('$ Warning: cannot write object field <%s>', k))
end
end
self:writeObject(var)
else
error(string.format('<%s> is a non-serializable Torch object', torch.typename(object)))
end
else -- it is a table
local size = 0; for k,v in pairs(object) do size = size + 1 end
self:writeInt(size)
for k,v in pairs(object) do
self:writeObject(k)
self:writeObject(v)
end
end
end
else
error('Unwritable object')
end
end
function File:readObject()
-- we use an environment to keep a record of read objects
if not torch.getenv(self).writeObjects then
torch.setenv(self, {writeObjects={}, writeObjectsRef={}, readObjects={}})
end
local force = torch.getenv(self).force
-- read the typeidx
local typeidx = self:readInt()
-- is it nil?
if typeidx == TYPE_NIL then
return nil
end
if typeidx == TYPE_NUMBER then
return self:readDouble()
elseif typeidx == TYPE_BOOLEAN then
return self:readBool()
elseif typeidx == TYPE_STRING then
local size = self:readInt()
return self:readChar(size):string()
elseif typeidx == TYPE_FUNCTION then
local size = self:readInt()
local dumped = self:readChar(size):string()
local func = loadstring(dumped)
local upvalues = self:readObject()
for index,upvalue in ipairs(upvalues) do
debug.setupvalue(func, index, upvalue)
end
return func
elseif typeidx == TYPE_TABLE or typeidx == TYPE_TORCH or typeidx == TYPE_RECUR_FUNCTION or typeidx == LEGACY_TYPE_RECUR_FUNCTION then
-- read the index
local index = self:readInt()
-- check it is loaded already
local objects = torch.getenv(self).readObjects
if objects[index] and not force then
return objects[index]
end
-- otherwise read it
if typeidx == TYPE_RECUR_FUNCTION or typeidx == LEGACY_TYPE_RECUR_FUNCTION then
local size = self:readInt()
local dumped = self:readChar(size):string()
local func = loadstring(dumped)
if not force then
objects[index] = func
end
local upvalues = self:readObject()
for index,upvalue in ipairs(upvalues) do
if typeidx == LEGACY_TYPE_RECUR_FUNCTION then
debug.setupvalue(func, index, upvalue)
elseif upvalue.name == '_ENV' then
debug.setupvalue(func, index, _ENV)
else
debug.setupvalue(func, index, upvalue.value)
end
end
return func
elseif typeidx == TYPE_TORCH then
local version, className, versionNumber
version = self:readChar(self:readInt()):string()
versionNumber = tonumber(string.match(version, '^V (.*)$'))
if not versionNumber then
className = version
versionNumber = 0 -- file created before existence of versioning system
else
className = self:readChar(self:readInt()):string()
end
if not torch.factory(className) then
error(string.format('unknown Torch class <%s>', tostring(className)))
end
local object = torch.factory(className)(self)
if not force then
objects[index] = object
end
local read = getmetamethod(object, 'read')
if read then
read(object, self, versionNumber)
elseif type(object) == 'table' then
local var = self:readObject()
for k,v in pairs(var) do
object[k] = v
end
else
error(string.format('Cannot load object class <%s>', tostring(className)))
end
return object
else -- it is a table
local size = self:readInt()
local object = {}
if not force then
objects[index] = object
end
for i = 1,size do
local k = self:readObject()
local v = self:readObject()
object[k] = v
end
return object
end
else
error('unknown object')
end
end
-- simple helpers to save/load arbitrary objects/tables
function torch.save(filename, object, mode, referenced)
assert(mode == nil or mode == 'binary' or mode == 'ascii', '"binary" or "ascii" (or nil) expected for mode')
assert(referenced == nil or referenced == true or referenced == false, 'true or false (or nil) expected for referenced')
mode = mode or 'binary'
referenced = referenced == nil and true or referenced
local file = torch.DiskFile(filename, 'w')
file[mode](file)
file:referenced(referenced)
file:writeObject(object)
file:close()
end
function torch.load(filename, mode, referenced)
assert(mode == nil or mode == 'binary' or mode == 'ascii', '"binary" or "ascii" (or nil) expected for mode')
assert(referenced == nil or referenced == true or referenced == false, 'true or false (or nil) expected for referenced')
mode = mode or 'binary'
referenced = referenced == nil and true or referenced
local file = torch.DiskFile(filename, 'r')
file[mode](file)
file:referenced(referenced)
local object = file:readObject()
file:close()
return object
end
-- simple helpers to serialize/deserialize arbitrary objects/tables
function torch.serialize(object, mode)
local storage = torch.serializeToStorage(object, mode)
return storage:string()
end
-- Serialize to a CharStorage, not a lua string. This avoids
function torch.serializeToStorage(object, mode)
mode = mode or 'binary'
local f = torch.MemoryFile()
f = f[mode](f)
f:writeObject(object)
local storage = f:storage()
f:close()
return storage
end
function torch.deserializeFromStorage(storage, mode)
mode = mode or 'binary'
local tx = torch.CharTensor(storage)
local xp = torch.CharStorage(tx:size(1)+1)
local txp = torch.CharTensor(xp)
txp:narrow(1,1,tx:size(1)):copy(tx)
txp[tx:size(1)+1] = 0
local f = torch.MemoryFile(xp)
f = f[mode](f)
local object = f:readObject()
f:close()
return object
end
function torch.deserialize(str, mode)
local storage = torch.CharStorage():string(str)
return torch.deserializeFromStorage(storage, mode)
end
-- public API (saveobj/loadobj are safe for global import)
torch.saveobj = torch.save
torch.loadobj = torch.load
| bsd-3-clause |
nesstea/darkstar | scripts/zones/Sauromugue_Champaign_[S]/npcs/Indescript_Markings.lua | 26 | 1405 | -----------------------------------
-- Area: Sauromugue Champaign [S]
-- NPC: Indescript Markings
-- @pos 322 24 113
-- Quest NPC
-----------------------------------
package.loaded["scripts/zones/Sauromugue_Champaign_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sauromugue_Champaign_[S]/TextIDs");
require("scripts/globals/campaign");
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR, DOWNWARD_HELIX) == QUEST_ACCEPTED and player:getVar("DownwardHelix") == 3) then
player:startEvent(0x0004);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID:",csid);
-- printf("RESULT:",option);
if (csid == 0x0004) then
player:setVar("DownwardHelix",4);
end
end; | gpl-3.0 |
vonflynee/opencomputersserver | world/opencomputers/7c9ad1a8-61e1-4046-a969-190bd5607730/boot/02_os.lua | 15 | 2296 | local computer = require("computer")
local event = require("event")
local fs = require("filesystem")
local shell = require("shell")
local unicode = require("unicode")
local function env()
-- copy parent env when first requested; easiest way to keep things
-- like number of env vars trivial (#vars).
local data = require("process").info().data
if not rawget(data, "vars") then
local vars = {}
for k, v in pairs(data.vars or {}) do
vars[k] = v
end
data.vars = vars
end
data.vars = data.vars or {}
return data.vars
end
os.execute = function(command)
if not command then
return type(shell) == "table"
end
return shell.execute(command)
end
function os.exit(code)
error({reason="terminated", code=code~=false}, 0)
end
function os.getenv(varname)
if varname == '#' then
return #env()
elseif varname ~= nil then
return env()[varname]
else
return env()
end
end
function os.setenv(varname, value)
checkArg(1, varname, "string", "number")
if value == nil then
env()[varname] = nil
else
local success, val = pcall(tostring, value)
if success then
env()[varname] = val
return env()[varname]
else
return nil, val
end
end
end
function os.remove(...)
return fs.remove(...)
end
function os.rename(...)
return fs.rename(...)
end
function os.sleep(timeout)
checkArg(1, timeout, "number", "nil")
local deadline = computer.uptime() + (timeout or 0)
repeat
event.pull(deadline - computer.uptime())
until computer.uptime() >= deadline
end
function os.tmpname()
local path = os.getenv("TMPDIR") or "/tmp"
if fs.exists(path) then
for i = 1, 10 do
local name = fs.concat(path, tostring(math.random(1, 0x7FFFFFFF)))
if not fs.exists(name) then
return name
end
end
end
end
os.setenv("EDITOR", "/bin/edit")
os.setenv("HISTSIZE", "10")
os.setenv("HOME", "/home")
os.setenv("IFS", " ")
os.setenv("MANPATH", "/usr/man:.")
os.setenv("PAGER", "/bin/more")
os.setenv("PATH", "/bin:/usr/bin:/home/bin:.")
os.setenv("PS1", "$PWD# ")
os.setenv("PWD", "/")
os.setenv("SHELL", "/bin/sh")
os.setenv("TMP", "/tmp") -- Deprecated
os.setenv("TMPDIR", "/tmp")
if computer.tmpAddress() then
fs.mount(computer.tmpAddress(), os.getenv("TMPDIR") or "/tmp")
end
| mit |
nesstea/darkstar | scripts/zones/Southern_San_dOria/npcs/Machielle.lua | 12 | 1979 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Machielle
-- Only sells when Bastok controls Norvallen Region
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/events/harvest_festivals");
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/globals/conquest");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == 1) then
if (trade:hasItemQty(532,1) == true and trade:getItemCount() == 1) then
player:messageSpecial(FLYER_REFUSED);
end
else
onHalloweenTrade(player,trade,npc);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(NORVALLEN);
if (RegionOwner ~= SANDORIA) then
player:showText(npc,MACHIELLE_CLOSED_DIALOG);
else
player:showText(npc,MACHIELLE_OPEN_DIALOG);
stock = {0x02b0,18, --Arrowwood Log
0x026d,25, --Crying Mustard
0x026a,25, --Blue Peas
0x02ba,88} --Ash Log
showShop(player,SANDORIA,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/abilities/pets/attachments/tension_spring_ii.lua | 27 | 1092 | -----------------------------------
-- Attachment: Tension Spring II
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onUseAbility
-----------------------------------
function onEquip(pet)
pet:addMod(MOD_ATTP, 6)
pet:addMod(MOD_RATTP, 6)
end
function onUnequip(pet)
pet:delMod(MOD_ATTP, 6)
pet:addMod(MOD_RATTP, 6)
end
function onManeuverGain(pet,maneuvers)
if (maneuvers == 1) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 2) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 3) then
pet:addMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
end
end
function onManeuverLose(pet,maneuvers)
if (maneuvers == 1) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 2) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
elseif (maneuvers == 3) then
pet:delMod(MOD_ATTP, 3);
pet:addMod(MOD_RATTP, 3)
end
end
| gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_!Core/libs/_SVUI_Lib/SpecialFX.lua | 3 | 10803 | --[[
/$$$$$$ /$$ /$$ /$$$$$$$$ /$$ /$$
/$$__ $$ |__/ | $$| $$_____/| $$ / $$
| $$ \__/ /$$$$$$ /$$$$$$ /$$$$$$$ /$$ /$$$$$$ | $$| $$ | $$/ $$/
| $$$$$$ /$$__ $$ /$$__ $$ /$$_____/| $$ |____ $$| $$| $$$$$ \ $$$$/
\____ $$| $$ \ $$| $$$$$$$$| $$ | $$ /$$$$$$$| $$| $$__/ >$$ $$
/$$ \ $$| $$ | $$| $$_____/| $$ | $$ /$$__ $$| $$| $$ /$$/\ $$
| $$$$$$/| $$$$$$$/| $$$$$$$| $$$$$$$| $$| $$$$$$$| $$| $$ | $$ \ $$
\______/ | $$____/ \_______/ \_______/|__/ \_______/|__/|__/ |__/ |__/
| $$
| $$
|__/
--]]
--[[ LOCALIZED GLOBALS ]]--
--GLOBAL NAMESPACE
local _G = getfenv(0);
--LUA
local select = _G.select;
local assert = _G.assert;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local print = _G.print;
local ipairs = _G.ipairs;
local pairs = _G.pairs;
local next = _G.next;
local rawset = _G.rawset;
local rawget = _G.rawget;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local getmetatable = _G.getmetatable;
local setmetatable = _G.setmetatable;
--STRING
local string = _G.string;
local upper = string.upper;
local format = string.format;
local find = string.find;
local match = string.match;
local gsub = string.gsub;
--MATH
local math = _G.math;
local random = math.random;
local floor = math.floor
--TABLE
local table = _G.table;
local tsort = table.sort;
local tconcat = table.concat;
local tremove = _G.tremove;
local twipe = _G.wipe;
local CreateFrame = _G.CreateFrame;
--[[ LIB CONSTRUCT ]]--
local lib = Librarian:NewLibrary("SpecialFX")
if not lib then return end
--[[ LIB EFFECT TABLES ]]--
local DEFAULT_MODEL = [[Spells\Missile_bomb.m2]];
local DEFAULT_EFFECT = {DEFAULT_MODEL, 0, 0, 0, 0, 0.75, 0, 0};
local EFFECTS_LIST = setmetatable({
["default"] = {[[Spells\Missile_bomb.m2]], -12, 12, 12, -12, 0.4, 0.125, 0.05},
["holy"] = {[[Spells\Solar_precast_hand.m2]], -12, 12, 12, -12, 0.23, 0, 0},
["shadow"] = {[[Spells\Shadow_precast_uber_hand.m2]], -12, 12, 12, -12, 0.23, -0.1, 0.1},
["arcane"] = {[[Spells\Cast_arcane_01.m2]], -12, 12, 12, -12, 0.25, 0, 0},
["fire"] = {[[Spells\Bloodlust_state_hand.m2]], -8, 4, 24, -24, 0.70, -0.22, 0.22},
["frost"] = {[[Spells\Ice_cast_low_hand.m2]], -12, 12, 12, -12, 0.25, -0.2, -0.35},
["chi"] = {[[Spells\Fel_fire_precast_high_hand.m2]], -12, 12, 12, -12, 0.3, -0.04, -0.1},
["lightning"] = {[[Spells\Fill_lightning_cast_01.m2]], -12, 12, 12, -12, 1.25, 0, 0},
["water"] = {[[Spells\Monk_drunkenhaze_impact.m2]], -12, 12, 12, -12, 0.9, 0, 0},
["earth"] = {[[Spells\Sand_precast_hand.m2]], -12, 12, 12, -12, 0.23, 0, 0},
}, { __index = function(t, k)
return DEFAULT_EFFECT
end });
local DEFAULT_ROUTINE = {0, 2000};
local MODEL_ROUTINES = setmetatable({
["idle"] = {0, 2000},
["walk"] = {4, 2000},
["run"] = {5, 2000},
["attack1"] = {26, 2000},
["falling"] = {40, 2000},
["casting1"] = {52, 2000},
["static_roar"] = {55, 2000},
["chat"] = {60, 2000},
["yell"] = {64, 2000},
["shrug"] = {65, 2000},
["dance"] = {69, 2000},
["roar"] = {74, 2000},
["attack2"] = {111, 2000},
["sneak"] = {119, 2000},
["stealth"] = {120, 2000},
["casting2"] = {125, 2000},
["crafting"] = {138, 2000},
["kneel"] = {141, 2000},
["cannibalize"] = {203, 2000},
["cower"] = {225, 2000},
}, { __index = function(t, k)
return DEFAULT_ROUTINE
end });
--[[ CHARACTER MODEL METHODS ]]--
local CharacterModel_OnUpdate = function(self, elapsed)
if(self.___frameIndex < self.___maxIndex) then
self.___frameIndex = (self.___frameIndex + (elapsed * 1000));
else
self.___frameIndex = 0;
self:SetAnimation(0);
self:SetScript("OnUpdate", nil);
end
end
local CharacterModel_UseAnimation = function(self, animationName)
animationName = animationName or self.___currentAnimation;
local effectTable = self.___routines[effectName];
self.___frameIndex = 0;
self.___maxIndex = effectTable[2];
self.___currentAnimation = animationName;
self:SetAnimation(effectTable[1]);
self:SetScript("OnUpdate", CharacterModel_OnUpdate);
end
--[[ EFFECT FRAME METHODS ]]--
local EffectModel_SetAnchorParent = function(self, frame)
self.___anchorParent = frame;
self:SetEffect(self.currentEffect);
end
local EffectModel_OnShow = function(self)
self.FX:UpdateEffect();
end
local EffectModel_UpdateEffect = function(self)
local effect = self.currentEffect;
local effectTable = self.___fx[effect];
self:ClearModel();
self:SetModel(effectTable[1]);
end
local EffectModel_SetEffect = function(self, effectName)
effectName = effectName or self.currentEffect;
local effectTable = self.___fx[effectName];
local parent = self.___anchorParent;
self:ClearAllPoints();
self:SetPoint("TOPLEFT", parent, "TOPLEFT", effectTable[2], effectTable[3]);
self:SetPoint("BOTTOMRIGHT", parent, "BOTTOMRIGHT", effectTable[4], effectTable[5]);
self:ClearModel();
self:SetModel(effectTable[1]);
self:SetCamDistanceScale(effectTable[6]);
self:SetPosition(0, effectTable[7], effectTable[8]);
self:SetPortraitZoom(0);
self.currentEffect = effectName;
end
--[[ LIB METHODS ]]--
function lib:Register(request, modelFile, leftX, leftY, rightX, rightY, zoom, posX, posY)
if(type(request) == 'string') then
request = request:lower();
modelFile = modelFile or DEFAULT_MODEL;
leftX = leftX or 0;
leftY = leftY or 0;
rightX = rightX or 0;
rightY = rightY or 0;
zoom = zoom or 0.75;
posX = posX or 0;
posY = posY or 0;
rawset(EFFECTS_LIST, request, {modelFile, leftX, leftY, rightX, rightY, zoom, posX, posY})
elseif(request.SetAnimation) then
request.___routines = {};
setmetatable(request.___routines, { __index = ANIMATION_IDS });
request.___frameIndex = 0;
request.___maxIndex = 2000;
request.___currentAnimation = "idle";
request.UseAnimation = CharacterModel_UseAnimation;
end
end;
function lib:SetFXFrame(parent, defaultEffect, noScript, anchorParent)
defaultEffect = defaultEffect or "default"
local model = CreateFrame("PlayerModel", nil, parent);
model.___fx = {};
setmetatable(model.___fx, { __index = EFFECTS_LIST });
model.___anchorParent = anchorParent or parent;
model.SetEffect = EffectModel_SetEffect;
model.SetAnchorParent = EffectModel_SetAnchorParent;
model.UpdateEffect = EffectModel_UpdateEffect;
model.currentEffect = defaultEffect;
parent.FX = model;
--print(defaultEffect)
EffectModel_SetEffect(model, defaultEffect)
if(not noScript) then
if(parent:GetScript("OnShow")) then
parent:HookScript("OnShow", EffectModel_OnShow)
else
parent:SetScript("OnShow", EffectModel_OnShow)
end
end
end
--[[ MODEL FILES FOUND FOR EFFECTS ]]--
-- [[Spells\Fel_fire_precast_high_hand.m2]]
-- [[Spells\Fire_precast_high_hand.m2]]
-- [[Spells\Fire_precast_low_hand.m2]]
-- [[Spells\Focused_casting_state.m2]]
-- [[Spells\Fill_holy_cast_01.m2]]
-- [[Spells\Fill_fire_cast_01.m2]]
-- [[Spells\Paladin_healinghands_state_01.m2]]
-- [[Spells\Fill_magma_cast_01.m2]]
-- [[Spells\Fill_shadow_cast_01.m2]]
-- [[Spells\Fill_arcane_precast_01.m2]]
-- [[Spells\Ice_cast_low_hand.m2]]
-- [[Spells\Immolate_state.m2]]
-- [[Spells\Immolate_state_v2_illidari.m2]]
-- [[Spells\Intervenetrail.m2]]
-- [[Spells\Invisibility_impact_base.m2]]
-- [[Spells\Fire_dot_state_chest.m2]]
-- [[Spells\Fire_dot_state_chest_jade.m2]]
-- [[Spells\Cast_arcane_01.m2]]
-- [[Spells\Spellsteal_missile.m2]]
-- [[Spells\Missile_bomb.m2]]
-- [[Spells\Shadow_frost_weapon_effect.m2]]
-- [[Spells\Shadow_precast_high_base.m2]]
-- [[Spells\Shadow_precast_high_hand.m2]]
-- [[Spells\Shadow_precast_low_hand.m2]]
-- [[Spells\Shadow_precast_med_base.m2]]
-- [[Spells\Shadow_precast_uber_hand.m2]]
-- [[Spells\Shadow_strikes_state_hand.m2]]
-- [[Spells\Shadowbolt_missile.m2]]
-- [[Spells\Shadowworddominate_chest.m2]]
-- [[Spells\Infernal_smoke_rec.m2]]
-- [[Spells\Largebluegreenradiationfog.m2]]
-- [[Spells\Leishen_lightning_fill.m2]]
-- [[Spells\Mage_arcanebarrage_missile.m2]]
-- [[Spells\Mage_firestarter.m2]]
-- [[Spells\Mage_greaterinvis_state_chest.m2]]
-- [[Spells\Magicunlock.m2]]
-- [[Spells\Chiwave_impact_hostile.m2]]
-- [[Spells\Cripple_state_base.m2]]
-- [[Spells\Monk_expelharm_missile.m2]]
-- [[Spells\Monk_forcespere_orb.m2]]
-- [[Spells\Fill_holy_cast_01.m2]]
-- [[Spells\Fill_fire_cast_01.m2]]
-- [[Spells\Fill_lightning_cast_01.m2]]
-- [[Spells\Fill_magma_cast_01.m2]]
-- [[Spells\Fill_shadow_cast_01.m2]]
-- [[Spells\Sprint_impact_chest.m2]]
-- [[Spells\Spellsteal_missile.m2]]
-- [[Spells\Warlock_destructioncharge_impact_chest.m2]]
-- [[Spells\Warlock_destructioncharge_impact_chest_fel.m2]]
-- [[Spells\Xplosion_twilight_impact_noflash.m2]]
-- [[Spells\Warlock_bodyofflames_medium_state_shoulder_right_purple.m2]]
-- [[Spells\Blink_impact_chest.m2]]
-- [[Spells\Christmassnowrain.m2]]
-- [[Spells\Detectinvis_impact_base.m2]]
-- [[Spells\Eastern_plaguelands_beam_effect.m2]]
-- [[Spells\battlemasterglow_high.m2]]
-- [[Spells\blueflame_low.m2]]
-- [[Spells\greenflame_low.m2]]
-- [[Spells\purpleglow_high.m2]]
-- [[Spells\redflame_low.m2]]
-- [[Spells\poisondrip.m2]]
-- [[Spells\savageryglow_high.m2]]
-- [[Spells\spellsurgeglow_high.m2]]
-- [[Spells\sunfireglow_high.m2]]
-- [[Spells\whiteflame_low.m2]]
-- [[Spells\yellowflame_low.m2]]
-- [[Spells\Food_healeffect_base.m2]]
-- [[Spells\Bloodlust_state_hand.m2]]
-- [[Spells\Deathwish_state_hand.m2]]
-- [[Spells\Disenchant_precast_hand.m2]]
-- [[Spells\Enchant_cast_hand.m2]]
-- [[Spells\Eviscerate_cast_hands.m2]]
-- [[Spells\Fire_blue_precast_hand.m2]]
-- [[Spells\Fire_blue_precast_high_hand.m2]]
-- [[Spells\Fire_precast_hand.m2]]
-- [[Spells\Fire_precast_hand_pink.m2]]
-- [[Spells\Fire_precast_hand_sha.m2]]
-- [[Spells\Fire_precast_high_hand.m2]]
-- [[Spells\Fire_precast_low_hand.m2]]
-- [[Spells\Ice_precast_high_hand.m2]]
-- [[Spells\Sand_precast_hand.m2]]
-- [[Spells\Solar_precast_hand.m2]]
-- [[Spells\Twilight_fire_precast_high_hand.m2]]
-- [[Spells\Vengeance_state_hand.m2]]
-- [[Spells\Fel_djinndeath_fire_02.m2]]
| mit |
UnfortunateFruit/darkstar | scripts/zones/Garlaige_Citadel/npcs/Grounds_Tome.lua | 34 | 1145 | -----------------------------------
-- Area: Garlaige Citidel
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_GARLAIGE_CITADEL,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,703,704,705,706,707,708,708,710,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,703,704,705,706,707,708,708,710,0,0,GOV_MSG_GARLAIGE_CITADEL);
end;
| gpl-3.0 |
cmassiot/vlc-broadcast | share/lua/playlist/break.lua | 113 | 1995 | --[[
$Id$
Copyright © 2007 the VideoLAN team
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, "^break.com" )
or string.match( vlc.path, "^www.break.com" ) )
end
-- Parse function.
function parse()
filepath = ""
filename = ""
filetitle = ""
arturl = ""
while true do
line = vlc.readline()
if not line then break end
if string.match( line, "sGlobalContentFilePath=" ) then
_,_,filepath= string.find( line, "sGlobalContentFilePath='(.-)'" )
end
if string.match( line, "sGlobalFileName=" ) then
_,_,filename = string.find( line, ".*sGlobalFileName='(.-)'")
end
if string.match( line, "sGlobalContentTitle=" ) then
_,_,filetitle = string.find( line, "sGlobalContentTitle='(.-)'")
end
if string.match( line, "el=\"videothumbnail\" href=\"" ) then
_,_,arturl = string.find( line, "el=\"videothumbnail\" href=\"(.-)\"" )
end
if string.match( line, "videoPath" ) then
_,_,videopath = string.find( line, ".*videoPath', '(.-)'" )
return { { path = videopath..filepath.."/"..filename..".flv"; title = filetitle; arturl = arturl } }
end
end
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/items/dil.lua | 18 | 1252 | -----------------------------------------
-- ID: 5457
-- Item: Dil
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 4
-- Mind -6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5457);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -6);
end;
| gpl-3.0 |
Xileck/forgottenserver | data/lib/core/game.lua | 32 | 1507 | function Game.broadcastMessage(message, messageType)
if messageType == nil then
messageType = MESSAGE_STATUS_WARNING
end
for _, player in ipairs(Game.getPlayers()) do
player:sendTextMessage(messageType, message)
end
end
function Game.convertIpToString(ip)
local band = bit.band
local rshift = bit.rshift
return string.format("%d.%d.%d.%d",
band(ip, 0xFF),
band(rshift(ip, 8), 0xFF),
band(rshift(ip, 16), 0xFF),
rshift(ip, 24)
)
end
function Game.getReverseDirection(direction)
if direction == WEST then
return EAST
elseif direction == EAST then
return WEST
elseif direction == NORTH then
return SOUTH
elseif direction == SOUTH then
return NORTH
elseif direction == NORTHWEST then
return SOUTHEAST
elseif direction == NORTHEAST then
return SOUTHWEST
elseif direction == SOUTHWEST then
return NORTHEAST
elseif direction == SOUTHEAST then
return NORTHWEST
end
return NORTH
end
function Game.getSkillType(weaponType)
if weaponType == WEAPON_CLUB then
return SKILL_CLUB
elseif weaponType == WEAPON_SWORD then
return SKILL_SWORD
elseif weaponType == WEAPON_AXE then
return SKILL_AXE
elseif weaponType == WEAPON_DISTANCE then
return SKILL_DISTANCE
elseif weaponType == WEAPON_SHIELD then
return SKILL_SHIELD
end
return SKILL_FIST
end
if not globalStorageTable then
globalStorageTable = {}
end
function Game.getStorageValue(key)
return globalStorageTable[key]
end
function Game.setStorageValue(key, value)
globalStorageTable[key] = value
end
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Windurst_Woods/npcs/Pulonono.lua | 13 | 1060 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Pulonono
-- Type: VCS Chocobo Trainer
-- @zone: 241
-- @pos 130.124 -6.35 -119.341
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02e5);
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 |
reonZ/project-arena | game/dota_addons/project_arenas/scripts/vscripts/libraries/animations.lua | 8 | 15147 | ANIMATIONS_VERSION = "0.83"
--[[
Lua-controlled Animations Library by BMD
Installation
-"require" this file inside your code in order to gain access to the StartAnmiation and EndAnimation global.
-Additionally, ensure that this file is placed in the vscripts/libraries path and that the vscripts/libraries/modifiers/modifier_animation.lua, modifier_animation_translate.lua, and modifier_animation_translate_permanent.lua files exist and are in the correct path
Usage
-Animations can be started for any unit and are provided as a table of information to the StartAnimation call
-Repeated calls to StartAnimation for a single unit will cancel any running animation and begin the new animation
-EndAnimation can be called in order to cancel a running animation
-Animations are specified by a table which has as potential parameters:
-duration: The duration to play the animation. The animation will be cancelled regardless of how far along it is at the end fo the duration.
-activity: An activity code which will be used as the base activity for the animation i.e. DOTA_ACT_RUN, DOTA_ACT_ATTACK, etc.
-rate: An optional (will be 1.0 if unspecified) animation rate to be used when playing this animation.
-translate: An optional translate activity modifier string which can be used to modify the animation sequence.
Example: For ACT_DOTA_RUN+haste, this should be "haste"
-translate2: A second optional translate activity modifier string which can be used to modify the animation sequence further.
Example: For ACT_DOTA_ATTACK+sven_warcry+sven_shield, this should be "sven_warcry" or "sven_shield" while the translate property is the other translate modifier
-A permanent activity translate can be applied to a unit by calling AddAnimationTranslate for that unit. This allows for a permanent "injured" or "aggressive" animation stance.
-Permanent activity translate modifiers can be removed with RemoveAnimationTranslate.
Notes
-Animations can only play for valid activities/sequences possessed by the model the unit is using.
-Sequences requiring 3+ activity modifier translates (i.e "stun+fear+loadout" or similar) are not possible currently in this library.
-Calling EndAnimation and attempting to StartAnimation a new animation for the same unit withing ~2 server frames of the animation end will likely fail to play the new animation.
Calling StartAnimation directly without ending the previous animation will automatically add in this delay and cancel the previous animation.
-The maximum animation rate which can be used is 12.75, and animation rates can only exist at a 0.05 resolution (i.e. 1.0, 1.05, 1.1 and not 1.06)
-StartAnimation and EndAnimation functions can also be accessed through GameRules as GameRules.StartAnimation and GameRules.EndAnimation for use in scoped lua files (triggers, vscript ai, etc)
-This library requires that the "libraries/timers.lua" be present in your vscripts directory.
Examples:
--Start a running animation at 2.5 rate for 2.5 seconds
StartAnimation(unit, {duration=2.5, activity=ACT_DOTA_RUN, rate=2.5})
--End a running animation
EndAnimation(unit)
--Start a running + hasted animation at .8 rate for 5 seconds
StartAnimation(unit, {duration=5, activity=ACT_DOTA_RUN, rate=0.8, translate="haste"})
--Start a shield-bash animation for sven with variable rate
StartAnimation(unit, {duration=1.5, activity=ACT_DOTA_ATTACK, rate=RandomFloat(.5, 1.5), translate="sven_warcry", translate2="sven_shield"})
--Start a permanent injured translate modifier
AddAnimationTranslate(unit, "injured")
--Remove a permanent activity translate modifier
RemoveAnimationTranslate(unit)
]]
LinkLuaModifier( "modifier_animation", "libraries/modifiers/modifier_animation.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_animation_translate", "libraries/modifiers/modifier_animation_translate.lua", LUA_MODIFIER_MOTION_NONE )
LinkLuaModifier( "modifier_animation_translate_permanent", "libraries/modifiers/modifier_animation_translate_permanent.lua", LUA_MODIFIER_MOTION_NONE )
require('libraries/timers')
local _ANIMATION_TRANSLATE_TO_CODE = {
abysm= 13,
admirals_prow= 307,
agedspirit= 3,
aggressive= 4,
agrressive= 163,
am_blink= 182,
ancestors_edge= 144,
ancestors_pauldron= 145,
ancestors_vambrace= 146,
ancestral_scepter= 67,
ancient_armor= 6,
anvil= 7,
arcana= 8,
armaments_set= 20,
axes= 188,
backstab= 41,
backstroke_gesture= 283,
backward= 335,
ball_lightning= 231,
batter_up= 43,
bazooka= 284,
belly_flop= 180,
berserkers_blood= 35,
black= 44,
black_hole= 194,
bladebiter= 147,
blood_chaser= 134,
bolt= 233,
bot= 47,
brain_sap= 185,
broodmother_spin= 50,
burning_fiend= 148,
burrow= 229,
burrowed= 51,
cat_dancer_gesture= 285,
cauldron= 29,
charge= 97,
charge_attack= 98,
chase= 246,
chasm= 57,
chemical_rage= 2,
chicken_gesture= 258,
come_get_it= 39,
corpse_dress= 104,
corpse_dresstop= 103,
corpse_scarf= 105,
cryAnimationExportNode= 341,
crystal_nova= 193,
culling_blade= 184,
dagger_twirl= 143,
dark_wraith= 174,
darkness= 213,
dc_sb_charge= 107,
dc_sb_charge_attack= 108,
dc_sb_charge_finish= 109,
dc_sb_ultimate= 110,
deadwinter_soul= 96,
death_protest= 94,
demon_drain= 116,
desolation= 55,
digger= 176,
dismember= 218,
divine_sorrow= 117,
divine_sorrow_loadout= 118,
divine_sorrow_loadout_spawn= 119,
divine_sorrow_sunstrike= 120,
dizzying_punch= 343,
dog_of_duty= 342,
dogofduty= 340,
dominator= 254,
dryad_tree= 311,
dualwield= 14,
duel_kill= 121,
earthshock= 235,
emp= 259,
enchant_totem= 313,
["end"]= 243,
eyeoffetizu= 34,
f2p_doom= 131,
face_me= 286,
faces_hakama= 111,
faces_mask= 113,
faces_wraps= 112,
fast= 10,
faster= 11,
fastest= 12,
fear= 125,
fiends_grip= 186,
fiery_soul= 149,
finger= 200,
firefly= 190,
fish_slap= 123,
fishstick= 339,
fissure= 195,
flying= 36,
focusfire= 124,
forcestaff_enemy= 122,
forcestaff_friendly= 15,
forward= 336,
fountain= 49,
freezing_field= 191,
frost_arrow= 37,
frostbite= 192,
frostiron_raider= 150,
frostivus= 54,
ftp_dendi_back= 126,
gale= 236,
get_burned= 288,
giddy_up_gesture= 289,
glacier= 101,
glory= 345,
good_day_sir= 40,
great_safari= 267,
greevil_black_hole= 58,
greevil_blade_fury= 59,
greevil_bloodlust= 60,
greevil_cold_snap= 61,
greevil_decrepify= 62,
greevil_diabolic_edict= 63,
greevil_echo_slam= 64,
greevil_fatal_bonds= 65,
greevil_ice_wall= 66,
greevil_laguna_blade= 68,
greevil_leech_seed= 69,
greevil_magic_missile= 70,
greevil_maledict= 71,
greevil_miniboss_black_brain_sap= 72,
greevil_miniboss_black_nightmare= 73,
greevil_miniboss_blue_cold_feet= 74,
greevil_miniboss_blue_ice_vortex= 75,
greevil_miniboss_green_living_armor= 76,
greevil_miniboss_green_overgrowth= 77,
greevil_miniboss_orange_dragon_slave= 78,
greevil_miniboss_orange_lightstrike_array= 79,
greevil_miniboss_purple_plague_ward= 80,
greevil_miniboss_purple_venomous_gale= 81,
greevil_miniboss_red_earthshock= 82,
greevil_miniboss_red_overpower= 83,
greevil_miniboss_white_purification= 84,
greevil_miniboss_yellow_ion_shell= 85,
greevil_miniboss_yellow_surge= 86,
greevil_natures_attendants= 87,
greevil_phantom_strike= 88,
greevil_poison_nova= 89,
greevil_purification= 90,
greevil_shadow_strike= 91,
greevil_shadow_wave= 92,
groove_gesture= 305,
ground_pound= 128,
guardian_angel= 215,
guitar= 290,
hang_loose_gesture= 291,
happy_dance= 293,
harlequin= 129,
haste= 45,
hook= 220,
horn= 292,
immortal= 28,
impale= 201,
impatient_maiden= 100,
impetus= 138,
injured= 5,
["injured rare"]= 247,
injured_aggressive= 130,
instagib= 21,
iron= 255,
iron_surge= 99,
item_style_2= 133,
jump_gesture= 294,
laguna= 202,
leap= 206,
level_1= 140,
level_2= 141,
level_3= 142,
life_drain= 219,
loadout= 0,
loda= 173,
lodestar= 114,
loser= 295,
lsa= 203,
lucentyr= 158,
lute= 296,
lyreleis_breeze= 159,
mace= 160,
mag_power_gesture= 298,
magic_ends_here= 297,
mana_drain= 204,
mana_void= 183,
manias_mask= 135,
manta= 38,
mask_lord= 299,
masquerade= 25,
meld= 162,
melee= 334,
miniboss= 164,
moon_griffon= 166,
moonfall= 165,
moth= 53,
nihility= 95,
obeisance_of_the_keeper= 151,
obsidian_helmet= 132,
odachi= 32,
offhand_basher= 42,
omnislash= 198,
overpower1= 167,
overpower2= 168,
overpower3= 169,
overpower4= 170,
overpower5= 171,
overpower6= 172,
pegleg= 248,
phantom_attack= 16,
pinfold= 175,
plague_ward= 237,
poison_nova= 238,
portrait_fogheart= 177,
poundnpoint= 300,
powershot= 242,
punch= 136,
purification= 216,
pyre= 26,
qop_blink= 221,
ravage= 225,
red_moon= 30,
reincarnate= 115,
remnant= 232,
repel= 217,
requiem= 207,
roar= 187,
robot_gesture= 301,
roshan= 181,
salvaged_sword= 152,
sandking_rubyspire_burrowstrike= 52,
sb_bracers= 251,
sb_helmet= 250,
sb_shoulder= 252,
sb_spear= 253,
scream= 222,
serene_honor= 153,
shadow_strike= 223,
shadowraze= 208,
shake_moneymaker= 179,
sharp_blade= 303,
shinobi= 27,
shinobi_mask= 154,
shinobi_tail= 23,
shrapnel= 230,
silent_ripper= 178,
slam= 196,
slasher_chest= 262,
slasher_mask= 263,
slasher_offhand= 261,
slasher_weapon= 260,
sm_armor= 264,
sm_head= 56,
sm_shoulder= 265,
snipe= 226,
snowangel= 17,
snowball= 102,
sonic_wave= 224,
sparrowhawk_bow= 269,
sparrowhawk_cape= 270,
sparrowhawk_hood= 272,
sparrowhawk_quiver= 271,
sparrowhawk_shoulder= 273,
spin= 199,
split_shot= 1,
sprint= 275,
sprout= 209,
staff_swing= 304,
stalker_exo= 93,
start= 249,
stinger= 280,
stolen_charge= 227,
stolen_firefly= 189,
strike= 228,
sugarrush= 276,
suicide_squad= 18,
summon= 210,
sven_shield= 256,
sven_warcry= 257,
swag_gesture= 287,
swordonshoulder= 155,
taunt_fullbody= 19,
taunt_killtaunt= 139,
taunt_quickdraw_gesture= 268,
taunt_roll_gesture= 302,
techies_arcana= 9,
telebolt= 306,
teleport= 211,
thirst= 137,
tidebringer= 24,
tidehunter_boat= 22,
tidehunter_toss_fish= 312,
tidehunter_yippy= 347,
timelord_head= 309,
tinker_rollermaw= 161,
torment= 279,
totem= 197,
transition= 278,
trapper= 314,
tree= 310,
trickortreat= 277,
triumphant_timelord= 127,
turbulent_teleport= 308,
twinblade_attack= 315,
twinblade_attack_b= 316,
twinblade_attack_c= 317,
twinblade_attack_d= 318,
twinblade_attack_injured= 319,
twinblade_death= 320,
twinblade_idle= 321,
twinblade_idle_injured= 322,
twinblade_idle_rare= 323,
twinblade_injured_attack_b= 324,
twinblade_jinada= 325,
twinblade_jinada_injured= 326,
twinblade_shuriken_toss= 327,
twinblade_shuriken_toss_injured= 328,
twinblade_spawn= 329,
twinblade_stun= 330,
twinblade_track= 331,
twinblade_track_injured= 332,
twinblade_victory= 333,
twister= 274,
unbroken= 106,
vendetta= 337,
viper_strike= 239,
viridi_set= 338,
void= 214,
vortex= 234,
wall= 240,
ward= 241,
wardstaff= 344,
wave= 205,
web= 48,
whalehook= 156,
whats_that= 281,
when_nature_attacks= 31,
white= 346,
windrun= 244,
windy= 245,
winterblight= 157,
witchdoctor_jig= 282,
with_item= 46,
wolfhound= 266,
wraith_spin= 33,
wrath= 212,
rampant= 348,
overload= 349,
surge=350,
es_prosperity=351,
Espada_pistola=352,
overload_injured=353,
ss_fortune=354,
liquid_fire=355,
jakiro_icemelt=356,
jakiro_roar=357,
chakram=358,
doppelwalk=359,
enrage=360,
fast_run=361,
overpower=362,
overwhelmingodds=363,
pregame=364,
shadow_dance=365,
shukuchi=366,
strength=367,
twinblade_run=368,
twinblade_run_injured=369,
windwalk=370,
}
function StartAnimation(unit, table)
local duration = table.duration
local activity = table.activity
local translate = table.translate
local translate2 = table.translate2
local rate = table.rate or 1.0
rate = math.floor(math.max(0,math.min(255/20, rate)) * 20 + .5)
local stacks = activity + bit.lshift(rate,11)
if translate ~= nil then
if _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then
print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.")
return
end
stacks = stacks + bit.lshift(_ANIMATION_TRANSLATE_TO_CODE[translate],19)
end
if translate2 ~= nil and _ANIMATION_TRANSLATE_TO_CODE[translate2] == nil then
print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate2 .. "'. This translate may be misspelled or need to be added to the enum manually.")
return
end
if unit:HasModifier("modifier_animation") or (unit._animationEnd ~= nil and unit._animationEnd + .067 > GameRules:GetGameTime()) then
EndAnimation(unit)
Timers:CreateTimer(.066, function()
if translate2 ~= nil then
unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2})
unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2])
end
unit._animationEnd = GameRules:GetGameTime() + duration
unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate})
unit:SetModifierStackCount("modifier_animation", unit, stacks)
end)
else
if translate2 ~= nil then
unit:AddNewModifier(unit, nil, "modifier_animation_translate", {duration=duration, translate=translate2})
unit:SetModifierStackCount("modifier_animation_translate", unit, _ANIMATION_TRANSLATE_TO_CODE[translate2])
end
unit._animationEnd = GameRules:GetGameTime() + duration
unit:AddNewModifier(unit, nil, "modifier_animation", {duration=duration, translate=translate})
unit:SetModifierStackCount("modifier_animation", unit, stacks)
end
end
function EndAnimation(unit)
unit._animationEnd = GameRules:GetGameTime()
unit:RemoveModifierByName("modifier_animation")
unit:RemoveModifierByName("modifier_animation_translate")
end
function AddAnimationTranslate(unit, translate)
if translate == nil or _ANIMATION_TRANSLATE_TO_CODE[translate] == nil then
print("[ANIMATIONS.lua] ERROR, no translate-code found for '" .. translate .. "'. This translate may be misspelled or need to be added to the enum manually.")
return
end
unit:AddNewModifier(unit, nil, "modifier_animation_translate_permanent", {duration=duration, translate=translate})
unit:SetModifierStackCount("modifier_animation_translate_permanent", unit, _ANIMATION_TRANSLATE_TO_CODE[translate])
end
function RemoveAnimationTranslate(unit)
unit:RemoveModifierByName("modifier_animation_translate_permanent")
end
GameRules.StartAnimation = StartAnimation
GameRules.EndAnimation = EndAnimation
GameRules.AddAnimationTranslate = AddAnimationTranslate
GameRules.RemoveAnimationTranslate = RemoveAnimationTranslate | gpl-2.0 |
nesstea/darkstar | scripts/globals/items/slice_of_cerberus_meat.lua | 18 | 1503 | -----------------------------------------
-- ID: 5565
-- Item: slice_of_cerberus_meat
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Health 10
-- Magic -10
-- Strength 6
-- Intelligence -6
-----------------------------------------
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,1800,5565);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_MP, -10);
target:addMod(MOD_STR, 6);
target:addMod(MOD_INT, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_MP, -10);
target:delMod(MOD_STR, 6);
target:delMod(MOD_INT, -6);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/items/bowl_of_adamantoise_soup.lua | 18 | 1601 | -----------------------------------------
-- ID: 5210
-- Item: Bowl of Adamantoise Soup
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength -7
-- Dexterity -7
-- Agility -7
-- Vitality -7
-- Intelligence -7
-- Mind -7
-- Charisma -7
-----------------------------------------
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,5210);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -7);
target:addMod(MOD_DEX, -7);
target:addMod(MOD_AGI, -7);
target:addMod(MOD_VIT, -7);
target:addMod(MOD_INT, -7);
target:addMod(MOD_MND, -7);
target:addMod(MOD_CHR, -7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -7);
target:delMod(MOD_DEX, -7);
target:delMod(MOD_AGI, -7);
target:delMod(MOD_VIT, -7);
target:delMod(MOD_INT, -7);
target:delMod(MOD_MND, -7);
target:delMod(MOD_CHR, -7);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/The_Shrine_of_RuAvitau/npcs/blank_4.lua | 31 | 4968 | -----------------------------------
-- Area: The Shrine of Ru'Avitau
-- NPC: ??? divine might mission
-- @pos -40 0 -151 178
-----------------------------------
package.loaded["scripts/zones/The_Shrine_of_RuAvitau/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Shrine_of_RuAvitau/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentZM = player:getCurrentMission(ZILART);
local ZMProgress = player:getVar("ZilartStatus");
local DMStatus = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT);
local DMRepeat = player:getQuestStatus(OUTLANDS,DIVINE_MIGHT_REPEAT);
local AAKeyitems = 0;
local DMEarrings = 0;
local DivineStatus = player:getVar("DivineMight");
local MoonOre = player:hasKeyItem(MOONLIGHT_ORE);
-- Count keyitems
for i=SHARD_OF_APATHY, SHARD_OF_RAGE do
if (player:hasKeyItem(i) == true) then
AAKeyitems = AAKeyitems + 1;
end
end
-- Count Earrings
for i=14739, 14743 do
if (player:hasItem(i) == true) then
DMEarrings = DMEarrings + 1;
end
end
if (CurrentZM == ARK_ANGELS and ZMProgress == 0 and DMEarrings <= NUMBER_OF_DM_EARRINGS) then -- First step in Ark Angels
player:startEvent(53,917,1408,1550);
elseif (CurrentZM == ARK_ANGELS and ZMProgress == 1 and DivineStatus < 2) then -- Reminder CS/starts Divine Might (per Wiki)
player:startEvent(54,917,1408,1550);
elseif (CurrentZM >= ARK_ANGELS and DMStatus == QUEST_AVAILABLE and AAKeyitems > 0) then -- Alternative cutscene for those that have done one or more AA fight
player:startEvent(56,917,1408,1550);
elseif (DMStatus == QUEST_ACCEPTED and DivineStatus >= 2) then -- CS when player has completed Divine might, award earring
player:startEvent(55,14739,14740,14741,14742,14743);
elseif (DMStatus == QUEST_COMPLETED and DMEarrings < NUMBER_OF_DM_EARRINGS and DMRepeat ~= QUEST_ACCEPTED) then -- You threw away old Earring, start the repeat quest
player:startEvent(57,player:getVar("DM_Earring"));
elseif (DMRepeat == QUEST_ACCEPTED and DivineStatus < 2) then
if (MoonOre == false) then
player:startEvent(58); -- Reminder for Moonlight Ore
else
player:startEvent(56,917,1408,1550); -- Reminder for Ark Pentasphere
end
elseif (DMRepeat == QUEST_ACCEPTED and DivineStatus == 2 and MoonOre == true) then -- Repeat turn in
player:startEvent(59);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY); -- Need some kind of feedback
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 59 and option == 2) then
player:updateEvent(14739,14740,14741,14742,14743);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 53) then -- Got the required cutscene for AA
player:setVar("ZilartStatus",1);
elseif ((csid == 54 or csid == 56) and player:getQuestStatus(OUTLANDS,DIVINE_MIGHT) == QUEST_AVAILABLE) then -- Flag Divine Might
player:addQuest(OUTLANDS,DIVINE_MIGHT);
elseif (csid == 57) then -- Divine Might Repeat
player:delQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
player:addQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
elseif (csid == 55 or csid == 59) then -- Turning in Divine Might or Repeat
local reward = 0;
if (option == 1) then
reward = 14739; -- Suppanomimi
elseif (option == 2) then
reward = 14740; -- Knight's Earring
elseif (option == 3) then
reward = 14741; -- Abyssal Earring
elseif (option == 4) then
reward = 14742; -- Beastly Earring
elseif (option == 5) then
reward = 14743; -- Bushinomimi
end
if (reward ~= 0) then
if (player:getFreeSlotsCount() >= 1 and player:hasItem(reward) == false) then
player:addItem(reward);
player:messageSpecial(ITEM_OBTAINED,reward);
if (csid == 55) then
player:completeQuest(OUTLANDS,DIVINE_MIGHT);
else
player:completeQuest(OUTLANDS,DIVINE_MIGHT_REPEAT);
player:delKeyItem(MOONLIGHT_ORE);
end
player:setVar("DivineMight",0);
player:setVar("DM_Earring",reward);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,reward);
end
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_Jeuno/npcs/Red_Ghost.lua | 34 | 2108 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Red Ghost
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Jeuno/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/pathfind");
local path = {
-96.823616, 0.001000, -3.722488,
-96.761887, 0.001000, -2.632236,
-96.698341, 0.001000, -1.490001,
-96.636963, 0.001000, -0.363672,
-96.508736, 0.001000, 2.080966,
-96.290009, 0.001000, 6.895948,
-96.262505, 0.001000, 7.935584,
-96.282127, 0.001000, 6.815756,
-96.569176, 0.001000, -7.781419,
-96.256729, 0.001000, 8.059505,
-96.568405, 0.001000, -7.745419,
-96.254066, 0.001000, 8.195477,
-96.567200, 0.001000, -7.685426
};
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
function onPath(npc)
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatJeuno = player:getVar("WildcatJeuno");
if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,15) == false) then
player:startEvent(314);
else
player:startEvent(0x22);
end
-- wait until event is over
npc:wait(-1);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,npc)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 314) then
player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",15,true);
end
npc:wait(0);
end;
| gpl-3.0 |
amirmrbad/teleatom | bot/creedbot.lua | 1 | 15612 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
".",
"Feedback",
"plugins",
"lock_join",
"antilink",
"antitag",
"gps",
"auto_leave",
"cpu",
"calc",
"bin",
"tagall",
"text",
"info",
"bot_on_off",
"welcome",
"webshot",
"google",
"sms",
"anti_spam",
"add_bot",
"owners",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban"
},
sudo_users = {144152859,41471906},--Sudo users
disabled_chann144152859els = {},
realm = {},--Realms Id
moderation = {data = 'data/moderation.json'},
about_text = [[Creed bot 2.3
Hello my Good friends
‼️ this bot is made by : @creed_is_dead
〰〰〰〰〰〰〰〰
ߔࠀ our admins are :
ߔࠀ @amirmr33
ߔࠀ @Xx0_amin_oxX
♻️ You can send your Ideas and messages to Us By sending them into bots account by this command :
تمامی درخواست ها و همه ی انتقادات و حرفاتونو با دستور زیر بفرستین به ما
!feedback (your ideas and messages)
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
گروه جدیدی بسازید
!createrealm [Name]
Create a realm
گروه مادر جدیدی بسازید
!setname [Name]
Set realm name
اسم گروه مادر را تغییر بدهید
!setabout [GroupID] [Text]
Set a group's about text
در مورد آن گروه توضیحاتی را بنویسید (ای دی گروه را بدهید )
!setrules [GroupID] [Text]
Set a group's rules
در مورد آن گروه قوانینی تعیین کنید ( ای دی گروه را بدهید )
!lock [GroupID] [setting]
Lock a group's setting
تنظیکات گروهی را قفل بکنید
!unlock [GroupID] [setting]
Unock a group's setting
تنظیمات گروهی را از قفل در بیاورید
!wholist
Get a list of members in group/realm
لیست تمامی اعضای گروه رو با ای دی شون نشون میده
!who
Get a file of members in group/realm
لیست تمامی اعضای گروه را با ای دی در فایل متنی دریافت کنید
!type
Get group type
در مورد نقش گروه بگیرید
!kill chat [GroupID]
Kick all memebers and delete group ⛔️⛔️
⛔️تمامی اعضای گروه را حذف میکند ⛔️
!kill realm [RealmID]
Kick all members and delete realm⛔️⛔️
تمامی اعضای گروه مارد را حذف میکند
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
ادمینی را اضافه بکنید
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only❗️❗️
❗️❗️ادمینی را با این دستور صلب مقام میکنید ❗️❗️
!list groups
Get a list of all groups
لیست تمامی گروه هارو میده
!list realms
Get a list of all realms
لیست گروه های مادر را میدهد
!log
Get a logfile of current group or realm
تمامی عملیات گروه را میدهد
!broadcast [text]
Send text to all groups ✉️
✉️ با این دستور به تمامی گروه ها متنی را همزمان میفرستید .
!br [group_id] [text]
This command will send text to [group_id]✉️
با این دستور میتونید به گروه توسط ربات متنی را بفرستید
You Can user both "!" & "/" for them
میتوانید از هردوی کاراکتر های ! و / برای دستورات استفاده کنید
]],
help_text = [[
Creed bots Help for mods : Plugins
Banhammer :
Help For Banhammer دستوراتی برای کنترل گروه
!Kick @UserName or ID
شخصی را از گروه حذف کنید . همچنین با ریپلی هم میشه
!Ban @UserName or ID
برای بن کردن شخص اسفاده میشود . با ریپلی هم میشه
!Unban @UserName
برای آنبن کردن شخصی استفاده میشود . همچنین با ریپلی هم میشه
For Admins :
!banall ID
برای بن گلوبال کردن از تمامی گروه هاست باید ای دی بدین با ریپلی هم میشه
!unbanall ID
برای آنبن کردن استفاده میشود ولی فقط با ای دی میشود
〰〰〰〰〰〰〰〰〰〰
2. GroupManager :
!lock leave
اگر کسی از گروه برود نمیتواند برگردد
!lock tag
برای مجوز ندادن به اعضا از استفاده کردن @ و # برای تگ
!Creategp "GroupName"
you can Create group with this comman
با این دستور برای ساخت گروه استفاده بکنید
!lock member
For locking Inviting users
برای جلوگیری از آمدن اعضای جدید استفاده میشود
!lock bots
for Locking Bots invitation
برای جلوگیری از ادد کردن ربا استفاده میشود
!lock name ❤️
To lock the group name for every bodey
برای قفل کردن اسم استفاده میشود
!setfloodߘ㊓et the group flood control߈銙囌زان اسپم را در گروه تعیین میکنید
!settings ❌
Watch group settings
تنظیمات فعلی گروه را میبینید
!owner
watch group owner
آیدی سازنده گروه رو میبینید
!setowner user_id❗️
You can set someone to the group owner‼️
برای گروه سازنده تعیین میکنید
!modlist
catch Group mods
لیست مدیران گروه را میگیرید
!lock join
to lock joining the group by link
برای جلوگیری از وارد شدن به کروه با لینک
!lock flood⚠️
lock group flood
از اسپم دادن در گروه جلوگیری کنید
!unlock (bots-member-flood-photo-name-tag-link-join-Arabic)✅
Unlock Something
موارد بالا را با این دستور آزاد میسازید
!rules && !set rules
TO see group rules or set rules
برای دیدن قوانین گروه و یا انتخاب قوانین
!about or !set about
watch about group or set about
در مورد توضیحات گروه میدهد و یا توضیحات گروه رو تعیین کنید
!res @username
see Username INfo
در مورد اسم و ای دی شخص بهتون میده
!who♦️
Get Ids Chat
امی ای دی های موجود در چت رو بهتون میده
!log
get members id ♠️
تمامی فعالیت های انجام یافته توسط شما و یا مدیران رو نشون میده
!all
Says every thing he knows about a group
در مورد تمامی اطلاعات ثبت شده در مورد گروه میدهد
!newlink
Changes or Makes new group link
لینک گروه رو عوض میکنه
!getlink
gets The Group link
لینک گروه را در گروه نمایش میده
!linkpv
sends the group link to the PV
برای دریافت لینک در پیوی استفاده میشه
〰〰〰〰〰〰〰〰
Admins :®
!add
to add the group as knows
برای مجوز دادن به ربات برای استفاده در گروه
!rem
to remove the group and be unknown
برای ناشناس کردن گروه برای ربات توسط مدیران اصلی
!setgpowner (Gpid) user_id ⚫️
For Set a Owner of group from realm
برای تعیین سازنده ای برای گروه از گروه مادر
!addadmin [Username]
to add a Global admin to the bot
برای ادد کردن ادمین اصلی ربات
!removeadmin [username]
to remove an admin from global admins
برای صلب ادمینی از ادمینای اصلی
!plugins - [plugins]
To Disable the plugin
برای غیر فعال کردن پلاگین توسط سازنده
!plugins + [plugins]
To enable a plugins
برای فعال کردن چلاگین توسط سازنده
!plugins ?
To reload al plugins
رای تازه سازی تمامی پلاگین های فعال
!plugins
Shows the list of all plugins
لیست تمامی پلاگین هارو نشون میده
!sms [id] (text)
To send a message to an account by his/her ID
برای فرستادن متنی توسط ربات به شخصی با ای دی اون
〰〰〰〰〰〰〰〰〰〰〰
3. Stats :©
!stats creedbot (sudoers)✔️
To see the stats of creed bot
برای دیدن آمار ربات
!stats
To see the group stats
برای دیدن آمار گروه
〰〰〰〰〰〰〰〰
4. Feedback⚫️
!feedback (text)
To send your ideas to the Moderation group
برای فرستادن انتقادات و پیشنهادات و حرف خود با مدیر ها استفاده میشه
〰〰〰〰〰〰〰〰〰〰〰
5. Tagall◻️
!tagall (text)
To tags the every one and sends your message at bottom
تگ کردن همه ی اعضای گروه و نوشتن پیام شما زیرش
〰〰〰〰〰〰〰〰〰
More plugins soon ...
⚠️ We are Creeds ⚠️
our channel : @creedantispam_channel
کانال ما
You Can user both "!" & "/" for them
می توانید از دو شکلک ! و / برای دادن دستورات استفاده کنید
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Norg/npcs/Aeka.lua | 18 | 3050 | -----------------------------------
-- Area: Norg
-- NPC: Aeka
-- Involved in Quest: Forge Your Destiny
-- @zone 252
-- @pos 4 0 -4
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
questItem = player:getVar("ForgeYourDestiny_Event");
checkItem = testflag(tonumber(questItem),0x01);
if(checkItem == true) then
if(trade:hasItemQty(645,1) and trade:getItemCount() == 1) then
player:startEvent(0x002f,0,1151,645); -- Oriental Steel, Darksteel Ore
end
end
end;
-----------------------------------
-- Event Check
-----------------------------------
function testflag(set,flag)
return (set % (2*flag) >= flag)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
swordTimer = player:getVar("ForgeYourDestiny_timer")
if(player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED and swordTimer == 0) then
if(player:hasItem(1152)) then
player:startEvent(0x0030,1152); -- Bomb Steel
elseif(player:hasItem(1151) == false) then
questItem = player:getVar("ForgeYourDestiny_Event");
checkItem = testflag(tonumber(questItem),0x01);
if(checkItem == false) then
player:startEvent(0x002c,1152,1151); -- Bomb Steel, Oriental Steel
elseif(checkItem == true) then
player:startEvent(0x002e,0,1151,645); -- Oriental Steel, Darksteel Ore
end
elseif(player:hasItem(1151)) then
player:startEvent(0x002d,1152,1151); -- Bomb Steel, Oriental Steel
end
elseif(swordTimer > 0) then
player:startEvent(0x0032);
else
player:startEvent(0x0078);
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);
questItem = player:getVar("ForgeYourDestiny_Event");
if(csid == 0x002c) then
if(player:getFreeSlotsCount(0) >= 1) then
player:addItem(1151);
player:messageSpecial(ITEM_OBTAINED, 1151); -- Oriental Steel
player:setVar("ForgeYourDestiny_Event",questItem + 0x01);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1151); -- Oriental Steel
end
elseif(csid == 0x002f) then
if(player:getFreeSlotsCount(0) >= 1) then
player:tradeComplete();
player:addItem(1151);
player:messageSpecial(ITEM_OBTAINED, 1151); -- Oriental Steel
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1151); -- Oriental Steel
end
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/weaponskills/trueflight.lua | 6 | 1939 | -----------------------------------
-- Skill Level: N/A
-- Description: Deals light elemental damage. Damage varies with TP. Gastraphetes: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Ranger) quest.
-- Does not work with Flashy Shot.
-- Does not work with Stealth Shot.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Properties
-- Element: Light
-- Skillchain Properties: Fragmentation/Scission
-- Modifiers: AGI:30%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 4.0 4.25 4.75
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0;
params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
params.ele = ELE_LIGHT;
params.skill = SKILL_MRK;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 3.8906; params.ftp200 = 6.3906; params.ftp300 = 9.3906;
params.agi_wsc = 1.0;
end
local damage, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
if ((player:getEquipID(SLOT_RANGED) == 19001) and (player:getMainJob() == JOB_RNG)) then
if (damage > 0) then
local params = initAftermathParams()
params.subpower.lv1 = 3
params.subpower.lv2 = 4
params.subpower.lv3 =2
applyAftermathEffect(player, tp, params)
end
end
return tpHits, extraHits, criticalHit, damage;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/effects/dex_down.lua | 19 | 1086 | -----------------------------------
--
-- EFFECT_DEX_DOWN
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if((target:getStat(MOD_DEX) - effect:getPower()) < 0) then
effect:setPower(target:getStat(MOD_DEX));
end
target:addMod(MOD_DEX,-effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
-- the effect restore dexterity of 1 every 3 ticks.
local downDEX_effect_size = effect:getPower()
if(downDEX_effect_size > 0) then
effect:setPower(downDEX_effect_size - 1)
target:delMod(MOD_DEX,-1);
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
downDEX_effect_size = effect:getPower()
if(downDEX_effect_size > 0) then
target:delMod(MOD_DEX,-downDEX_effect_size);
end
end;
| gpl-3.0 |
bowlofstew/Macaroni | Next/Tests/Features/BoostBuild/SomeApp/project.lua | 2 | 3012 | --------------------------------------------------------------------------------
-- Plugins
--------------------------------------------------------------------------------
porg = plugins:Get("Porg")
cpp = plugins:Get("Cpp")
html = plugins:Get("HtmlView")
bjam = plugins:Get("BoostBuild2")
--------------------------------------------------------------------------------
-- Dependencies
--------------------------------------------------------------------------------
-- Added to init.lua:
boost_version = properties.boost.version
boost = load("Macaroni", "Boost-headers", boost_version):Target("lib")
cppstd = load("Macaroni", "CppStd", "2003"):Target("lib")
someLibB = load("Macaroni.Tests", "Features-BoostBuild-SomeLibB", "1.0.0.0")
:Target("lib")
someLibA = load("Macaroni.Tests", "Features-BoostBuild-SomeLibA", "1.0.0.0")
:Target("lib")
--------------------------------------------------------------------------------
-- File Paths
--------------------------------------------------------------------------------
sourcePath = "Source"
outputPath = "Target"
--------------------------------------------------------------------------------
-- Project Model Information
--------------------------------------------------------------------------------
project = context:Group("Macaroni.Tests")
:Project("Features-BoostBuild-SomeApp")
:Version("1.0.0.0");
lib = project:Library{
name = "lib",
headers = pathList{sourcePath, outputPath},
sources = pathList{sourcePath},
dependencies = {
cppstd,
boost,
someLibB,
someLibA
}
}
local testSrc = Macaroni.IO.Path.New("Tests")
--TODO: Make this work. Can't pull in Boost Test framework at the moment.
--lib:AddTest("Test", testSrc:NewPathForceSlash("Test.cpp"))
lib:AddExe("Start", testSrc:NewPathForceSlash("Start.cpp"))
porg:Run("Generate", {target=lib})
--------------------------------------------------------------------------------
-- Actions
--------------------------------------------------------------------------------
generated = false
built = false
installed = false
function clean()
local dir = Macaroni.IO.Path.New(outputPath)
dir:ClearDirectoryContents();
end
function generate()
if generated then return end
local outputPath = filePath(outputPath)
cpp:Run("Generate", { projectVersion=project, path=outputPath })
html:Run("Generate", { target=lib, path=outputPath})
bjam:Run("Generate", { jamroot=outputPath:NewPath("/jamroot.jam"),
projectVersion=project,
output=output
})
generated = true
end
function build()
if built then return end
generate()
os.execute("bjam " .. properties.bjam_options .. " " .. outputPath)
built = true
end
function install()
if installed then return end
sinstall(project, filePath("./"))
installed = true
end
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Cloister_of_Gales/Zone.lua | 32 | 1656 | -----------------------------------
--
-- Zone: Cloister_of_Gales (201)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Gales/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Gales/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-399.541,-1.697,-420,252);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/abilities/rapture.lua | 27 | 1094 | -----------------------------------
-- Ability: Rapture
-- Enhances the potency of your next white magic spell.
-- Obtained: Scholar Level 55
-- Recast Time: Stratagem Charge
-- Duration: 1 white magic spell or 60 seconds, whichever occurs first
--
-- Level |Charges |Recharge Time per Charge
-- ----- -------- ---------------
-- 10 |1 |4:00 minutes
-- 30 |2 |2:00 minutes
-- 50 |3 |1:20 minutes
-- 70 |4 |1:00 minute
-- 90 |5 |48 seconds
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_RAPTURE) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
player:addStatusEffect(EFFECT_RAPTURE,1,0,60);
return EFFECT_RAPTURE;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/bundle_of_shirataki.lua | 35 | 1199 | -----------------------------------------
-- ID: 5237
-- Item: Bundle of Shirataki
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Strength -3
-- Mind 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5237);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, -3);
target:addMod(MOD_MND, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, -3);
target:delMod(MOD_MND, 1);
end;
| gpl-3.0 |
Mashape/kong | kong/plugins/oauth2/migrations/003_130_to_140.lua | 2 | 1447 | return {
postgres = {
up = [[
DO $$
BEGIN
ALTER TABLE IF EXISTS ONLY oauth2_credentials ADD tags TEXT[];
EXCEPTION WHEN DUPLICATE_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS oauth2_credentials_tags_idex_tags_idx ON oauth2_credentials USING GIN(tags);
EXCEPTION WHEN UNDEFINED_COLUMN THEN
-- Do nothing, accept existing state
END$$;
DROP TRIGGER IF EXISTS oauth2_credentials_sync_tags_trigger ON oauth2_credentials;
DO $$
BEGIN
CREATE TRIGGER oauth2_credentials_sync_tags_trigger
AFTER INSERT OR UPDATE OF tags OR DELETE ON oauth2_credentials
FOR EACH ROW
EXECUTE PROCEDURE sync_tags();
EXCEPTION WHEN UNDEFINED_COLUMN OR UNDEFINED_TABLE THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS oauth2_authorization_codes_ttl_idx ON oauth2_authorization_codes (ttl);
EXCEPTION WHEN UNDEFINED_TABLE THEN
-- Do nothing, accept existing state
END$$;
DO $$
BEGIN
CREATE INDEX IF NOT EXISTS oauth2_tokens_ttl_idx ON oauth2_tokens (ttl);
EXCEPTION WHEN UNDEFINED_TABLE THEN
-- Do nothing, accept existing state
END$$;
]],
},
cassandra = {
up = [[
ALTER TABLE oauth2_credentials ADD tags set<text>;
]],
}
}
| apache-2.0 |
nesstea/darkstar | scripts/zones/La_Theine_Plateau/npcs/Faurbellant.lua | 13 | 1759 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Faurbellant
-- Type: Quest NPC
-- Involved in Quest: Gates of Paradise
-- @pos 484 24 -89 102
-----------------------------------
package.loaded["scripts/zones/La_Theine_Plateau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/La_Theine_Plateau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gates = player:getQuestStatus(SANDORIA,GATES_TO_PARADISE);
if (gates == QUEST_COMPLETED) then
player:showText(npc, FAURBELLANT_4);
elseif (gates == QUEST_ACCEPTED) then
if (player:hasKeyItem(SCRIPTURE_OF_WIND) == true) then
player:showText(npc, FAURBELLANT_2, 0, SCRIPTURE_OF_WIND);
player:delKeyItem(SCRIPTURE_OF_WIND);
player:addKeyItem(SCRIPTURE_OF_WATER);
player:messageSpecial(KEYITEM_OBTAINED, SCRIPTURE_OF_WATER)
else
player:showText(npc, FAURBELLANT_3, SCRIPTURE_OF_WATER);
end;
else
player:showText(npc, FAURBELLANT_1);
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 |
jj918160/cocos2d-x-samples | samples/FantasyWarrior3D/frameworks/runtime-src/Classes/custom/api/DrawNode3D.lua | 9 | 2791 |
--------------------------------
-- @module DrawNode3D
-- @extend Node
-- @parent_module cc
--------------------------------
-- js NA<br>
-- lua NA
-- @function [parent=#DrawNode3D] getBlendFunc
-- @param self
-- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc)
--------------------------------
-- code<br>
-- When this function bound into js or lua,the parameter will be changed<br>
-- In js: var setBlendFunc(var src, var dst)<br>
-- endcode<br>
-- lua NA
-- @function [parent=#DrawNode3D] setBlendFunc
-- @param self
-- @param #cc.BlendFunc blendFunc
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
-- Draw 3D Line
-- @function [parent=#DrawNode3D] drawLine
-- @param self
-- @param #vec3_table from
-- @param #vec3_table to
-- @param #color4f_table color
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
-- Clear the geometry in the node's buffer.
-- @function [parent=#DrawNode3D] clear
-- @param self
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
--
-- @function [parent=#DrawNode3D] onDraw
-- @param self
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
--
-- @function [parent=#DrawNode3D] init
-- @param self
-- @return bool#bool ret (return value: bool)
--------------------------------
-- Draw 3D cube<br>
-- param point to a vertex array who has 8 element.<br>
-- vertices[0]:Left-top-front,<br>
-- vertices[1]:Left-bottom-front,<br>
-- vertices[2]:Right-bottom-front,<br>
-- vertices[3]:Right-top-front,<br>
-- vertices[4]:Right-top-back,<br>
-- vertices[5]:Right-bottom-back,<br>
-- vertices[6]:Left-bottom-back,<br>
-- vertices[7]:Left-top-back.<br>
-- param color
-- @function [parent=#DrawNode3D] drawCube
-- @param self
-- @param #vec3_table vertices
-- @param #color4f_table color
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
-- creates and initialize a DrawNode3D node
-- @function [parent=#DrawNode3D] create
-- @param self
-- @return DrawNode3D#DrawNode3D ret (return value: cc.DrawNode3D)
--------------------------------
--
-- @function [parent=#DrawNode3D] draw
-- @param self
-- @param #cc.Renderer renderer
-- @param #mat4_table transform
-- @param #unsigned int flags
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
--------------------------------
--
-- @function [parent=#DrawNode3D] DrawNode3D
-- @param self
-- @return DrawNode3D#DrawNode3D self (return value: cc.DrawNode3D)
return nil
| mit |
UnfortunateFruit/darkstar | scripts/zones/Port_Bastok/npcs/Kagetora.lua | 17 | 1720 | -----------------------------------
-- Area: Port Bastok
-- NPC: Kagetora
-- Involved in Quest: Ayame and Kaede, 20 in Pirate Years
-- @zone 236
-- @pos -96 -2 29
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(BASTOK,AYAME_AND_KAEDE) == QUEST_ACCEPTED) then
AyameAndKaede = player:getVar("AyameAndKaede_Event");
if(AyameAndKaede == 0) then
player:startEvent(0x00f1);
elseif(AyameAndKaede > 2) then
player:startEvent(0x00f4);
else
player:startEvent(0x0017);
end
elseif(player:getVar("twentyInPirateYearsCS") == 1) then
player:startEvent(0x0105);
else
player:startEvent(0x0017);
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 == 0x00f1) then
player:setVar("AyameAndKaede_Event",1);
elseif(csid == 0x0105) then
player:setVar("twentyInPirateYearsCS",2);
end
end; | gpl-3.0 |
0xd4d/iced | src/rust/iced-x86-lua/lua/types/iced_x86/Encoder.lua | 1 | 5725 | -- SPDX-License-Identifier: MIT
-- Copyright (C) 2018-present iced project and contributors
-- ⚠️This file was generated by GENERATOR!🦹♂️
---@meta
---@diagnostic disable unused-local
---Encodes instructions decoded by the decoder or instructions created by other code.
---See also `BlockEncoder` which can encode any number of instructions.
---
---@class Encoder
local Encoder = {}
---Encodes instructions decoded by the decoder or instructions created by other code.
---
---See also `BlockEncoder` which can encode any number of instructions.
---
---@param bitness integer #16, 32 or 64
---@param capacity? integer #(default = 0) Initial capacity of the byte buffer
---@return Encoder
---
---# Examples
---
---```lua
---local Decoder = require("iced_x86.Decoder")
---local Encoder = require("iced_x86.Encoder")
---
----- xchg ah,[rdx+rsi+16h]
---local data = "\134\100\050\022"
---local decoder = Decoder.new(64, data, nil, 0x12345678)
---local instr = decoder:decode()
---
---local encoder = Encoder.new(64)
---local instr_len = encoder:encode(instr, 0x55555555)
---assert(instr_len == 4)
---
----- We're done, take ownership of the buffer
---local buffer = encoder:take_buffer()
---assert(buffer == "\134\100\050\022")
---```
function Encoder.new(bitness, capacity) end
---Encodes an instruction and returns the size of the encoded instruction
---
---Error if it failed to encode the instruction (eg. a target branch / RIP-rel operand is too far away)
---
---@param instruction Instruction #Instruction to encode
---@param rip integer #(`u64`) `RIP` of the encoded instruction
---@return integer #Size of the encoded instruction
---
---# Examples
---
---```lua
---local Decoder = require("iced_x86.Decoder")
---local Encoder = require("iced_x86.Encoder")
---
----- je short $+4
---local data = "\117\002"
---local decoder = Decoder.new(64, data, nil, 0x12345678)
---local instr = decoder:decode()
---
---local encoder = Encoder.new(64)
----- Use a different IP (orig rip + 0x10)
---local instr_len = encoder:encode(instr, 0x12345688)
---assert(instr_len == 2)
---
----- We're done, take ownership of the buffer
---local buffer = encoder:take_buffer()
---assert(buffer == "\117\242")
---```
function Encoder:encode(instruction, rip) end
---Writes a byte to the output buffer
---
---@param value integer #(`u8`) Value to write
---
---# Examples
---
---```lua
---local Decoder = require("iced_x86.Decoder")
---local Encoder = require("iced_x86.Encoder")
---
----- je short $+4
---local data = "\117\002"
---local decoder = Decoder.new(64, data, nil, 0x12345678)
---local instr = decoder:decode()
---
---local encoder = Encoder.new(64)
----- Add a random byte
---encoder:write_u8(0x90)
---
----- Use a different IP (orig rip + 0x10)
---local instr_len = encoder:encode(instr, 0x12345688)
---assert(instr_len == 2)
---
----- Add a random byte
---encoder:write_u8(0x90)
---
----- We're done, take ownership of the buffer
---local buffer = encoder:take_buffer()
---assert(buffer == "\144\117\242\144")
---```
function Encoder:write_u8(value) end
---Returns the buffer and initializes the internal buffer to an empty array.
---
---Should be called when you've encoded all instructions and need the raw instruction bytes.
---
---@return string #The encoded instructions
function Encoder:take_buffer() end
---Gets the offsets of the constants (memory displacement and immediate) in the encoded instruction.
---
---The caller can use this information to add relocations if needed.
---
---@return ConstantOffsets #Offsets and sizes of immediates
function Encoder:get_constant_offsets() end
---Disables 2-byte VEX encoding and encodes all VEX instructions with the 3-byte VEX encoding
---
---@return boolean
function Encoder:prevent_vex2() end
---Disables 2-byte VEX encoding and encodes all VEX instructions with the 3-byte VEX encoding
---
---@param new_value boolean #New value
function Encoder:set_prevent_vex2(new_value) end
---Value of the `VEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@return integer
function Encoder:vex_wig() end
---Value of the `VEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@param new_value integer #New value
function Encoder:set_vex_wig(new_value) end
---Value of the `VEX.L` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@return integer
function Encoder:vex_lig() end
---Value of the `VEX.L` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@param new_value integer #New value
function Encoder:set_vex_lig(new_value) end
---Value of the `EVEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@return integer
function Encoder:evex_wig() end
---Value of the `EVEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@param new_value integer #New value
function Encoder:set_evex_wig(new_value) end
---Value of the `EVEX.L'L` bits to use if it's an instruction that ignores the bits. Default is 0.
---
---@return integer
function Encoder:evex_lig() end
---Value of the `EVEX.L'L` bits to use if it's an instruction that ignores the bits. Default is 0.
---
---@param new_value integer #New value
function Encoder:set_evex_lig(new_value) end
---Value of the `MVEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@return integer
function Encoder:mvex_wig() end
---Value of the `MVEX.W` bit to use if it's an instruction that ignores the bit. Default is 0.
---
---@param new_value integer #New value
function Encoder:set_mvex_wig(new_value) end
---Gets the bitness (16, 32 or 64)
---
---@return integer
function Encoder:bitness() end
return Encoder
| mit |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Woods/npcs/Umumu.lua | 34 | 2869 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Umumu
-- Involved In Quest: Making Headlines
-- @pos 32.575 -5.250 141.372 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
local MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,3) == false) then
player:startEvent(0x02db);
elseif (MakingHeadlines == 1) then
local prog = player:getVar("QuestMakingHeadlines_var");
-- Variable to track if player has talked to 4 NPCs and a door
-- 1 = Kyume
-- 2 = Yujuju
-- 4 = Hiwom
-- 8 = Umumu
-- 16 = Mahogany Door
if (testflag(tonumber(prog),16) == true) then
player:startEvent(0x017f); -- Advised to go to Naiko
elseif (testflag(tonumber(prog),8) == false) then
player:startEvent(0x017d); -- Get scoop and asked to validate
else
player:startEvent(0x017e); -- Reminded to validate
end
elseif (MakingHeadlines == 2) then
local rand = math.random(1,3);
if (rand == 1) then
player:startEvent(0x0181); -- Conversation after quest completed
elseif (rand == 2) then
player:startEvent(0x0182); -- Conversation after quest completed
elseif (rand == 3) then
player:startEvent(0x019e); -- Standard Conversation
end
else
player:startEvent(0x019e); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x017d) then
prog = player:getVar("QuestMakingHeadlines_var");
player:addKeyItem(WINDURST_WOODS_SCOOP);
player:messageSpecial(KEYITEM_OBTAINED,WINDURST_WOODS_SCOOP);
player:setVar("QuestMakingHeadlines_var",prog+8);
elseif (csid == 0x02db) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",3,true);
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/abilities/chi_blast.lua | 30 | 1077 | -----------------------------------
-- Ability: Chi Blast
-- Releases Chi to attack an enemy.
-- Obtained: Monk Level 41
-- Recast Time: 3:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local boost = player:getStatusEffect(EFFECT_BOOST);
local multiplier = 1.0;
if (boost ~= nil) then
multiplier = (boost:getPower()/100) * 4; --power is the raw % atk boost
end
local dmg = math.floor(player:getStat(MOD_MND)*(0.5+(math.random()/2))) * multiplier;
dmg = utils.stoneskin(target, dmg);
target:delHP(dmg);
target:updateClaim(player);
target:updateEnmityFromDamage(player,dmg);
player:delStatusEffect(EFFECT_BOOST);
return dmg;
end;
| gpl-3.0 |
xpol/luv | examples/echo-server-client.lua | 10 | 1516 | local p = require('lib/utils').prettyPrint
local uv = require('luv')
local function create_server(host, port, on_connection)
local server = uv.new_tcp()
p(1, server)
uv.tcp_bind(server, host, port)
uv.listen(server, 128, function(err)
assert(not err, err)
local client = uv.new_tcp()
uv.accept(server, client)
on_connection(client)
end)
return server
end
local server = create_server("0.0.0.0", 0, function (client)
p("new client", client, uv.tcp_getsockname(client), uv.tcp_getpeername(client))
uv.read_start(client, function (err, chunk)
p("onread", {err=err,chunk=chunk})
-- Crash on errors
assert(not err, err)
if chunk then
-- Echo anything heard
uv.write(client, chunk)
else
-- When the stream ends, close the socket
uv.close(client)
end
end)
end)
local address = uv.tcp_getsockname(server)
p("server", server, address)
local client = uv.new_tcp()
uv.tcp_connect(client, "127.0.0.1", address.port, function (err)
assert(not err, err)
uv.read_start(client, function (err, chunk)
p("received at client", {err=err,chunk=chunk})
assert(not err, err)
if chunk then
uv.shutdown(client)
p("client done shutting down")
else
uv.close(client)
uv.close(server)
end
end)
p("writing from client")
uv.write(client, "Hello")
uv.write(client, "World")
end)
-- Start the main event loop
uv.run()
-- Close any stray handles when done
uv.walk(uv.close)
uv.run()
uv.loop_close()
| apache-2.0 |
gabealmer/dotfiles | hammerspoon/init.lua | 1 | 3603 | local mash = {
split = {"ctrl", "alt", "cmd"},
corner = {"ctrl", "alt", "shift"},
focus = {"ctrl", "alt"}
}
-- Resize windows
local function adjust(x, y, w, h)
return function()
local win = hs.window.focusedWindow()
if not win then return end
local f = win:frame()
local max = win:screen():frame()
f.w = math.floor(max.w * w)
f.h = math.floor(max.h * h)
f.x = math.floor((max.w * x) + max.x)
f.y = math.floor((max.h * y) + max.y)
win:setFrame(f)
end
end
-- top half
hs.hotkey.bind(mash.split, "K", adjust(0, 0, 1, 0.5))
-- -- right half
hs.hotkey.bind(mash.split, "L", adjust(0.5, 0, 0.5, 1))
-- -- bottom half
hs.hotkey.bind(mash.split, "J", adjust(0, 0.5, 1, 0.5))
-- -- left half
hs.hotkey.bind(mash.split, "H", adjust(0, 0, 0.5, 1))
-- -- top left
hs.hotkey.bind(mash.corner, "J", adjust(0, 0, 0.5, 0.5))
-- -- top right
hs.hotkey.bind(mash.corner, "K", adjust(0.5, 0, 0.5, 0.5))
-- -- bottom right
hs.hotkey.bind(mash.corner, "L", adjust(0.5, 0.5, 0.5, 0.5))
-- -- bottom left
hs.hotkey.bind(mash.corner, "H", adjust(0, 0.5, 0.5, 0.5))
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "R", function()
hs.reload()
end)
hs.alert.show("Config loaded")
hs.hotkey.bind({"cmd", "alt", "ctrl"}, "M", function()
local win = hs.window.focusedWindow()
win:maximize()
end)
-- hs.hotkey.bind({"cmd"}, "J", function()
-- local app = hs.application.frontmostApplication()
-- if app:name() == "Mail" then
-- hs.eventtap.keyStroke({}, "down")
-- end
-- end)
--hs.hotkey.bind({"cmd"}, "K", function()
-- local app = hs.application.frontmostApplication()
-- if app:name() == "Mail" then
-- hs.eventtap.keyStroke({}, "up")
-- end
--end)
local function appl(appName)
return function()
hs.application.launchOrFocus(appName)
end
end
-- hs.hotkey.bind(mash.focus, "H", appl("HipChat"))
-- hs.hotkey.bind(mash.focus, "B", appl("Safari"))
-- hs.hotkey.bind(mash.focus, "M", appl("Mail"))
-- hs.hotkey.bind(mash.focus, "I", appl("iTerm"))
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "H", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
--
-- f.x = max.x
-- f.y = max.y
-- f.w = max.w / 2
-- f.h = max.h
-- win:setFrame(f)
-- end)
--
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "J", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
--
-- f.x = max.x
-- f.y = max.y + (max.h / 2)
-- f.w = max.w
-- f.h = max.h / 2
-- win:setFrame(f)
-- end)
--
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "K", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
--
-- f.x = max.x
-- f.y = max.y
-- f.w = max.w
-- f.h = max.h / 2
-- win:setFrame(f)
-- end)
--
-- hs.hotkey.bind({"cmd", "alt", "ctrl"}, "L", function()
-- local win = hs.window.focusedWindow()
-- local f = win:frame()
-- local screen = win:screen()
-- local max = screen:frame()
--
-- f.x = max.x + (max.w / 2)
-- f.y = max.y
-- f.w = max.w / 2
-- f.h = max.h
-- win:setFrame(f)
-- end)
--
hs.hotkey.bind({"shift", "cmd", "alt", "ctrl"}, "H", function()
local win = hs.window.focusedWindow()
local nextScreen = win:screen():previous()
win:moveToScreen(nextScreen)
end)
hs.hotkey.bind({"shift", "cmd", "alt", "ctrl"}, "L", function()
local win = hs.window.focusedWindow()
local nextScreen = win:screen():next()
win:moveToScreen(nextScreen)
end)
| mit |
nesstea/darkstar | scripts/globals/items/slice_of_lynx_meat.lua | 18 | 1344 | -----------------------------------------
-- ID: 5667
-- Item: Slice of Lynx Meat
-- Food Effect: 5 Min, Galka only
-----------------------------------------
-- Strength 5
-- Intelligence -7
-----------------------------------------
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,5667);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_INT, -7);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_INT, -7);
end;
| gpl-3.0 |
focusworld/aabb | plugins/youtube.lua | 644 | 1722 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
function get_yt_data (yt_code)
local url = 'https://www.googleapis.com/youtube/v3/videos?'
url = url .. 'id=' .. URL.escape(yt_code) .. '&part=snippet'
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
return httpsRequest(url)
end
function send_youtube_data(data, receiver)
local title = data.title
local description = data.description
local uploader = data.channelTitle
local text = title..' ('..uploader..')\n'..description
local image_url = data.thumbnails.high.url or data.thumbnails.default.url
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
function run(msg, matches)
local yt_code = matches[1]
local data = get_yt_data(yt_code)
if data == nil or #data.items == 0 then
return "I didn't find info about that video."
end
local senddata = data.items[1].snippet
local receiver = get_receiver(msg)
send_youtube_data(senddata, receiver)
end
return {
description = "Sends YouTube info and image.",
usage = "",
patterns = {
"youtu.be/([_A-Za-z0-9-]+)",
"youtube.com/watch%?v=([_A-Za-z0-9-]+)",
},
run = run
}
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Cloister_of_Tremors/Zone.lua | 32 | 1667 | -----------------------------------
--
-- Zone: Cloister_of_Tremors (209)
--
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Tremors/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Cloister_of_Tremors/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-636.001,-16.563,-500.023,205);
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 |
heyuqi/wxFormBuilder | sdk/plugin_interface/premake.lua | 1 | 8815 | --*****************************************************************************
--* Author: RJP Computing <rjpcomputing@gmail.com>
--* Date: 12/15/2006
--* Version: 1.00-beta
--* Copyright (C) 2006 RJP Computing
--*
--* 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.
--*
--* NOTES:
--* - use the '/' slash for all paths.
--*****************************************************************************
-- wxWidgets version
local wx_ver = "28"
--******* Initial Setup ************
--* Most of the setting are set here.
--**********************************
-- Set the name of your package.
package.name = "plugin-interface"
-- Set this if you want a different name for your target than the package's name.
local targetName = "fbPluginInterface"
-- Set the kind of package you want to create.
-- Options: exe | winexe | lib | dll
package.kind = "lib"
-- Set the files to include.
package.files = { matchrecursive( "*.cpp", "*.h", "*.rc", "*.fbp" ) }
-- Set the include paths.
package.includepaths = { "../tinyxml" }
-- Set the libraries it links to.
package.links = { "TiCPP" }
package.libdir = "../lib"
-- Set the defines.
package.defines = { "TIXML_USE_TICPP" }
-- Hack the dll output to prefix 'lib' to the begining.
package.targetprefix = "lib"
--------------------------- DO NOT EDIT BELOW ----------------------------------
--******* GENAERAL SETUP **********
--* Settings that are not dependant
--* on the operating system.
--*********************************
-- Package options
addoption( "unicode", "Use the Unicode character set" )
addoption( "with-wx-shared", "Link against wxWidgets as a shared library" )
if ( not windows ) then
addoption( "disable-wx-debug", "Compile against a wxWidgets library without debugging" )
end
-- Common setup
package.language = "c++"
-- Set object output directory.
if ( options["unicode"] ) then
package.config["Debug"].objdir = ".objsud"
package.config["Release"].objdir = ".objsu"
else
package.config["Debug"].objdir = ".objsd"
package.config["Release"].objdir = ".objs"
end
-- Set debug flags
if ( options["disable-wx-debug"] and ( not windows ) ) then
debug_option = "--debug=no"
debug_macro = { "NDEBUG", "__WXFB_DEBUG__" }
else
debug_option = "--debug=yes"
debug_macro = { "DEBUG", "_DEBUG", "__WXDEBUG__", "__WXFB_DEBUG__"}
end
-- Set the default targetName if none is specified.
if ( string.len( targetName ) == 0 ) then
targetName = package.name
end
-- Set the targets.
package.config["Release"].target = targetName
package.config["Debug"].target = targetName.."d"
-- Set the build options.
package.buildflags = { "extra-warnings" }
package.config["Release"].buildflags = { "no-symbols", "optimize-speed" }
if ( options["unicode"] ) then
table.insert( package.buildflags, "unicode" )
end
if ( string.find( target or "", ".*-gcc" ) or target == "gnu" ) then
table.insert( package.config["Debug"].buildoptions, "-O0" )
table.insert( package.config["Release"].buildoptions, "-fno-strict-aliasing" )
end
-- Set the defines.
if ( options["with-wx-shared"] ) then
table.insert( package.defines, "WXUSINGDLL" )
end
if ( options["unicode"] ) then
table.insert( package.defines, { "UNICODE", "_UNICODE" } )
end
table.insert( package.defines, "__WX__" )
table.insert( package.config["Debug"].defines, debug_macro )
table.insert( package.config["Release"].defines, "NDEBUG" )
if ( windows ) then
--******* WINDOWS SETUP ***********
--* Settings that are Windows specific.
--*********************************
-- Set wxWidgets include paths
if ( target == "cb-gcc" ) then
table.insert( package.includepaths, "$(#WX.include)" )
else
table.insert( package.includepaths, "$(WXWIN)/include" )
end
-- Set the correct 'setup.h' include path.
if ( options["with-wx-shared"] ) then
if ( options["unicode"] ) then
if ( target == "cb-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_dll/mswud" )
table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_dll/mswu" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_dll/mswud" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_dll/mswu" )
else
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_dll/mswud" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_dll/mswu" )
end
else
if ( target == "cb-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_dll/mswd" )
table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_dll/msw" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_dll/mswd" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_dll/msw" )
else
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_dll/mswd" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_dll/msw" )
end
end
else
if ( options["unicode"] ) then
if ( target == "cb-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_lib/mswud" )
table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_lib/mswu" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_lib/mswud" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_lib/mswu" )
else
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_lib/mswud" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_lib/mswu" )
end
else
if ( target == "cb-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(#WX.lib)/gcc_lib/mswd" )
table.insert( package.config["Release"].includepaths, "$(#WX.lib)/gcc_lib/msw" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/gcc_lib/mswd" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/gcc_lib/msw" )
else
table.insert( package.config["Debug"].includepaths, "$(WXWIN)/lib/vc_lib/mswd" )
table.insert( package.config["Release"].includepaths, "$(WXWIN)/lib/vc_lib/msw" )
end
end
end
-- Set the linker options.
if ( options["with-wx-shared"] ) then
if ( target == "cb-gcc" ) then
table.insert( package.libpaths, "$(#WX.lib)/gcc_dll" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.libpaths, "$(WXWIN)/lib/gcc_dll" )
else
table.insert( package.libpaths, "$(WXWIN)/lib/vc_dll" )
end
else
if ( target == "cb-gcc" ) then
table.insert( package.libpaths, "$(#WX.lib)/gcc_lib" )
elseif ( target == "gnu" or target == "cl-gcc" ) then
table.insert( package.libpaths, "$(WXWIN)/lib/gcc_lib" )
else
table.insert( package.libpaths, "$(WXWIN)/lib/vc_lib" )
end
end
-- Set wxWidgets libraries to link.
if ( options["unicode"] ) then
table.insert( package.config["Release"].links, "wxmsw"..wx_ver.."u" )
table.insert( package.config["Debug"].links, "wxmsw"..wx_ver.."ud" )
else
table.insert( package.config["Release"].links, "wxmsw"..wx_ver )
table.insert( package.config["Debug"].links, "wxmsw"..wx_ver.."d" )
end
-- Set the Windows defines.
table.insert( package.defines, { "__WXMSW__", "WIN32", "_WINDOWS" } )
else
--******* LINUX SETUP *************
--* Settings that are Linux specific.
--*********************************
-- Ignore resource files in Linux.
table.insert( package.excludes, matchrecursive( "*.rc" ) )
table.insert( package.buildoptions, "-fPIC" )
-- Set wxWidgets build options.
table.insert( package.config["Debug"].buildoptions, "`wx-config "..debug_option.." --cflags`" )
table.insert( package.config["Release"].buildoptions, "`wx-config --debug=no --cflags`" )
-- Set the wxWidgets link options.
table.insert( package.config["Debug"].linkoptions, "`wx-config "..debug_option.." --libs`" )
table.insert( package.config["Release"].linkoptions, "`wx-config --libs`" )
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Kazham/npcs/Tahn_Posbei.lua | 37 | 1510 | -----------------------------------
-- Area: Kazham
-- NPC: Tahn Posbei
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,TAHNPOSBEI_SHOP_DIALOG);
stock = {0x3001,110, -- Lauan Shield
0x3004,4531, -- Mahogany Shield
0x3007,59607, -- Round Shield
0x30A7,7026, -- Beetle Mask
0x3127,10833, -- Beetle Harness
0x31A7,5707, -- Beetle Mittens
0x3223,8666, -- Beetle Subligar
0x32A7,5332, -- Beetre Leggins
0x3098,404, -- Leather Bandana
0x3118,618, -- Leather Vest
0x3198,331, -- Leather Gloves
0x3298,309, -- Leather Highboots
0x3324,28777} -- Coeurl Gorget
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
ndbeals/Luabox | lua/luabox/ui/filetree_node.lua | 2 | 3516 | local PANEL = {}
PANEL.ClassName = "Luabox_File_Tree_Node"
PANEL.Base = "DTree_Node"
function PANEL:Init()
self.Label.DoDoubleClick = function( lbl )
self:InternalDoDoubleClick()
end
self.Files = {}
self.Directories = {}
end
function PANEL:DoDoubleClick()
end
function PANEL:InternalDoDoubleClick()
self:GetRoot():SetSelectedItem( self )
if ( self:DoDoubleClick() ) then return end
if ( self:GetRoot():DoClick( self ) ) then return end
if self.m_bDoubleClickToOpen then
self:SetExpanded( !self.m_bExpanded )
end
end
function PANEL:InternalDoClick()
self:GetRoot():SetSelectedItem( self )
if ( self:DoClick() ) then return end
if ( self:GetRoot():DoClick( self ) ) then return end
if self.m_bDoubleClickToOpen and (SysTime() - self.fLastClick < 0.2 ) then
self:SetExpanded( !self.m_bExpanded )
end
self.fLastClick = SysTime()
end
function PANEL:AddNode( strName, strIcon )
self:CreateChildNodes()
local pNode = vgui.Create( "Luabox_File_Tree_Node", self )
pNode:SetText( strName )
pNode:SetParentNode( self )
pNode:SetRoot( self:GetRoot() )
pNode:SetIcon( strIcon )
pNode:SetDrawLines( !self:IsRootNode() )
self:InstallDraggable( pNode )
self.ChildNodes:Add( pNode )
self:InvalidateLayout()
return pNode
end
local function expandhelper( node , expanded )
expanded = expanded or {}
for i , v in ipairs( node.ChildNodes:GetChildren() ) do
expanded[ v:GetFileSystem() ] = {Expanded = v:GetExpanded()}
if v.ChildNodes then
expandhelper( v , expanded[v:GetFileSystem()] )
end
end
return expanded
end
function PANEL:SetExpandedRecurse( expanded , supressanim )
supressanim = supressanim or true
if not expanded then return end
self:SetExpanded( expanded.Expanded , supressanim)
for i , v in ipairs( self.ChildNodes:GetChildren() ) do
if #v.Directories > 0 or #v.Files > 0 then
v:SetExpandedRecurse( expanded[ v:GetFileSystem() ] )
end
end
end
function PANEL:SetFileSystem( fs )
self.FileSystem = fs
self.Files = {}
self.Directories = {}
self:CreateChildNodes()
if fs:GetSingleFile() then return end
for i , v in ipairs( fs:GetDirectories() ) do
local node = self:AddNode( v:GetName() )
node:SetFileSystem( v )
self.Directories[ i ] = node
end
for i , v in ipairs( fs:GetFiles() ) do
local node = self:AddNode( v:GetName() , "icon16/page.png")
node:SetFileSystem( v )
self.Files[ i ] = node
end
end
function PANEL:GetFileSystem()
return self.FileSystem
end
function PANEL:Refresh()
if not self.ChildNodes or not self.FileSystem then return end
local wasexpanded = self:GetExpanded() or false
local expanded = expandhelper( self )
local del = self.ChildNodes
self.ChildNodes = nil
self:CreateChildNodes()
del:Remove()
del = nil
self.Files = {}
self.Directories = {}
self.FileSystem:Refresh( true )
for i , v in ipairs( self.FileSystem:GetDirectories() ) do
local node = self:AddNode( v:GetName() )
node:SetFileSystem( v )
if #v.Directories > 0 or #v.Files > 0 then
node:SetExpandedRecurse( expanded[ v ] , true )
end
self.Directories[ i ] = node
end
for i , v in ipairs( self.FileSystem:GetFiles() ) do
local node = self:AddNode( v:GetName() , "icon16/page.png")
node:SetFileSystem( v )
self.Files[ i ] = node
end
end
function PANEL:GetExpanded()
return self.m_bExpanded
end
vgui.Register( PANEL.ClassName , PANEL, PANEL.Base )
| gpl-3.0 |
nesstea/darkstar | scripts/globals/spells/vital_etude.lua | 27 | 1611 | -----------------------------------------
-- Spell: Vital Etude
-- Static VIT Boost, BRD 70
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- 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 = 0;
if (sLvl+iLvl <= 416) then
power = 12;
elseif ((sLvl+iLvl >= 417) and (sLvl+iLvl <= 445)) then
power = 13;
elseif ((sLvl+iLvl >= 446) and (sLvl+iLvl <= 474)) then
power = 14;
elseif (sLvl+iLvl >= 475) then
power = 15;
end
local iBoost = caster:getMod(MOD_ETUDE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_ETUDE,power,10,duration,caster:getID(), MOD_VIT, 2)) then
spell:setMsg(75);
end
return EFFECT_ETUDE;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Arrapago_Reef/npcs/qm6.lua | 42 | 1099 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ??? (corsair job flag quest)
--
-----------------------------------
package.loaded["scripts/zones/Arrapago_Reef/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
LuckOfTheDraw = player:getVar("LuckOfTheDraw");
if (LuckOfTheDraw ==2) then
player:startEvent(0x00D3);
player:setVar("LuckOfTheDraw",3);
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 |
Wedmer/packages | utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/netdev.lua | 66 | 1077 |
local netdevsubstat = {
"receive_bytes_total",
"receive_packets_total",
"receive_errs_total",
"receive_drop_total",
"receive_fifo_total",
"receive_frame_total",
"receive_compressed_total",
"receive_multicast_total",
"transmit_bytes_total",
"transmit_packets_total",
"transmit_errs_total",
"transmit_drop_total",
"transmit_fifo_total",
"transmit_colls_total",
"transmit_carrier_total",
"transmit_compressed_total"
}
local pattern = "([^%s:]+):%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)%s+(%d+)"
local function scrape()
local nds_table = {}
for line in io.lines("/proc/net/dev") do
local t = {string.match(line, pattern)}
if #t == 17 then
nds_table[t[1]] = t
end
end
for i, ndss in ipairs(netdevsubstat) do
netdev_metric = metric("node_network_" .. ndss, "counter")
for dev, nds_dev in pairs(nds_table) do
netdev_metric({device=dev}, nds_dev[i+1])
end
end
end
return { scrape = scrape }
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Port_San_dOria/npcs/Raqtibahl.lua | 13 | 1359 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Raqtibahl
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x802f7);
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 |
nesstea/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Komalata.lua | 13 | 1554 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Komalata
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,KOMALATA_SHOP_DIALOG);
stock = {0x1118,110, -- Meat Jerky
0x03a8,14, -- Rock Salt
0x0263,36, -- Rye Flour
0x119d,10, -- Distilled Water
0x0271,91, -- Apple Vinegar (COP 4+ only)
0x110c,110, -- Black Bread (COP 4+ only)
0x0262,55, -- San d'Orian Flour (COP 4+ only)
0x1125,29, -- San d'Orian Carrot (COP 4+ only)
0x0275,44, -- Millioncorn (COP 4+ only)
0x05f3,290} -- Apple Mint (COP 4+ only)
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
vonflynee/opencomputersserver | world/opencomputers/a3abb948-eba5-4c6b-9388-1bb1f150ed2b/bin/edit.lua | 15 | 16517 | local component = require("component")
local event = require("event")
local fs = require("filesystem")
local keyboard = require("keyboard")
local shell = require("shell")
local term = require("term")
local text = require("text")
local unicode = require("unicode")
if not term.isAvailable() then
return
end
local args, options = shell.parse(...)
if #args == 0 then
io.write("Usage: edit <filename>")
return
end
local filename = shell.resolve(args[1])
local readonly = options.r or fs.get(filename) == nil or fs.get(filename).isReadOnly()
if not fs.exists(filename) then
if fs.isDirectory(filename) then
io.stderr:write("file is a directory")
return
elseif readonly then
io.stderr:write("file system is read only")
return
end
end
local function loadConfig()
-- Try to load user settings.
local env = {}
local config = loadfile("/etc/edit.cfg", nil, env)
if config then
pcall(config)
end
-- Fill in defaults.
env.keybinds = env.keybinds or {
left = {{"left"}},
right = {{"right"}},
up = {{"up"}},
down = {{"down"}},
home = {{"home"}},
eol = {{"end"}},
pageUp = {{"pageUp"}},
pageDown = {{"pageDown"}},
backspace = {{"back"}},
delete = {{"delete"}},
deleteLine = {{"control", "delete"}, {"shift", "delete"}},
newline = {{"enter"}},
save = {{"control", "s"}},
close = {{"control", "w"}},
find = {{"control", "f"}},
findnext = {{"control", "g"}, {"control", "n"}, {"f3"}}
}
-- Generate config file if it didn't exist.
if not config then
local root = fs.get("/")
if root and not root.isReadOnly() then
fs.makeDirectory("/etc")
local f = io.open("/etc/edit.cfg", "w")
if f then
local serialization = require("serialization")
for k, v in pairs(env) do
f:write(k.."="..tostring(serialization.serialize(v, math.huge)).."\n")
end
f:close()
end
end
end
return env
end
term.clear()
term.setCursorBlink(true)
local running = true
local buffer = {}
local scrollX, scrollY = 0, 0
local config = loadConfig()
local getKeyBindHandler -- forward declaration for refind()
local function helpStatusText()
local function prettifyKeybind(label, command)
local keybind = type(config.keybinds) == "table" and config.keybinds[command]
if type(keybind) ~= "table" or type(keybind[1]) ~= "table" then return "" end
local alt, control, shift, key
for _, value in ipairs(keybind[1]) do
if value == "alt" then alt = true
elseif value == "control" then control = true
elseif value == "shift" then shift = true
else key = value end
end
if not key then return "" end
return label .. ": [" ..
(control and "Ctrl+" or "") ..
(alt and "Alt+" or "") ..
(shift and "Shift+" or "") ..
unicode.upper(key) ..
"] "
end
return prettifyKeybind("Save", "save") ..
prettifyKeybind("Close", "close") ..
prettifyKeybind("Find", "find")
end
-------------------------------------------------------------------------------
local function setStatus(value)
local w, h = component.gpu.getResolution()
component.gpu.set(1, h, text.padRight(unicode.sub(value, 1, w - 10), w - 10))
end
local function getSize()
local w, h = component.gpu.getResolution()
return w, h - 1
end
local function getCursor()
local cx, cy = term.getCursor()
return cx + scrollX, cy + scrollY
end
local function line()
local cbx, cby = getCursor()
return buffer[cby]
end
local function setCursor(nbx, nby)
local w, h = getSize()
nby = math.max(1, math.min(#buffer, nby))
local ncy = nby - scrollY
if ncy > h then
term.setCursorBlink(false)
local sy = nby - h
local dy = math.abs(scrollY - sy)
scrollY = sy
component.gpu.copy(1, 1 + dy, w, h - dy, 0, -dy)
for by = nby - (dy - 1), nby do
local str = text.padRight(unicode.sub(buffer[by], 1 + scrollX), w)
component.gpu.set(1, by - scrollY, str)
end
elseif ncy < 1 then
term.setCursorBlink(false)
local sy = nby - 1
local dy = math.abs(scrollY - sy)
scrollY = sy
component.gpu.copy(1, 1, w, h - dy, 0, dy)
for by = nby, nby + (dy - 1) do
local str = text.padRight(unicode.sub(buffer[by], 1 + scrollX), w)
component.gpu.set(1, by - scrollY, str)
end
end
term.setCursor(term.getCursor(), nby - scrollY)
nbx = math.max(1, math.min(unicode.len(line()) + 1, nbx))
local ncx = nbx - scrollX
if ncx > w then
term.setCursorBlink(false)
local sx = nbx - w
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + dx, 1, w - dx, h, -dx, 0)
for by = 1 + scrollY, math.min(h + scrollY, #buffer) do
local str = unicode.sub(buffer[by], nbx - (dx - 1), nbx)
str = text.padRight(str, dx)
component.gpu.set(1 + (w - dx), by - scrollY, str)
end
elseif ncx < 1 then
term.setCursorBlink(false)
local sx = nbx - 1
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1, 1, w - dx, h, dx, 0)
for by = 1 + scrollY, math.min(h + scrollY, #buffer) do
local str = unicode.sub(buffer[by], nbx, nbx + dx)
--str = text.padRight(str, dx)
component.gpu.set(1, by - scrollY, str)
end
end
term.setCursor(nbx - scrollX, nby - scrollY)
component.gpu.set(w - 9, h + 1, text.padLeft(string.format("%d,%d", nby, nbx), 10))
end
local function highlight(bx, by, length, enabled)
local w, h = getSize()
local cx, cy = bx - scrollX, by - scrollY
cx = math.max(1, math.min(w, cx))
cy = math.max(1, math.min(h, cy))
length = math.max(1, math.min(w - cx, length))
local fg, fgp = component.gpu.getForeground()
local bg, bgp = component.gpu.getBackground()
if enabled then
component.gpu.setForeground(bg, bgp)
component.gpu.setBackground(fg, fgp)
end
local value = ""
for x = cx, cx + length - 1 do
value = value .. component.gpu.get(x, cy)
end
component.gpu.set(cx, cy, value)
if enabled then
component.gpu.setForeground(fg, fgp)
component.gpu.setBackground(bg, bgp)
end
end
local function home()
local cbx, cby = getCursor()
setCursor(1, cby)
end
local function ende()
local cbx, cby = getCursor()
setCursor(unicode.len(line()) + 1, cby)
end
local function left()
local cbx, cby = getCursor()
if cbx > 1 then
setCursor(cbx - 1, cby)
return true -- for backspace
elseif cby > 1 then
setCursor(cbx, cby - 1)
ende()
return true -- again, for backspace
end
end
local function right(n)
n = n or 1
local cbx, cby = getCursor()
local be = unicode.len(line()) + 1
if cbx < be then
setCursor(cbx + n, cby)
elseif cby < #buffer then
setCursor(1, cby + 1)
end
end
local function up(n)
n = n or 1
local cbx, cby = getCursor()
if cby > 1 then
setCursor(cbx, cby - n)
if getCursor() > unicode.len(line()) then
ende()
end
end
end
local function down(n)
n = n or 1
local cbx, cby = getCursor()
if cby < #buffer then
setCursor(cbx, cby + n)
if getCursor() > unicode.len(line()) then
ende()
end
end
end
local function delete(fullRow)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
local function deleteRow(row)
local content = table.remove(buffer, row)
local rcy = cy + (row - cby)
if rcy <= h then
component.gpu.copy(1, rcy + 1, w, h - rcy, 0, -1)
component.gpu.set(1, h, text.padRight(buffer[row + (h - rcy)], w))
end
return content
end
if fullRow then
term.setCursorBlink(false)
if #buffer > 1 then
deleteRow(cby)
else
buffer[cby] = ""
component.gpu.fill(1, cy, w, 1, " ")
end
setCursor(1, cby)
elseif cbx <= unicode.len(line()) then
term.setCursorBlink(false)
buffer[cby] = unicode.sub(line(), 1, cbx - 1) ..
unicode.sub(line(), cbx + 1)
component.gpu.copy(cx + 1, cy, w - cx, 1, -1, 0)
local br = cbx + (w - cx)
local char = unicode.sub(line(), br, br)
if not char or unicode.len(char) == 0 then
char = " "
end
component.gpu.set(w, cy, char)
elseif cby < #buffer then
term.setCursorBlink(false)
local append = deleteRow(cby + 1)
buffer[cby] = buffer[cby] .. append
component.gpu.set(cx, cy, append)
else
return
end
setStatus(helpStatusText())
end
local function insert(value)
if not value or unicode.len(value) < 1 then
return
end
term.setCursorBlink(false)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
buffer[cby] = unicode.sub(line(), 1, cbx - 1) ..
value ..
unicode.sub(line(), cbx)
local len = unicode.len(value)
local n = w - (cx - 1) - len
if n > 0 then
component.gpu.copy(cx, cy, n, 1, len, 0)
end
component.gpu.set(cx, cy, value)
right(len)
setStatus(helpStatusText())
end
local function enter()
term.setCursorBlink(false)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
table.insert(buffer, cby + 1, unicode.sub(buffer[cby], cbx))
buffer[cby] = unicode.sub(buffer[cby], 1, cbx - 1)
component.gpu.fill(cx, cy, w - (cx - 1), 1, " ")
if cy < h then
if cy < h - 1 then
component.gpu.copy(1, cy + 1, w, h - (cy + 1), 0, 1)
end
component.gpu.set(1, cy + 1, text.padRight(buffer[cby + 1], w))
end
setCursor(1, cby + 1)
setStatus(helpStatusText())
end
local findText = ""
local function find()
local w, h = getSize()
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local ibx, iby = cbx, cby
while running do
if unicode.len(findText) > 0 then
local sx, sy
for syo = 1, #buffer do -- iterate lines with wraparound
sy = (iby + syo - 1 + #buffer - 1) % #buffer + 1
sx = string.find(buffer[sy], findText, syo == 1 and ibx or 1)
if sx and (sx >= ibx or syo > 1) then
break
end
end
if not sx then -- special case for single matches
sy = iby
sx = string.find(buffer[sy], findText)
end
if sx then
cbx, cby = sx, sy
setCursor(cbx, cby)
highlight(cbx, cby, unicode.len(findText), true)
end
end
term.setCursor(7 + unicode.len(findText), h + 1)
setStatus("Find: " .. findText)
local _, _, char, code = event.pull("key_down")
local handler, name = getKeyBindHandler(code)
highlight(cbx, cby, unicode.len(findText), false)
if name == "newline" then
break
elseif name == "close" then
handler()
elseif name == "backspace" then
findText = unicode.sub(findText, 1, -2)
elseif name == "find" or name == "findnext" then
ibx = cbx + 1
iby = cby
elseif not keyboard.isControl(char) then
findText = findText .. unicode.char(char)
end
end
setCursor(cbx, cby)
setStatus(helpStatusText())
end
-------------------------------------------------------------------------------
local keyBindHandlers = {
left = left,
right = right,
up = up,
down = down,
home = home,
eol = ende,
pageUp = function()
local w, h = getSize()
up(h - 1)
end,
pageDown = function()
local w, h = getSize()
down(h - 1)
end,
backspace = function()
if not readonly and left() then
delete()
end
end,
delete = function()
if not readonly then
delete()
end
end,
deleteLine = function()
if not readonly then
delete(true)
end
end,
newline = function()
if not readonly then
enter()
end
end,
save = function()
if readonly then return end
local new = not fs.exists(filename)
local backup
if not new then
backup = filename .. "~"
for i = 1, math.huge do
if not fs.exists(backup) then
break
end
backup = filename .. "~" .. i
end
fs.copy(filename, backup)
end
local f, reason = io.open(filename, "w")
if f then
local chars, firstLine = 0, true
for _, line in ipairs(buffer) do
if not firstLine then
line = "\n" .. line
end
firstLine = false
f:write(line)
chars = chars + unicode.len(line)
end
f:close()
local format
if new then
format = [["%s" [New] %dL,%dC written]]
else
format = [["%s" %dL,%dC written]]
end
setStatus(string.format(format, fs.name(filename), #buffer, chars))
else
setStatus(reason)
end
if not new then
fs.remove(backup)
end
end,
close = function()
-- TODO ask to save if changed
running = false
end,
find = function()
findText = ""
find()
end,
findnext = find
}
getKeyBindHandler = function(code)
if type(config.keybinds) ~= "table" then return end
-- Look for matches, prefer more 'precise' keybinds, e.g. prefer
-- ctrl+del over del.
local result, resultName, resultWeight = nil, nil, 0
for command, keybinds in pairs(config.keybinds) do
if type(keybinds) == "table" and keyBindHandlers[command] then
for _, keybind in ipairs(keybinds) do
if type(keybind) == "table" then
local alt, control, shift, key
for _, value in ipairs(keybind) do
if value == "alt" then alt = true
elseif value == "control" then control = true
elseif value == "shift" then shift = true
else key = value end
end
if (not alt or keyboard.isAltDown()) and
(not control or keyboard.isControlDown()) and
(not shift or keyboard.isShiftDown()) and
code == keyboard.keys[key] and
#keybind > resultWeight
then
resultWeight = #keybind
resultName = command
result = keyBindHandlers[command]
end
end
end
end
end
return result, resultName
end
-------------------------------------------------------------------------------
local function onKeyDown(char, code)
local handler = getKeyBindHandler(code)
if handler then
handler()
elseif readonly and code == keyboard.keys.q then
running = false
elseif not readonly then
if not keyboard.isControl(char) then
insert(unicode.char(char))
elseif unicode.char(char) == "\t" then
insert(" ")
end
end
end
local function onClipboard(value)
value = value:gsub("\r\n", "\n")
local cbx, cby = getCursor()
local start = 1
local l = value:find("\n", 1, true)
if l then
repeat
local line = string.sub(value, start, l - 1)
line = text.detab(line, 2)
insert(line)
enter()
start = l + 1
l = value:find("\n", start, true)
until not l
end
insert(string.sub(value, start))
end
local function onClick(x, y)
setCursor(x + scrollX, y + scrollY)
end
local function onScroll(direction)
local cbx, cby = getCursor()
setCursor(cbx, cby - direction * 12)
end
-------------------------------------------------------------------------------
do
local f = io.open(filename)
if f then
local w, h = getSize()
local chars = 0
for line in f:lines() do
if line:sub(-1) == "\r" then
line = line:sub(1, -2)
end
table.insert(buffer, line)
chars = chars + unicode.len(line)
if #buffer <= h then
component.gpu.set(1, #buffer, line)
end
end
f:close()
if #buffer == 0 then
table.insert(buffer, "")
end
local format
if readonly then
format = [["%s" [readonly] %dL,%dC]]
else
format = [["%s" %dL,%dC]]
end
setStatus(string.format(format, fs.name(filename), #buffer, chars))
else
table.insert(buffer, "")
setStatus(string.format([["%s" [New File] ]], fs.name(filename)))
end
setCursor(1, 1)
end
while running do
local event, address, arg1, arg2, arg3 = event.pull()
if type(address) == "string" and component.isPrimary(address) then
local blink = true
if event == "key_down" then
onKeyDown(arg1, arg2)
elseif event == "clipboard" and not readonly then
onClipboard(arg1)
elseif event == "touch" or event == "drag" then
onClick(arg1, arg2)
elseif event == "scroll" then
onScroll(arg3)
else
blink = false
end
if blink then
term.setCursorBlink(true)
term.setCursorBlink(true) -- force toggle to caret
end
end
end
term.clear()
term.setCursorBlink(false)
| mit |
vonflynee/opencomputersserver | world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/bin/edit.lua | 15 | 16517 | local component = require("component")
local event = require("event")
local fs = require("filesystem")
local keyboard = require("keyboard")
local shell = require("shell")
local term = require("term")
local text = require("text")
local unicode = require("unicode")
if not term.isAvailable() then
return
end
local args, options = shell.parse(...)
if #args == 0 then
io.write("Usage: edit <filename>")
return
end
local filename = shell.resolve(args[1])
local readonly = options.r or fs.get(filename) == nil or fs.get(filename).isReadOnly()
if not fs.exists(filename) then
if fs.isDirectory(filename) then
io.stderr:write("file is a directory")
return
elseif readonly then
io.stderr:write("file system is read only")
return
end
end
local function loadConfig()
-- Try to load user settings.
local env = {}
local config = loadfile("/etc/edit.cfg", nil, env)
if config then
pcall(config)
end
-- Fill in defaults.
env.keybinds = env.keybinds or {
left = {{"left"}},
right = {{"right"}},
up = {{"up"}},
down = {{"down"}},
home = {{"home"}},
eol = {{"end"}},
pageUp = {{"pageUp"}},
pageDown = {{"pageDown"}},
backspace = {{"back"}},
delete = {{"delete"}},
deleteLine = {{"control", "delete"}, {"shift", "delete"}},
newline = {{"enter"}},
save = {{"control", "s"}},
close = {{"control", "w"}},
find = {{"control", "f"}},
findnext = {{"control", "g"}, {"control", "n"}, {"f3"}}
}
-- Generate config file if it didn't exist.
if not config then
local root = fs.get("/")
if root and not root.isReadOnly() then
fs.makeDirectory("/etc")
local f = io.open("/etc/edit.cfg", "w")
if f then
local serialization = require("serialization")
for k, v in pairs(env) do
f:write(k.."="..tostring(serialization.serialize(v, math.huge)).."\n")
end
f:close()
end
end
end
return env
end
term.clear()
term.setCursorBlink(true)
local running = true
local buffer = {}
local scrollX, scrollY = 0, 0
local config = loadConfig()
local getKeyBindHandler -- forward declaration for refind()
local function helpStatusText()
local function prettifyKeybind(label, command)
local keybind = type(config.keybinds) == "table" and config.keybinds[command]
if type(keybind) ~= "table" or type(keybind[1]) ~= "table" then return "" end
local alt, control, shift, key
for _, value in ipairs(keybind[1]) do
if value == "alt" then alt = true
elseif value == "control" then control = true
elseif value == "shift" then shift = true
else key = value end
end
if not key then return "" end
return label .. ": [" ..
(control and "Ctrl+" or "") ..
(alt and "Alt+" or "") ..
(shift and "Shift+" or "") ..
unicode.upper(key) ..
"] "
end
return prettifyKeybind("Save", "save") ..
prettifyKeybind("Close", "close") ..
prettifyKeybind("Find", "find")
end
-------------------------------------------------------------------------------
local function setStatus(value)
local w, h = component.gpu.getResolution()
component.gpu.set(1, h, text.padRight(unicode.sub(value, 1, w - 10), w - 10))
end
local function getSize()
local w, h = component.gpu.getResolution()
return w, h - 1
end
local function getCursor()
local cx, cy = term.getCursor()
return cx + scrollX, cy + scrollY
end
local function line()
local cbx, cby = getCursor()
return buffer[cby]
end
local function setCursor(nbx, nby)
local w, h = getSize()
nby = math.max(1, math.min(#buffer, nby))
local ncy = nby - scrollY
if ncy > h then
term.setCursorBlink(false)
local sy = nby - h
local dy = math.abs(scrollY - sy)
scrollY = sy
component.gpu.copy(1, 1 + dy, w, h - dy, 0, -dy)
for by = nby - (dy - 1), nby do
local str = text.padRight(unicode.sub(buffer[by], 1 + scrollX), w)
component.gpu.set(1, by - scrollY, str)
end
elseif ncy < 1 then
term.setCursorBlink(false)
local sy = nby - 1
local dy = math.abs(scrollY - sy)
scrollY = sy
component.gpu.copy(1, 1, w, h - dy, 0, dy)
for by = nby, nby + (dy - 1) do
local str = text.padRight(unicode.sub(buffer[by], 1 + scrollX), w)
component.gpu.set(1, by - scrollY, str)
end
end
term.setCursor(term.getCursor(), nby - scrollY)
nbx = math.max(1, math.min(unicode.len(line()) + 1, nbx))
local ncx = nbx - scrollX
if ncx > w then
term.setCursorBlink(false)
local sx = nbx - w
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + dx, 1, w - dx, h, -dx, 0)
for by = 1 + scrollY, math.min(h + scrollY, #buffer) do
local str = unicode.sub(buffer[by], nbx - (dx - 1), nbx)
str = text.padRight(str, dx)
component.gpu.set(1 + (w - dx), by - scrollY, str)
end
elseif ncx < 1 then
term.setCursorBlink(false)
local sx = nbx - 1
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1, 1, w - dx, h, dx, 0)
for by = 1 + scrollY, math.min(h + scrollY, #buffer) do
local str = unicode.sub(buffer[by], nbx, nbx + dx)
--str = text.padRight(str, dx)
component.gpu.set(1, by - scrollY, str)
end
end
term.setCursor(nbx - scrollX, nby - scrollY)
component.gpu.set(w - 9, h + 1, text.padLeft(string.format("%d,%d", nby, nbx), 10))
end
local function highlight(bx, by, length, enabled)
local w, h = getSize()
local cx, cy = bx - scrollX, by - scrollY
cx = math.max(1, math.min(w, cx))
cy = math.max(1, math.min(h, cy))
length = math.max(1, math.min(w - cx, length))
local fg, fgp = component.gpu.getForeground()
local bg, bgp = component.gpu.getBackground()
if enabled then
component.gpu.setForeground(bg, bgp)
component.gpu.setBackground(fg, fgp)
end
local value = ""
for x = cx, cx + length - 1 do
value = value .. component.gpu.get(x, cy)
end
component.gpu.set(cx, cy, value)
if enabled then
component.gpu.setForeground(fg, fgp)
component.gpu.setBackground(bg, bgp)
end
end
local function home()
local cbx, cby = getCursor()
setCursor(1, cby)
end
local function ende()
local cbx, cby = getCursor()
setCursor(unicode.len(line()) + 1, cby)
end
local function left()
local cbx, cby = getCursor()
if cbx > 1 then
setCursor(cbx - 1, cby)
return true -- for backspace
elseif cby > 1 then
setCursor(cbx, cby - 1)
ende()
return true -- again, for backspace
end
end
local function right(n)
n = n or 1
local cbx, cby = getCursor()
local be = unicode.len(line()) + 1
if cbx < be then
setCursor(cbx + n, cby)
elseif cby < #buffer then
setCursor(1, cby + 1)
end
end
local function up(n)
n = n or 1
local cbx, cby = getCursor()
if cby > 1 then
setCursor(cbx, cby - n)
if getCursor() > unicode.len(line()) then
ende()
end
end
end
local function down(n)
n = n or 1
local cbx, cby = getCursor()
if cby < #buffer then
setCursor(cbx, cby + n)
if getCursor() > unicode.len(line()) then
ende()
end
end
end
local function delete(fullRow)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
local function deleteRow(row)
local content = table.remove(buffer, row)
local rcy = cy + (row - cby)
if rcy <= h then
component.gpu.copy(1, rcy + 1, w, h - rcy, 0, -1)
component.gpu.set(1, h, text.padRight(buffer[row + (h - rcy)], w))
end
return content
end
if fullRow then
term.setCursorBlink(false)
if #buffer > 1 then
deleteRow(cby)
else
buffer[cby] = ""
component.gpu.fill(1, cy, w, 1, " ")
end
setCursor(1, cby)
elseif cbx <= unicode.len(line()) then
term.setCursorBlink(false)
buffer[cby] = unicode.sub(line(), 1, cbx - 1) ..
unicode.sub(line(), cbx + 1)
component.gpu.copy(cx + 1, cy, w - cx, 1, -1, 0)
local br = cbx + (w - cx)
local char = unicode.sub(line(), br, br)
if not char or unicode.len(char) == 0 then
char = " "
end
component.gpu.set(w, cy, char)
elseif cby < #buffer then
term.setCursorBlink(false)
local append = deleteRow(cby + 1)
buffer[cby] = buffer[cby] .. append
component.gpu.set(cx, cy, append)
else
return
end
setStatus(helpStatusText())
end
local function insert(value)
if not value or unicode.len(value) < 1 then
return
end
term.setCursorBlink(false)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
buffer[cby] = unicode.sub(line(), 1, cbx - 1) ..
value ..
unicode.sub(line(), cbx)
local len = unicode.len(value)
local n = w - (cx - 1) - len
if n > 0 then
component.gpu.copy(cx, cy, n, 1, len, 0)
end
component.gpu.set(cx, cy, value)
right(len)
setStatus(helpStatusText())
end
local function enter()
term.setCursorBlink(false)
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = getSize()
table.insert(buffer, cby + 1, unicode.sub(buffer[cby], cbx))
buffer[cby] = unicode.sub(buffer[cby], 1, cbx - 1)
component.gpu.fill(cx, cy, w - (cx - 1), 1, " ")
if cy < h then
if cy < h - 1 then
component.gpu.copy(1, cy + 1, w, h - (cy + 1), 0, 1)
end
component.gpu.set(1, cy + 1, text.padRight(buffer[cby + 1], w))
end
setCursor(1, cby + 1)
setStatus(helpStatusText())
end
local findText = ""
local function find()
local w, h = getSize()
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local ibx, iby = cbx, cby
while running do
if unicode.len(findText) > 0 then
local sx, sy
for syo = 1, #buffer do -- iterate lines with wraparound
sy = (iby + syo - 1 + #buffer - 1) % #buffer + 1
sx = string.find(buffer[sy], findText, syo == 1 and ibx or 1)
if sx and (sx >= ibx or syo > 1) then
break
end
end
if not sx then -- special case for single matches
sy = iby
sx = string.find(buffer[sy], findText)
end
if sx then
cbx, cby = sx, sy
setCursor(cbx, cby)
highlight(cbx, cby, unicode.len(findText), true)
end
end
term.setCursor(7 + unicode.len(findText), h + 1)
setStatus("Find: " .. findText)
local _, _, char, code = event.pull("key_down")
local handler, name = getKeyBindHandler(code)
highlight(cbx, cby, unicode.len(findText), false)
if name == "newline" then
break
elseif name == "close" then
handler()
elseif name == "backspace" then
findText = unicode.sub(findText, 1, -2)
elseif name == "find" or name == "findnext" then
ibx = cbx + 1
iby = cby
elseif not keyboard.isControl(char) then
findText = findText .. unicode.char(char)
end
end
setCursor(cbx, cby)
setStatus(helpStatusText())
end
-------------------------------------------------------------------------------
local keyBindHandlers = {
left = left,
right = right,
up = up,
down = down,
home = home,
eol = ende,
pageUp = function()
local w, h = getSize()
up(h - 1)
end,
pageDown = function()
local w, h = getSize()
down(h - 1)
end,
backspace = function()
if not readonly and left() then
delete()
end
end,
delete = function()
if not readonly then
delete()
end
end,
deleteLine = function()
if not readonly then
delete(true)
end
end,
newline = function()
if not readonly then
enter()
end
end,
save = function()
if readonly then return end
local new = not fs.exists(filename)
local backup
if not new then
backup = filename .. "~"
for i = 1, math.huge do
if not fs.exists(backup) then
break
end
backup = filename .. "~" .. i
end
fs.copy(filename, backup)
end
local f, reason = io.open(filename, "w")
if f then
local chars, firstLine = 0, true
for _, line in ipairs(buffer) do
if not firstLine then
line = "\n" .. line
end
firstLine = false
f:write(line)
chars = chars + unicode.len(line)
end
f:close()
local format
if new then
format = [["%s" [New] %dL,%dC written]]
else
format = [["%s" %dL,%dC written]]
end
setStatus(string.format(format, fs.name(filename), #buffer, chars))
else
setStatus(reason)
end
if not new then
fs.remove(backup)
end
end,
close = function()
-- TODO ask to save if changed
running = false
end,
find = function()
findText = ""
find()
end,
findnext = find
}
getKeyBindHandler = function(code)
if type(config.keybinds) ~= "table" then return end
-- Look for matches, prefer more 'precise' keybinds, e.g. prefer
-- ctrl+del over del.
local result, resultName, resultWeight = nil, nil, 0
for command, keybinds in pairs(config.keybinds) do
if type(keybinds) == "table" and keyBindHandlers[command] then
for _, keybind in ipairs(keybinds) do
if type(keybind) == "table" then
local alt, control, shift, key
for _, value in ipairs(keybind) do
if value == "alt" then alt = true
elseif value == "control" then control = true
elseif value == "shift" then shift = true
else key = value end
end
if (not alt or keyboard.isAltDown()) and
(not control or keyboard.isControlDown()) and
(not shift or keyboard.isShiftDown()) and
code == keyboard.keys[key] and
#keybind > resultWeight
then
resultWeight = #keybind
resultName = command
result = keyBindHandlers[command]
end
end
end
end
end
return result, resultName
end
-------------------------------------------------------------------------------
local function onKeyDown(char, code)
local handler = getKeyBindHandler(code)
if handler then
handler()
elseif readonly and code == keyboard.keys.q then
running = false
elseif not readonly then
if not keyboard.isControl(char) then
insert(unicode.char(char))
elseif unicode.char(char) == "\t" then
insert(" ")
end
end
end
local function onClipboard(value)
value = value:gsub("\r\n", "\n")
local cbx, cby = getCursor()
local start = 1
local l = value:find("\n", 1, true)
if l then
repeat
local line = string.sub(value, start, l - 1)
line = text.detab(line, 2)
insert(line)
enter()
start = l + 1
l = value:find("\n", start, true)
until not l
end
insert(string.sub(value, start))
end
local function onClick(x, y)
setCursor(x + scrollX, y + scrollY)
end
local function onScroll(direction)
local cbx, cby = getCursor()
setCursor(cbx, cby - direction * 12)
end
-------------------------------------------------------------------------------
do
local f = io.open(filename)
if f then
local w, h = getSize()
local chars = 0
for line in f:lines() do
if line:sub(-1) == "\r" then
line = line:sub(1, -2)
end
table.insert(buffer, line)
chars = chars + unicode.len(line)
if #buffer <= h then
component.gpu.set(1, #buffer, line)
end
end
f:close()
if #buffer == 0 then
table.insert(buffer, "")
end
local format
if readonly then
format = [["%s" [readonly] %dL,%dC]]
else
format = [["%s" %dL,%dC]]
end
setStatus(string.format(format, fs.name(filename), #buffer, chars))
else
table.insert(buffer, "")
setStatus(string.format([["%s" [New File] ]], fs.name(filename)))
end
setCursor(1, 1)
end
while running do
local event, address, arg1, arg2, arg3 = event.pull()
if type(address) == "string" and component.isPrimary(address) then
local blink = true
if event == "key_down" then
onKeyDown(arg1, arg2)
elseif event == "clipboard" and not readonly then
onClipboard(arg1)
elseif event == "touch" or event == "drag" then
onClick(arg1, arg2)
elseif event == "scroll" then
onScroll(arg3)
else
blink = false
end
if blink then
term.setCursorBlink(true)
term.setCursorBlink(true) -- force toggle to caret
end
end
end
term.clear()
term.setCursorBlink(false)
| mit |
UnfortunateFruit/darkstar | scripts/zones/Port_Bastok/npcs/Patient_Wheel.lua | 38 | 1386 | -----------------------------------
-- Area: Port Bastok
-- NPC: Patient Wheel
-- Type: Quest NPC
-- @pos -107.988 3.898 52.557 236
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatBastok = player:getVar("WildcatBastok");
if (player:getQuestStatus(BASTOK,LURE_OF_THE_WILDCAT_BASTOK) == QUEST_ACCEPTED and player:getMaskBit(WildcatBastok,1) == false) then
player:startEvent(0x0162);
else
player:startEvent(0x0145);
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 == 0x0162) then
player:setMaskBit(player:getVar("WildcatBastok"),"WildcatBastok",1,true);
end
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/pitcher_of_homemade_herbal_tea.lua | 35 | 1140 | -----------------------------------------
-- ID: 5221
-- Item: pitcher_of_homemade_herbal_tea
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Charisma 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5221);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, 1);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Batallia_Downs/npcs/Stone_Monument.lua | 32 | 1287 | -----------------------------------
-- Area: Batallia Downs
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-- @pos 185.669 9.049 -614.025 105
-----------------------------------
package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Batallia_Downs/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:messageSpecial(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x10000);
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 |
nesstea/darkstar | scripts/zones/Nashmau/npcs/Tsutsuroon.lua | 13 | 1296 | -----------------------------------
-- Area: Nashmau
-- NPC: Tsutsuroon
-- Type: Tenshodo Merchant
-- @pos -15.193 0.000 31.356 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/keyitems");
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(TENSHODO_MEMBERS_CARD)) then
if (player:sendGuild(60431, 1, 23, 7)) then
player:showText(npc,TSUTSUROON_SHOP_DIALOG);
end
else
-- player:startEvent(0x0096);
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 |
Mashape/kong | spec/03-plugins/05-syslog/01-log_spec.lua | 2 | 3477 | 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("#flaky Plugin: syslog (log) [#" .. strategy .. "]", function()
local proxy_client
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" },
}
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",
},
}
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",
}))
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)
local uuid = utils.uuid()
local response = assert(proxy_client:send {
method = "GET",
path = "/request",
headers = {
host = host,
sys_log_uuid = uuid,
}
})
assert.res_status(200, response)
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
elseif expecting_same then
local _, _, stdout = assert(helpers.execute("find /var/log -type f -mmin -5 2>/dev/null | xargs grep -l " .. uuid))
assert.True(#stdout > 0)
end
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)
end)
end
| apache-2.0 |
nesstea/darkstar | scripts/zones/Jugner_Forest_[S]/npcs/Telepoint.lua | 13 | 1225 | -----------------------------------
-- Area: Jugner Forest [S]
-- NPC: Telepoint
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Jugner_Forest_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(JUGNER_GATE_CRYSTAL) == false) then
player:addKeyItem(JUGNER_GATE_CRYSTAL);
player:messageSpecial(KEYITEM_OBTAINED,JUGNER_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 |
nesstea/darkstar | scripts/zones/Windurst_Woods/npcs/An_Polaali.lua | 13 | 1099 | -----------------------------------
-- Area: Windurst Woods
-- NPC: An Polaali
-- Working 100%
-----------------------------------
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(126) == true) then
player:startEvent(0x0197);
elseif (player:getVar("CHASING_TALES_TRACK_BOOK") == 1) then
player:startEvent(0x0194); -- Neeed CS here
else
player:startEvent(0x2c);
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 |
albfan/clink | clink/lua/hg.lua | 4 | 1836 | --
-- Copyright (c) 2012 Martin Ridgers
--
-- Permission is hereby granted, free of charge, to any person obtaining a copy
-- of this software and associated documentation files (the "Software"), to deal
-- in the Software without restriction, including without limitation the rights
-- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-- copies of the Software, and to permit persons to whom the Software is
-- furnished to do so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in
-- all copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE.
--
--------------------------------------------------------------------------------
local hg_tree = {
"add", "addremove", "annotate", "archive", "backout", "bisect", "bookmarks",
"branch", "branches", "bundle", "cat", "clone", "commit", "copy", "diff",
"export", "forget", "grep", "heads", "help", "identify", "import",
"incoming", "init", "locate", "log", "manifest", "merge", "outgoing",
"parents", "paths", "pull", "push", "recover", "remove", "rename", "resolve",
"revert", "rollback", "root", "serve", "showconfig", "status", "summary",
"tag", "tags", "tip", "unbundle", "update", "verify", "version", "graft",
"phases"
}
clink.arg.register_parser("hg", hg_tree)
-- vim: expandtab
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Windurst_Waters/npcs/HomePoint#2.lua | 27 | 1272 | -----------------------------------
-- Area: Windurst Waters
-- NPC: HomePoint#1
-- @pos 138 0.001 -14 238
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Waters/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 18);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
malortie/gmod-addons | th_weapons/lua/entities/ent_weapon_th_medkit/init.lua | 1 | 1180 | -- Only enable this addon if HL:S is mounted.
if !IsHL1Mounted() then return end
-------------------------------------
-- Weapon Medkit spawning.
-------------------------------------
AddCSLuaFile('cl_init.lua')
AddCSLuaFile('shared.lua')
include('shared.lua')
-- Define a global variable to ease calling base class methods.
DEFINE_BASECLASS( 'base_point' )
--[[---------------------------------------------------------
Called to spawn this entity.
@param ply The player spawner.
@param tr The trace result from player's eye to the spawn point.
@param ClassName The entity's class name.
@return true on success.
@return false on failure.
-----------------------------------------------------------]]
function ENT:SpawnFunction( ply, tr, ClassName )
-- Do not spawn at an invalid position.
if ( !tr.Hit ) then return end
-- Spawn the entity at the hit position,
-- facing toward the player.
local SpawnPos = tr.HitPos + tr.HitNormal
local SpawnAng = ply:EyeAngles()
SpawnAng.p = 0
SpawnAng.y = SpawnAng.y + 180
local ent = ents.Create( 'weapon_th_medkit' )
ent:SetPos( SpawnPos )
ent:SetAngles( SpawnAng )
ent:Spawn()
ent:Activate()
return ent
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Kuftal_Tunnel/npcs/Treasure_Coffer.lua | 6 | 4406 | -----------------------------------
-- Area: Kuftal Tunnel
-- NPC: Treasure Coffer
-- @zone 174
-----------------------------------
package.loaded["scripts/zones/Kuftal_Tunnel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/treasure");
require("scripts/globals/quests");
require("scripts/zones/Kuftal_Tunnel/TextIDs");
local TreasureType = "Coffer";
local TreasureLvL = 53;
local TreasureMinLvL = 43;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- trade:hasItemQty(1051,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(1051,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then
-- IMPORTANT ITEM: AF Keyitems, AF Items, & Map -----------
local mJob = player:getMainJob();
local zone = player:getZoneID();
local AFHandsActivated = player:getVar("BorghertzAlreadyActiveWithJob");
if(AFHandsActivated == 12 and player:hasKeyItem(OLD_GAUNTLETS) == false) then
questItemNeeded = 1;
elseif(player:getQuestStatus(OUTLANDS,TRUE_WILL) == QUEST_ACCEPTED and player:getVar("trueWillCS") == 2 and player:hasKeyItem(LARGE_TRICK_BOX) == false) then
questItemNeeded = 2;
elseif(player:getQuestStatus(SANDORIA,KNIGHT_STALKER) == QUEST_ACCEPTED and player:getVar("KnightStalker_Progress") == 1) then
questItemNeeded = 3;
elseif(player:hasKeyItem(MAP_OF_THE_KUFTAL_TUNNEL) == false) then
questItemNeeded = 4;
end
--------------------------------------
local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded);
local success = 0;
if(pack[2] ~= nil) then
player:messageSpecial(pack[2]);
success = pack[1];
else
success = pack[1];
end
if(success ~= -2) then
player:tradeComplete();
if(math.random() <= success) then
-- Succeded to open the coffer
player:messageSpecial(CHEST_UNLOCKED);
if(questItemNeeded == 1) then
player:addKeyItem(OLD_GAUNTLETS);
player:messageSpecial(KEYITEM_OBTAINED,OLD_GAUNTLETS); -- Old Gauntlets (KI)
elseif(questItemNeeded == 2) then
player:addKeyItem(LARGE_TRICK_BOX);
player:messageSpecial(KEYITEM_OBTAINED,LARGE_TRICK_BOX); -- Large Trick Box (KI, NIN AF3)
elseif(questItemNeeded == 3) then
player:addKeyItem(CHALLENGE_TO_THE_ROYAL_KNIGHTS); -- DRG AF3 (KI)
player:messageSpecial(KEYITEM_OBTAINED,CHALLENGE_TO_THE_ROYAL_KNIGHTS);
elseif(questItemNeeded == 4) then
player:addKeyItem(MAP_OF_THE_KUFTAL_TUNNEL);
player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_THE_KUFTAL_TUNNEL); -- Map of the Kuftal Tunnel (KI)
else
player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME));
local loot = cofferLoot(zone,npc);
-- print("loot array: "); -- debug
-- print("[1]", loot[1]); -- debug
-- print("[2]", loot[2]); -- debug
if(loot[1]=="gil") then
player:addGil(loot[2]);
player:messageSpecial(GIL_OBTAINED,loot[2]);
else
-- Item
player:addItem(loot[2]);
player:messageSpecial(ITEM_OBTAINED,loot[2]);
end
end
UpdateTreasureSpawnPoint(npc:getID());
else
player:messageSpecial(CHEST_MIMIC);
spawnMimic(zone,npc,player);
UpdateTreasureSpawnPoint(npc:getID(), true);
end
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(CHEST_LOCKED,1051);
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 |
jj918160/cocos2d-x-samples | samples/FantasyWarrior3D/src/Helper.lua | 8 | 4136 | --global var
camera =nil
CC_CONTENT_SCALE_FACTOR = function()
return cc.Director:getInstance():getContentScaleFactor()
end
CC_POINT_PIXELS_TO_POINTS = function(pixels)
return cc.p(pixels.x/CC_CONTENT_SCALE_FACTOR(), pixels.y/CC_CONTENT_SCALE_FACTOR())
end
CC_POINT_POINTS_TO_PIXELS = function(points)
return cc.p(points.x*CC_CONTENT_SCALE_FACTOR(), points.y*CC_CONTENT_SCALE_FACTOR())
end
--print table
function printTab(tab)
for i,v in pairs(tab) do
if type(v) == "table" then
print("table",i,"{")
printTab(v)
print("}")
else
print(v)
end
end
end
--radiansNormalizer
function radNormalize(rad)
local pi2 = 2*math.pi
rad = rad % pi2
rad = (rad + pi2)%pi2
if rad > math.pi then
rad = rad - math.pi
end
return rad
end
-- getpostable
function getPosTable(obj)
local posX,posY = obj:getPosition()
return {x= posX,y=posY}
end
--getnextpos
function getNextStepPos(curPos, targetPos, speed, dt)
local angel = math.atan2(targetPos.y-curPos.y,targetPos.x-curPos.x)
return {x = curPos.x+math.cos(angel)*speed*dt, y = curPos.y+math.sin(angel)*speed*dt}
end
--createAnimationStruct
function createAnimationStruct(var1, var2, var3)
local timerange = {begin = var1, ended = var2, speed=var3}
return timerange
end
function createAnimation(file, begin, finish, speed)
--TODO: we don't need to create the same Animation3D all the time
local animation3d = cc.Animation3D:create(file)
local animate3d = cc.Animate3D:create(animation3d, begin/30,(finish-begin)/30)
animate3d:setSpeed(speed)
animate3d:retain()
return animate3d
end
--createKnockedMessageStruct
function createKnockedMsgStruct(object)
local msgStruct = {attacker = object, target = object._target}
return msgStruct
end
-- cclog
cclog = function(...)
print(string.format(...))
end
-- change table to enum type
function CreateEnumTable(tbl, index)
local enumTable = {}
local enumIndex = index or -1
for i, v in ipairs(tbl) do
enumTable[v] = enumIndex + i
end
return enumTable
end
function removeAll(table)
while true do
local k =next(table)
if not k then break end
table[k] = nil
end
end
List = {}
function List.new()
return {first = 0, last = -1}
end
function List.pushfirst(list, value)
local first = list.first - 1
list.first = first
list[first] = value
end
function List.pushlast(list, value)
local last = list.last + 1
list.last = last
list[last] = value
end
function List.popfirst(list)
local first = list.first
if first > list.last then return nil end
local value = list[first]
list[first] = nil
list.first = first + 1
return value
end
function List.poplast(list)
local last = list.last
if list.first > last then return nil end
local value = list[last]
list[last] = nil
list.last = last - 1
return value
end
function List.removeAll(list)
removeAll(list)
list.first = 0
list.last = -1
end
function List.getSize(list)
return list.last - list.first + 1
end
function List.first(list)
local value = nil
if list.first <= list.last then
value = list[first]
end
return value
end
function List.remove(list, index)
if index < list.first or index > list.last then return end
while index <= list.last do
list[index] = nil
list[index] = list[index+1]
index = index + 1
end
list.last = list.last -1
end
function List.removeObj(list, obj)
if obj == nil or List.getSize(list) == 0 then return end
for index=list.first, List.getSize(list) do
if list[index] == obj then
List.remove(list,index)
break
end
end
end
function copyTable(t1, t2)
for key, var in pairs(t1) do
t2[key] = var
end
end
function delayExecute(target, func, delay)
local wait = cc.DelayTime:create(delay)
target:runAction(cc.Sequence:create(wait, cc.CallFunc:create(func)))
end
function DEGREES_TO_RADIANS(__ANGLE__)
return __ANGLE__ * 0.01745329252
end
function RADIANS_TO_DEGREES(__ANGLE__)
return __ANGLE__ * 57.29577951
end | mit |
thesharp/dotfiles | nvim/lua/filetypes.lua | 1 | 2202 | --- Python
vim.cmd("au FileType python setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
vim.cmd("au FileType python set colorcolumn=80,110")
--- HTML
vim.cmd("au FileType html setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- Markdown
vim.cmd("au FileType markdown setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
vim.cmd("autocmd FileType markdown setlocal spell")
vim.g.vim_markdown_folding_disabled = 1
--- gitcommit
vim.cmd("autocmd FileType gitcommit setlocal spell")
--- mail
vim.cmd("autocmd FileType mail setlocal spell")
--- RST
vim.cmd("au FileType rst setlocal tabstop=6 expandtab shiftwidth=3 softtabstop=3")
--- JSON
vim.cmd("au FileType json setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
--- Puppet
vim.cmd("au FileType puppet setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- Ansible
vim.cmd("au FileType ansible setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
vim.cmd("au FileType yaml.ansible setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
vim.g.ansible_extra_keywords_highlight = 1
--- YAML
vim.cmd("au FileType yaml setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- LUA
vim.cmd("au FileType lua setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- Ruby
vim.cmd("au FileType ruby setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
--- XML
vim.cmd("au FileType xml setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
--- VimL
vim.cmd("au FileType vim setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
--- Prometheus
vim.cmd("au FileType prometheus setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- TOML
vim.cmd("au FileType toml setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- Go
vim.cmd("au BufNewFile,BufRead *.go setlocal noet ts=4 sw=4 sts=4")
vim.cmd("au FileType gohtmltmpl setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
--- Jenkinsfile
vim.cmd("au FileType Jenkinsfile setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
vim.cmd("au FileType groovy setlocal tabstop=8 expandtab shiftwidth=4 softtabstop=4")
--- LaTeX
vim.cmd("au FileType tex setlocal tabstop=4 expandtab shiftwidth=2 softtabstop=2")
| mit |
dpino/snabbswitch | lib/luajit/src/jit/p.lua | 4 | 10734 | ----------------------------------------------------------------------------
-- LuaJIT profiler.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module is a simple command line interface to the built-in
-- low-overhead profiler of LuaJIT.
--
-- The lower-level API of the profiler is accessible via the "jit.profile"
-- module or the luaJIT_profile_* C API.
--
-- Example usage:
--
-- luajit -jp myapp.lua
-- luajit -jp=s myapp.lua
-- luajit -jp=-s myapp.lua
-- luajit -jp=vl myapp.lua
-- luajit -jp=G,profile.txt myapp.lua
--
-- The following dump features are available:
--
-- f Stack dump: function name, otherwise module:line. Default mode.
-- F Stack dump: ditto, but always prepend module.
-- l Stack dump: module:line.
-- <number> stack dump depth (callee < caller). Default: 1.
-- -<number> Inverse stack dump depth (caller > callee).
-- s Split stack dump after first stack level. Implies abs(depth) >= 2.
-- p Show full path for module names.
-- v Show VM states. Can be combined with stack dumps, e.g. vf or fv.
-- z Show zones. Can be combined with stack dumps, e.g. zf or fz.
-- r Show raw sample counts. Default: show percentages.
-- a Annotate excerpts from source code files.
-- A Annotate complete source code files.
-- G Produce raw output suitable for graphical tools (e.g. flame graphs).
-- m<number> Minimum sample percentage to be shown. Default: 3.
-- i<number> Sampling interval in milliseconds. Default: 10.
-- S[<string>] Events source if performace events are enabled
--
----------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local profile = require("jit.profile")
local vmdef = require("jit.vmdef")
local jutil = require("jit.util")
local dump = require("jit.dump")
local math = math
local pairs, ipairs, tonumber, floor = pairs, ipairs, tonumber, math.floor
local sort, format = table.sort, string.format
local stdout = io.stdout
local zone -- Load jit.zone module on demand.
-- Output file handle.
local out
------------------------------------------------------------------------------
local prof_ud
local prof_states, prof_split, prof_min, prof_raw, prof_fmt, prof_depth
local prof_ann, prof_count1, prof_count2, prof_samples
local map_vmmode = {
N = "Compiled",
I = "Interpreted",
C = "C code",
G = "Garbage Collector",
J = "JIT Compiler",
}
-- Profiler callback.
local function prof_cb(th, samples, vmmode)
prof_samples = prof_samples + samples
local key_stack, key_stack2, key_state
-- Collect keys for sample.
if prof_states then
if prof_states == "v" then
if map_vmmode[vmmode] then
key_state = map_vmmode[vmmode]
else
-- Sampling a trace: make an understandable one-line description.
local tr = tonumber(vmmode)
local info = jutil.traceinfo(tr)
local extra = dump.info[tr]
-- Show the parent of this trace (if this is a side trace)
local parent = ""
if extra and extra.otr and extra.oex then
parent = "("..extra.otr.."/"..extra.oex..")"
end
-- Show what the end of the trace links to (e.g. loop or other trace)
local lnk = ""
local link, ltype = info.link, info.linktype
if link == tr or link == 0 then lnk = "->"..ltype
elseif ltype == "root" then lnk = "->"..link
else lnk = "->"..link.." "..ltype end
-- Show the current zone (if zone profiling is enabled)
local z = ""
if zone and zone:get() then
z = (" %-16s"):format(zone:get())
end
-- Show the source location where the trace starts
local loc = ""
if extra and extra.func then
local fi = jutil.funcinfo(extra.func, extra.pc)
if fi.loc then loc = fi.loc end
end
local s = ("TRACE %3d %-8s %-10s%s %s"):format(vmmode, parent, lnk, z, loc)
key_state = map_vmmode[vmmode] or s
end
else
key_state = zone:get() or "(none)"
end
end
if prof_fmt then
key_stack = profile.dumpstack(th, prof_fmt, prof_depth)
key_stack = key_stack:gsub("%[builtin#(%d+)%]", function(x)
return vmdef.ffnames[tonumber(x)]
end)
if prof_split == 2 then
local k1, k2 = key_stack:match("(.-) [<>] (.*)")
if k2 then key_stack, key_stack2 = k1, k2 end
elseif prof_split == 3 then
key_stack2 = profile.dumpstack(th, "l", 1)
end
end
-- Order keys.
local k1, k2
if prof_split == 1 then
if key_state then
k1 = key_state
if key_stack then k2 = key_stack end
end
elseif key_stack then
k1 = key_stack
if key_stack2 then k2 = key_stack2 elseif key_state then k2 = key_state end
end
-- Coalesce samples in one or two levels.
if k1 then
local t1 = prof_count1
t1[k1] = (t1[k1] or 0) + samples
if k2 then
local t2 = prof_count2
local t3 = t2[k1]
if not t3 then t3 = {}; t2[k1] = t3 end
t3[k2] = (t3[k2] or 0) + samples
end
end
end
------------------------------------------------------------------------------
-- Show top N list.
local function prof_top(count1, count2, samples, indent)
local t, n = {}, 0
for k in pairs(count1) do
n = n + 1
t[n] = k
end
sort(t, function(a, b) return count1[a] > count1[b] end)
for i=1,n do
local k = t[i]
local v = count1[k]
local pct = floor(v*100/samples + 0.5)
if pct < prof_min then break end
if not prof_raw then
out:write(format("%s%2d%% %s\n", indent, pct, k))
elseif prof_raw == "r" then
out:write(format("%s%5d %s\n", indent, v, k))
else
out:write(format("%s %d\n", k, v))
end
if count2 then
local r = count2[k]
if r then
prof_top(r, nil, v, (prof_split == 3 or prof_split == 1) and " -- " or
(prof_depth < 0 and " -> " or " <- "))
end
end
end
end
-- Annotate source code
local function prof_annotate(count1, samples)
local files = {}
local ms = 0
for k, v in pairs(count1) do
local pct = floor(v*100/samples + 0.5)
ms = math.max(ms, v)
if pct >= prof_min then
local file, line = k:match("^(.*):(%d+)$")
if not file then file = k; line = 0 end
local fl = files[file]
if not fl then fl = {}; files[file] = fl; files[#files+1] = file end
line = tonumber(line)
fl[line] = prof_raw and v or pct
end
end
sort(files)
local fmtv, fmtn = " %3d%% | %s\n", " | %s\n"
if prof_raw then
local n = math.max(5, math.ceil(math.log10(ms)))
fmtv = "%"..n.."d | %s\n"
fmtn = (" "):rep(n).." | %s\n"
end
local ann = prof_ann
for _, file in ipairs(files) do
local f0 = file:byte()
if f0 == 40 or f0 == 91 then
out:write(format("\n====== %s ======\n[Cannot annotate non-file]\n", file))
break
end
local fp, err = io.open(file)
if not fp then
out:write(format("====== ERROR: %s: %s\n", file, err))
break
end
out:write(format("\n====== %s ======\n", file))
local fl = files[file]
local n, show = 1, false
if ann ~= 0 then
for i=1,ann do
if fl[i] then show = true; out:write("@@ 1 @@\n"); break end
end
end
for line in fp:lines() do
if line:byte() == 27 then
out:write("[Cannot annotate bytecode file]\n")
break
end
local v = fl[n]
if ann ~= 0 then
local v2 = fl[n+ann]
if show then
if v2 then show = n+ann elseif v then show = n
elseif show+ann < n then show = false end
elseif v2 then
show = n+ann
out:write(format("@@ %d @@\n", n))
end
if not show then goto next end
end
if v then
out:write(format(fmtv, v, line))
else
out:write(format(fmtn, line))
end
::next::
n = n + 1
end
fp:close()
end
end
------------------------------------------------------------------------------
-- Finish profiling and dump result.
local function prof_finish()
if prof_ud then
profile.stop()
local samples = prof_samples
if samples == 0 then
if prof_raw ~= true then out:write("[No samples collected]\n") end
return
end
if prof_ann then
prof_annotate(prof_count1, samples)
else
prof_top(prof_count1, prof_count2, samples, "")
end
prof_count1 = nil
prof_count2 = nil
prof_ud = nil
end
end
-- Start profiling.
local function prof_start(mode)
local interval = ""
mode = mode:gsub("i%d+", function(s) interval = s; return "" end)
prof_min = 3
mode = mode:gsub("m(%d+)", function(s) prof_min = tonumber(s); return "" end)
prof_depth = 1
mode = mode:gsub("%-?%d+", function(s) prof_depth = tonumber(s); return "" end)
local flavour = "S[vanilla]"
mode = mode:gsub("S%[.+%]", function(s) flavour = s; return "" end)
local m = {}
for c in mode:gmatch(".") do m[c] = c end
prof_states = m.v or m.z
if m.z == "z" then zone = require("jit.zone") end
local scope = m.l or m.f or m.F or (prof_states and "" or "f")
local flags = (m.p or "")
prof_raw = m.r
if m.s then
prof_split = 2
if prof_depth == -1 or m["-"] then prof_depth = -2
elseif prof_depth == 1 then prof_depth = 2 end
elseif mode:find("[fF].*l") then
scope = "l"
prof_split = 3
else
prof_split = (scope == "" or mode:find("[zv].*[lfF]")) and 1 or 0
end
prof_ann = m.A and 0 or (m.a and 3)
if prof_ann then
scope = "l"
prof_fmt = "pl"
prof_split = 0
prof_depth = 1
elseif m.G and scope ~= "" then
prof_fmt = flags..scope.."Z;"
prof_depth = -100
prof_raw = true
prof_min = 0
elseif scope == "" then
prof_fmt = false
else
local sc = prof_split == 3 and m.f or m.F or scope
prof_fmt = flags..sc..(prof_depth >= 0 and "Z < " or "Z > ")
end
prof_count1 = {}
prof_count2 = {}
prof_samples = 0
profile.start(scope:lower()..interval..flavour, prof_cb)
prof_ud = newproxy(true)
getmetatable(prof_ud).__gc = prof_finish
end
------------------------------------------------------------------------------
local function start(mode, outfile)
if not outfile then outfile = os.getenv("LUAJIT_PROFILEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stdout
end
prof_start(mode or "f")
end
-- Public module functions.
return {
start = start, -- For -j command line option.
stop = prof_finish
}
| apache-2.0 |
akdor1154/awesome | lib/beautiful/init.lua | 3 | 5030 | ----------------------------------------------------------------------------
--- Theme library.
--
-- @author Damien Leone <damien.leone@gmail.com>
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Damien Leone, Julien Danjou
-- @release @AWESOME_VERSION@
-- @module beautiful
----------------------------------------------------------------------------
-- Grab environment
local os = os
local pairs = pairs
local type = type
local dofile = dofile
local setmetatable = setmetatable
local lgi = require("lgi")
local Pango = lgi.Pango
local PangoCairo = lgi.PangoCairo
local gears_debug = require("gears.debug")
local protected_call = require("gears.protected_call")
local xresources = require("beautiful.xresources")
local beautiful = { xresources = xresources, mt = {} }
-- Local data
local theme = {}
local descs = setmetatable({}, { __mode = 'k' })
local fonts = setmetatable({}, { __mode = 'v' })
local active_font
--- Load a font from a string or a font description.
--
-- @see https://developer.gnome.org/pango/stable/pango-Fonts.html#pango-font-description-from-string
-- @tparam string|lgi.Pango.FontDescription name Font, which can be a
-- string or a lgi.Pango.FontDescription.
-- @treturn table A table with `name`, `description` and `height`.
local function load_font(name)
name = name or active_font
if name and type(name) ~= "string" then
if descs[name] then
name = descs[name]
else
name = name:to_string()
end
end
if fonts[name] then
return fonts[name]
end
-- Load new font
local desc = Pango.FontDescription.from_string(name)
local ctx = PangoCairo.font_map_get_default():create_context()
ctx:set_resolution(beautiful.xresources.get_dpi())
-- Apply default values from the context (e.g. a default font size)
desc:merge(ctx:get_font_description(), false)
-- Calculate font height.
local metrics = ctx:get_metrics(desc, nil)
local height = math.ceil((metrics:get_ascent() + metrics:get_descent()) / Pango.SCALE)
local font = { name = name, description = desc, height = height }
fonts[name] = font
descs[desc] = name
return font
end
--- Set an active font
--
-- @param name The font
local function set_font(name)
active_font = load_font(name).name
end
--- Get a font description.
--
-- See https://developer.gnome.org/pango/stable/pango-Fonts.html#PangoFontDescription.
-- @tparam string|lgi.Pango.FontDescription name The name of the font.
-- @treturn lgi.Pango.FontDescription
function beautiful.get_font(name)
return load_font(name).description
end
--- Get a new font with merged attributes, based on another one.
--
-- See https://developer.gnome.org/pango/stable/pango-Fonts.html#pango-font-description-from-string.
-- @tparam string|Pango.FontDescription name The base font.
-- @tparam string merge Attributes that should be merged, e.g. "bold".
-- @treturn lgi.Pango.FontDescription
function beautiful.get_merged_font(name, merge)
local font = beautiful.get_font(name)
merge = Pango.FontDescription.from_string(merge)
local merged = font:copy_static()
merged:merge(merge, true)
return beautiful.get_font(merged:to_string())
end
--- Get the height of a font.
--
-- @param name Name of the font
function beautiful.get_font_height(name)
return load_font(name).height
end
--- Init function, should be runned at the beginning of configuration file.
-- @tparam string|table config The theme to load. It can be either the path to
-- the theme file (returning a table) or directly the table
-- containing all the theme values.
function beautiful.init(config)
if config then
local homedir = os.getenv("HOME")
-- If `config` is the path to a theme file, run this file,
-- otherwise if it is a theme table, save it.
if type(config) == 'string' then
-- Expand the '~' $HOME shortcut
config = config:gsub("^~/", homedir .. "/")
theme = protected_call(dofile, config)
elseif type(config) == 'table' then
theme = config
end
if theme then
-- expand '~'
if homedir then
for k, v in pairs(theme) do
if type(v) == "string" then theme[k] = v:gsub("^~/", homedir .. "/") end
end
end
if theme.font then set_font(theme.font) end
else
return gears_debug.print_error("beautiful: error loading theme file " .. config)
end
else
return gears_debug.print_error("beautiful: error loading theme: no theme specified")
end
end
--- Get the current theme.
--
-- @treturn table The current theme table.
function beautiful.get()
return theme
end
function beautiful.mt:__index(k)
return theme[k]
end
-- Set the default font
set_font("sans 8")
return setmetatable(beautiful, beautiful.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Bastok_Mines/npcs/HomePoint#1.lua | 27 | 1269 | -----------------------------------
-- Area: Bastok Mines
-- NPC: HomePoint#1
-- @pos 39.189 0.001 -42.618 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Bastok_Mines/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 9);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
kirangonella/torch7 | TensorMath.lua | 28 | 42196 | local wrap = require 'cwrap'
require 'torchcwrap'
local interface = wrap.CInterface.new()
local method = wrap.CInterface.new()
interface:print([[
#include "TH.h"
#include "luaT.h"
#include "utils.h"
]])
-- specific to torch: we generate a 'dispatch' function
-- first we create a helper function
-- note that it let the "torch" table on the stack
interface:print([[
static const void* torch_istensortype(lua_State *L, const char *tname)
{
if(!tname)
return NULL;
if(!luaT_pushmetatable(L, tname))
return NULL;
lua_pushstring(L, "torch");
lua_rawget(L, -2);
if(lua_istable(L, -1))
return tname;
else
{
lua_pop(L, 2);
return NULL;
}
return NULL;
}
]])
interface.dispatchregistry = {}
function interface:wrap(name, ...)
-- usual stuff
wrap.CInterface.wrap(self, name, ...)
-- dispatch function
if not interface.dispatchregistry[name] then
interface.dispatchregistry[name] = true
table.insert(interface.dispatchregistry, {name=name, wrapname=string.format("torch_%s", name)})
interface:print(string.gsub([[
static int torch_NAME(lua_State *L)
{
int narg = lua_gettop(L);
const void *tname;
if(narg >= 1 && (tname = torch_istensortype(L, luaT_typename(L, 1)))) /* first argument is tensor? */
{
}
else if(narg >= 2 && (tname = torch_istensortype(L, luaT_typename(L, 2)))) /* second? */
{
}
else if(narg >= 1 && lua_type(L, narg) == LUA_TSTRING
&& (tname = torch_istensortype(L, lua_tostring(L, narg)))) /* do we have a valid tensor type string then? */
{
lua_remove(L, -2);
}
else if(!(tname = torch_istensortype(L, torch_getdefaulttensortype(L))))
luaL_error(L, "internal error: the default tensor type does not seem to be an actual tensor");
lua_pushstring(L, "NAME");
lua_rawget(L, -2);
if(lua_isfunction(L, -1))
{
lua_insert(L, 1);
lua_pop(L, 2); /* the two tables we put on the stack above */
lua_call(L, lua_gettop(L)-1, LUA_MULTRET);
}
else
return luaL_error(L, "%s does not implement the torch.NAME() function", tname);
return lua_gettop(L);
}
]], 'NAME', name))
end
end
function interface:dispatchregister(name)
local txt = self.txt
table.insert(txt, string.format('static const struct luaL_Reg %s [] = {', name))
for _,reg in ipairs(self.dispatchregistry) do
table.insert(txt, string.format('{"%s", %s},', reg.name, reg.wrapname))
end
table.insert(txt, '{NULL, NULL}')
table.insert(txt, '};')
table.insert(txt, '')
self.dispatchregistry = {}
end
interface:print('/* WARNING: autogenerated file */')
interface:print('')
local function wrap(...)
local args = {...}
-- interface
interface:wrap(...)
-- method: we override things possibly in method table field
for _,x in ipairs(args) do
if type(x) == 'table' then -- ok, now we have a list of args
for _, arg in ipairs(x) do
if arg.method then
for k,v in pairs(arg.method) do
if v == 'nil' then -- special case, we erase the field
arg[k] = nil
else
arg[k] = v
end
end
end
end
end
end
local unpack = unpack or table.unpack
method:wrap(unpack(args))
end
local reals = {ByteTensor='unsigned char',
CharTensor='char',
ShortTensor='short',
IntTensor='int',
LongTensor='long',
FloatTensor='float',
DoubleTensor='double'}
local accreals = {ByteTensor='long',
CharTensor='long',
ShortTensor='long',
IntTensor='long',
LongTensor='long',
FloatTensor='double',
DoubleTensor='double'}
for _,Tensor in ipairs({"ByteTensor", "CharTensor",
"ShortTensor", "IntTensor", "LongTensor",
"FloatTensor", "DoubleTensor"}) do
local real = reals[Tensor]
local accreal = accreals[Tensor]
function interface.luaname2wrapname(self, name)
return string.format('torch_%s_%s', Tensor, name)
end
function method.luaname2wrapname(self, name)
return string.format('m_torch_%s_%s', Tensor, name)
end
local function cname(name)
return string.format('TH%s_%s', Tensor, name)
end
local function lastdim(argn)
return function(arg)
return string.format("TH%s_nDimension(%s)", Tensor, arg.args[argn]:carg())
end
end
wrap("zero",
cname("zero"),
{{name=Tensor, returned=true}})
wrap("fill",
cname("fill"),
{{name=Tensor, returned=true},
{name=real}})
wrap("zeros",
cname("zeros"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name="LongArg"}})
wrap("ones",
cname("ones"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name="LongArg"}})
wrap("reshape",
cname("reshape"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="LongArg"}})
wrap("gather",
cname("gather"),
{{name=Tensor, default=true, returned=true,
init=function(arg)
return table.concat(
{
arg.__metatable.init(arg),
string.format("THLongStorage* %s_size = THLongTensor_newSizeOf(%s);", arg:carg(), arg.args[4]:carg()),
string.format("TH%s_resize(%s, %s_size, NULL);", Tensor, arg:carg(), arg:carg()),
string.format("THLongStorage_free(%s_size);", arg:carg())
}, '\n')
end
},
{name=Tensor},
{name="index"},
{name="IndexTensor", noreadadd=true}})
wrap("scatter",
cname("scatter"),
{{name=Tensor, returned=true},
{name="index"},
{name="IndexTensor", noreadadd=true},
{name=Tensor}},
cname("scatterFill"),
{{name=Tensor, returned=true},
{name="index"},
{name="IndexTensor", noreadadd=true},
{name=real}})
wrap("dot",
cname("dot"),
{{name=Tensor},
{name=Tensor},
{name=accreal, creturned=true}})
wrap("add",
cname("add"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real}},
cname("cadd"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real, default=1},
{name=Tensor}})
wrap("mul",
cname("mul"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real}})
wrap("div",
cname("div"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real}})
wrap("clamp",
cname("clamp"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real},
{name=real}})
wrap("match",
cname("match"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor},
{name=Tensor},
{name=real, default=1}
})
wrap("cmul",
cname("cmul"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=Tensor}})
wrap("cpow",
cname("cpow"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=Tensor}})
wrap("cdiv",
cname("cdiv"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=Tensor}})
wrap("addcmul",
cname("addcmul"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real, default=1},
{name=Tensor},
{name=Tensor}})
wrap("addcdiv",
cname("addcdiv"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real, default=1},
{name=Tensor},
{name=Tensor}})
wrap("mv",
cname("addmv"),
{{name=Tensor, default=true, returned=true, method={default='nil'},
init=function(arg)
return table.concat(
{
arg.__metatable.init(arg),
string.format("TH%s_resize1d(%s, %s->size[0]);", Tensor, arg:carg(), arg.args[5]:carg())
}, '\n')
end,
},
{name=real, default=0, invisible=true},
{name=Tensor, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=2},
{name=Tensor, dim=1}}
)
wrap("mm",
cname("addmm"),
{{name=Tensor, default=true, returned=true, method={default='nil'},
init=function(arg)
return table.concat(
{
arg.__metatable.init(arg),
string.format("TH%s_resize2d(%s, %s->size[0], %s->size[1]);", Tensor, arg:carg(), arg.args[5]:carg(), arg.args[6]:carg())
}, '\n')
end,
},
{name=real, default=0, invisible=true},
{name=Tensor, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=2},
{name=Tensor, dim=2}}
)
wrap("bmm",
cname("baddbmm"),
{{name=Tensor, default=true, returned=true, method={default='nil'},
init=function(arg)
return table.concat(
{
arg.__metatable.init(arg),
string.format("TH%s_resize3d(%s, %s->size[0], %s->size[1], %s->size[2]);",
Tensor, arg:carg(), arg.args[5]:carg(), arg.args[5]:carg(), arg.args[6]:carg())
}, '\n')
end,
},
{name=real, default=0, invisible=true},
{name=Tensor, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=3}}
)
wrap("ger",
cname("addr"),
{{name=Tensor, default=true, returned=true, method={default='nil'},
init=function(arg)
return table.concat(
{
arg.__metatable.init(arg),
string.format("TH%s_resize2d(%s, %s->size[0], %s->size[0]);", Tensor, arg:carg(), arg.args[5]:carg(), arg.args[6]:carg())
}, '\n')
end,
precall=function(arg)
return table.concat(
{
string.format("TH%s_zero(%s);", Tensor, arg:carg()),
arg.__metatable.precall(arg)
}, '\n')
end
},
{name=real, default=1, invisible=true},
{name=Tensor, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=1},
{name=Tensor, dim=1}}
)
for _,f in ipairs({
{name="addmv", dim1=1, dim2=2, dim3=1},
{name="addmm", dim1=2, dim2=2, dim3=2},
{name="addr", dim1=2, dim2=1, dim3=1},
{name="addbmm", dim1=2, dim2=3, dim3=3},
{name="baddbmm", dim1=3, dim2=3, dim3=3},
}
) do
interface:wrap(f.name,
cname(f.name),
{{name=Tensor, default=true, returned=true},
{name=real, default=1},
{name=Tensor, dim=f.dim1},
{name=real, default=1},
{name=Tensor, dim=f.dim2},
{name=Tensor, dim=f.dim3}})
-- there is an ambiguity here, hence the more complicated setup
method:wrap(f.name,
cname(f.name),
{{name=Tensor, returned=true, dim=f.dim1},
{name=real, default=1, invisible=true},
{name=Tensor, default=1, dim=f.dim1},
{name=real, default=1},
{name=Tensor, dim=f.dim2},
{name=Tensor, dim=f.dim3}},
cname(f.name),
{{name=Tensor, returned=true, dim=f.dim1},
{name=real},
{name=Tensor, default=1, dim=f.dim1},
{name=real},
{name=Tensor, dim=f.dim2},
{name=Tensor, dim=f.dim3}})
end
wrap("numel",
cname("numel"),
{{name=Tensor},
{name="long", creturned=true}})
for _,name in ipairs({"cumsum", "cumprod"}) do
wrap(name,
cname(name),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="index", default=1}})
end
wrap("sum",
cname("sumall"),
{{name=Tensor},
{name=accreal, creturned=true}},
cname("sum"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="index"}})
wrap("prod",
cname("prodall"),
{{name=Tensor},
{name=accreal, creturned=true}},
cname("prod"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="index"}})
for _,name in ipairs({"min", "max"}) do
wrap(name,
cname(name .. "all"),
{{name=Tensor},
{name=real, creturned=true}},
cname(name),
{{name=Tensor, default=true, returned=true},
{name="IndexTensor", default=true, returned=true, noreadadd=true},
{name=Tensor},
{name="index"}})
end
for _,name in ipairs({"cmin", "cmax"}) do
wrap(name,
cname(name),
{{name=Tensor, default=true, returned=true},
{name=Tensor, method={default=1}},
{name=Tensor}},
cname(name .. "Value"),
{{name=Tensor, default=true, returned=true},
{name=Tensor, method={default=1}},
{name=real}})
end
wrap("trace",
cname("trace"),
{{name=Tensor},
{name=accreal, creturned=true}})
wrap("cross",
cname("cross"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name=Tensor},
{name="index", default=0}})
wrap("diag",
cname("diag"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="long", default=0}})
wrap("eye",
cname("eye"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name="long"},
{name="long", default=0}})
wrap("range",
cname("range"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=accreal},
{name=accreal},
{name=accreal, default=1}})
wrap("randperm",
cname("randperm"),
{{name=Tensor, default=true, returned=true, method={default='nil'},
postcall=function(arg)
return table.concat(
{
arg.__metatable.postcall(arg),
string.format("TH%s_add(%s, %s, 1);", Tensor, arg:carg(), arg:carg())
}, '\n')
end},
{name="Generator", default=true},
{name="long"}})
wrap("sort",
cname("sort"),
{{name=Tensor, default=true, returned=true},
{name="IndexTensor", default=true, returned=true, noreadadd=true},
{name=Tensor},
{name="index", default=lastdim(3)},
{name="boolean", default=0}})
wrap("kthvalue",
cname("kthvalue"),
{{name=Tensor, default=true, returned=true},
{name="IndexTensor", default=true, returned=true, noreadadd=true},
{name=Tensor},
{name="index"},
{name="index", default=lastdim(3)}})
wrap("median",
cname("median"),
{{name=Tensor, default=true, returned=true},
{name="IndexTensor", default=true, returned=true, noreadadd=true},
{name=Tensor},
{name="index", default=lastdim(3)}})
wrap("tril",
cname("tril"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="int", default=0}})
wrap("triu",
cname("triu"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="int", default=0}})
wrap("cat",
cname("cat"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name=Tensor},
{name="index", default=lastdim(2)}})
if Tensor == 'ByteTensor' then -- we declare this only once
interface:print(
[[
static long THRandom_random2__(THGenerator *gen, long a, long b)
{
THArgCheck(b >= a, 2, "upper bound must be larger than lower bound");
return((THRandom_random(gen) % (b+1-a)) + a);
}
static long THRandom_random1__(THGenerator *gen, long b)
{
THArgCheck(b > 0, 1, "upper bound must be strictly positive");
return(THRandom_random(gen) % b + 1);
}
]])
end
interface:print(string.gsub(
[[
static void THTensor_random2__(THTensor *self, THGenerator *gen, long a, long b)
{
THArgCheck(b >= a, 2, "upper bound must be larger than lower bound");
TH_TENSOR_APPLY(real, self, *self_data = ((THRandom_random(gen) % (b+1-a)) + a);)
}
static void THTensor_random1__(THTensor *self, THGenerator *gen, long b)
{
THArgCheck(b > 0, 1, "upper bound must be strictly positive");
TH_TENSOR_APPLY(real, self, *self_data = (THRandom_random(gen) % b + 1);)
}
]], 'Tensor', Tensor):gsub('real', real))
wrap('random',
'THRandom_random2__',
{{name='Generator', default=true},
{name='long'},
{name='long'},
{name='long', creturned=true}},
'THRandom_random1__',
{{name='Generator', default=true},
{name='long'},
{name='long', creturned=true}},
'THRandom_random',
{{name='Generator', default=true},
{name='long', creturned=true}},
cname("random2__"),
{{name=Tensor, returned=true},
{name='Generator', default=true},
{name='long'},
{name='long'}},
cname("random1__"),
{{name=Tensor, returned=true},
{name='Generator', default=true},
{name='long'}},
cname("random"),
{{name=Tensor, returned=true},
{name='Generator', default=true}})
for _,f in ipairs({{name='geometric'},
{name='bernoulli', a=0.5}}) do
wrap(f.name,
string.format("THRandom_%s", f.name),
{{name='Generator', default=true},
{name="double", default=f.a},
{name="double", creturned=true}},
cname(f.name),
{{name=Tensor, returned=true},
{name='Generator', default=true},
{name="double", default=f.a}})
end
wrap("squeeze",
cname("squeeze"),
{{name=Tensor, default=true, returned=true, postcall=function(arg)
local txt = {}
if arg.returned then
table.insert(txt, string.format('if(arg%d->nDimension == 1 && arg%d->size[0] == 1)', arg.i, arg.i)) -- number
table.insert(txt, string.format('lua_pushnumber(L, (lua_Number)(*TH%s_data(arg%d)));', Tensor, arg.i))
end
return table.concat(txt, '\n')
end},
{name=Tensor}},
cname("squeeze1d"),
{{name=Tensor, default=true, returned=true,
postcall=
function(arg)
local txt = {}
if arg.returned then
table.insert(txt, string.format('if(!hasdims && arg%d->nDimension == 1 && arg%d->size[0] == 1)', arg.i, arg.i)) -- number
table.insert(txt, string.format('lua_pushnumber(L, (lua_Number)(*TH%s_data(arg%d)));}', Tensor, arg.i))
end
return table.concat(txt, '\n')
end},
{name=Tensor,
precall=
function(arg)
return string.format('{int hasdims = arg%d->nDimension > 1;', arg.i)
end},
{name="index"}})
wrap("sign",
cname("sign"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}}})
wrap("conv2",
cname("conv2Dmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=2},
{name=Tensor, dim=2},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}},
cname("conv2Dcmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=3},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}},
cname("conv2Dmv"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=4},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}}
)
wrap("xcorr2",
cname("conv2Dmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=2},
{name=Tensor, dim=2},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}},
cname("conv2Dcmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=3},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}},
cname("conv2Dmv"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=4},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}}
)
wrap("conv3",
cname("conv3Dmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=3},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}},
cname("conv3Dcmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=4},
{name=Tensor, dim=4},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}},
cname("conv3Dmv"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=4},
{name=Tensor, dim=5},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="C", invisible=true}}
)
wrap("xcorr3",
cname("conv3Dmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=3},
{name=Tensor, dim=3},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}},
cname("conv3Dcmul"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=4},
{name=Tensor, dim=4},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}},
cname("conv3Dmv"),
{{name=Tensor, default=true, returned=true},
{name=real, default=0, invisible=true},
{name=real, default=1, invisible=true},
{name=Tensor, dim=4},
{name=Tensor, dim=5},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name=real, default=1, invisible=true},
{name='charoption', values={'V', 'F'}, default='V'},
{name='charoption', default="X", invisible=true}}
)
for _,name in pairs({'lt','gt','le','ge','eq','ne'}) do
wrap(name,
cname(name .. 'Value'),
{{name='ByteTensor',default=true, returned=true},
{name=Tensor},
{name=real}},
cname(name .. 'ValueT'),
{{name=Tensor, returned=true},
{name=Tensor},
{name=real}},
cname(name .. 'Tensor'),
{{name='ByteTensor',default=true, returned=true},
{name=Tensor},
{name=Tensor}},
cname(name .. 'TensorT'),
{{name=Tensor, returned=true},
{name=Tensor},
{name=Tensor}})
end
wrap("nonzero",
cname("nonzero"),
{{name="IndexTensor", default=true, returned=true},
{name=Tensor}})
if Tensor == 'ByteTensor' then
-- Logical accumulators only apply to ByteTensor
for _,name in ipairs({'all', 'any'}) do
wrap(name,
cname('logical' .. name),
{{name=Tensor},
{name="boolean", creturned=true}})
end
end
if Tensor == 'IntTensor' then
wrap("abs",
cname("abs"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}}},
"abs",
{{name=real},
{name=real, creturned=true}})
elseif Tensor == 'LongTensor' then
wrap("abs",
cname("abs"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}}},
"labs",
{{name=real},
{name=real, creturned=true}})
end
if Tensor == 'FloatTensor' or Tensor == 'DoubleTensor' then
wrap("mean",
cname("meanall"),
{{name=Tensor},
{name=accreal, creturned=true}},
cname("mean"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="index"}})
for _,name in ipairs({"var", "std"}) do
wrap(name,
cname(name .. "all"),
{{name=Tensor},
{name=accreal, creturned=true}},
cname(name),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="index"},
{name="boolean", default=false}})
end
wrap("histc",
cname("histc"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name="long",default=100},
{name="double",default=0},
{name="double",default=0}})
wrap("norm",
cname("normall"),
{{name=Tensor},
{name=real, default=2},
{name=accreal, creturned=true}},
cname("norm"),
{{name=Tensor, default=true, returned=true},
{name=Tensor},
{name=real},
{name="index"}})
wrap("renorm",
cname("renorm"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real},
{name="index"},
{name=real}})
wrap("dist",
cname("dist"),
{{name=Tensor},
{name=Tensor},
{name=real, default=2},
{name=accreal, creturned=true}})
wrap("linspace",
cname("linspace"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=real},
{name=real},
{name="long", default=100}})
wrap("logspace",
cname("logspace"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=real},
{name=real},
{name="long", default=100}})
for _,name in ipairs({"log", "log1p", "exp",
"cos", "acos", "cosh",
"sin", "asin", "sinh",
"tan", "atan", "tanh",
"sqrt",
"round", "ceil", "floor"}) do
--"abs"}) do
wrap(name,
cname(name),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}}},
name,
{{name=real},
{name=real, creturned=true}})
end
wrap("abs",
cname("abs"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}}},
"fabs",
{{name=real},
{name=real, creturned=true}})
wrap("atan2",
cname("atan2"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=Tensor}},
"atan2",
{{name=real},
{name=real},
{name=real, creturned=true}}
)
wrap("pow",
cname("pow"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=Tensor, method={default=1}},
{name=real}},
cname("tpow"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name=real},
{name=Tensor, method={default=1}}},
"pow",
{{name=real},
{name=real},
{name=real, creturned=true}})
wrap("rand",
cname("rand"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name='Generator', default=true},
{name="LongArg"}})
wrap("randn",
cname("randn"),
{{name=Tensor, default=true, returned=true, method={default='nil'}},
{name='Generator', default=true},
{name="LongArg"}})
wrap("multinomial",
cname("multinomial"),
{{name="IndexTensor", default=true, returned=true, method={default='nil'}},
{name='Generator', default=true},
{name=Tensor},
{name="int"},
{name="boolean", default=false}})
for _,f in ipairs({{name='uniform', a=0, b=1},
{name='normal', a=0, b=1},
{name='cauchy', a=0, b=1},
{name='logNormal', a=1, b=2}}) do
wrap(f.name,
string.format("THRandom_%s", f.name),
{{name='Generator', default=true},
{name="double", default=f.a},
{name="double", default=f.b},
{name="double", creturned=true}},
cname(f.name),
{{name=Tensor, returned=true},
{name='Generator', default=true},
{name=real, default=f.a},
{name=real, default=f.b}})
end
for _,f in ipairs({{name='exponential'}}) do
wrap(f.name,
string.format("THRandom_%s", f.name),
{{name='Generator', default=true},
{name="double", default=f.a},
{name="double", creturned=true}},
cname(f.name),
{{name=Tensor, returned=true},
{name='Generator', default=true},
{name=real, default=f.a}})
end
for _,name in ipairs({"gesv","gels"}) do
interface:wrap(name,
cname(name),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor},
{name=Tensor}},
cname(name),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name=Tensor}}
)
end
interface:wrap("trtrs",
cname("trtrs"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor},
{name=Tensor},
{name='charoption', values={'U', 'L'}, default='U'}, -- uplo
{name='charoption', values={'N', 'T'}, default='N'}, -- trans
{name='charoption', values={'N', 'U'}, default='N'}}, -- diag
cname("trtrs"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name=Tensor},
{name='charoption', values={'U', 'L'}, default='U'}, -- uplo
{name='charoption', values={'N', 'T'}, default='N'}, -- trans
{name='charoption', values={'N', 'U'}, default='N'}} -- diag
)
interface:wrap("symeig",
cname("syev"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor},
{name='charoption', values={'N', 'V'}, default='N'},
{name='charoption', values={'U', 'L'}, default='U'}},
cname("syev"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name='charoption', values={'N', 'V'}, default='N'},
{name='charoption', values={'U', 'L'}, default='U'}}
)
interface:wrap("eig",
cname("geev"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor},
{name='charoption', values={'N', 'V'}, default='N'}},
cname("geev"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name='charoption', values={'N', 'V'}, default='N'}}
)
interface:wrap("svd",
cname("gesvd"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor},
{name='charoption', values={'A', 'S'}, default='S'}},
cname("gesvd"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name='charoption', values={'A', 'S'}, default='S'}}
)
interface:wrap("inverse",
cname("getri"),
{{name=Tensor, returned=true},
{name=Tensor}},
cname("getri"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor}}
)
interface:wrap("potri",
cname("potri"),
{{name=Tensor, returned=true},
{name=Tensor}},
cname("potri"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor}}
)
interface:wrap("potrf",
cname("potrf"),
{{name=Tensor, returned=true},
{name=Tensor}},
cname("potrf"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor}}
)
interface:wrap("qr",
cname("qr"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor}},
cname("qr"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor}}
)
interface:wrap("geqrf",
cname("geqrf"),
{{name=Tensor, returned=true},
{name=Tensor, returned=true},
{name=Tensor}},
cname("geqrf"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor}}
)
interface:wrap("orgqr",
cname("orgqr"),
{{name=Tensor, returned=true},
{name=Tensor},
{name=Tensor}},
cname("orgqr"),
{{name=Tensor, default=true, returned=true, invisible=true},
{name=Tensor},
{name=Tensor}}
)
end
method:register(string.format("m_torch_%sMath__", Tensor))
interface:print(method:tostring())
method:clearhistory()
interface:register(string.format("torch_%sMath__", Tensor))
interface:print(string.gsub([[
static void torch_TensorMath_init(lua_State *L)
{
luaT_pushmetatable(L, "torch.Tensor");
/* register methods */
luaT_setfuncs(L, m_torch_TensorMath__, 0);
/* register functions into the "torch" field of the tensor metaclass */
lua_pushstring(L, "torch");
lua_newtable(L);
luaT_setfuncs(L, torch_TensorMath__, 0);
lua_rawset(L, -3);
lua_pop(L, 1);
}
]], 'Tensor', Tensor))
end
interface:dispatchregister("torch_TensorMath__")
interface:print([[
void torch_TensorMath_init(lua_State *L)
{
torch_ByteTensorMath_init(L);
torch_CharTensorMath_init(L);
torch_ShortTensorMath_init(L);
torch_IntTensorMath_init(L);
torch_LongTensorMath_init(L);
torch_FloatTensorMath_init(L);
torch_DoubleTensorMath_init(L);
luaT_setfuncs(L, torch_TensorMath__, 0);
}
]])
if arg[1] then
interface:tofile(arg[1])
else
print(interface:tostring())
end
| bsd-3-clause |
vonflynee/opencomputersserver | world/opencomputers/506bbd88-8247-4944-9b91-7506cac9fcb5/boot/90_filesystem.lua | 16 | 1952 | local component = require("component")
local event = require("event")
local fs = require("filesystem")
local shell = require("shell")
local isInitialized, pendingAutoruns = false, {}
local function onInit()
isInitialized = true
for _, run in ipairs(pendingAutoruns) do
local result, reason = pcall(run)
if not result then
local path = fs.concat(os.getenv("TMPDIR") or "/tmp", "event.log")
local log = io.open(path, "a")
if log then
log:write(reason .. "\n")
log:close()
end
end
end
pendingAutoruns = nil
end
local function onComponentAdded(_, address, componentType)
if componentType == "filesystem" then
local proxy = component.proxy(address)
if proxy then
local name = address:sub(1, 3)
while fs.exists(fs.concat("/mnt", name)) and
name:len() < address:len() -- just to be on the safe side
do
name = address:sub(1, name:len() + 1)
end
name = fs.concat("/mnt", name)
fs.mount(proxy, name)
if fs.isAutorunEnabled() then
local function run()
local file = shell.resolve(fs.concat(name, "autorun"), "lua") or
shell.resolve(fs.concat(name, ".autorun"), "lua")
if file then
local result, reason = shell.execute(file, _ENV, proxy)
if not result then
error(reason, 0)
end
end
end
if isInitialized then
run()
else
table.insert(pendingAutoruns, run)
end
end
end
end
end
local function onComponentRemoved(_, address, componentType)
if componentType == "filesystem" then
if fs.get(shell.getWorkingDirectory()).address == address then
shell.setWorkingDirectory("/")
end
fs.umount(address)
end
end
event.listen("init", onInit)
event.listen("component_added", onComponentAdded)
event.listen("component_removed", onComponentRemoved)
| mit |
nesstea/darkstar | scripts/globals/weaponskills/dulling_arrow.lua | 11 | 1353 | -----------------------------------
-- Dulling Arrow
-- Archery weapon skill
-- Skill level: 80
-- Lowers enemy's INT. Chance of params.critical varies with TP.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: STR:16% ; AGI:25%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.16; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.25; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.1; params.crit200 = 0.3; params.crit300 = 0.5;
params.canCrit = true;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.2; params.agi_wsc = 0.5;
end
local damage, criticalHit, tpHits, extraHits = doRangedWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nesstea/darkstar | scripts/globals/items/plate_of_yahata-style_carp_sushi.lua | 18 | 1408 | -----------------------------------------
-- ID: 5186
-- Item: plate_of_yahata-style_carp_sushi
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Dexterity 2
-- Accuracy % 11
-- HP Recovered While Healing 2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5186);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_FOOD_ACCP, 11);
target:addMod(MOD_FOOD_ACC_CAP, 999);
target:addMod(MOD_HPHEAL, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_FOOD_ACCP, 11);
target:delMod(MOD_FOOD_ACC_CAP, 999);
target:delMod(MOD_HPHEAL, 2);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/mobskills/PW_Thundris_Shriek.lua | 13 | 1172 | ---------------------------------------------
-- Thundris Shriek
--
-- Description: Deals heavy lightning damage to targets in area of effect. Additional effect: Terror
-- Type: Magical
-- Utsusemi/Blink absorb: Wipes shadows
-- Range: Unknown
-- Notes: Players will begin to be intimidated by the dvergr after this attack.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local mobSkin = mob:getModelId();
if (mobSkin == 1839) then
return 0;
else
return 1;
end
end;
function onMobWeaponSkill(target, mob, skill)
local dmgmod = 1;
local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_THUNDER,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_THUNDER,MOBPARAM_WIPE_SHADOWS);
local typeEffect = EFFECT_TERROR;
MobStatusEffectMove(mob, target, typeEffect, 1, 0, 30);
target:delHP(dmg);
return dmg;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Hajaom.lua | 34 | 1031 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Hajaom
-- Standard Info NPC
-----------------------------------
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(0x029A);
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 |
nesstea/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/npcs/_iyq.lua | 13 | 1512 | -----------------------------------
-- Area: Grand Palace of Hu'Xzoi
-- NPC: cermet portal
-- @pos 440 0 401 34
-----------------------------------
package.loaded["scripts/zones/Grand_Palace_of_HuXzoi/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Grand_Palace_of_HuXzoi/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == A_FATE_DECIDED and player:getVar("PromathiaStatus")==1) then
SpawnMob(16916813,180):updateClaim(player);
elseif (player:getCurrentMission(COP) == A_FATE_DECIDED and player:getVar("PromathiaStatus")==2) then
player:startEvent(0x0003);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0003) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,A_FATE_DECIDED);
player:addMission(COP,WHEN_ANGELS_FALL);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Al_Zahbi/npcs/Dabigo.lua | 38 | 1030 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Dabigo
-- Type: Delivery Box Manager
-- @zone: 48
-- @pos -34.289 -1 -129.141
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x00d2);
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 |
akdor1154/awesome | lib/awful/autofocus.lua | 1 | 2392 | ---------------------------------------------------------------------------
--- Autofocus functions.
--
-- When loaded, this module makes sure that there's always a client that will
-- have focus on events such as tag switching, client unmanaging, etc.
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @module awful.autofocus
---------------------------------------------------------------------------
local client = client
local aclient = require("awful.client")
local atag = require("awful.tag")
local timer = require("gears.timer")
--- Give focus when clients appear/disappear.
--
-- @param obj An object that should have a .screen property.
local function check_focus(obj)
-- When no visible client has the focus...
if not client.focus or not client.focus:isvisible() then
local c = aclient.focus.history.get(screen[obj.screen], 0, aclient.focus.filter)
if c then
c:emit_signal("request::activate", "autofocus.check_focus",
{raise=false})
end
end
end
--- Check client focus (delayed).
-- @param obj An object that should have a .screen property.
local function check_focus_delayed(obj)
timer.delayed_call(check_focus, {screen = obj.screen})
end
--- Give focus on tag selection change.
--
-- @param tag A tag object
local function check_focus_tag(t)
local s = atag.getscreen(t)
if not s then return end
s = screen[s]
check_focus({ screen = s })
if client.focus and screen[client.focus.screen] ~= s then
local c = aclient.focus.history.get(s, 0, aclient.focus.filter)
if c then
c:emit_signal("request::activate", "autofocus.check_focus_tag",
{raise=false})
end
end
end
tag.connect_signal("property::selected", function (t)
timer.delayed_call(check_focus_tag, t)
end)
client.connect_signal("unmanage", check_focus_delayed)
client.connect_signal("tagged", check_focus_delayed)
client.connect_signal("untagged", check_focus_delayed)
client.connect_signal("property::hidden", check_focus_delayed)
client.connect_signal("property::minimized", check_focus_delayed)
client.connect_signal("property::sticky", check_focus_delayed)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
Spartan322/finalfrontier | gamemode/sgui/shipview.lua | 3 | 5298 | -- Copyright (c) 2014 James King [metapyziks@gmail.com]
--
-- This file is part of Final Frontier.
--
-- Final Frontier is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as
-- published by the Free Software Foundation, either version 3 of
-- the License, or (at your option) any later version.
--
-- Final Frontier 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 Lesser General Public License
-- along with Final Frontier. If not, see <http://www.gnu.org/licenses/>.
local BASE = "container"
GUI.BaseName = BASE
GUI._ship = nil
if CLIENT then
GUI._shipSynced = false
end
GUI._rooms = nil
GUI._doors = nil
GUI._canClickRooms = false
GUI._canClickDoors = false
if SERVER then
GUI._roomOnClickHandler = nil
GUI._doorOnClickHandler = nil
elseif CLIENT then
GUI._roomColourFunction = nil
end
function GUI:GetCanClickRooms()
return self._canClickRooms
end
function GUI:SetCanClickRooms(canClick)
self._canClickRooms = canClick
self:_UpdateElements()
end
function GUI:GetCanClickDoors()
return self._canClickDoors
end
function GUI:SetCanClickDoors(canClick)
self._canClickDoors = canClick
self:_UpdateElements()
end
function GUI:GetCurrentShip()
return self._ship
end
if SERVER then
function GUI:SetRoomOnClickHandler(func)
self._roomOnClickHandler = func
self:_UpdateElements()
end
function GUI:SetDoorOnClickHandler(func)
self._doorOnClickHandler = func
self:_UpdateElements()
end
elseif CLIENT then
function GUI:SetRoomColourFunction(func)
self._roomColourFunction = func
self:_UpdateElements()
end
end
function GUI:SetCurrentShip(ship)
if self._ship == ship then return end
self._ship = ship
if CLIENT then
self._shipSynced = false
end
if not ship then
self:RemoveAllChildren()
self._rooms = nil
self._doors = nil
else
self._doors = {}
self._rooms = {}
if SERVER or ship:IsCurrent() then
self:_SetupShip()
end
end
end
function GUI:_SetupShip()
for i, door in ipairs(self._ship:GetDoors()) do
local doorview = sgui.Create(self, "doorview")
doorview:SetCurrentDoor(door)
self._doors[i] = doorview
end
for i, room in ipairs(self._ship:GetRooms()) do
local roomview = sgui.Create(self, "roomview")
roomview:SetCurrentRoom(room)
self._rooms[i] = roomview
end
if CLIENT then
self._shipSynced = true
self:FindTransform()
end
self:_UpdateElements()
end
function GUI:_UpdateElements()
if CLIENT and not self._shipSynced then return end
for i, door in ipairs(self._doors) do
door.Enabled = self._canClickDoors
door.NeedsPermission = not self._canClickDoors
if SERVER then
if self._canClickDoors and self._doorOnClickHandler then
door.OnClick = self._doorOnClickHandler
end
end
end
for i, room in ipairs(self._rooms) do
room.CanClick = self._canClickRooms
if SERVER then
if self._canClickRooms and self._roomOnClickHandler then
room.OnClick = self._roomOnClickHandler
end
elseif CLIENT and self._roomColourFunction then
room.GetRoomColor = self._roomColourFunction
end
end
end
function GUI:GetRoomElements()
return self._rooms
end
function GUI:GetDoorElements()
return self._doors
end
if SERVER then
function GUI:UpdateLayout(layout)
self.Super[BASE].UpdateLayout(self, layout)
if self._ship then
layout.ship = self._ship:GetName()
else
layout.ship = nil
end
end
end
if CLIENT then
GUI._transform = nil
function GUI:SetBounds(bounds)
self.Super[BASE].SetBounds(self, bounds)
self:FindTransform()
end
function GUI:FindTransform()
if not self._ship or not self._shipSynced then return end
self:ApplyTransform(FindBestTransform(self._ship:GetBounds(),
self:GetGlobalBounds(), true, true))
end
function GUI:ApplyTransform(transform)
if self._transform == transform or not self._ship or not self._shipSynced then return end
self._transform = transform
for _, room in pairs(self._rooms) do
room:ApplyTransform(transform, true)
end
for _, door in pairs(self._doors) do
door:ApplyTransform(transform)
end
end
function GUI:UpdateLayout(layout)
self.Super[BASE].UpdateLayout(self, layout)
if layout.ship then
if not self._ship or self._ship:GetName() ~= layout.ship then
self:SetCurrentShip(ships.GetByName(layout.ship))
end
else
self._ship = nil
end
if self._ship and not self._shipSynced and self._ship:IsCurrent() then
self:_SetupShip()
end
end
end
| lgpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/The_Sanctuary_of_ZiTah/TextIDs.lua | 5 | 1760 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
FULL_INVENTORY_AFTER_TRADE = 6381; -- You cannot obtain the <item>. Try trading again after sorting your inventory.
ITEM_OBTAINED = 6382; -- Obtained: <item>.
GIL_OBTAINED = 6383; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>.
ITEMS_OBTAINED = 6388; -- You obtain <param2 number> <param1 item>!
BEASTMEN_BANNER = 7117; -- There is a beastmen's banner.
FISHING_MESSAGE_OFFSET = 7537; -- You can't fish here.
-- Conquest
CONQUEST = 7204; -- You've earned conquest points!
-- Quest Dialogs
SENSE_OF_FOREBODING = 6397; -- You are suddenly overcome with a sense of foreboding...
STURDY_BRANCH = 7745; -- It is a beautiful, sturdy branch.
NOTHING_OUT_OF_ORDINARY = 6396; -- There is nothing out of the ordinary here.
-- ZM4 Dialog
CANNOT_REMOVE_FRAG = 7718; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7719; -- You have already obtained this monument's
FOUND_ALL_FRAGS = 7721; -- You now have all 8 fragments of light!
ZILART_MONUMENT = 7722; -- It is an ancient Zilart monument.
-- conquest Base
CONQUEST_BASE = 7036; -- Tallying conquest results...
-- chocobo digging
DIG_THROW_AWAY = 7550; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full.
FIND_NOTHING = 7552; -- You dig and you dig, but find nothing.
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5f1.lua | 34 | 1105 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Shiva's Gate
-- @pos 215 -34 20 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
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 |
nesstea/darkstar | scripts/globals/effects/mnd_down.lua | 34 | 1108 | -----------------------------------
--
-- EFFECT_MND_DOWN
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
if ((target:getStat(MOD_MND) - effect:getPower()) < 0) then
effect:setPower(target:getStat(MOD_MND));
end
target:addMod(MOD_MND,-effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
-- the effect restore mind of 1 every 3 ticks.
local downMND_effect_size = effect:getPower()
if (downMND_effect_size > 0) then
effect:setPower(downMND_effect_size - 1)
target:delMod(MOD_MND,-1);
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local downMND_effect_size = effect:getPower()
if (downMND_effect_size > 0) then
target:delMod(MOD_MND,-downMND_effect_size);
end
end;
| gpl-3.0 |
bowlofstew/Macaroni | Next/Tests/Features/LanguageFeatures/manifest.lua | 2 | 1531 | require "os"
require "Macaroni.Model.Library"
upper = getUpperLibrary();
id =
{
group=upper.Group,
name=upper.Name .. ".LanguageFeatures",
version=upper.Version
}
-- Life cycle:
-- Read file.
-- For each dependency, load manifest and parse.
-- Take id and use it to create the current library.
-- For all sources defined, call Macaroni parser to create model.
-- call default, which is defined to be "generate"
description="An example Test Project to be compiled by Macaroni."
source "Source"
output = "GeneratedSource"
dependency {group="Macaroni", name="Boost-filesystem", version="1.52"}
dependency {group="Macaroni", name="Boost-smart_ptr", version="1.52"}
dependency {group="Macaroni", name="CppStd", version="2003"}
function generate()
print "A call was made to GENERATE!!!\n\n"
run("HtmlView");
run "InterfaceMh"
run "Cpp"
--run "JamGenerator"
--local rtnCode = os.execute("bjam")
--print("BJAM return code = " .. rtnCode .. ".")
--if (rtnCode ~= 0) then
-- error("Looks like the plan's not going swell.")
--end
end
jamArgs =
{
ExcludePattern = "Main.cpp .svn *Test.cpp",
ExtraTargets = [[
exe LuaTest
: library
../Source/Main.cpp
;
]]
};
function build()
startTime = os.clock()
run("BoostBuild", jamArgs)
endTime = os.clock()
print("Build time = " .. tostring(endTime - startTime))
end
function test()
--run("BoostBuild", jamArgs);
end
function install()
end
| apache-2.0 |
Mashape/kong | spec/02-integration/02-cmd/09-prepare_spec.lua | 2 | 2069 | local helpers = require "spec.helpers"
local TEST_PREFIX = "servroot_prepared_test"
describe("kong prepare", function()
lazy_setup(function()
pcall(helpers.dir.rmtree, TEST_PREFIX)
end)
after_each(function()
pcall(helpers.dir.rmtree, TEST_PREFIX)
end)
it("prepares a prefix", function()
assert(helpers.kong_exec("prepare -c " .. helpers.test_conf_path, {
prefix = TEST_PREFIX
}))
assert.truthy(helpers.path.exists(TEST_PREFIX))
local admin_access_log_path = helpers.path.join(TEST_PREFIX, helpers.test_conf.admin_access_log)
local admin_error_log_path = helpers.path.join(TEST_PREFIX, helpers.test_conf.admin_error_log)
assert.truthy(helpers.path.exists(admin_access_log_path))
assert.truthy(helpers.path.exists(admin_error_log_path))
end)
it("prepares a prefix from CLI arg option", function()
assert(helpers.kong_exec("prepare -c " .. helpers.test_conf_path ..
" -p " .. TEST_PREFIX))
assert.truthy(helpers.path.exists(TEST_PREFIX))
local admin_access_log_path = helpers.path.join(TEST_PREFIX, helpers.test_conf.admin_access_log)
local admin_error_log_path = helpers.path.join(TEST_PREFIX, helpers.test_conf.admin_error_log)
assert.truthy(helpers.path.exists(admin_access_log_path))
assert.truthy(helpers.path.exists(admin_error_log_path))
end)
describe("errors", function()
it("on inexistent Kong conf file", function()
local ok, stderr = helpers.kong_exec "prepare --conf foobar.conf"
assert.False(ok)
assert.is_string(stderr)
assert.matches("Error: no file at: foobar.conf", stderr, nil, true)
end)
it("on invalid nginx directive", function()
local ok, stderr = helpers.kong_exec("prepare --conf spec/fixtures/invalid_nginx_directives.conf" ..
" -p " .. TEST_PREFIX)
assert.False(ok)
assert.is_string(stderr)
assert.matches("[emerg] unknown directive \"random_directive\"", stderr,
nil, true)
end)
end)
end)
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/chocobo_mazurka.lua | 31 | 1189 | -----------------------------------------
-- Spell: Chocobo Mazurka
-- Gives party members enhanced movement
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local power = 24;
local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
duration = duration * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
duration = duration * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then
spell:setMsg(75);
end
return EFFECT_MAZURKA;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Woods/npcs/Nalta.lua | 38 | 1033 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Nalta
-- Type: Conquest Troupe
-- @zone: 241
-- @pos 19.140 1 -51.297
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0036);
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 |
DaemonSnake/vlc | share/lua/intf/cli.lua | 43 | 31858 | --[==========================================================================[
cli.lua: CLI module for VLC
--[==========================================================================[
Copyright (C) 2007-2011 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
Pierre Ynard
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.
--]==========================================================================]
description=
[============================================================================[
Command Line Interface for VLC
This is a modules/control/oldrc.c look alike (with a bunch of new features).
It also provides a VLM interface copied from the telnet interface.
Use on local term:
vlc -I cli
Use on tcp connection:
vlc -I cli --lua-config "cli={host='localhost:4212'}"
Use on telnet connection:
vlc -I cli --lua-config "cli={host='telnet://localhost:4212'}"
Use on multiple hosts (term + plain tcp port + telnet):
vlc -I cli --lua-config "cli={hosts={'*console','localhost:4212','telnet://localhost:5678'}}"
Note:
-I cli and -I luacli are aliases for -I luaintf --lua-intf cli
Configuration options settable through the --lua-config option are:
* hosts: A list of hosts to listen on.
* host: A host to listen on. (won't be used if `hosts' is set)
* password: The password used for telnet clients.
The following can be set using the --lua-config option or in the interface
itself using the `set' command:
* prompt: The prompt.
* welcome: The welcome message.
* width: The default terminal width (used to format text).
* autocompletion: When issuing an unknown command, print a list of
possible commands to autocomplete with. (0 to disable,
1 to enable).
* autoalias: If autocompletion returns only one possibility, use it
(0 to disable, 1 to enable).
* flatplaylist: 0 to disable, 1 to enable.
]============================================================================]
require("common")
skip = common.skip
skip2 = function(foo) return skip(skip(foo)) end
setarg = common.setarg
strip = common.strip
_ = vlc.gettext._
N_ = vlc.gettext.N_
running = true
--[[ Setup default environement ]]
env = { prompt = "> ";
width = 70;
autocompletion = 1;
autoalias = 1;
welcome = _("Command Line Interface initialized. Type `help' for help.");
flatplaylist = 0;
}
--[[ Import custom environement variables from the command line config (if possible) ]]
for k,v in pairs(env) do
if config[k] then
if type(env[k]) == type(config[k]) then
env[k] = config[k]
vlc.msg.dbg("set environment variable `"..k.."' to "..tostring(env[k]))
else
vlc.msg.err("environment variable `"..k.."' should be of type "..type(env[k])..". config value will be discarded.")
end
end
end
--[[ Command functions ]]
function set_env(name,client,value)
if value then
local var,val = split_input(value)
if val then
local s = string.gsub(val,"\"(.*)\"","%1")
if type(client.env[var])==type(1) then
client.env[var] = tonumber(s)
else
client.env[var] = s
end
else
client:append( tostring(client.env[var]) )
end
else
for e,v in common.pairs_sorted(client.env) do
client:append(e.."="..v)
end
end
end
function save_env(name,client,value)
env = common.table_copy(client.env)
end
function alias(client,value)
if value then
local var,val = split_input(value)
if commands[var] and type(commands[var]) ~= type("") then
client:append("Error: cannot use a primary command as an alias name")
else
if commands[val] then
commands[var]=val
else
client:append("Error: unknown primary command `"..val.."'.")
end
end
else
for c,v in common.pairs_sorted(commands) do
if type(v)==type("") then
client:append(c.."="..v)
end
end
end
end
function lock(name,client)
if client.type == host.client_type.telnet then
client:switch_status( host.status.password )
client.buffer = ""
else
client:append("Error: the prompt can only be locked when logged in through telnet")
end
end
function logout(name,client)
if client.type == host.client_type.net
or client.type == host.client_type.telnet then
client:send("Bye-bye!\r\n")
client:del()
else
client:append("Error: Can't logout of stdin/stdout. Use quit or shutdown to close VLC.")
end
end
function shutdown(name,client)
client:append("Bye-bye!")
h:broadcast("Shutting down.\r\n")
vlc.msg.info("Requested shutdown.")
vlc.misc.quit()
running = false
end
function quit(name,client)
if client.type == host.client_type.net
or client.type == host.client_type.telnet then
logout(name,client)
else
shutdown(name,client)
end
end
function add(name,client,arg)
-- TODO: parse single and double quotes properly
local f
if name == "enqueue" then
f = vlc.playlist.enqueue
else
f = vlc.playlist.add
end
local options = {}
for o in string.gmatch(arg," +:([^ ]*)") do
table.insert(options,o)
end
arg = string.gsub(arg," +:.*$","")
local uri = vlc.strings.make_uri(arg)
f({{path=uri,options=options}})
end
function move(name,client,arg)
local x,y
local tbl = {}
for token in string.gmatch(arg, "[^%s]+") do
table.insert(tbl,token)
end
x = tonumber(tbl[1])
y = tonumber(tbl[2])
local res = vlc.playlist.move(x,y)
if res == (-1) then
client:append("You should choose valid id.")
end
end
function playlist_is_tree( client )
if client.env.flatplaylist == 0 then
return true
else
return false
end
end
function playlist(name,client,arg)
function playlist0(item,prefix)
local prefix = prefix or ""
if not item.flags.disabled then
local str = "| "..prefix..tostring(item.id).." - "..item.name
if item.duration > 0 then
str = str.." ("..common.durationtostring(item.duration)..")"
end
if item.nb_played > 0 then
str = str.." [played "..tostring(item.nb_played).." time"
if item.nb_played > 1 then
str = str .. "s"
end
str = str .. "]"
end
client:append(str)
end
if item.children then
for _, c in ipairs(item.children) do
playlist0(c,prefix.." ")
end
end
end
local playlist
local tree = playlist_is_tree(client)
if name == "search" then
playlist = vlc.playlist.search(arg or "", tree)
else
if tonumber(arg) then
playlist = vlc.playlist.get(tonumber(arg), tree)
elseif arg then
playlist = vlc.playlist.get(arg, tree)
else
playlist = vlc.playlist.get(nil, tree)
end
end
if name == "search" then
client:append("+----[ Search - "..(arg or "`reset'").." ]")
else
client:append("+----[ Playlist - "..playlist.name.." ]")
end
if playlist.children then
for _, item in ipairs(playlist.children) do
playlist0(item)
end
else
playlist0(playlist)
end
if name == "search" then
client:append("+----[ End of search - Use `search' to reset ]")
else
client:append("+----[ End of playlist ]")
end
end
function playlist_sort(name,client,arg)
if not arg then
client:append("Valid sort keys are: id, title, artist, genre, random, duration, album.")
else
local tree = playlist_is_tree(client)
vlc.playlist.sort(arg,false,tree)
end
end
function services_discovery(name,client,arg)
if arg then
if vlc.sd.is_loaded(arg) then
vlc.sd.remove(arg)
client:append(arg.." disabled.")
else
vlc.sd.add(arg)
client:append(arg.." enabled.")
end
else
local sd = vlc.sd.get_services_names()
client:append("+----[ Services discovery ]")
for n,ln in pairs(sd) do
local status
if vlc.sd.is_loaded(n) then
status = "enabled"
else
status = "disabled"
end
client:append("| "..n..": " .. ln .. " (" .. status .. ")")
end
client:append("+----[ End of services discovery ]")
end
end
function load_vlm(name, client, value)
if vlm == nil then
vlm = vlc.vlm()
end
end
function print_text(label,text)
return function(name,client)
client:append("+----[ "..label.." ]")
client:append "|"
for line in string.gmatch(text,".-\r?\n") do
client:append("| "..string.gsub(line,"\r?\n",""))
end
client:append "|"
client:append("+----[ End of "..string.lower(label).." ]")
end
end
function help(name,client,arg)
if arg == nil and vlm ~= nil then
client:append("+----[ VLM commands ]")
local message, vlc_err = vlm:execute_command("help")
vlm_message_to_string( client, message, "|" )
end
local width = client.env.width
local long = (name == "longhelp")
local extra = ""
if arg then extra = "matching `" .. arg .. "' " end
client:append("+----[ CLI commands "..extra.."]")
for i, cmd in ipairs(commands_ordered) do
if (cmd == "" or not commands[cmd].adv or long)
and (not arg or string.match(cmd,arg)) then
local str = "| " .. cmd
if cmd ~= "" then
local val = commands[cmd]
if val.aliases then
for _,a in ipairs(val.aliases) do
str = str .. ", " .. a
end
end
if val.args then str = str .. " " .. val.args end
if #str%2 == 1 then str = str .. " " end
str = str .. string.rep(" .",math.floor((width-(#str+#val.help)-1)/2))
str = str .. string.rep(" ",width-#str-#val.help) .. val.help
end
client:append(str)
end
end
client:append("+----[ end of help ]")
end
function input_info(name,client)
local item = vlc.input.item()
if(item == nil) then return end
local categories = item:info()
for cat, infos in pairs(categories) do
client:append("+----[ "..cat.." ]")
client:append("|")
for name, value in pairs(infos) do
client:append("| "..name..": "..value)
end
client:append("|")
end
client:append("+----[ end of stream info ]")
end
function stats(name,client)
local item = vlc.input.item()
if(item == nil) then return end
local stats_tab = item:stats()
client:append("+----[ begin of statistical info")
client:append("+-[Incoming]")
client:append("| input bytes read : "..string.format("%8.0f KiB",stats_tab["read_bytes"]/1024))
client:append("| input bitrate : "..string.format("%6.0f kb/s",stats_tab["input_bitrate"]*8000))
client:append("| demux bytes read : "..string.format("%8.0f KiB",stats_tab["demux_read_bytes"]/1024))
client:append("| demux bitrate : "..string.format("%6.0f kb/s",stats_tab["demux_bitrate"]*8000))
client:append("| demux corrupted : "..string.format("%5i",stats_tab["demux_corrupted"]))
client:append("| discontinuities : "..string.format("%5i",stats_tab["demux_discontinuity"]))
client:append("|")
client:append("+-[Video Decoding]")
client:append("| video decoded : "..string.format("%5i",stats_tab["decoded_video"]))
client:append("| frames displayed : "..string.format("%5i",stats_tab["displayed_pictures"]))
client:append("| frames lost : "..string.format("%5i",stats_tab["lost_pictures"]))
client:append("|")
client:append("+-[Audio Decoding]")
client:append("| audio decoded : "..string.format("%5i",stats_tab["decoded_audio"]))
client:append("| buffers played : "..string.format("%5i",stats_tab["played_abuffers"]))
client:append("| buffers lost : "..string.format("%5i",stats_tab["lost_abuffers"]))
client:append("|")
client:append("+-[Streaming]")
client:append("| packets sent : "..string.format("%5i",stats_tab["sent_packets"]))
client:append("| bytes sent : "..string.format("%8.0f KiB",stats_tab["sent_bytes"]/1024))
client:append("| sending bitrate : "..string.format("%6.0f kb/s",stats_tab["send_bitrate"]*8000))
client:append("+----[ end of statistical info ]")
end
function playlist_status(name,client)
local item = vlc.input.item()
if(item ~= nil) then
client:append( "( new input: " .. vlc.strings.decode_uri(item:uri()) .. " )" )
end
client:append( "( audio volume: " .. tostring(vlc.volume.get()) .. " )")
client:append( "( state " .. vlc.playlist.status() .. " )")
end
function is_playing(name,client)
if vlc.input.is_playing() then client:append "1" else client:append "0" end
end
function get_title(name,client)
local item = vlc.input.item()
if item then
client:append(item:name())
else
client:append("")
end
end
function ret_print(foo,start,stop)
local start = start or ""
local stop = stop or ""
return function(discard,client,...) client:append(start..tostring(foo(...))..stop) end
end
function get_time(var)
return function(name,client)
local input = vlc.object.input()
if input then
client:append(math.floor(vlc.var.get( input, var ) / 1000000))
else
client:append("")
end
end
end
function titlechap(name,client,value)
local input = vlc.object.input()
local var = string.gsub( name, "_.*$", "" )
if value then
vlc.var.set( input, var, value )
else
local item = vlc.var.get( input, var )
-- Todo: add item name conversion
client:append(item)
end
end
function titlechap_offset(var,offset)
local input = vlc.object.input()
vlc.var.set( input, var, vlc.var.get( input, var ) + offset )
end
function title_next(name,client,value)
titlechap_offset('title', 1)
end
function title_previous(name,client,value)
titlechap_offset('title', -1)
end
function chapter_next(name,client,value)
titlechap_offset('chapter', 1)
end
function chapter_previous(name,client,value)
titlechap_offset('chapter', -1)
end
function seek(name,client,value)
common.seek(value)
end
function volume(name,client,value)
if value then
common.volume(value)
else
client:append(tostring(vlc.volume.get()))
end
end
function rate(name,client,value)
local input = vlc.object.input()
if name == "rate" then
vlc.var.set(input, "rate", common.us_tonumber(value))
elseif name == "normal" then
vlc.var.set(input,"rate",1)
else
vlc.var.set(input,"rate-"..name,nil)
end
end
function frame(name,client)
vlc.var.trigger_callback(vlc.object.input(),"frame-next");
end
function listvalue(obj,var)
return function(client,value)
local o
if obj == "input" then
o = vlc.object.input()
elseif obj == "aout" then
o = vlc.object.aout()
elseif obj == "vout" then
o = vlc.object.vout()
end
if not o then return end
if value then
vlc.var.set( o, var, value )
else
local c = vlc.var.get( o, var )
local v, l = vlc.var.get_list( o, var )
client:append("+----[ "..var.." ]")
for i,val in ipairs(v) do
local mark = (val==c)and " *" or ""
client:append("| "..tostring(val).." - "..tostring(l[i])..mark)
end
client:append("+----[ end of "..var.." ]")
end
end
end
function hotkey(name, client, value)
if not value then
client:append("Please specify a hotkey (ie key-quit or quit)")
elseif not common.hotkey(value) and not common.hotkey("key-"..value) then
client:append("Unknown hotkey '"..value.."'")
end
end
--[[ Declare commands, register their callback functions and provide
help strings here.
Syntax is:
"<command name>"; { func = <function>; [ args = "<str>"; ] help = "<str>"; [ adv = <bool>; ] [ aliases = { ["<str>";]* }; ] }
]]
commands_ordered = {
{ "add"; { func = add; args = "XYZ"; help = "add XYZ to playlist" } };
{ "enqueue"; { func = add; args = "XYZ"; help = "queue XYZ to playlist" } };
{ "playlist"; { func = playlist; help = "show items currently in playlist" } };
{ "search"; { func = playlist; args = "[string]"; help = "search for items in playlist (or reset search)" } };
{ "delete"; { func = skip2(vlc.playlist.delete); args = "[X]"; help = "delete item X in playlist" } };
{ "move"; { func = move; args = "[X][Y]"; help = "move item X in playlist after Y" } };
{ "sort"; { func = playlist_sort; args = "key"; help = "sort the playlist" } };
{ "sd"; { func = services_discovery; args = "[sd]"; help = "show services discovery or toggle" } };
{ "play"; { func = skip2(vlc.playlist.play); help = "play stream" } };
{ "stop"; { func = skip2(vlc.playlist.stop); help = "stop stream" } };
{ "next"; { func = skip2(vlc.playlist.next); help = "next playlist item" } };
{ "prev"; { func = skip2(vlc.playlist.prev); help = "previous playlist item" } };
{ "goto"; { func = skip2(vlc.playlist.gotoitem); help = "goto item at index" ; aliases = { "gotoitem" } } };
{ "repeat"; { func = skip2(vlc.playlist.repeat_); args = "[on|off]"; help = "toggle playlist repeat" } };
{ "loop"; { func = skip2(vlc.playlist.loop); args = "[on|off]"; help = "toggle playlist loop" } };
{ "random"; { func = skip2(vlc.playlist.random); args = "[on|off]"; help = "toggle playlist random" } };
{ "clear"; { func = skip2(vlc.playlist.clear); help = "clear the playlist" } };
{ "status"; { func = playlist_status; help = "current playlist status" } };
{ "title"; { func = titlechap; args = "[X]"; help = "set/get title in current item" } };
{ "title_n"; { func = title_next; help = "next title in current item" } };
{ "title_p"; { func = title_previous; help = "previous title in current item" } };
{ "chapter"; { func = titlechap; args = "[X]"; help = "set/get chapter in current item" } };
{ "chapter_n"; { func = chapter_next; help = "next chapter in current item" } };
{ "chapter_p"; { func = chapter_previous; help = "previous chapter in current item" } };
{ "" };
{ "seek"; { func = seek; args = "X"; help = "seek in seconds, for instance `seek 12'" } };
{ "pause"; { func = skip2(vlc.playlist.pause); help = "toggle pause" } };
{ "fastforward"; { func = setarg(common.hotkey,"key-jump+extrashort"); help = "set to maximum rate" } };
{ "rewind"; { func = setarg(common.hotkey,"key-jump-extrashort"); help = "set to minimum rate" } };
{ "faster"; { func = rate; help = "faster playing of stream" } };
{ "slower"; { func = rate; help = "slower playing of stream" } };
{ "normal"; { func = rate; help = "normal playing of stream" } };
{ "rate"; { func = rate; args = "[playback rate]"; help = "set playback rate to value" } };
{ "frame"; { func = frame; help = "play frame by frame" } };
{ "fullscreen"; { func = skip2(vlc.video.fullscreen); args = "[on|off]"; help = "toggle fullscreen"; aliases = { "f", "F" } } };
{ "info"; { func = input_info; help = "information about the current stream" } };
{ "stats"; { func = stats; help = "show statistical information" } };
{ "get_time"; { func = get_time("time"); help = "seconds elapsed since stream's beginning" } };
{ "is_playing"; { func = is_playing; help = "1 if a stream plays, 0 otherwise" } };
{ "get_title"; { func = get_title; help = "the title of the current stream" } };
{ "get_length"; { func = get_time("length"); help = "the length of the current stream" } };
{ "" };
{ "volume"; { func = volume; args = "[X]"; help = "set/get audio volume" } };
{ "volup"; { func = ret_print(vlc.volume.up,"( audio volume: "," )"); args = "[X]"; help = "raise audio volume X steps" } };
{ "voldown"; { func = ret_print(vlc.volume.down,"( audio volume: "," )"); args = "[X]"; help = "lower audio volume X steps" } };
-- { "adev"; { func = skip(listvalue("aout","audio-device")); args = "[X]"; help = "set/get audio device" } };
{ "achan"; { func = skip(listvalue("aout","stereo-mode")); args = "[X]"; help = "set/get stereo audio output mode" } };
{ "atrack"; { func = skip(listvalue("input","audio-es")); args = "[X]"; help = "set/get audio track" } };
{ "vtrack"; { func = skip(listvalue("input","video-es")); args = "[X]"; help = "set/get video track" } };
{ "vratio"; { func = skip(listvalue("vout","aspect-ratio")); args = "[X]"; help = "set/get video aspect ratio" } };
{ "vcrop"; { func = skip(listvalue("vout","crop")); args = "[X]"; help = "set/get video crop"; aliases = { "crop" } } };
{ "vzoom"; { func = skip(listvalue("vout","zoom")); args = "[X]"; help = "set/get video zoom"; aliases = { "zoom" } } };
{ "vdeinterlace"; { func = skip(listvalue("vout","deinterlace")); args = "[X]"; help = "set/get video deinterlace" } };
{ "vdeinterlace_mode"; { func = skip(listvalue("vout","deinterlace-mode")); args = "[X]"; help = "set/get video deinterlace mode" } };
{ "snapshot"; { func = common.snapshot; help = "take video snapshot" } };
{ "strack"; { func = skip(listvalue("input","spu-es")); args = "[X]"; help = "set/get subtitle track" } };
{ "hotkey"; { func = hotkey; args = "[hotkey name]"; help = "simulate hotkey press"; adv = true; aliases = { "key" } } };
{ "" };
{ "vlm"; { func = load_vlm; help = "load the VLM" } };
{ "set"; { func = set_env; args = "[var [value]]"; help = "set/get env var"; adv = true } };
{ "save_env"; { func = save_env; help = "save env vars (for future clients)"; adv = true } };
{ "alias"; { func = skip(alias); args = "[cmd]"; help = "set/get command aliases"; adv = true } };
{ "description"; { func = print_text("Description",description); help = "describe this module" } };
{ "license"; { func = print_text("License message",vlc.misc.license()); help = "print VLC's license message"; adv = true } };
{ "help"; { func = help; args = "[pattern]"; help = "a help message"; aliases = { "?" } } };
{ "longhelp"; { func = help; args = "[pattern]"; help = "a longer help message" } };
{ "lock"; { func = lock; help = "lock the telnet prompt" } };
{ "logout"; { func = logout; help = "exit (if in a socket connection)" } };
{ "quit"; { func = quit; help = "quit VLC (or logout if in a socket connection)" } };
{ "shutdown"; { func = shutdown; help = "shutdown VLC" } };
}
commands = {}
for i, cmd in ipairs( commands_ordered ) do
if #cmd == 2 then
commands[cmd[1]]=cmd[2]
if cmd[2].aliases then
for _,a in ipairs(cmd[2].aliases) do
commands[a]=cmd[1]
end
end
end
commands_ordered[i]=cmd[1]
end
--[[ From now on commands_ordered is a list of the different command names
and commands is a associative array indexed by the command name. ]]
-- Compute the column width used when printing a the autocompletion list
env.colwidth = 0
for c,_ in pairs(commands) do
if #c > env.colwidth then env.colwidth = #c end
end
env.coldwidth = env.colwidth + 1
--[[ Utils ]]
function split_input(input)
local input = strip(input)
local s = string.find(input," ")
if s then
return string.sub(input,0,s-1), strip(string.sub(input,s))
else
return input
end
end
function vlm_message_to_string(client,message,prefix)
local prefix = prefix or ""
if message.value then
client:append(prefix .. message.name .. " : " .. message.value)
else
client:append(prefix .. message.name)
end
if message.children then
for i,c in ipairs(message.children) do
vlm_message_to_string(client,c,prefix.." ")
end
end
end
--[[ Command dispatch ]]
function call_command(cmd,client,arg)
if type(commands[cmd]) == type("") then
cmd = commands[cmd]
end
local ok, msg
if arg ~= nil then
ok, msg = pcall( commands[cmd].func, cmd, client, arg )
else
ok, msg = pcall( commands[cmd].func, cmd, client )
end
if not ok then
local a = arg and " "..arg or ""
client:append("Error in `"..cmd..a.."' ".. msg)
end
end
function call_vlm_command(cmd,client,arg)
if vlm == nil then
return -1
end
if arg ~= nil then
cmd = cmd.." "..arg
end
local message, vlc_err = vlm:execute_command( cmd )
-- the VLM doesn't let us know if the command exists,
-- so we need this ugly hack
if vlc_err ~= 0 and message.value == "Unknown VLM command" then
return vlc_err
end
vlm_message_to_string( client, message )
return 0
end
function call_libvlc_command(cmd,client,arg)
local ok, vlcerr = pcall( vlc.var.libvlc_command, cmd, arg )
if not ok then
local a = arg and " "..arg or ""
client:append("Error in `"..cmd..a.."' ".. vlcerr) -- when pcall fails, the 2nd arg is the error message.
end
return vlcerr
end
function client_command( client )
local cmd,arg = split_input(client.buffer)
client.buffer = ""
if commands[cmd] then
call_command(cmd,client,arg)
elseif call_vlm_command(cmd,client,arg) == 0 then
--
elseif client.type == host.client_type.stdio
and call_libvlc_command(cmd,client,arg) == 0 then
--
else
local choices = {}
if client.env.autocompletion ~= 0 then
for v,_ in common.pairs_sorted(commands) do
if string.sub(v,0,#cmd)==cmd then
table.insert(choices, v)
end
end
end
if #choices == 1 and client.env.autoalias ~= 0 then
-- client:append("Aliasing to \""..choices[1].."\".")
cmd = choices[1]
call_command(cmd,client,arg)
else
client:append("Unknown command `"..cmd.."'. Type `help' for help.")
if #choices ~= 0 then
client:append("Possible choices are:")
local cols = math.floor(client.env.width/(client.env.colwidth+1))
local fmt = "%-"..client.env.colwidth.."s"
for i = 1, #choices do
choices[i] = string.format(fmt,choices[i])
end
for i = 1, #choices, cols do
local j = i + cols - 1
if j > #choices then j = #choices end
client:append(" "..table.concat(choices," ",i,j))
end
end
end
end
end
--[[ Some telnet command special characters ]]
WILL = "\251" -- Indicates the desire to begin performing, or confirmation that you are now performing, the indicated option.
WONT = "\252" -- Indicates the refusal to perform, or continue performing, the indicated option.
DO = "\253" -- Indicates the request that the other party perform, or confirmation that you are expecting the other party to perform, the indicated option.
DONT = "\254" -- Indicates the demand that the other party stop performing, or confirmation that you are no longer expecting the other party to perform, the indicated option.
IAC = "\255" -- Interpret as command
ECHO = "\001"
function telnet_commands( client )
-- remove telnet command replies from the client's data
client.buffer = string.gsub( client.buffer, IAC.."["..DO..DONT..WILL..WONT.."].", "" )
end
--[[ Client status change callbacks ]]
function on_password( client )
client.env = common.table_copy( env )
if client.type == host.client_type.telnet then
client:send( "Password: " ..IAC..WILL..ECHO )
else
if client.env.welcome ~= "" then
client:send( client.env.welcome .. "\r\n")
end
client:switch_status( host.status.read )
end
end
-- Print prompt when switching a client's status to `read'
function on_read( client )
client:send( client.env.prompt )
end
function on_write( client )
end
--[[ Setup host ]]
require("host")
h = host.host()
h.status_callbacks[host.status.password] = on_password
h.status_callbacks[host.status.read] = on_read
h.status_callbacks[host.status.write] = on_write
h:listen( config.hosts or config.host or "*console" )
password = config.password or "admin"
--[[ The main loop ]]
while running do
local write, read = h:accept_and_select()
for _, client in pairs(write) do
local len = client:send()
client.buffer = string.sub(client.buffer,len+1)
if client.buffer == "" then client:switch_status(host.status.read) end
end
for _, client in pairs(read) do
local input = client:recv(1000)
if input == nil -- the telnet client program has left
or ((client.type == host.client_type.net
or client.type == host.client_type.telnet)
and input == "\004") then
-- Caught a ^D
client.cmds = "quit\n"
else
client.cmds = client.cmds .. input
end
client.buffer = ""
-- split the command at the first '\n'
while string.find(client.cmds, "\n") do
-- save the buffer to send to the client
local saved_buffer = client.buffer
-- get the next command
local index = string.find(client.cmds, "\n")
client.buffer = strip(string.sub(client.cmds, 0, index - 1))
client.cmds = string.sub(client.cmds, index + 1)
-- Remove telnet commands from the command line
if client.type == host.client_type.telnet then
telnet_commands( client )
end
-- Run the command
if client.status == host.status.password then
if client.buffer == password then
client:send( IAC..WONT..ECHO.."\r\nWelcome, Master\r\n" )
client.buffer = ""
client:switch_status( host.status.write )
elseif client.buffer == "quit" then
client_command( client )
else
client:send( "\r\nWrong password\r\nPassword: " )
client.buffer = ""
end
else
client:switch_status( host.status.write )
client_command( client )
end
client.buffer = saved_buffer .. client.buffer
end
end
end
--[[ Clean up ]]
vlm = nil
| gpl-2.0 |
NezzKryptic/Wire-Extras | lua/weapons/gmod_tool/stools/wire_keycard.lua | 3 | 9962 | TOOL.Category = "Wire Extras/Input, Output"
TOOL.Name = "Keycard"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool.wire_keycard.name", "Keycard Tool (Wire)" )
language.Add( "Tool.wire_keycard.desc", "Create portable media for use with the wire system." )
language.Add( "Tool.wire_keycard.0", "Primary: Create/Update Spawner Secondary: Create/Update Reader" )
language.Add( "sboxlimit_wire_keycardspawners", "You've hit keycard spawner limit!" )
language.Add( "sboxlimit_wire_keycardreaders", "You've hit keycard reader limit!" )
language.Add( "undone_wirekeycardspawner", "Undone Wire Keycard Spawner" )
language.Add( "undone_wirekeycardreader", "Undone Wire Keycard Reader" )
language.Add( "WireKeycardTool_GeneralOpt", "General Options" )
language.Add( "WireKeycardTool_LockCode", "Lock Code Modifier" )
language.Add( "WireKeycardTool_ReaderOpt", "Reader Options" )
language.Add( "WireKeycardTool_ReadMode", "Read Mode" )
language.Add( "WireKeycardTool_LCMode", "Lock Code Matching" )
language.Add( "WireKeycardTool_BeamLength", "Range" )
CreateClientConVar("wire_keycardtool_lockcode", "0", true, true)
CreateClientConVar("wire_keycardtool_beamlength", "100", true, true)
CreateClientConVar("wire_keycardtool_readmode", "0", true, true)
CreateClientConVar("wire_keycardtool_lcmode", "0", true, true)
end
if (SERVER) then
CreateConVar('sbox_maxwire_keycardspawners', 10)
CreateConVar('sbox_maxwire_keycardreaders', 10)
end
// TOOL.ClientConVar[ "z_only" ] = "1"
TOOL.Model = "models/keycardspawner/keycardspawner.mdl"
cleanup.Register( "wire_keycardspawners" )
cleanup.Register( "wire_keycardreaders" )
function TOOL:LeftClick( trace )
if trace.Entity && trace.Entity:IsPlayer() then return false end
// If there's no physics object then we can't constraint it!
if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
if (CLIENT) then return true end
local ply = self:GetOwner()
// local z_only = (self:GetClientNumber("z_only") ~= 0)
// If we shot a wire_keycardspawner or wire_keycardreader do nothing
if ( trace.Entity:IsValid() && trace.Entity.pl == ply ) then
if (trace.Entity:GetClass() == "gmod_wire_keycardspawner") then
// trace.Entity:Setup(z_only)
// trace.Entity.z_only = z_only
return true
elseif (trace.Entity:GetClass() == "gmod_wire_keycardreader") then
// Handle card reader stuff on right-click.
return true
end
end
if ( !self:GetSWEP():CheckLimit( "wire_keycardspawners" ) ) then return false end
if (not util.IsValidModel(self.Model)) then return false end
if (not util.IsValidProp(self.Model)) then return false end // Allow ragdolls to be used?
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
wire_keycardspawner = MakeWireKeycardSpawner( ply, Ang, trace.HitPos ) // TODO: pass configs as parameters to this fn (eg. z_only)
local min = wire_keycardspawner:OBBMins()
wire_keycardspawner:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_keycardspawner, trace.Entity, trace.PhysicsBone, true)
undo.Create("WireKeycardSpawner")
undo.AddEntity( wire_keycardspawner )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_keycardspawner", wire_keycardspawner )
ply:AddCleanup( "wire_keycardspawner", const )
return true
end
function TOOL:RightClick( trace )
if trace.Entity && trace.Entity:IsPlayer() then return false end
// If there's no physics object then we can't constraint it!
if ( SERVER && !util.IsValidPhysicsObject( trace.Entity, trace.PhysicsBone ) ) then return false end
if (CLIENT) then return true end
local ply = self:GetOwner()
// local z_only = (self:GetClientNumber("z_only") ~= 0)
// If we shot a wire_keycardspawner or wire_keycardreader do nothing
if ( trace.Entity:IsValid() && trace.Entity.pl == ply ) then
if (trace.Entity:GetClass() == "gmod_wire_keycardspawner") then
// Handle card spawner stuff on right-click.
return true
elseif (trace.Entity:GetClass() == "gmod_wire_keycardreader") then
// trace.Entity:Setup(z_only)
// trace.Entity.z_only = z_only
return true
end
end
if ( !self:GetSWEP():CheckLimit( "wire_keycardreaders" ) ) then return false end
if (not util.IsValidModel(self.Model)) then return false end
if (not util.IsValidProp(self.Model)) then return false end // Allow ragdolls to be used?
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
wire_keycardreader = MakeWireKeycardReader( ply, Ang, trace.HitPos ) // TODO: pass configs as parameters to this fn (eg. z_only)
local min = wire_keycardreader:OBBMins()
wire_keycardreader:SetPos( trace.HitPos - trace.HitNormal * min.z )
wire_keycardreader:SetRange(math.Max(0, ply:GetInfoNum("wire_keycardtool_beamlength", 100)))
wire_keycardreader:SetReadMode(ply:GetInfoNum("wire_keycardtool_readmode", 0))
wire_keycardreader:SetLCMatchMode(ply:GetInfoNum("wire_keycardtool_lcmode", 0))
local const = WireLib.Weld(wire_keycardreader, trace.Entity, trace.PhysicsBone, true)
undo.Create("WireKeycardReader")
undo.AddEntity( wire_keycardreader )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_keycardreader", wire_keycardreader )
ply:AddCleanup( "wire_keycardreader", const )
return true
end
if (SERVER) then
function MakeWireKeycardSpawner( pl, Ang, Pos )
if ( !pl:CheckLimit( "wire_keycardspawners" ) ) then return false end
local wire_keycardspawner = ents.Create( "gmod_wire_keycardspawner" )
if (!wire_keycardspawner:IsValid()) then return false end
wire_keycardspawner:SetAngles( Ang )
wire_keycardspawner:SetPos( Pos )
wire_keycardspawner:SetModel( Model("models/keycardspawner/keycardspawner.mdl") )
wire_keycardspawner:SetLockCode((pl:UserID() + 1) * 100 + math.Clamp(math.Round(pl:GetInfoNum("wire_keycardtool_lockcode", 0)), 0, 99))
wire_keycardspawner:Spawn()
pl:AddCount( "wire_keycardspawners", wire_keycardspawner )
return wire_keycardspawner
end
function MakeWireKeycardReader( pl, Ang, Pos )
if ( !pl:CheckLimit( "wire_keycardreaders" ) ) then return false end
local wire_keycardreader = ents.Create( "gmod_wire_keycardreader" )
if (!wire_keycardreader:IsValid()) then return false end
wire_keycardreader:SetAngles( Ang )
wire_keycardreader:SetPos( Pos )
wire_keycardreader:SetModel( Model("models/jaanus/wiretool/wiretool_range.mdl") )
wire_keycardreader:SetLockCode((pl:UserID() + 1) * 100 + math.Clamp(math.Round(pl:GetInfoNum("wire_keycardtool_lockcode", 0)), 0, 99))
wire_keycardreader:SetRange(math.Max(0, pl:GetInfoNum("wire_keycardtool_beamlength", 100)))
wire_keycardreader:SetReadMode(pl:GetInfoNum("wire_keycardtool_readmode", 0))
wire_keycardreader:SetLCMatchMode(pl:GetInfoNum("wire_keycardtool_lcmode", 0))
wire_keycardreader:Spawn()
pl:AddCount( "wire_keycardreaders", wire_keycardreader )
return wire_keycardreader
end
// TODO: Examine this. Keycards need to be Duplicator compatible.
// duplicator.RegisterEntityClass("gmod_wire_keycardspawner", MakeWireKeycardSpawner, "Ang", "Pos", "z_only", "nocollide", "Vel", "aVel", "frozen")
// duplicator.RegisterEntityClass("gmod_wire_keycardreader", MakeWireKeycardReader, "Ang", "Pos", "z_only", "nocollide", "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostWireKeycardSpawner( ent, player )
if ( !ent ) then return end
if ( !ent:IsValid() ) then return end
local tr = util.GetPlayerTrace( player, player:GetAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit) then return end
if (trace.Entity && trace.Entity:GetClass() == "gmod_wire_keycardspawner" || trace.Entity:IsPlayer()) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then
self:MakeGhostEntity( self.Model, Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostWireKeycardSpawner( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_keycard.name", Description = "#Tool.wire_keycard.desc" })
panel:AddControl("Header", { Text = "#WireKeycardTool_GeneralOpt" } )
panel:AddControl("Slider", { Label = "#WireKeycardTool_LockCode",
Description = "", Type = "Integer", Min = "0", Max = "99", Command = "wire_keycardtool_lockcode"})
panel:AddControl("Header", { Text = "#WireKeycardTool_ReaderOpt" } )
local combobox = {}
combobox.Label = "#WireKeycardTool_ReadMode"
combobox.MenuButton = 0
combobox.Options = {}
combobox.Options["Read with a beam"] = {wire_keycardtool_readmode = 0}
combobox.Options["Read nearest keycard"] = {wire_keycardtool_readmode = 1}
panel:AddControl("ComboBox", combobox)
local combobox = {}
combobox.Label = "#WireKeycardTool_LCMode"
combobox.MenuButton = 0
combobox.Options = {}
combobox.Options["Inclusive (read even if lock code is different)"] = {wire_keycardtool_lcmode = 0}
combobox.Options["Exclusive (ignore if lock code is different)"] = {wire_keycardtool_lcmode = 1}
panel:AddControl("ComboBox", combobox)
panel:AddControl("Slider", { Label = "#WireKeycardTool_BeamLength",
Description = "", Type = "Float", Min = "1", Max = "1000", Command = "wire_keycardtool_beamlength"})
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/weaponskills/avalanche_axe.lua | 30 | 1353 | -----------------------------------
-- Avalanche Axe
-- Axe weapon skill
-- Skill level: 100
-- Delivers a single-hit attack. Damage varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Soil Gorget & Thunder Gorget.
-- Aligned with the Soil Belt & Thunder Belt.
-- Element: None
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- 1.50 2.00 2.50
-----------------------------------
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.5; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.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 = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Konschtat_Highlands/TextIDs.lua | 13 | 1468 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6384; -- Obtained: <item>.
GIL_OBTAINED = 6385; -- Obtained <number> gil.
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>.
ALREADY_OBTAINED_TELE = 7204; -- You already possess the gate crystal for this telepoint.
-- Other texts
SIGNPOST3 = 7374; -- North: Valkurm Dunes South: North Gustaberg East: Gusgen Mines, Pashhow Marshlands
SIGNPOST2 = 7375; -- North: Pashhow Marshlands West: Valkurm Dunes, North Gustaberg Southeast: Gusgen Mines
SIGNPOST_DIALOG_1 = 7376; -- North: Valkurm Dunes South: To Gustaberg
SIGNPOST_DIALOG_2 = 7377; -- You see something stuck behind the signpost.
SOMETHING_BURIED_HERE = 7378; -- Something has been buried here.
FIND_NOTHING = 7379; -- You thought you saw something, but find nothing.
NOTHING_HAPPENS = 119; -- Nothing happens...
NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here.
TELEPOINT_HAS_BEEN_SHATTERED = 7468; -- The telepoint has been shattered into a thousand pieces...
-- conquest Base
CONQUEST_BASE = 7045; -- Tallying conquest results...
--chocobo digging
DIG_THROW_AWAY = 7221; -- You dig up$, but your inventory is full. You regretfully throw the # away.
FIND_NOTHING = 7223; -- You dig and you dig, but find nothing.
| gpl-3.0 |
mobinantispam/irantg | plugins/inrealm.lua | 34 | 22928 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group '..string.gsub(group_name, '_', ' ')..' has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function group_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
function run(msg, matches)
--vardump(msg)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/logs/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
return create_group(msg)
end
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if not is_realm(msg) then
return
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'setting' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
if matches[1] == 'setname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
group_list(msg)
send_document("chat#id"..msg.to.id, "groups.txt", ok_cb, false)
return " Group list created" --group_list(msg)
end
end
return {
patterns = {
"^[!/](creategroup) (.*)$",
"^[!/](setabout) (%d+) (.*)$",
"^[!/](setrules) (%d+) (.*)$",
"^[!/](setname) (.*)$",
"^[!/](setgpname) (%d+) (.*)$",
"^[!/](setname) (%d+) (.*)$",
"^[!/](lock) (%d+) (.*)$",
"^[!/](unlock) (%d+) (.*)$",
"^[!/](setting) (%d+)$",
"^[!/](wholist)$",
"^[!/](who)$",
"^[!/](type)$",
"^[!/](kill) (chat) (%d+)$",
"^[!/](kill) (realm) (%d+)$",
"^[!/](addadmin) (.*)$", -- sudoers only
"^[!/](removeadmin) (.*)$", -- sudoers only
"^[!/](list) (.*)$",
"^[!/](log)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Sauromugue_Champaign/npcs/qm7.lua | 10 | 2481 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: qm7 (???) (Tower 7)
-- Involved in Quest: THF AF "As Thick As Thieves"
-- @pos -193.869 15.400 276.837 120
-----------------------------------
package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Sauromugue_Champaign/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS");
if (thickAsThievesGrapplingCS >= 2 and thickAsThievesGrapplingCS <= 7) then
if (trade:hasItemQty(17474,1) and trade:getItemCount() == 1) then -- Trade grapel
player:messageSpecial(THF_AF_WALL_OFFSET+3,0,17474); -- You cannot get a decent grip on the wall using the [Grapnel].
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES);
local thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS");
if (thickAsThieves == QUEST_ACCEPTED) then
if (thickAsThievesGrapplingCS == 7) then
player:messageSpecial(THF_AF_MOB);
GetMobByID(17269107):setSpawn(-194,15,269);
SpawnMob(17269107,120):updateClaim(player); -- Climbpix Highrise
elseif (thickAsThievesGrapplingCS == 0 or thickAsThievesGrapplingCS == 1 or
thickAsThievesGrapplingCS == 2 or thickAsThievesGrapplingCS == 3 or
thickAsThievesGrapplingCS == 4 or thickAsThievesGrapplingCS == 5 or
thickAsThievesGrapplingCS == 6) then
player:messageSpecial(THF_AF_WALL_OFFSET);
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Northern_San_dOria/npcs/Pirvidiauce.lua | 13 | 2100 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Pirvidiauce
-- Conquest depending medicine seller
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,PIRVIDIAUCE_SHOP_DIALOG);
stock = {0x32ba,9180,1, --Chestnut Sabbots
0x1020,4445,1, --Ether
0x1010,837,1, --Potion
0x43b8,6,2, --Crossbow bolt
0x1037,720,2, --Echo Drops
0x32b9,1462,2, --Holly Clogs
0x1034,284,3, --Antidote
0x32b8,111,3, --Ash Clogs
0x00db,900,3, --Ceramic Flowerpot
0x1036,2335,3, --Eye Drops
0x06ee,1984,3, --Red Gravel
0x43a6,3,3, --Wooden Arrow
0x0b2e,9200,3} --Kingdom Waystone
showNationShop(player, SANDORIA, 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 |
nesstea/darkstar | scripts/globals/items/plate_of_anchovies.lua | 17 | 1190 | -----------------------------------------
-- ID: 5652
-- Item: plate_of_anchovies
-- Food Effect: 3Min, All Races
-----------------------------------------
-- Dexterity 1
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,180,5652);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_FOOD_ACCP, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_FOOD_ACCP, -3);
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.