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 |
|---|---|---|---|---|---|
nesstea/darkstar | scripts/zones/Temple_of_Uggalepih/npcs/qm2.lua | 25 | 1099 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: ??? (Uggalepih Offering ITEM)
-- @pos 388 0 269 159
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
respawn = GetServerVariable("[TEMP]Respawn_qm2_for_offering");
if (player:hasItem(1183) == false and player:getFreeSlotsCount() >= 1 and respawn <= os.time(t)) then
player:addItem(1183);
player:messageSpecial(ITEM_OBTAINED,1183); -- Uggalepih Offering
SetServerVariable("[TEMP]Respawn_qm2_for_offering",os.time(t) + 7200); -- 2 hours
-- ??? dissapears for 2 hours and reappears on new position
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Windurst_Waters_[S]/npcs/Llewellyn.lua | 13 | 1065 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Llewellyn
-- Type: Campaign Evaluator
-- @zone: 94
-- @pos -6.907 -2 42.871
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x000a);
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 |
FailcoderAddons/supervillain-ui | SVUI_Skins/components/blizzard/archeology.lua | 2 | 4809 | --[[
##############################################################################
S V U I By: Failcoder
##############################################################################
--]]
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
--[[ ADDON ]]--
local SV = _G['SVUI'];
local L = SV.L;
local MOD = SV.Skins;
local Schema = MOD.Schema;
--[[
##########################################################
ARCHEOLOGYFRAME MODR
##########################################################
]]--
local function ArchaeologyStyle()
if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.archaeology ~= true then return end
ArchaeologyFrame:RemoveTextures()
ArchaeologyFrameInset:RemoveTextures()
ArchaeologyFrame:SetStyle("Frame", "Window")
ArchaeologyFrame.Panel:SetAllPoints()
ArchaeologyFrame.portrait:SetAlpha(0)
ArchaeologyFrameInset:SetStyle("Frame", "Inset")
ArchaeologyFrameInset.Panel:SetPoint("TOPLEFT")
ArchaeologyFrameInset.Panel:SetPoint("BOTTOMRIGHT", -3, -1)
ArchaeologyFrameArtifactPageSolveFrameSolveButton:SetStyle("Button")
ArchaeologyFrameArtifactPageBackButton:SetStyle("Button")
ArchaeologyFrameRaceFilter:SetFrameLevel(ArchaeologyFrameRaceFilter:GetFrameLevel()+2)
SV.API:Set("DropDown", ArchaeologyFrameRaceFilter, 125)
SV.API:Set("PageButton", ArchaeologyFrameCompletedPageNextPageButton)
SV.API:Set("PageButton", ArchaeologyFrameCompletedPagePrevPageButton)
ArchaeologyFrameRankBar:RemoveTextures()
ArchaeologyFrameRankBar:SetStatusBarTexture(SV.media.statusbar.default)
ArchaeologyFrameRankBar:SetFrameLevel(ArchaeologyFrameRankBar:GetFrameLevel()+2)
ArchaeologyFrameRankBar:SetStyle("Frame", "Default")
ArchaeologyFrameArtifactPageSolveFrameStatusBar:RemoveTextures()
ArchaeologyFrameArtifactPageSolveFrameStatusBar:SetStatusBarTexture(SV.media.statusbar.default)
ArchaeologyFrameArtifactPageSolveFrameStatusBar:SetStatusBarColor(0.7, 0.2, 0)
ArchaeologyFrameArtifactPageSolveFrameStatusBar:SetFrameLevel(ArchaeologyFrameArtifactPageSolveFrameStatusBar:GetFrameLevel()+2)
ArchaeologyFrameArtifactPageSolveFrameStatusBar:SetStyle("Frame", "Default")
for b = 1, ARCHAEOLOGY_MAX_COMPLETED_SHOWN do
local c = _G["ArchaeologyFrameCompletedPageArtifact"..b]
if c then
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Border"]:Die()
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Bg"]:Die()
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"]:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"].backdrop = CreateFrame("Frame", nil, c)
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"].backdrop:SetStyle("!_Frame", "Default")
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"].backdrop:WrapPoints(_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"])
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"].backdrop:SetFrameLevel(c:GetFrameLevel()-2)
_G["ArchaeologyFrameCompletedPageArtifact"..b.."Icon"]:SetDrawLayer("OVERLAY")
end
end
ArchaeologyFrameArtifactPageIcon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
ArchaeologyFrameArtifactPageIcon.backdrop = CreateFrame("Frame", nil, ArchaeologyFrameArtifactPage)
ArchaeologyFrameArtifactPageIcon.backdrop:SetStyle("!_Frame", "Default")
ArchaeologyFrameArtifactPageIcon.backdrop:WrapPoints(ArchaeologyFrameArtifactPageIcon)
ArchaeologyFrameArtifactPageIcon.backdrop:SetFrameLevel(ArchaeologyFrameArtifactPage:GetFrameLevel())
ArchaeologyFrameArtifactPageIcon:SetParent(ArchaeologyFrameArtifactPageIcon.backdrop)
ArchaeologyFrameArtifactPageIcon:SetDrawLayer("OVERLAY")
SV.API:Set("CloseButton", ArchaeologyFrameCloseButton)
local progressBarHolder = CreateFrame("Frame", "SVUI_ArcheologyProgressBar", SV.Screen)
progressBarHolder:SetSize(240, 24)
progressBarHolder:SetPoint("TOP", SV.Screen, "CENTER", 0, -180)
SV:NewAnchor(progressBarHolder, "Archeology Progress Bar")
ArcheologyDigsiteProgressBar:SetAllPoints(progressBarHolder)
progressBarHolder:SetParent(ArcheologyDigsiteProgressBar)
ArcheologyDigsiteProgressBar.Shadow:SetTexture("Interface\\AddOns\\SVUI_Skins\\artwork\\ArcheologyToast")
ArcheologyDigsiteProgressBar.BarBackground:SetTexture("Interface\\AddOns\\SVUI_Skins\\artwork\\ArcheologyToast")
ArcheologyDigsiteProgressBar.BarBorderAndOverlay:SetTexture("Interface\\AddOns\\SVUI_Skins\\artwork\\ArcheologyToast")
ArcheologyDigsiteProgressBar.Flash:SetTexture("Interface\\AddOns\\SVUI_Skins\\artwork\\ArcheologyToast")
ArcheologyDigsiteProgressBar.FillBar:SetStatusBarTexture("Interface\\AddOns\\SVUI_Skins\\artwork\\Arch-Progress-Fill")
end
--[[
##########################################################
MOD LOADING
##########################################################
]]--
MOD:SaveBlizzardStyle("Blizzard_ArchaeologyUI", ArchaeologyStyle)
| mit |
nesstea/darkstar | scripts/zones/Temenos/mobs/Telchines_Bard.lua | 7 | 1120 | -----------------------------------
-- Area: Temenos N T
-- NPC: Telchines_Bard
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
if (IsMobDead(16928788)==true and IsMobDead(16928789)==true and IsMobDead(16928792)==true and IsMobDead(16928793)==true ) then
GetNPCByID(16928768+26):setPos(19,80,430);
GetNPCByID(16928768+26):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+160):setPos(16,80,430);
GetNPCByID(16928768+160):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+211):setPos(22,80,430);
GetNPCByID(16928768+211):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/bar_of_campfire_chocolate.lua | 36 | 1080 | -----------------------------------------
-- ID: 5941
-- Item: Bar of Campfire Chocolate
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Mind +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5941);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MND, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MND, 1);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Norg/npcs/Deigoff.lua | 13 | 3114 | -----------------------------------
-- Area: Norg
-- NPC: Deigoff
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
require("scripts/zones/Norg/TextIDs");
require("scripts/globals/pathfind");
local path = {
-15.048376, -1.476800, 30.425398,
-15.526757, -1.225124, 29.480957,
-14.723476, -1.423349, 30.104301,
-13.893593, -1.648318, 30.828171,
-12.975020, -1.871566, 31.517338,
-12.044265, -2.053941, 31.966581,
-11.003557, -2.393157, 32.302952,
-9.985520, -2.708733, 32.557224,
-8.916955, -3.017504, 32.716526,
-7.803241, -3.231221, 32.842529,
-6.703550, -3.548066, 32.933296,
-2.621637, -4.728867, 33.234219,
-3.692678, -4.392691, 33.156784,
-4.784571, -4.086610, 33.078362,
-7.672429, -3.273804, 32.870365,
-8.728366, -3.020066, 32.775761,
-9.767247, -2.778361, 32.601532,
-10.786559, -2.469297, 32.379894,
-11.791664, -2.154150, 32.110737,
-12.739241, -1.916063, 31.632357,
-13.613935, -1.713264, 31.018566,
-14.453866, -1.501245, 30.353886,
-15.187916, -1.273126, 29.586229,
-15.810313, -1.031864, 28.727566,
-16.338600, -0.821452, 27.804821,
-16.721289, -0.631609, 26.800562,
-17.015059, -0.430842, 25.772522,
-17.276829, -0.226373, 24.724413,
-17.057823, -0.418425, 25.708294,
-16.776665, -0.621304, 26.739079,
-16.362362, -0.804862, 27.727364,
-15.858993, -1.014936, 28.676291,
-15.207123, -1.261934, 29.550617,
-14.408654, -1.502193, 30.350636,
-13.596487, -1.725003, 31.070555,
-12.709093, -1.926028, 31.662998,
-11.711613, -2.167211, 32.087074,
-10.711581, -2.485834, 32.386322,
-9.675041, -2.801156, 32.616379,
-8.606792, -3.039549, 32.759628,
-7.521237, -3.312841, 32.868916,
-6.463308, -3.617169, 32.952408,
-2.352002, -4.875265, 33.252991,
-3.373222, -4.489793, 33.181557,
-8.309618, -3.099132, 32.823685,
-9.346218, -2.897947, 32.683289,
-10.356988, -2.596533, 32.481487,
-11.362209, -2.289157, 32.248039,
-12.344488, -1.993539, 31.858101,
-13.248831, -1.799422, 31.288286,
-14.096587, -1.592161, 30.646973,
-14.883204, -1.374069, 29.931999,
-15.547549, -1.137073, 29.104630,
-16.128418, -0.943367, 28.213142,
-16.578665, -0.713513, 27.230043,
-16.879889, -0.529637, 26.273342,
-17.146322, -0.330673, 25.258379,
-17.403625, -0.115268, 24.211039
};
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)
player:startEvent(0x0056);
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);
npc:wait(0);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Dangruf_Wadi/npcs/_5b1.lua | 13 | 2972 | -----------------------------------
-- Area: Dangruf Wadi
-- NPC: Strange Apparatus
-- @pos: -494 -4 -100 191
-----------------------------------
package.loaded["scripts/zones/Dangruf_Wadi/TextIDs"] = nil;
require("scripts/zones/Dangruf_Wadi/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0003, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0001, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0001) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0003) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/cup_of_date_tea.lua | 18 | 1397 | -----------------------------------------
-- ID: 5926
-- Item: Cup of Date Tea
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- HP 20
-- MP 30
-- Vitality -1
-- Charisma 5
-- Intelligence 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5926);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_MP, 30);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_CHR, 5);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_MP, 30);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_CHR, 5);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
dpino/snabbswitch | src/apps/intel/loadgen.lua | 14 | 2678 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
local C = ffi.C
local lib = require("core.lib")
local app = require("core.app")
local link = require("core.link")
local intel10g = require("apps.intel.intel10g")
local memory = require("core.memory")
local register = require("lib.hardware.register")
local receive, empty = link.receive, link.empty
local can_transmit, transmit
LoadGen = {}
function LoadGen:new (pciaddress)
local o = { pciaddress = pciaddress,
dev = intel10g.new_sf({pciaddr=pciaddress}) }
o.dev:open()
o.dev:wait_linkup()
disable_tx_descriptor_writeback(o.dev)
zero_descriptors(o.dev)
can_transmit, transmit = o.dev.can_transmit, o.dev.transmit
return setmetatable(o, {__index = LoadGen})
end
function disable_tx_descriptor_writeback (dev)
-- Disable writeback of transmit descriptors.
-- That way our transmit descriptors stay fresh and reusable.
-- Tell hardware write them to this other memory instead.
local bytes = intel10g.ring_buffer_size() * ffi.sizeof(intel10g.rxdesc_t)
local ptr, phy = memory.dma_alloc(bytes)
dev.r.TDWBAL(phy % 2^32)
dev.r.TDWBAH(phy / 2^32)
end
function zero_descriptors (dev)
-- Clear unused descriptors
local b = memory.dma_alloc(4096)
for i = 0, intel10g.ring_buffer_size()-1 do
-- Make each descriptors point to valid DMA memory but be 0 bytes long.
dev.txdesc[i].address = memory.virtual_to_physical(b)
dev.txdesc[i].options = bit.lshift(1, 24) -- End of Packet flag
end
end
function LoadGen:push ()
if self.input.input then
while not link.empty(self.input.input) and can_transmit(self.dev) do
do local p = receive(self.input.input)
transmit(self.dev, p)
end
end
end
end
function LoadGen:pull ()
-- Set TDT behind TDH to make all descriptors available for TX.
local dev = self.dev
local tdh = dev.r.TDH()
if dev.tdt == 0 then return end
C.full_memory_barrier()
if tdh == 0 then
dev.r.TDT(intel10g.ring_buffer_size())
else
dev.r.TDT(tdh - 1)
end
end
function LoadGen:report ()
print(self.pciaddress,
"TXDGPC (TX packets)", lib.comma_value(tonumber(self.dev.s.TXDGPC())),
"GOTCL (TX octets)", lib.comma_value(tonumber(self.dev.s.GOTCL())))
print(self.pciaddress,
"RXDGPC (RX packets)", lib.comma_value(tonumber(self.dev.s.RXDGPC())),
"GORCL (RX octets)", lib.comma_value(tonumber(self.dev.s.GORCL())))
self.dev.s.TXDGPC:reset()
self.dev.s.GOTCL:reset()
self.dev.s.RXDGPC:reset()
self.dev.s.GORCL:reset()
end
| apache-2.0 |
nesstea/darkstar | scripts/globals/items/zafmlug_bass.lua | 18 | 1319 | -----------------------------------------
-- ID: 4385
-- Item: zafmlug_bass
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4385);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
dpino/snabbswitch | lib/ljsyscall/syscall/netbsd/ioctl.lua | 24 | 9458 | -- ioctls, filling in as needed
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local s, t = types.s, types.t
local strflag = require("syscall.helpers").strflag
local bit = require "syscall.bit"
local band = bit.band
local function bor(...)
local r = bit.bor(...)
if r < 0 then r = r + 4294967296 end -- want unsigned range
return r
end
local lshift = bit.lshift
local rshift = bit.rshift
local IOC = {
VOID = 0x20000000,
OUT = 0x40000000,
IN = 0x80000000,
DIRMASK = 0xe0000000,
PARM_MASK = 0x1fff,
PARM_SHIFT = 16,
GROUP_SHIFT = 8,
}
IOC.INOUT = IOC.IN + IOC.OUT
local function ioc(dir, ch, nr, size)
return t.ulong(bor(dir,
lshift(band(size, IOC.PARM_MASK), IOC.PARM_SHIFT),
lshift(ch, IOC.GROUP_SHIFT),
nr))
end
local singletonmap = {
int = "int1",
char = "char1",
uint = "uint1",
uint64 = "uint64_1",
}
local function _IOC(dir, ch, nr, tp)
if type(ch) == "string" then ch = ch:byte() end
if type(tp) == "number" then return ioc(dir, ch, nr, tp) end
local size = s[tp]
local singleton = singletonmap[tp] ~= nil
tp = singletonmap[tp] or tp
return {number = ioc(dir, ch, nr, size),
read = dir == IOC.OUT or dir == IOC.INOUT, write = dir == IOC.IN or dir == IOC.INOUT,
type = t[tp], singleton = singleton}
end
local _IO = function(ch, nr) return _IOC(IOC.VOID, ch, nr, 0) end
local _IOR = function(ch, nr, tp) return _IOC(IOC.OUT, ch, nr, tp) end
local _IOW = function(ch, nr, tp) return _IOC(IOC.IN, ch, nr, tp) end
local _IOWR = function(ch, nr, tp) return _IOC(IOC.INOUT, ch, nr, tp) end
--[[
#define IOCPARM_LEN(x) (((x) >> IOCPARM_SHIFT) & IOCPARM_MASK)
#define IOCBASECMD(x) ((x) & ~(IOCPARM_MASK << IOCPARM_SHIFT))
#define IOCGROUP(x) (((x) >> IOCGROUP_SHIFT) & 0xff)
#define IOCPARM_MAX NBPG /* max size of ioctl args, mult. of NBPG */
]]
local ioctl = strflag {
-- tty ioctls
TIOCEXCL = _IO('t', 13),
TIOCNXCL = _IO('t', 14),
TIOCFLUSH = _IOW('t', 16, "int"),
TIOCGETA = _IOR('t', 19, "termios"),
TIOCSETA = _IOW('t', 20, "termios"),
TIOCSETAW = _IOW('t', 21, "termios"),
TIOCSETAF = _IOW('t', 22, "termios"),
TIOCGETD = _IOR('t', 26, "int"),
TIOCSETD = _IOW('t', 27, "int"),
--#define TTLINEDNAMELEN 32
--typedef char linedn_t[TTLINEDNAMELEN]
--TIOCGLINED = _IOR('t', 66, linedn_t),
--TIOCSLINED = _IOW('t', 67, linedn_t),
TIOCSBRK = _IO('t', 123),
TIOCCBRK = _IO('t', 122),
TIOCSDTR = _IO('t', 121),
TIOCCDTR = _IO('t', 120),
TIOCGPGRP = _IOR('t', 119, "int"),
TIOCSPGRP = _IOW('t', 118, "int"),
TIOCOUTQ = _IOR('t', 115, "int"),
TIOCSTI = _IOW('t', 114, "char"),
TIOCNOTTY = _IO('t', 113),
TIOCPKT = _IOW('t', 112, "int"), -- TODO this defines constants eg TIOCPKT_DATA need way to support
TIOCSTOP = _IO('t', 111),
TIOCSTART = _IO('t', 110),
TIOCMSET = _IOW('t', 109, "int"), -- todo uses constants eg TIOCM_LE
TIOCMBIS = _IOW('t', 108, "int"),
TIOCMBIC = _IOW('t', 107, "int"),
TIOCMGET = _IOR('t', 106, "int"),
TIOCREMOTE = _IOW('t', 105, "int"),
TIOCGWINSZ = _IOR('t', 104, "winsize"),
TIOCSWINSZ = _IOW('t', 103, "winsize"),
TIOCUCNTL = _IOW('t', 102, "int"),
TIOCSTAT = _IOW('t', 101, "int"),
--UIOCCMD(n) = _IO('u', n), /* usr cntl op "n" */
TIOCGSID = _IOR('t', 99, "int"),
TIOCCONS = _IOW('t', 98, "int"),
TIOCSCTTY = _IO('t', 97),
TIOCEXT = _IOW('t', 96, "int"),
TIOCSCTTY = _IO('t', 97),
TIOCEXT = _IOW('t', 96, "int"),
TIOCSIG = _IO('t', 95),
TIOCDRAIN = _IO('t', 94),
TIOCGFLAGS = _IOR('t', 93, "int"),
TIOCSFLAGS = _IOW('t', 92, "int"), -- TODO defines flags TIOCFLAG_*
TIOCDCDTIMESTAMP=_IOR('t', 88, "timeval"),
--TIOCRCVFRAME = _IOW('t', 69, struct mbuf *), -- TODO pointer not struct
--TIOCXMTFRAME = _IOW('t', 68, struct mbuf *), -- TODO pointer not struct
TIOCPTMGET = _IOR('t', 70, "ptmget"),
TIOCGRANTPT = _IO('t', 71),
TIOCPTSNAME = _IOR('t', 72, "ptmget"),
TIOCSQSIZE = _IOW('t', 128, "int"),
TIOCGQSIZE = _IOR('t', 129, "int"),
-- socket ioctls
SIOCSHIWAT = _IOW('s', 0, "int"),
SIOCGHIWAT = _IOR('s', 1, "int"),
SIOCSLOWAT = _IOW('s', 2, "int"),
SIOCGLOWAT = _IOR('s', 3, "int"),
SIOCATMARK = _IOR('s', 7, "int"),
SIOCSPGRP = _IOW('s', 8, "int"),
SIOCGPGRP = _IOR('s', 9, "int"),
--SIOCADDRT = _IOW('r', 10, "ortentry"),
--SIOCDELRT = _IOW('r', 11, "ortentry"),
SIOCSIFADDR = _IOW('i', 12, "ifreq"),
SIOCGIFADDR = _IOWR('i', 33, "ifreq"),
SIOCSIFDSTADDR = _IOW('i', 14, "ifreq"),
SIOCGIFDSTADDR = _IOWR('i', 34, "ifreq"),
SIOCSIFFLAGS = _IOW('i', 16, "ifreq"),
SIOCGIFFLAGS = _IOWR('i', 17, "ifreq"),
SIOCGIFBRDADDR = _IOWR('i', 35, "ifreq"),
SIOCSIFBRDADDR = _IOW('i', 19, "ifreq"),
--SIOCGIFCONF = _IOWR('i', 38, "ifconf"),
SIOCGIFNETMASK = _IOWR('i', 37, "ifreq"),
SIOCSIFNETMASK = _IOW('i', 22, "ifreq"),
SIOCGIFMETRIC = _IOWR('i', 23, "ifreq"),
SIOCSIFMETRIC = _IOW('i', 24, "ifreq"),
SIOCDIFADDR = _IOW('i', 25, "ifreq"),
SIOCAIFADDR = _IOW('i', 26, "ifaliasreq"),
SIOCGIFALIAS = _IOWR('i', 27, "ifaliasreq"),
--SIOCALIFADDR = _IOW('i', 28, "if_laddrreq"),
--SIOCGLIFADDR = _IOWR('i', 29, "if_laddrreq"),
--SIOCDLIFADDR = _IOW('i', 30, "if_laddrreq"),
--SIOCSIFADDRPREF= _IOW('i', 31, "if_addrprefreq"),
--SIOCGIFADDRPREF= _IOWR('i', 32, "if_addrprefreq"),
SIOCADDMULTI = _IOW('i', 49, "ifreq"),
SIOCDELMULTI = _IOW('i', 50, "ifreq"),
--SIOCGETVIFCNT = _IOWR('u', 51, "sioc_vif_req"),
--SIOCGETSGCNT = _IOWR('u', 52, "sioc_sg_req"),
SIOCSIFMEDIA = _IOWR('i', 53, "ifreq"),
--SIOCGIFMEDIA = _IOWR('i', 54, "ifmediareq"),
SIOCSIFGENERIC = _IOW('i', 57, "ifreq"),
SIOCGIFGENERIC = _IOWR('i', 58, "ifreq"),
SIOCSIFPHYADDR = _IOW('i', 70, "ifaliasreq"),
SIOCGIFPSRCADDR= _IOWR('i', 71, "ifreq"),
SIOCGIFPDSTADDR= _IOWR('i', 72, "ifreq"),
SIOCDIFPHYADDR = _IOW('i', 73, "ifreq"),
--SIOCSLIFPHYADDR= _IOW('i', 74, "if_laddrreq"),
--SIOCGLIFPHYADDR= _IOWR('i', 75, "if_laddrreq"),
SIOCSIFMTU = _IOW('i', 127, "ifreq"),
SIOCGIFMTU = _IOWR('i', 126, "ifreq"),
SIOCSDRVSPEC = _IOW('i', 123, "ifdrv"),
SIOCGDRVSPEC = _IOWR('i', 123, "ifdrv"),
SIOCIFCREATE = _IOW('i', 122, "ifreq"),
SIOCIFDESTROY = _IOW('i', 121, "ifreq"),
--SIOCIFGCLONERS = _IOWR('i', 120, "if_clonereq"),
SIOCGIFDLT = _IOWR('i', 119, "ifreq"),
--SIOCGIFCAP = _IOWR('i', 118, "ifcapreq"),
--SIOCSIFCAP = _IOW('i', 117, "ifcapreq"),
SIOCSVH = _IOWR('i', 130, "ifreq"),
SIOCGVH = _IOWR('i', 131, "ifreq"),
--SIOCINITIFADDR = _IOWR('i', 132, "ifaddr"),
--SIOCGIFDATA = _IOWR('i', 133, "ifdatareq"),
--SIOCZIFDATA = _IOWR('i', 134, "ifdatareq"),
SIOCGLINKSTR = _IOWR('i', 135, "ifdrv"),
SIOCSLINKSTR = _IOW('i', 136, "ifdrv"),
SIOCSETPFSYNC = _IOW('i', 247, "ifreq"),
SIOCGETPFSYNC = _IOWR('i', 248, "ifreq"),
-- ipv6 ioctls
SIOCSIFADDR_IN6 = _IOW('i', 12, "in6_ifreq"),
SIOCGIFADDR_IN6 = _IOWR('i', 33, "in6_ifreq"),
SIOCGIFDSTADDR_IN6 = _IOWR('i', 34, "in6_ifreq"),
SIOCGIFNETMASK_IN6 = _IOWR('i', 37, "in6_ifreq"),
SIOCDIFADDR_IN6 = _IOW('i', 25, "in6_ifreq"),
SIOCGIFPSRCADDR_IN6 = _IOWR('i', 71, "in6_ifreq"),
SIOCGIFPDSTADDR_IN6 = _IOWR('i', 72, "in6_ifreq"),
SIOCGIFAFLAG_IN6 = _IOWR('i', 73, "in6_ifreq"),
--SIOCGDRLST_IN6 = _IOWR('i', 74, "in6_drlist"),
--SIOCGPRLST_IN6 = _IOWR('i', 75, "in6_oprlist"),
SIOCSNDFLUSH_IN6 = _IOWR('i', 77, "in6_ifreq"),
--SIOCGNBRINFO_IN6 = _IOWR('i', 78, "in6_nbrinfo"),
SIOCSPFXFLUSH_IN6 = _IOWR('i', 79, "in6_ifreq"),
SIOCSRTRFLUSH_IN6 = _IOWR('i', 80, "in6_ifreq"),
SIOCGIFSTAT_IN6 = _IOWR('i', 83, "in6_ifreq"),
SIOCGIFSTAT_ICMP6 = _IOWR('i', 84, "in6_ifreq"),
--SIOCSDEFIFACE_IN6 = _IOWR('i', 85, "in6_ndifreq"),
--SIOCGDEFIFACE_IN6 = _IOWR('i', 86, "in6_ndifreq"),
--SIOCSIFINFO_FLAGS = _IOWR('i', 87, "in6_ndireq"),
--SIOCSIFPREFIX_IN6 = _IOW('i', 100, "in6_prefixreq"),
--SIOCGIFPREFIX_IN6 = _IOWR('i', 101, "in6_prefixreq"),
--SIOCDIFPREFIX_IN6 = _IOW('i', 102, "in6_prefixreq"),
--SIOCAIFPREFIX_IN6 = _IOW('i', 103, "in6_rrenumreq"),
--SIOCCIFPREFIX_IN6 = _IOW('i', 104, "in6_rrenumreq"),
--SIOCSGIFPREFIX_IN6 = _IOW('i', 105, "in6_rrenumreq"),
SIOCGIFALIFETIME_IN6= _IOWR('i', 106, "in6_ifreq"),
SIOCAIFADDR_IN6 = _IOW('i', 107, "in6_aliasreq"),
--SIOCGIFINFO_IN6 = _IOWR('i', 108, struct in6_ndireq),
--SIOCSIFINFO_IN6 = _IOWR('i', 109, struct in6_ndireq),
SIOCSIFPHYADDR_IN6 = _IOW('i', 110, "in6_aliasreq"),
-- kqueue ioctls
KFILTER_BYFILTER = _IOWR('k', 0, "kfilter_mapping"),
KFILTER_BYNAME = _IOWR('k', 1, "kfilter_mapping"),
-- allow user defined ioctls
_IO = _IO,
_IOR = _IOR,
_IOW = _IOW,
_IOWR = _IOWR,
}
ioctl.TIOCM_CD = ioctl.TIOCM_CAR
ioctl.TIOCM_RI = ioctl.TIOCM_RNG
return ioctl
end
return {init = init}
| apache-2.0 |
akdor1154/awesome | lib/awful/widget/taglist.lua | 1 | 9606 | ---------------------------------------------------------------------------
--- Taglist widget module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @classmod awful.widget.taglist
---------------------------------------------------------------------------
-- Grab environment we need
local capi = { screen = screen,
awesome = awesome,
client = client }
local setmetatable = setmetatable
local pairs = pairs
local ipairs = ipairs
local table = table
local common = require("awful.widget.common")
local util = require("awful.util")
local tag = require("awful.tag")
local beautiful = require("beautiful")
local fixed = require("wibox.layout.fixed")
local surface = require("gears.surface")
local timer = require("gears.timer")
local function get_screen(s)
return s and capi.screen[s]
end
local taglist = { mt = {} }
taglist.filter = {}
local instances = nil
function taglist.taglist_label(t, args)
if not args then args = {} end
local theme = beautiful.get()
local fg_focus = args.fg_focus or theme.taglist_fg_focus or theme.fg_focus
local bg_focus = args.bg_focus or theme.taglist_bg_focus or theme.bg_focus
local fg_urgent = args.fg_urgent or theme.taglist_fg_urgent or theme.fg_urgent
local bg_urgent = args.bg_urgent or theme.taglist_bg_urgent or theme.bg_urgent
local bg_occupied = args.bg_occupied or theme.taglist_bg_occupied
local fg_occupied = args.fg_occupied or theme.taglist_fg_occupied
local bg_empty = args.bg_empty or theme.taglist_bg_empty
local fg_empty = args.fg_empty or theme.taglist_fg_empty
local taglist_squares_sel = args.squares_sel or theme.taglist_squares_sel
local taglist_squares_unsel = args.squares_unsel or theme.taglist_squares_unsel
local taglist_squares_sel_empty = args.squares_sel_empty or theme.taglist_squares_sel_empty
local taglist_squares_unsel_empty = args.squares_unsel_empty or theme.taglist_squares_unsel_empty
local taglist_squares_resize = theme.taglist_squares_resize or args.squares_resize or "true"
local taglist_disable_icon = args.taglist_disable_icon or theme.taglist_disable_icon or false
local font = args.font or theme.taglist_font or theme.font or ""
local text = nil
local sel = capi.client.focus
local bg_color = nil
local fg_color = nil
local bg_image
local icon
-- TODO: Re-implement bg_resize
local bg_resize = false -- luacheck: ignore
local is_selected = false
local cls = t:clients()
if sel and taglist_squares_sel then
-- Check that the selected client is tagged with 't'.
local seltags = sel:tags()
for _, v in ipairs(seltags) do
if v == t then
bg_image = taglist_squares_sel
bg_resize = taglist_squares_resize == "true"
is_selected = true
break
end
end
end
if #cls == 0 and t.selected and taglist_squares_sel_empty then
bg_image = taglist_squares_sel_empty
bg_resize = taglist_squares_resize == "true"
elseif not is_selected then
if #cls > 0 then
if taglist_squares_unsel then
bg_image = taglist_squares_unsel
bg_resize = taglist_squares_resize == "true"
end
if bg_occupied then bg_color = bg_occupied end
if fg_occupied then fg_color = fg_occupied end
else
if taglist_squares_unsel_empty then
bg_image = taglist_squares_unsel_empty
bg_resize = taglist_squares_resize == "true"
end
if bg_empty then bg_color = bg_empty end
if fg_empty then fg_color = fg_empty end
end
end
if t.selected then
bg_color = bg_focus
fg_color = fg_focus
elseif tag.getproperty(t, "urgent") then
if bg_urgent then bg_color = bg_urgent end
if fg_urgent then fg_color = fg_urgent end
end
if not tag.getproperty(t, "icon_only") then
text = "<span font_desc='"..font.."'>"
if fg_color then
text = text .. "<span color='" .. util.ensure_pango_color(fg_color) ..
"'>" .. (util.escape(t.name) or "") .. "</span>"
else
text = text .. (util.escape(t.name) or "")
end
text = text .. "</span>"
end
if not taglist_disable_icon then
if tag.geticon(t) then
icon = surface.load(tag.geticon(t))
end
end
return text, bg_color, bg_image, not taglist_disable_icon and icon or nil
end
local function taglist_update(s, w, buttons, filter, data, style, update_function)
local tags = {}
for _, t in ipairs(tag.gettags(s)) do
if not tag.getproperty(t, "hide") and filter(t) then
table.insert(tags, t)
end
end
local function label(c) return taglist.taglist_label(c, style) end
update_function(w, buttons, label, data, tags)
end
--- Create a new taglist widget. The last two arguments (update_function
-- and base_widget) serve to customize the layout of the taglist (eg. to
-- make it vertical). For that, you will need to copy the
-- awful.widget.common.list_update function, make your changes to it
-- and pass it as update_function here. Also change the base_widget if the
-- default is not what you want.
-- @param screen The screen to draw taglist for.
-- @param filter Filter function to define what clients will be listed.
-- @param buttons A table with buttons binding to set.
-- @param style The style overrides default theme.
-- @param[opt] update_function Function to create a tag widget on each
-- update. @see awful.widget.common.
-- @param[opt] base_widget Optional container widget for tag widgets. Default
-- is wibox.layout.fixed.horizontal().
-- @param base_widget.bg_focus The background color for focused client.
-- @param base_widget.fg_focus The foreground color for focused client.
-- @param base_widget.bg_urgent The background color for urgent clients.
-- @param base_widget.fg_urgent The foreground color for urgent clients.
-- @param[opt] base_widget.squares_sel A user provided image for selected squares.
-- @param[opt] base_widget.squares_unsel A user provided image for unselected squares.
-- @param[opt] base_widget.squares_sel_empty A user provided image for selected squares for empty tags.
-- @param[opt] base_widget.squares_unsel_empty A user provided image for unselected squares for empty tags.
-- @param[opt] base_widget.squares_resize True or false to resize squares.
-- @param base_widget.font The font.
function taglist.new(screen, filter, buttons, style, update_function, base_widget)
screen = get_screen(screen)
local uf = update_function or common.list_update
local w = base_widget or fixed.horizontal()
local data = setmetatable({}, { __mode = 'k' })
local queued_update = {}
function w._do_taglist_update()
-- Add a delayed callback for the first update.
if not queued_update[screen] then
timer.delayed_call(function()
taglist_update(screen, w, buttons, filter, data, style, uf)
queued_update[screen] = false
end)
queued_update[screen] = true
end
end
if instances == nil then
instances = {}
local function u(s)
local i = instances[get_screen(s)]
if i then
for _, tlist in pairs(i) do
tlist._do_taglist_update()
end
end
end
local uc = function (c) return u(c.screen) end
local ut = function (t) return u(tag.getscreen(t)) end
capi.client.connect_signal("focus", uc)
capi.client.connect_signal("unfocus", uc)
tag.attached_connect_signal(nil, "property::selected", ut)
tag.attached_connect_signal(nil, "property::icon", ut)
tag.attached_connect_signal(nil, "property::hide", ut)
tag.attached_connect_signal(nil, "property::name", ut)
tag.attached_connect_signal(nil, "property::activated", ut)
tag.attached_connect_signal(nil, "property::screen", ut)
tag.attached_connect_signal(nil, "property::index", ut)
tag.attached_connect_signal(nil, "property::urgent", ut)
capi.client.connect_signal("property::screen", function(c, old_screen)
u(c.screen)
u(old_screen)
end)
capi.client.connect_signal("tagged", uc)
capi.client.connect_signal("untagged", uc)
capi.client.connect_signal("unmanage", uc)
end
w._do_taglist_update()
local list = instances[screen]
if not list then
list = setmetatable({}, { __mode = "v" })
instances[screen] = list
end
table.insert(list, w)
return w
end
--- Filtering function to include all nonempty tags on the screen.
-- @param t The tag.
-- @return true if t is not empty, else false
function taglist.filter.noempty(t)
return #t:clients() > 0 or t.selected
end
--- Filtering function to include selected tags on the screen.
-- @param t The tag.
-- @return true if t is not empty, else false
function taglist.filter.selected(t)
return t.selected
end
--- Filtering function to include all tags on the screen.
-- @return true
function taglist.filter.all()
return true
end
function taglist.mt:__call(...)
return taglist.new(...)
end
return setmetatable(taglist, taglist.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/mobskills/Lateral_Slash.lua | 25 | 1073 | ---------------------------------------------
-- Lateral Slash
--
-- Description: Laterally slashes a single target. Additional effect: Defense Down
-- Type: Physical
-- Utsusemi/Blink absorb: 1 shadow
-- Range: Melee
-- Notes: Reduces defense by 75%. Can be removed with Monk Job Ability Counterstance.
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 2;
local dmgmod = 2.7;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local typeEffect = EFFECT_DEFENSE_DOWN;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 75, 0, 60);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Melleupaux.lua | 37 | 1310 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Melleupaux
-- 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,MELLEUPAUX_SHOP_DIALOG);
stock = {0x4042,1867, --Dagger
0x40b6,8478, --Longsword
0x43B7,8, --Rusty Bolt
0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet)
0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet)
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 |
nesstea/darkstar | scripts/globals/weaponskills/bora_axe.lua | 11 | 1740 | -----------------------------------
-- Bora Axe
-- Axe weapon skill
-- Skill level: 290
-- Delivers a single-hit ranged attack at a maximum distance of 15.7'. Chance of binding varies with TP
-- Bind doesn't always break from hitting mob.
-- This Weapon Skill's first hit params.ftp is duplicated for all additional hits
-- Not natively available to RNG
-- Aligned with the ?? Gorget.
-- Element: Ice
-- Modifiers: DEX 60% -- http://wiki.bluegartr.com/bg/Bora_Axe
-- 100%TP 200%TP 300%TP
-- 1.0 1.0 1.0
-----------------------------------
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.0; params.ftp200 = 1.0; params.ftp300 = 1.0;
params.str_wsc = 0.0; params.dex_wsc = 0.6; 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 = 3.5;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 4.5; params.ftp200 = 4.5; params.ftp300 = 4.5;
params.dex_wsc = 1.0;
params.atkmulti = 1.0;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
if (damage > 0 and target:hasStatusEffect(EFFECT_BIND) == false) then
target:addStatusEffect(EFFECT_BIND, 1, 0, 20);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Qufim_Island/npcs/Hieroglyphics.lua | 17 | 2168 | -----------------------------------
-- Area: Qufim_Island
-- NPC: Hieroglyphics
-- Dynamis Qufim Entrance
-- @pos 117 -10 133 172 118
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/globals/missions");
require("scripts/zones/Qufim_Island/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:hasCompletedMission(COP,DARKNESS_NAMED) or FREE_COP_DYNAMIS == 1) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if(player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaQufim]UniqueID")) then
player:startEvent(0x0003,9,0,0,BETWEEN_2DYNA_WAIT_TIME,32,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
--printf("dayRemaining : %u",dayRemaining );
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,8);
end
else
player:messageSpecial(MYSTERIOUS_VOICE);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if(csid == 0x0003 and option == 0) then
player:setPos(-19,-17,104,253,41);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Southern_San_dOria_[S]/npcs/Moogle.lua | 29 | 1205 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Moogle
-- @zone 80
-- @pos <many>
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
require("scripts/globals/moghouse")
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
moogleTrade(player,npc,trade);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (not moogleTrigger(player,npc)) then
player:startEvent(0x003D);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x7530) then
player:setVar("MoghouseExplication",0);
end
end; | gpl-3.0 |
Irubataru/dotfiles | roles/awesome/config/config/keys/global/awesome.lua | 1 | 1939 | local awful = require("awful")
local launcher = require("modules.launcher")
local hotkeys_popup = require("awful.hotkeys_popup").widget
local apps = require("config.apps")
local modkey = require("config.keys.mod").mod_key
awful.keyboard.append_global_keybindings({
awful.key({ modkey }, "s", hotkeys_popup.show_help, { description = "show help", group = "awesome" }),
awful.key({ modkey }, "w", function()
launcher:show()
end, { description = "show main menu", group = "awesome" }),
-- Standard program
awful.key({ modkey }, "Return", function()
awful.spawn(apps.default.open_terminal)
end, { description = "open a terminal", group = "launcher" }),
awful.key({ modkey, "Control" }, "r", awesome.restart, { description = "reload awesome", group = "awesome" }),
awful.key({ modkey, "Shift" }, "q", awesome.quit, { description = "quit awesome", group = "awesome" }),
-- Prompt
awful.key({ modkey }, "r", function()
awful.spawn("rofi -show drun")
end, { description = "run prompt", group = "rofi" }),
awful.key({ modkey, "Shift" }, "r", function()
awful.screen.focused().prompt:run()
end, { description = "run prompt", group = "launcher" }),
awful.key({ modkey }, "x", function()
awful.prompt.run({
prompt = "Run Lua code: ",
textbox = awful.screen.focused().prompt.widget,
exe_callback = awful.util.eval,
history_path = awful.util.get_cache_dir() .. "/history_eval",
})
end, { description = "lua execute prompt", group = "awesome" }),
awful.key({ modkey }, ".", function()
awful.spawn("rofi -show emoji")
end, { description = "show emoji menu", group = "rofi" }),
awful.key({}, "XF86Calculator", function()
awful.spawn("rofi -show calc")
end, { description = "show calculator", group = "rofi" }),
awful.key({ modkey }, "b", function()
awful.spawn("rofi -show window")
end, { description = "window switcher", group = "rofi" }),
})
| mit |
LuaDist/im | doc/html/examples/info_serialize.lua | 1 | 5167 | require"imlua"
require"lfs"
function serialize (o, indent)
-- this function enables most types of data to be printed
-- it is based on examples in "Programming in Lua" 2nd edition
-- by Roberto Ierusalimschy
indent = indent or 0
if type(o) == "number" then
io.write(string.rep(" ",indent),o) -- string.rep repeats argument
elseif type(o) == "string" then
io.write(string.rep(" ",indent),string.format("%q",o))
elseif type(o) == "table" then
io.write(string.rep(" ",indent-2),"{\n")
for k,v in pairs(o) do -- pairs gets the key and value for the next
-- element of the table
io.write(string.rep(" ",indent), k, " = ")
serialize(v, indent+2)
io.write(string.rep(" ",indent),",\n")
end
io.write(string.rep(" ",indent-2),"}\n")
else
error("cannot serialize a " ..type(o))
end
end
function PrintError(error)
local msg = {}
msg[im.ERR_OPEN] = "Error Opening File."
msg[im.ERR_MEM] = "Insuficient memory."
msg[im.ERR_ACCESS] = "Error Accessing File."
msg[im.ERR_DATA] = "Image type not Suported."
msg[im.ERR_FORMAT] = "Invalid Format."
msg[im.ERR_COMPRESS] = "Invalid or unsupported compression."
if msg[error] then
print(msg[error])
else
print("Unknown Error.")
end
end
function FindZero(data)
if (not data) then return false end
for i = 1, table.getn(data) do
if data[i] == 0 then
return true
end
end
return false
end
function AttribData2Str(data, data_type)
local data_str
if data_type == im.BYTE then
data_str = string.format("%3d", data[1])
elseif data_type == im.USHORT then
data_str = string.format("%5d", data[1])
elseif data_type == im.INT then
data_str = string.format("%5d", data[1])
elseif data_type == im.FLOAT then
data_str = string.format("%5.2f", data[1])
elseif data_type == im.CFLOAT then
data_str = string.format("%5.2f, %5.2f", data[1], data[2])
end
return data_str
end
function GetSizeDesc(size)
local size_desc
if size < 1024 then
size_desc = "b"
else
size = size / 1024
if size < 1024 then
size_desc = "Kb"
else
size = size / 1024
size_desc = "Mb"
end
end
return size, size_desc
end
function FileSize(file_name)
if lfs then
local attr = lfs.attributes(file_name)
return attr.size
else
return 0
end
end
function PrintImageInfo(file_name)
print("IM Info")
print(string.format(" File Name:\n %s", file_name))
local ifile, error = im.FileOpen(file_name)
if not ifile then
PrintError(error)
return nil
end
local file_size = FileSize(file_name)
print(string.format(" File Size: %.2f %s", GetSizeDesc(file_size)))
local format, compression, image_count = ifile:GetInfo()
local error, format_desc = im.FormatInfo(format)
print(string.format(" Format: %s - %s", format, format_desc))
print(string.format(" Compression: %s", compression))
print(string.format(" Image Count: %d", image_count))
for i = 1, image_count do
local error, width, height, color_mode, data_type = ifile:ReadImageInfo(i-1)
if width == nil then
PrintError(height)
ifile:Close()
return nil
end
print(string.format(" Image #%d", i))
print(string.format(" Width: %d", width))
print(string.format(" Height: %d", height))
print(string.format(" Color Space: %s", im.ColorModeSpaceName(color_mode)))
print(string.format(" Has Alpha: %s", im.ColorModeHasAlpha(color_mode) and "Yes" or "No"))
print(string.format(" Is Packed: %s", im.ColorModeIsPacked(color_mode) and "Yes" or "No"))
print(string.format(" Is Top Down: %s", im.ColorModeIsTopDown(color_mode) and "Yes" or "No"))
print(string.format(" Data Type: %s", im.DataTypeName(data_type)))
local image_size = im.ImageDataSize(width, height, color_mode, data_type)
print(string.format(" Data Size: %.2f %s", GetSizeDesc(image_size)))
local attrib_list = ifile:GetAttributeList()
for a = 1, table.getn(attrib_list) do
if a == 1 then
print(" Attributes:")
end
local attrib_data, attrib_data_type = ifile:GetAttribute(attrib_list[a])
if table.getn(attrib_data) == 1 then
print(string.format(" %s: %s", attrib_list[a], AttribData2Str(attrib_data, attrib_data_type)))
elseif attrib_data_type == im.BYTE and FindZero(attrib_data) then
attrib_data = ifile:GetAttribute(attrib_list[a], true)
print(string.format(" %s: %s", attrib_list[a], attrib_data))
else
--print(string.format(" %s: %s ...", attrib_list[a], AttribData2Str(attrib_data, attrib_data_type)))
print(string.format(" %s: ", attrib_list[a] ))
serialize(attrib_data, 8)
end
end
end
ifile:Close()
end
function main(arg)
if (not arg or table.getn(arg) < 1) then
print("Invalid number of arguments.")
return nil
end
PrintImageInfo(arg[1])
return 1
end
main(arg)
| mit |
cloner-hooshesiyah/ppbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/slow_ii.lua | 11 | 1662 | -----------------------------------------
-- Spell: Slow II
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point
-- Slow II value per point is '1' This is a constant set in the table 'merits'
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND));
local potency = 230 + math.floor(dMND * 1.6);
-- ([230] + [y * 10] + [floor(dMND * 1.6)])/1024
if(potency > 350) then
potency = 350;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
potency = potency * 2;
end
local merits = caster:getMerit(MERIT_SLOW_II);
--Power.
local power = (potency + (merits * 10));
--Duration, including resistance.
local duration = 180 * applyResistanceEffect(caster,spell,target,dMND,35,merits*2,EFFECT_SLOW);
if(duration >= 60) then --Do it!
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
if(target:addStatusEffect(EFFECT_SLOW,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
return EFFECT_SLOW;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Attarena.lua | 30 | 1955 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Attarena
-- Only sells when San d'Oria controlls Li'Telor Region
-----------------------------------
package.loaded["scripts/zones/Northern_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/Northern_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(LITELOR);
if (RegionOwner ~= SANDORIA) then
player:showText(npc,ATTARENA_CLOSED_DIALOG);
else
player:showText(npc,ATTARENA_OPEN_DIALOG);
stock = {0x026f,119, -- Bay Leaves
0x103a,6440} -- Holy Water
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/zones/Windurst_Waters_[S]/npcs/Kocco_Ehllek.lua | 13 | 1068 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Kocco Ehllek
-- Type: Quest Giver
-- @zone: 94
-- @pos -41.465 -2.125 -163.018
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x008c);
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 |
FailcoderAddons/supervillain-ui | SVUI_!Core/system/misc.lua | 2 | 28209 | --[[
##########################################################
S V U I By: Failcoder
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
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 tostring = _G.tostring;
local tonumber = _G.tonumber;
local collectgarbage = _G.collectgarbage;
local string = _G.string;
local split = string.split;
local upper = string.upper;
local format = string.format;
local find = string.find;
local match = string.match;
local gsub = string.gsub;
local math = _G.math;
local min = math.min;
local cos, deg, rad, sin = math.cos, math.deg, math.rad, math.sin;
local random = math.random;
local wipe = _G.wipe;
--BLIZZARD API
local CreateFrame = _G.CreateFrame;
local InCombatLockdown = _G.InCombatLockdown;
local GameTooltip = _G.GameTooltip;
local ReloadUI = _G.ReloadUI;
local hooksecurefunc = _G.hooksecurefunc;
local IsAltKeyDown = _G.IsAltKeyDown;
local IsShiftKeyDown = _G.IsShiftKeyDown;
local IsControlKeyDown = _G.IsControlKeyDown;
local IsModifiedClick = _G.IsModifiedClick;
local PlaySound = _G.PlaySound;
local PlaySoundFile = _G.PlaySoundFile;
local PlayMusic = _G.PlayMusic;
local StopMusic = _G.StopMusic;
local ToggleFrame = _G.ToggleFrame;
local ERR_NOT_IN_COMBAT = _G.ERR_NOT_IN_COMBAT;
local RAID_CLASS_COLORS = _G.RAID_CLASS_COLORS;
local CUSTOM_CLASS_COLORS = _G.CUSTOM_CLASS_COLORS;
local SendChatMessage = _G.SendChatMessage;
local GetSpellLink = _G.GetSpellLink;
local UnitName = _G.UnitName;
local UnitClass = _G.UnitClass;
local UnitIsPlayer = _G.UnitIsPlayer;
local UnitReaction = _G.UnitReaction;
local UnitExists = _G.UnitExists;
local UnitIsUnit = _G.UnitIsUnit;
local UnitInRaid = _G.UnitInRaid;
local UnitInParty = _G.UnitInParty;
local UnitGUID = _G.UnitGUID;
local UnitIsDead = _G.UnitIsDead;
local UnitIsGroupLeader = _G.UnitIsGroupLeader;
local UnitIsGroupAssistant = _G.UnitIsGroupAssistant;
local IsEveryoneAssistant = _G.IsEveryoneAssistant;
local GetItemInfo = _G.GetItemInfo;
local BuyMerchantItem = _G.BuyMerchantItem;
local GetMerchantItemLink = _G.GetMerchantItemLink;
local GetMerchantItemMaxStack = _G.GetMerchantItemMaxStack;
local UnitDetailedThreatSituation = _G.UnitDetailedThreatSituation;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = select(2, ...);
local L = SV.L;
--[[
##########################################################
LOCALS
##########################################################
]]--
local PlayerName = UnitName("player");
local ThreatMeter = _G["SVUI_ThreatOMeter"];
--[[ LOCALS ]]--
local BARFILE = [[Interface\AddOns\SVUI_!Core\assets\textures\Doodads\THREAT-BAR]];
local TEXTUREFILE = [[Interface\AddOns\SVUI_!Core\assets\textures\Doodads\THREAT-BAR-ELEMENTS]];
local REACTION_COLORS = {
[1] = {0.92, 0.15, 0.15},
[2] = {0.92, 0.15, 0.15},
[3] = {0.92, 0.15, 0.15},
[4] = {0.85, 0.85, 0.13},
[5] = {0.19, 0.85, 0.13},
[6] = {0.19, 0.85, 0.13},
[7] = {0.19, 0.85, 0.13},
[8] = {0.19, 0.85, 0.13},
};
local Reactions = {
Woot = {
[29166] = true, [20484] = true, [61999] = true,
[20707] = true, [50769] = true, [2006] = true,
[7328] = true, [2008] = true, [115178] = true,
[110478] = true, [110479] = true, [110482] = true,
[110483] = true, [110484] = true, [110485] = true,
[110486] = true, [110488] = true, [110490] = true,
[110491] = true
},
LookWhatICanDo = {
34477, 19801, 57934, 633, 20484, 113269, 61999,
20707, 2908, 120668, 16190, 64901, 108968
},
Toys = {
[61031] = true, [49844] = true
},
Bots = {
[22700] = true, [44389] = true, [54711] = true,
[67826] = true, [126459] = true
},
Portals = {
[10059] = true, [11416] = true, [11419] = true,
[32266] = true, [49360] = true, [33691] = true,
[88345] = true, [132620] = true, [11417] = true,
[11420] = true, [11418] = true, [32267] = true,
[49361] = true, [35717] = true, [88346] = true,
[132626] = true, [53142] = true
},
StupidHat = {
[1] = {88710, 33820, 19972, 46349, 92738},
[2] = {32757},
[8] = {50287, 19969},
[15] = {65360, 65274},
[16] = {44050, 19970, 84660, 84661, 45992, 86559, 45991},
[17] = {86558}
}
};
local SAPPED_MESSAGE = {
"Oh Hell No ... {rt8}SAPPED{rt8}",
"{rt8}SAPPED{rt8} ...Someone's about to get slapped!",
"Mother Fu... {rt8}SAPPED{rt8}",
"{rt8}SAPPED{rt8} ...How cute",
"{rt8}SAPPED{rt8} ...Ain't Nobody Got Time For That!",
"Uh-Oh... {rt8}SAPPED{rt8}"
};
local ReactionEmotes = {
"SALUTE",
"THANK",
"DRINK"
};
local REACTION_INTERRUPT, REACTION_WOOT, REACTION_LOOKY, REACTION_SHARE, REACTION_EMOTE, REACTION_CHAT = false, false, false, false, false, false;
local MsgTest = function(warning)
if IsInGroup(LE_PARTY_CATEGORY_INSTANCE) then
return "INSTANCE_CHAT"
elseif IsInRaid(LE_PARTY_CATEGORY_HOME) then
if warning and (UnitIsGroupLeader("player") or UnitIsGroupAssistant("player") or IsEveryoneAssistant()) then
return "RAID_WARNING"
else
return "RAID"
end
elseif IsInGroup(LE_PARTY_CATEGORY_HOME) then
return "PARTY"
end
return "SAY"
end
--[[
##########################################################
MERCHANT MAX STACK
##########################################################
]]--
local BuyMaxStack = function(self, ...)
if ( IsAltKeyDown() ) then
local index = self:GetID()
local itemLink = GetMerchantItemLink(index)
if not itemLink then return end
local price = select(3, GetMerchantItemInfo(index))
local maxStack = select(8, GetItemInfo(itemLink))
local currencyCount = GetMerchantItemCostInfo(index)
if ( maxStack and maxStack > 1 ) then
local maxAllowed = GetMerchantItemMaxStack(index);
if(currencyCount == 0) then
local canAfford = GetMoney() / maxStack;
BuyMerchantItem(index, min(maxAllowed,canAfford));
else
BuyMerchantItem(index, maxAllowed);
end
end
end
end
local MaxStackTooltip = function(self)
if(not GameTooltip.InjectedDouble) then
GameTooltip.InjectedDouble = {}
else
wipe(GameTooltip.InjectedDouble)
end
local itemLink = GetMerchantItemLink(self:GetID())
if not itemLink then return end
local maxStack = select(8, GetItemInfo(itemLink))
if((not maxStack) or (maxStack < 2)) then return end
GameTooltip.InjectedDouble[1] = "[Alt + Click]"
GameTooltip.InjectedDouble[2] = "Buy a full stack."
GameTooltip.InjectedDouble[3] = 0
GameTooltip.InjectedDouble[4] = 0.5
GameTooltip.InjectedDouble[5] = 1
GameTooltip.InjectedDouble[6] = 0.5
GameTooltip.InjectedDouble[7] = 1
GameTooltip.InjectedDouble[8] = 0.5
end
--[[
##########################################################
RAIDMARKERS
##########################################################
]]--
local RaidMarkFrame = _G["SVUI_RaidMarkFrame"];
RaidMarkFrame.Active = false;
do
RaidMarkFrame:EnableMouse(true)
RaidMarkFrame:SetSize(100, 100)
RaidMarkFrame:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
RaidMarkFrame:SetFrameStrata("DIALOG")
local RaidMarkButton_OnEnter = function(self)
self.Texture:ClearAllPoints()
self.Texture:SetPoint("TOPLEFT",-10,10)
self.Texture:SetPoint("BOTTOMRIGHT",10,-10)
end
local RaidMarkButton_OnLeave = function(self)
self.Texture:SetAllPoints()
end
local RaidMarkButton_OnClick = function(self, button)
PlaySound(SOUNDKIT.U_CHAT_SCROLL_BUTTON)
SetRaidTarget("target", button ~= "RightButton" and self:GetID() or 0)
self:GetParent():FadeOut(0.2, 1, 0, true)
end
for i=1,8 do
local mark = CreateFrame("Button", "RaidMarkIconButton"..i, RaidMarkFrame)
mark:SetSize(40, 40)
mark:SetID(i)
mark.Texture = mark:CreateTexture(mark:GetName().."NormalTexture", "ARTWORK")
mark.Texture:SetTexture([[Interface\TargetingFrame\UI-RaidTargetingIcons]])
mark.Texture:SetAllPoints()
SetRaidTargetIconTexture(mark.Texture, i)
mark:RegisterForClicks("LeftbuttonUp", "RightbuttonUp")
mark:SetScript("OnClick", RaidMarkButton_OnClick)
mark:SetScript("OnEnter", RaidMarkButton_OnEnter)
mark:SetScript("OnLeave", RaidMarkButton_OnLeave)
if(i == 8) then
mark:SetPoint("CENTER")
else
local radian = 360 / 7 * i;
mark:SetPoint("CENTER", sin(radian) * 60, cos(radian) * 60)
end
end
end
function RaidMarkFrame:IsAllowed(button)
if(button and button == "down") then
if GetNumGroupMembers()>0 then
if UnitIsGroupLeader('player') or UnitIsGroupAssistant("player") then
self.Active = true
elseif IsInGroup() and not IsInRaid() then
self.Active = true
else
UIErrorsFrame:AddMessage(L["You don't have permission to mark targets."], 1.0, 0.1, 0.1, 1.0, UIERRORS_HOLD_TIME)
self.Active = false
end
else
self.Active = true
end
else
self.Active = false
end
end
function RaidMarkFrame:Toggle(button)
local canFade = false;
if(button) then
canFade = true;
self:IsAllowed(button)
end
if(self.Active) then
if not UnitExists("target") or UnitIsDead("target") then return end
local x,y = GetCursorPosition()
local scale = SV.Screen:GetEffectiveScale()
self:SetPoint("CENTER", SV.Screen, "BOTTOMLEFT", (x / scale), (y / scale))
self:FadeIn()
elseif(canFade) then
self:FadeOut(0.2, 1, 0, true)
end
end
local RaidMarkFrame_OnEvent = function(self, event)
self:Toggle();
end
_G.RaidMark_HotkeyPressed = function(button)
RaidMarkFrame:Toggle(button)
end
--[[
##########################################################
DRESSUP HELPERS by: Leatrix
##########################################################
]]--
local CreateCharacterToggles;
do
local HelmetToggle;
local CloakToggle;
local DressUpdateTimer = 0;
local HShowing, CShowing, HChecked, CChecked
local function LockItem(item, lock)
if lock then
item:Disable()
item:SetAlpha(0.3)
else
item:Enable()
item:SetAlpha(1.0)
end
end
local function SetVanityPlacement()
HelmetToggle:ClearAllPoints();
HelmetToggle:SetPoint("TOPLEFT", 166, -326)
HelmetToggle:SetHitRectInsets(0, -10, 0, 0);
HelmetToggle.text:SetText("H");
HelmetToggle:SetAlpha(0.7);
CloakToggle:ClearAllPoints();
CloakToggle:SetPoint("TOPLEFT", 206, -326)
CloakToggle:SetHitRectInsets(0, -10, 0, 0);
CloakToggle.text:SetText("C");
CloakToggle:SetAlpha(0.7);
end
local MouseEventHandler = function(self, btn)
if btn == "RightButton" and IsShiftKeyDown() then
SetVanityPlacement();
end
end
local DressUpdateHandler = function(self, elapsed)
DressUpdateTimer = DressUpdateTimer + elapsed;
while (DressUpdateTimer > 0.05) do
if UnitIsDeadOrGhost("player") then
LockItem(HelmetToggle,true)
LockItem(CloakToggle,true)
return
else
LockItem(HelmetToggle,false)
LockItem(CloakToggle,false)
end
--[[
HShowing = ShowingHelm()
CShowing = ShowingCloak()
HChecked = HelmetToggle:GetChecked()
CChecked = CloakToggle:GetChecked()
if(HChecked ~= HShowing) then
if HelmetToggle:IsEnabled() then
HelmetToggle:Disable()
end
else
if not HelmetToggle:IsEnabled() then
HelmetToggle:Enable()
end
end
if(CChecked ~= CShowing) then
if CloakToggle:IsEnabled() then
CloakToggle:Disable()
end
else
if not CloakToggle:IsEnabled() then
CloakToggle:Enable()
end
end
HelmetToggle:SetChecked(HShowing);
CloakToggle:SetChecked(CShowing);
]]--
DressUpdateTimer = 0;
end
end
local DressUp_OnEnter = function(self)
if InCombatLockdown() then return end
GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT", 0, 4)
GameTooltip:ClearLines()
GameTooltip:AddLine(self.TText, 1, 1, 1)
GameTooltip:Show()
end
local DressUp_OnLeave = function(self)
if InCombatLockdown() then return end
if(GameTooltip:IsShown()) then GameTooltip:Hide() end
end
local Button_OnEnter = function(self, ...)
if InCombatLockdown() then return end
GameTooltip:SetOwner(self, "ANCHOR_TOPLEFT", 0, 4)
GameTooltip:ClearLines()
GameTooltip:AddLine(self.TText, 1, 1, 1)
GameTooltip:Show()
end
local function CreateSimpleButton(frame, label, anchor, x, y, width, height, tooltip)
local button = CreateFrame("Button", nil, frame, "UIPanelButtonTemplate")
button:SetWidth(width)
button:SetHeight(height)
button:SetPoint(anchor, x, y)
button:SetText(label)
button:RegisterForClicks("AnyUp")
button:SetHitRectInsets(0, 0, 0, 0);
button:SetFrameStrata("FULLSCREEN_DIALOG");
button.TText = tooltip
button:SetStyle("Button")
button:SetScript("OnEnter", Button_OnEnter)
button:SetScript("OnLeave", GameTooltip_Hide)
return button
end
function CreateCharacterToggles()
local BtnStrata = SideDressUpModelResetButton:GetFrameStrata();
local BtnLevel = SideDressUpModelResetButton:GetFrameLevel();
local tabard1 = CreateSimpleButton(DressUpFrame, "Tabard", "BOTTOMLEFT", 12, 12, 80, 22, "")
tabard1:SetScript("OnClick", function()
DressUpModel:UndressSlot(19)
end)
local tabard2 = CreateSimpleButton(SideDressUpFrame, "Tabard", "BOTTOMLEFT", 14, 20, 60, 22, "")
tabard2:SetFrameStrata(BtnStrata);
tabard2:SetFrameLevel(BtnLevel);
tabard2:SetScript("OnClick", function()
SideDressUpModel:UndressSlot(19)
end)
local nude1 = CreateSimpleButton(DressUpFrame, "Nude", "BOTTOMLEFT", 104, 12, 80, 22, "")
nude1:SetScript("OnClick", function()
DressUpFrameResetButton:Click()
for i = 1, 19 do
DressUpModel:UndressSlot(i)
end
end)
local nude2 = CreateSimpleButton(SideDressUpFrame, "Nude", "BOTTOMRIGHT", -18, 20, 60, 22, "")
nude2:SetFrameStrata(BtnStrata);
nude2:SetFrameLevel(BtnLevel);
nude2:SetScript("OnClick", function()
SideDressUpModelResetButton:Click()
for i = 1, 19 do
SideDressUpModel:UndressSlot(i)
end
end)
--[[
HelmetToggle = CreateFrame('CheckButton', nil, CharacterModelFrame, "OptionsCheckButtonTemplate")
HelmetToggle:SetSize(16, 16)
HelmetToggle:SetStyle("Checkbox")
HelmetToggle.text = HelmetToggle:CreateFontString(nil, 'OVERLAY', "GameFontNormal")
HelmetToggle.text:SetPoint("LEFT", 24, 0)
HelmetToggle.TText = "Show/Hide Helmet"
HelmetToggle:SetScript('OnEnter', DressUp_OnEnter)
HelmetToggle:SetScript('OnLeave', DressUp_OnLeave)
HelmetToggle:SetScript('OnUpdate', DressUpdateHandler)
CloakToggle = CreateFrame('CheckButton', nil, CharacterModelFrame, "OptionsCheckButtonTemplate")
CloakToggle:SetSize(16, 16)
CloakToggle:SetStyle("Checkbox")
CloakToggle.text = CloakToggle:CreateFontString(nil, 'OVERLAY', "GameFontNormal")
CloakToggle.text:SetPoint("LEFT", 24, 0)
CloakToggle.TText = "Show/Hide Cloak"
CloakToggle:SetScript('OnEnter', DressUp_OnEnter)
CloakToggle:SetScript('OnLeave', DressUp_OnLeave)
HelmetToggle:SetScript('OnClick', function(self, btn)
ShowHelm(HelmetToggle:GetChecked())
end)
CloakToggle:SetScript('OnClick', function(self, btn)
ShowCloak(CloakToggle:GetChecked())
end)
HelmetToggle:SetScript('OnMouseDown', MouseEventHandler)
CloakToggle:SetScript('OnMouseDown', MouseEventHandler)
CharacterModelFrame:HookScript("OnShow", SetVanityPlacement)
]]--
end
end
--[[
##########################################################
VARIOUS COMBAT REACTIONS
##########################################################
]]--
local ReactionListener = CreateFrame("Frame")
local function Thanks_Emote(sourceName)
if not REACTION_EMOTE then return end
local index = random(1,#ReactionEmotes)
DoEmote(ReactionEmotes[index], sourceName)
end
local function StupidHatEventHandler()
if(not IsInInstance()) then return end
local item = {}
for i = 1, 17 do
if Reactions.StupidHat[i] ~= nil then
item[i] = GetInventoryItemID("player", i) or 0
for j, baditem in pairs(Reactions.StupidHat[i]) do
if item[i] == baditem then
PlaySound(SOUNDKIT.RAID_WARNING)
RaidNotice_AddMessage(RaidWarningFrame, format("%s %s", CURRENTLY_EQUIPPED, GetItemInfo(item[i]).."!!!"), ChatTypeInfo["RAID_WARNING"])
print(format("|cffff3300%s %s", CURRENTLY_EQUIPPED, GetItemInfo(item[i]).."!!!|r"))
end
end
end
end
end
local function ChatLogEventHandler(...)
local _, subEvent, _, sourceGUID, sourceName, _, _, destGUID, destName, _, _, spellID, _, _, otherSpellID = ...
if not sourceName then return end
if(REACTION_INTERRUPT) then
if ((spellID == 6770) and (destName == PlayerName) and (subEvent == "SPELL_AURA_APPLIED" or subEvent == "SPELL_AURA_REFRESH")) then
local msg = SAPPED_MESSAGE[random(1,6)]
SendChatMessage(msg, "SAY")
SV:AddonMessage("Sapped by: "..sourceName)
DoEmote("CRACK", sourceName)
elseif(subEvent == "SPELL_INTERRUPT" and sourceGUID == UnitGUID("player") and IsInGroup()) then
SendChatMessage(INTERRUPTED.." "..destName..": "..GetSpellLink(otherSpellID), MsgTest())
end
end
if(REACTION_WOOT) then
for key, value in pairs(Reactions.Woot) do
if spellID == key and value == true and destName == PlayerName and sourceName ~= PlayerName and (subEvent == "SPELL_AURA_APPLIED" or subEvent == "SPELL_CAST_SUCCESS") then
Thanks_Emote(sourceName)
--SendChatMessage(L["Thanks for "]..GetSpellLink(spellID)..", "..sourceName, "WHISPER", nil, sourceName)
print(GetSpellLink(spellID)..L[" received from "]..sourceName)
end
end
end
if(REACTION_LOOKY) then
local outbound;
local spells = Reactions.LookWhatICanDo
local _, _, difficultyID = GetInstanceInfo()
if(difficultyID ~= 0 and subEvent == "SPELL_CAST_SUCCESS") then
if(not (sourceGUID == UnitGUID("player") and sourceName == PlayerName)) then
for i, spells in pairs(spells) do
if(spellID == spells) then
if(destName == nil) then
outbound = (L["%s used a %s."]):format(sourceName, GetSpellLink(spellID))
else
outbound = (L["%s used a %s."]):format(sourceName, GetSpellLink(spellID).." -> "..destName)
end
if(REACTION_CHAT) then
SendChatMessage(outbound, MsgTest())
else
print(outbound)
end
end
end
else
if(not (sourceGUID == UnitGUID("player") and sourceName == PlayerName)) then return end
for i, spells in pairs(spells) do
if(spellID == spells) then
if(destName == nil) then
outbound = (L["%s used a %s."]):format(sourceName, GetSpellLink(spellID))
else
outbound = GetSpellLink(spellID).." -> "..destName
end
if(REACTION_CHAT) then
SendChatMessage(outbound, MsgTest())
else
print(outbound)
end
end
end
end
end
end
if(REACTION_SHARE) then
if not IsInGroup() or InCombatLockdown() or not subEvent or not spellID then return end
if not UnitInRaid(sourceName) and not UnitInParty(sourceName) then return end
local sourceName = format(sourceName:gsub("%-[^|]+", ""))
if(not sourceName) then return end
local thanks = false
local outbound
if subEvent == "SPELL_CAST_SUCCESS" then
-- Feasts
if (spellID == 126492 or spellID == 126494) then
outbound = (L["%s has prepared a %s - [%s]."]):format(sourceName, GetSpellLink(spellID), SPELL_STAT1_NAME)
elseif (spellID == 126495 or spellID == 126496) then
outbound = (L["%s has prepared a %s - [%s]."]):format(sourceName, GetSpellLink(spellID), SPELL_STAT2_NAME)
elseif (spellID == 126501 or spellID == 126502) then
outbound = (L["%s has prepared a %s - [%s]."]):format(sourceName, GetSpellLink(spellID), SPELL_STAT3_NAME)
elseif (spellID == 126497 or spellID == 126498) then
outbound = (L["%s has prepared a %s - [%s]."]):format(sourceName, GetSpellLink(spellID), SPELL_STAT4_NAME)
elseif (spellID == 126499 or spellID == 126500) then
outbound = (L["%s has prepared a %s - [%s]."]):format(sourceName, GetSpellLink(spellID), SPELL_STAT5_NAME)
elseif (spellID == 104958 or spellID == 105193 or spellID == 126503 or spellID == 126504 or spellID == 145166 or spellID == 145169 or spellID == 145196) then
outbound = (L["%s has prepared a %s."]):format(sourceName, GetSpellLink(spellID))
-- Refreshment Table
elseif spellID == 43987 then
outbound = (L["%s has prepared a %s."]):format(sourceName, GetSpellLink(spellID))
-- Ritual of Summoning
elseif spellID == 698 then
outbound = (L["%s is casting %s. Click!"]):format(sourceName, GetSpellLink(spellID))
-- Piccolo of the Flaming Fire
elseif spellID == 18400 then
outbound = (L["%s used a %s."]):format(sourceName, GetSpellLink(spellID))
end
if(outbound) then thanks = true end
elseif subEvent == "SPELL_SUMMON" then
-- Repair Bots
if Reactions.Bots[spellID] then
outbound = (L["%s has put down a %s."]):format(sourceName, GetSpellLink(spellID))
thanks = true
end
elseif subEvent == "SPELL_CREATE" then
-- Ritual of Souls and MOLL-E
if (spellID == 29893 or spellID == 54710) then
outbound = (L["%s has put down a %s."]):format(sourceName, GetSpellLink(spellID))
thanks = true
-- Toys
elseif Reactions.Toys[spellID] then
outbound = (L["%s has put down a %s."]):format(sourceName, GetSpellLink(spellID))
-- Portals
elseif Reactions.Portals[spellID] then
outbound = (L["%s is casting %s."]):format(sourceName, GetSpellLink(spellID))
end
elseif subEvent == "SPELL_AURA_APPLIED" then
-- Turkey Feathers and Party G.R.E.N.A.D.E.
if (spellID == 61781 or ((spellID == 51508 or spellID == 51510) and destName == PlayerName)) then
outbound = (L["%s used a %s."]):format(sourceName, GetSpellLink(spellID))
end
end
if(outbound) then
if(REACTION_CHAT) then
SendChatMessage(outbound, MsgTest(true))
else
print(outbound)
end
if(thanks and sourceName) then
Thanks_Emote(sourceName)
end
end
end
end
local ReactionListener_OnEvent = function(self, event, ...)
if(event == "ZONE_CHANGED_NEW_AREA") then
StupidHatEventHandler()
elseif(event == "COMBAT_LOG_EVENT_UNFILTERED") then
ChatLogEventHandler(...)
end
end
function SV:ToggleReactions()
local settings = SV.db.Extras
REACTION_INTERRUPT = settings.pvpinterrupt
REACTION_WOOT = settings.woot
REACTION_LOOKY = settings.lookwhaticando
REACTION_SHARE = settings.sharingiscaring
REACTION_EMOTE = settings.reactionEmote
REACTION_CHAT = settings.reactionChat
if(settings.stupidhat) then
ReactionListener:RegisterEvent("ZONE_CHANGED_NEW_AREA")
else
ReactionListener:UnregisterEvent("ZONE_CHANGED_NEW_AREA")
end
if(not REACTION_SHARE) and (not REACTION_INTERRUPT) and (not REACTION_WOOT) and (not REACTION_LOOKY) then
ReactionListener:UnregisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
else
ReactionListener:RegisterEvent("COMBAT_LOG_EVENT_UNFILTERED")
end
end
--[[ HELPER ]]--
local function GetThreatBarColor(highest)
local unitReaction = UnitReaction(highest, 'player');
local r, g, b = 0.5, 0.5, 0.5;
if(UnitIsPlayer(highest)) then
local _,token = UnitClass(highest);
local colors = RAID_CLASS_COLORS[token];
if(colors) then
r, g, b = colors.r*255, colors.g*255, colors.b*255
end
elseif(unitReaction) then
local colors = REACTION_COLORS[unitReaction];
if(colors) then
r, g, b = colors[1], colors[2], colors[3]
end
end
return r, g, b
end
--[[ HANDLER ]]--
local ThreatBar_OnEvent = function(self, event)
local isTanking, status, scaledPercent = UnitDetailedThreatSituation('player', 'target')
if(scaledPercent and (scaledPercent > 0)) then
-- if SVUI is installed then fade instead of show
if(self.FadeIn) then
self:FadeIn()
else
self:Show()
end
local r,g,b = 0,0.9,0;
local peak = 0;
local unitKey, highest;
if(UnitExists('pet')) then
local threat = select(3, UnitDetailedThreatSituation('pet', 'target'))
if(threat and threat > peak) then
peak = threat;
highest = 'pet';
end
end
if(IsInRaid()) then
for i=1,40 do
unitKey = 'raid'..i;
if(UnitExists(unitKey) and not UnitIsUnit(unitKey, 'player')) then
local threat = select(3, UnitDetailedThreatSituation(unitKey, 'target'))
if(threat and threat > peak) then
peak = threat;
highest = 'pet';
end
end
end
elseif(IsInGroup()) then
for i=1,4 do
unitKey = 'party'..i;
if(UnitExists(unitKey)) then
local threat = select(3, UnitDetailedThreatSituation(unitKey, 'target'))
if(threat and threat > peak) then
peak = threat;
highest = 'pet';
end
end
end
end
if(highest) then
if(isTanking or (scaledPercent == 100)) then
peak = (scaledPercent - peak);
if(peak > 0) then
scaledPercent = peak;
end
else
r,g,b = GetThreatBarColor(highest)
end
elseif(status) then
r,g,b = GetThreatStatusColor(status);
end
self:SetStatusBarColor(r,g,b)
self:SetValue(scaledPercent)
self.text:SetFormattedText('%.0f%%', scaledPercent)
else
-- if SVUI is installed then fade instead of hide
if(self.FadeOut) then
self:FadeOut(0.2, 1, 0, true)
else
self:Hide()
end
end
end
--[[
##########################################################
LOAD BY TRIGGER
##########################################################
]]--
local function InitializeMisc()
hooksecurefunc("MerchantItemButton_OnEnter", MaxStackTooltip);
hooksecurefunc("MerchantItemButton_OnModifiedClick", BuyMaxStack);
RaidMarkFrame:RegisterEvent("PLAYER_TARGET_CHANGED")
RaidMarkFrame:SetScript("OnEvent", RaidMarkFrame_OnEvent)
if(not IsAddOnLoaded("DressingRoomFunctions")) then
CreateCharacterToggles()
end
SV:ToggleReactions()
ReactionListener:SetScript("OnEvent", ReactionListener_OnEvent)
if(SV.db.Extras.threatbar) then
ThreatMeter:SetParent(SV.Screen)
ThreatMeter:SetPoint('CENTER', UIParent, 'CENTER', 150, -150)
ThreatMeter:SetSize(50, 100)
ThreatMeter:SetStatusBarTexture(BARFILE)
ThreatMeter:SetFrameStrata('MEDIUM')
ThreatMeter:SetOrientation("VERTICAL")
ThreatMeter:SetMinMaxValues(0, 100)
ThreatMeter.backdrop = ThreatMeter:CreateTexture(nil,"BACKGROUND")
ThreatMeter.backdrop:SetAllPoints(ThreatMeter)
ThreatMeter.backdrop:SetTexture(TEXTUREFILE)
ThreatMeter.backdrop:SetTexCoord(0.5,0.75,0,0.5)
ThreatMeter.backdrop:SetBlendMode("ADD")
ThreatMeter.overlay = ThreatMeter:CreateTexture(nil,"OVERLAY",nil,1)
ThreatMeter.overlay:SetAllPoints(ThreatMeter)
ThreatMeter.overlay:SetTexture(TEXTUREFILE)
ThreatMeter.overlay:SetTexCoord(0.75,1,0,0.5)
ThreatMeter.text = ThreatMeter:CreateFontString(nil, 'OVERLAY')
ThreatMeter.text:SetFontObject(NumberFontNormal)
ThreatMeter.text:SetPoint('TOP',ThreatMeter,'BOTTOM',0,0)
ThreatMeter:RegisterEvent('PLAYER_TARGET_CHANGED');
ThreatMeter:RegisterEvent('UNIT_THREAT_LIST_UPDATE');
ThreatMeter:RegisterEvent('GROUP_ROSTER_UPDATE');
ThreatMeter:RegisterEvent('UNIT_PET');
ThreatMeter:SetScript("OnEvent", ThreatBar_OnEvent);
SV:NewAnchor(ThreatMeter, L["Threat-O-Meter"])
end
local cfg = CreateFrame("Button", "GameMenuButtonSVUI", GameMenuFrame, "GameMenuButtonTemplate")
cfg:SetSize(GameMenuButtonHelp:GetWidth(), GameMenuButtonHelp:GetHeight())
cfg:SetPoint(GameMenuButtonHelp:GetPoint())
cfg:SetScript("OnClick", function() SV:ToggleConfig() HideUIPanel(GameMenuFrame) end)
cfg:SetText("|cffFF9900SuperVillain UI|r")
GameMenuFrame:HookScript("OnShow", function()
GameMenuFrame:SetHeight(GameMenuFrame:GetHeight() + GameMenuButtonHelp:GetHeight() + 10)
end)
GameMenuButtonHelp:ClearAllPoints()
GameMenuButtonHelp:SetPoint("TOP", cfg, "BOTTOM", 0, -11)
end
SV.Events:On("CORE_INITIALIZED", InitializeMisc);
--[[
##########################################################
DIRTY DEEDS
##########################################################
]]--
LFRParentFrame:SetScript("OnHide", nil)
| mit |
UnfortunateFruit/darkstar | scripts/zones/Abyssea-Empyreal_Paradox/Zone.lua | 32 | 1433 | -----------------------------------
--
-- Zone: Abyssea - Empyreal_Paradox
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Empyreal_Paradox/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-Empyreal_Paradox/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(-495,0,483,205); -- BC Area
player:setPos(540,-500,-565,64);
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 |
dpino/snabbswitch | src/program/firehose/firehose.lua | 9 | 4736 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(..., package.seeall)
local lib = require("core.lib")
local long_opts = {
help = "h",
example = "e",
["print-header"] = "H",
time = "t",
input = "i",
["ring-size"] = "r",
}
function fatal (reason)
print(reason)
os.exit(1)
end
function run (args)
local usage = require("program.firehose.README_inc")
local header = require("program.firehose.firehose_h_inc")
local example = require("program.firehose.example_inc")
local opt = {}
local time = nil
local pciaddresses = {}
-- Maximum buffers to avoid packet drops
local ring_size = 2048
function opt.h (arg) print(usage) main.exit(0) end
function opt.H (arg) print(header) main.exit(0) end
function opt.e (arg) print(example) main.exit(0) end
function opt.t (arg)
time = tonumber(arg)
if type(time) ~= 'number' then fatal("bad time value: " .. arg) end
end
function opt.i (arg)
table.insert(pciaddresses, arg)
end
function opt.r (arg)
ring_size = tonumber(arg)
end
args = lib.dogetopt(args, opt, "hHet:i:r:", long_opts)
if #pciaddresses == 0 then
fatal("Usage error: no input sources given (-i). Use --help for usage.")
end
local sofile = args[1]
if sofile == nil then
fatal("Usage error: no shared library given. Use --help for usage.")
end
-- Load shared object
print("Loading shared object: "..sofile)
local ffi = require("ffi")
local C = ffi.C
local so = ffi.load(sofile)
ffi.cdef[[
void firehose_start();
void firehose_stop();
int firehose_callback_v1(const char *pciaddr, char **packets, void *rxring,
int ring_size, int index);
]]
-- Array where we store a function for each NIC that will process the traffic.
local run_functions = {}
for _,pciaddr in ipairs(pciaddresses) do
-- Initialize a device driver
print("Initializing NIC: "..pciaddr)
local pci = require("lib.hardware.pci")
pci.unbind_device_from_linux(pciaddr) -- make kernel/ixgbe release this device
local driver = require("apps.intel_mp.intel_mp").driver
local parse = require("core.lib").parse
local function new_nic (config)
return driver:new(parse(config, driver.config))
end
local nic = new_nic({ pciaddr=pciaddr, ring_buffer_size=ring_size })
nic:init()
-- Traffic processing
--
-- We are using a special-purpose receive method designed for fast
-- packet capture:
--
-- Statically allocate all packet buffers.
--
-- Statically initialize the hardware RX descriptor ring to point to
-- the preallocated packets.
--
-- Have the C callback loop directly over the RX ring to process the
-- packets that are ready.
--
-- This means that no work is done to allocate and free buffers or to
-- write new descriptors to the RX ring. This is expected to have
-- extremely low overhead to receive each packet.
-- Set NIC to "legacy" descriptor format. In this mode the NIC "write
-- back" does not overwrite the address stored in the descriptor and
-- so this can be reused. See 82599 datasheet section 7.1.5.
nic.r.SRRCTL(10 + bit.lshift(1, 28))
-- Array of packet data buffers. This will be passed to C.
local packets = ffi.new("char*[?]", ring_size)
for i = 0, ring_size-1 do
-- Statically allocate a packet and put the address in the array
local p = packet.allocate()
packets[i] = p.data
-- Statically allocate the matching hardware receive descriptor
nic.rxdesc[i].data.address = memory.virtual_to_physical(p.data)
nic.rxdesc[i].data.dd = 0
end
nic.r.RDT(ring_size-1)
local index = 0 -- ring index of next packet
local rxring = nic.rxdesc
local run = function ()
index = so.firehose_callback_v1(pciaddr, packets, rxring, ring_size, index)
nic.r.RDT(index==0 and ring_size or index-1)
end
table.insert(run_functions, run)
end
print("Initializing callback library")
so.firehose_start()
-- Process traffic in infinite loop
print("Processing traffic...")
local deadline = time and (C.get_monotonic_time() + time)
while true do
for i = 1, 10000 do
for i = 1, #run_functions do
-- Run the traffic processing function for each NIC.
run_functions[i]()
end
end
if deadline and (C.get_monotonic_time() > deadline) then
so.firehose_stop()
break
end
end
end
| apache-2.0 |
nesstea/darkstar | scripts/zones/Port_Jeuno/npcs/Leffquen.lua | 32 | 1034 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Leffquen
-- Type: Weather Reporter
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x82726,0,0,0,0,0,0,0,VanadielTime());
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 |
Jacklli/redis-leveldb | deps/lua/src/host/genminilua.lua | 14 | 11943 | ----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2012 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| bsd-3-clause |
trilastiko/keys | Build/VSCOKeys.lrplugin/halfway_server/socket/url.lua | 148 | 10529 | -----------------------------------------------------------------------------
-- URI parsing, composition and relative URL resolution
-- LuaSocket toolkit.
-- Author: Diego Nehab
-- RCS ID: $Id: url.lua,v 1.38 2006/04/03 04:45:42 diego Exp $
-----------------------------------------------------------------------------
-----------------------------------------------------------------------------
-- Declare module
-----------------------------------------------------------------------------
local string = require("string")
local base = _G
local table = require("table")
module("socket.url")
-----------------------------------------------------------------------------
-- Module version
-----------------------------------------------------------------------------
_VERSION = "URL 1.0.1"
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function escape(s)
return string.gsub(s, "([^A-Za-z0-9_])", function(c)
return string.format("%%%02x", string.byte(c))
end)
end
-----------------------------------------------------------------------------
-- Protects a path segment, to prevent it from interfering with the
-- url parsing.
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
local function make_set(t)
local s = {}
for i,v in base.ipairs(t) do
s[t[i]] = 1
end
return s
end
-- these are allowed withing a path segment, along with alphanum
-- other characters must be escaped
local segment_set = make_set {
"-", "_", ".", "!", "~", "*", "'", "(",
")", ":", "@", "&", "=", "+", "$", ",",
}
local function protect_segment(s)
return string.gsub(s, "([^A-Za-z0-9_])", function (c)
if segment_set[c] then return c
else return string.format("%%%02x", string.byte(c)) end
end)
end
-----------------------------------------------------------------------------
-- Encodes a string into its escaped hexadecimal representation
-- Input
-- s: binary string to be encoded
-- Returns
-- escaped representation of string binary
-----------------------------------------------------------------------------
function unescape(s)
return string.gsub(s, "%%(%x%x)", function(hex)
return string.char(base.tonumber(hex, 16))
end)
end
-----------------------------------------------------------------------------
-- Builds a path from a base path and a relative path
-- Input
-- base_path
-- relative_path
-- Returns
-- corresponding absolute path
-----------------------------------------------------------------------------
local function absolute_path(base_path, relative_path)
if string.sub(relative_path, 1, 1) == "/" then return relative_path end
local path = string.gsub(base_path, "[^/]*$", "")
path = path .. relative_path
path = string.gsub(path, "([^/]*%./)", function (s)
if s ~= "./" then return s else return "" end
end)
path = string.gsub(path, "/%.$", "/")
local reduced
while reduced ~= path do
reduced = path
path = string.gsub(reduced, "([^/]*/%.%./)", function (s)
if s ~= "../../" then return "" else return s end
end)
end
path = string.gsub(reduced, "([^/]*/%.%.)$", function (s)
if s ~= "../.." then return "" else return s end
end)
return path
end
-----------------------------------------------------------------------------
-- Parses a url and returns a table with all its parts according to RFC 2396
-- The following grammar describes the names given to the URL parts
-- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment>
-- <authority> ::= <userinfo>@<host>:<port>
-- <userinfo> ::= <user>[:<password>]
-- <path> :: = {<segment>/}<segment>
-- Input
-- url: uniform resource locator of request
-- default: table with default values for each field
-- Returns
-- table with the following fields, where RFC naming conventions have
-- been preserved:
-- scheme, authority, userinfo, user, password, host, port,
-- path, params, query, fragment
-- Obs:
-- the leading '/' in {/<path>} is considered part of <path>
-----------------------------------------------------------------------------
function parse(url, default)
-- initialize default parameters
local parsed = {}
for i,v in base.pairs(default or parsed) do parsed[i] = v end
-- empty url is parsed to nil
if not url or url == "" then return nil, "invalid url" end
-- remove whitespace
-- url = string.gsub(url, "%s", "")
-- get fragment
url = string.gsub(url, "#(.*)$", function(f)
parsed.fragment = f
return ""
end)
-- get scheme
url = string.gsub(url, "^([%w][%w%+%-%.]*)%:",
function(s) parsed.scheme = s; return "" end)
-- get authority
url = string.gsub(url, "^//([^/]*)", function(n)
parsed.authority = n
return ""
end)
-- get query stringing
url = string.gsub(url, "%?(.*)", function(q)
parsed.query = q
return ""
end)
-- get params
url = string.gsub(url, "%;(.*)", function(p)
parsed.params = p
return ""
end)
-- path is whatever was left
if url ~= "" then parsed.path = url end
local authority = parsed.authority
if not authority then return parsed end
authority = string.gsub(authority,"^([^@]*)@",
function(u) parsed.userinfo = u; return "" end)
authority = string.gsub(authority, ":([^:]*)$",
function(p) parsed.port = p; return "" end)
if authority ~= "" then parsed.host = authority end
local userinfo = parsed.userinfo
if not userinfo then return parsed end
userinfo = string.gsub(userinfo, ":([^:]*)$",
function(p) parsed.password = p; return "" end)
parsed.user = userinfo
return parsed
end
-----------------------------------------------------------------------------
-- Rebuilds a parsed URL from its components.
-- Components are protected if any reserved or unallowed characters are found
-- Input
-- parsed: parsed URL, as returned by parse
-- Returns
-- a stringing with the corresponding URL
-----------------------------------------------------------------------------
function build(parsed)
local ppath = parse_path(parsed.path or "")
local url = build_path(ppath)
if parsed.params then url = url .. ";" .. parsed.params end
if parsed.query then url = url .. "?" .. parsed.query end
local authority = parsed.authority
if parsed.host then
authority = parsed.host
if parsed.port then authority = authority .. ":" .. parsed.port end
local userinfo = parsed.userinfo
if parsed.user then
userinfo = parsed.user
if parsed.password then
userinfo = userinfo .. ":" .. parsed.password
end
end
if userinfo then authority = userinfo .. "@" .. authority end
end
if authority then url = "//" .. authority .. url end
if parsed.scheme then url = parsed.scheme .. ":" .. url end
if parsed.fragment then url = url .. "#" .. parsed.fragment end
-- url = string.gsub(url, "%s", "")
return url
end
-----------------------------------------------------------------------------
-- Builds a absolute URL from a base and a relative URL according to RFC 2396
-- Input
-- base_url
-- relative_url
-- Returns
-- corresponding absolute url
-----------------------------------------------------------------------------
function absolute(base_url, relative_url)
if base.type(base_url) == "table" then
base_parsed = base_url
base_url = build(base_parsed)
else
base_parsed = parse(base_url)
end
local relative_parsed = parse(relative_url)
if not base_parsed then return relative_url
elseif not relative_parsed then return base_url
elseif relative_parsed.scheme then return relative_url
else
relative_parsed.scheme = base_parsed.scheme
if not relative_parsed.authority then
relative_parsed.authority = base_parsed.authority
if not relative_parsed.path then
relative_parsed.path = base_parsed.path
if not relative_parsed.params then
relative_parsed.params = base_parsed.params
if not relative_parsed.query then
relative_parsed.query = base_parsed.query
end
end
else
relative_parsed.path = absolute_path(base_parsed.path or "",
relative_parsed.path)
end
end
return build(relative_parsed)
end
end
-----------------------------------------------------------------------------
-- Breaks a path into its segments, unescaping the segments
-- Input
-- path
-- Returns
-- segment: a table with one entry per segment
-----------------------------------------------------------------------------
function parse_path(path)
local parsed = {}
path = path or ""
--path = string.gsub(path, "%s", "")
string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end)
for i = 1, table.getn(parsed) do
parsed[i] = unescape(parsed[i])
end
if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end
if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end
return parsed
end
-----------------------------------------------------------------------------
-- Builds a path component from its segments, escaping protected characters.
-- Input
-- parsed: path segments
-- unsafe: if true, segments are not protected before path is built
-- Returns
-- path: corresponding path stringing
-----------------------------------------------------------------------------
function build_path(parsed, unsafe)
local path = ""
local n = table.getn(parsed)
if unsafe then
for i = 1, n-1 do
path = path .. parsed[i]
path = path .. "/"
end
if n > 0 then
path = path .. parsed[n]
if parsed.is_directory then path = path .. "/" end
end
else
for i = 1, n-1 do
path = path .. protect_segment(parsed[i])
path = path .. "/"
end
if n > 0 then
path = path .. protect_segment(parsed[n])
if parsed.is_directory then path = path .. "/" end
end
end
if parsed.is_absolute then path = "/" .. path end
return path
end
| gpl-2.0 |
hadi9090/celassicalteam | mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | unlicense |
oralius/byond1 | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-3.0 |
allwenandashi/ASHI | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
mrmost/mbc | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
cloner-hooshesiyah/ppbot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
PUMpITapp/instantpizza | src/ManageAccounts.lua | 1 | 10818 | --- Set if the program is running on the box or not
local onBox = true
--- Checks if the file was called from a test file.
-- @return #boolean true if called from a test file, indicating the file is being tested, else false
function checkTestMode()
runFile = debug.getinfo(2, "S").source:sub(2,3)
if (runFile ~= './' ) then
underGoingTest = false
elseif (runFile == './') then
underGoingTest = true
end
return underGoingTest
end
--- Chooses either the actual or the dummy gfx.
-- @return #string tempGfx Returns dummy gfx if the file is being tested, returns actual gfx if the file is being run.
function chooseGfx()
if not checkTestMode() then
tempGfx = require "gfx"
elseif checkTestMode() then
tempGfx = require "gfx_stub"
end
return tempGfx
end
--- Chooses the text
-- @return #string tempText Returns write_text_stub if the file is being tested, returns actual write_text if the file is being run.
function chooseText()
if not checkTestMode() then
tempText = require "write_text"
elseif checkTestMode() then
tempText = require "write_text_stub"
end
return tempText
end
local text = chooseText()
--- Change the path system if the app runs on the box comparing to the emulator
if onBox == true then
progress = "loadingPics..."
package.path = package.path .. ';' .. sys.root_path() .. 'Images/UserPage/?.png'
package.path = package.path .. ';' .. sys.root_path() .. 'Images/OrderPics/?.png'
package.path = package.path .. ';' .. sys.root_path() .. 'Images/PizzaPics/?.png'
dir = sys.root_path()
else
gfx = chooseGfx(checkTestMode())
sys = {}
sys.root_path = function () return '' end
dir = ""
end
local io = require "IOHandler"
--- Declare units in variables
local xUnit = gfx.screen:get_width()/16
local yUnit = gfx.screen:get_height()/9
---Temp save background
local tempCopy = nil
local tempCoord = {}
--Start position for x and y
local startPosY = yUnit*2.5
local startPosX = xUnit*3.2
---Margin between each field
local marginY = yUnit*1.2
---Current position for the highlightfield
local highlightPosY = 1
--- Declare the boundary levels for the input field set
local lowerBoundary = 1
local upperBoundary = 0
---Number of pages and the current page
local noOfPages = 0
local currentPage = 1
---Changes startvalue depending on the current page
local startingIndex = 1
local lastPage = 0
local deletedElement = false
local deleteMode = false
dofile(dir.."table.save.lua")
---Reads users from file and store them in a table
function readUsers()
userTable = io.readUserData()
noOfPages = math.ceil(#userTable/4)
if userTable == nil then
end
end
---Calculates no of pages
function getNoOfPages()
noOfPages = math.ceil(#userTable/4)
end
---Change visible page
--@param key is the key pressed by the user. (Left or right)
function changeCurrentPage(key)
if(key == 'left')then
if(currentPage > 1)then
currentPage = currentPage -1
startingIndex = startingIndex-4
end
elseif (key == 'right')then
if(currentPage < noOfPages)then
currentPage=currentPage+1
startingIndex = startingIndex+4
end
end
highlightPosY = 1
updateScreen()
end
---Display users on the screen.
function displayUsers()
foundUsers = false
yCoord = startPosY
upperBoundary = 0
if not (userTable == nil)then
if not (#userTable == 0) then
text.print(gfx.screen,"lato","black","small",tostring("Page: "..currentPage.."/"..noOfPages), startPosX*3.94, yCoord*2.85, xUnit*7, yUnit)
local accountTile = gfx.loadpng("Images/OrderPics/inputfield.png")
accountTile:premultiply()
--Depending on currentPage startingIndex decides where in the table to get users
for index = startingIndex, #userTable do
gfx.screen:copyfrom(accountTile,nil,{x=startPosX, y=yCoord, h=yUnit, w=xUnit*7},true)
text.print(gfx.screen,"lato","black","medium",tostring(userTable[index].email), startPosX*1.04, yCoord+marginY*0.2, xUnit*7, yUnit)
yCoord = yCoord+marginY
upperBoundary = upperBoundary+1
foundUsers = true
--Only prints 4 users
if(index == startingIndex+3)then
break
end
end
accountTile:destroy()
end
end
if(foundUsers==false)then
text.print(gfx.screen,"lato","black","medium","No users registered!", startPosX*1.9, yCoord+marginY*0.2, xUnit*7, yUnit)
end
end
---Returns the user that is highlighted
--@return the selected user
function getUser()
userIndex = (4*(currentPage-1)+highlightPosY)
user = userTable[userIndex]
user["editMode"] = "true"
user["editIndex"] = userIndex
return user
end
---Displays navigation arrows. Depending on the active page arrows are shown
function displayArrows()
if(noOfPages > 1 and currentPage < noOfPages)then
local rightArrow = gfx.loadpng("Images/PizzaPics/rightarrow.png")
rightArrow:premultiply()
gfx.screen:copyfrom(rightArrow, nil, {x = xUnit*14.7, y= yUnit*4, w = xUnit*1 , h =yUnit*2},true)
rightArrow:destroy()
end
if(currentPage > 1)then
local leftArrow = gfx.loadpng("Images/PizzaPics/leftarrow.png")
leftArrow:premultiply()
gfx.screen:copyfrom(leftArrow, nil, {x = xUnit*0.35, y= yUnit*4, w = xUnit*1 , h =yUnit*2},true)
leftArrow:destroy()
end
end
---Displays highligher
function displayHighlighter()
if(upperBoundary >0)then
local highlightTile = gfx.loadpng("Images/UserPage/userpressed.png")
highlightTile:premultiply()
local coord = {x = startPosX, y= startPosY + (highlightPosY - 1) * marginY, w = xUnit*10 , h =yUnit}
if tempCopy == nil then
tempCopy = gfx.new_surface(coord.w, coord.h)
tempCopy:copyfrom(gfx.screen,coord,nil)
tempCoord = coord
lastPage = currentPage
elseif lastPage == currentPage then
gfx.screen:copyfrom(tempCopy, nil,tempCoord,true)
tempCopy:copyfrom(gfx.screen,coord,nil)
tempCoord = coord
else
tempCopy:copyfrom(gfx.screen,coord,nil)
tempCoord = coord
lastPage = currentPage
end
gfx.screen:copyfrom(highlightTile, nil, coord,true)
highlightTile:destroy()
end
end
---Calls methods that builds GUI
function buildGUI()
displayBackground()
getNoOfPages()
displayUsers()
displayHighlighter()
displayArrows()
end
---Displays the background
function displayBackground()
local backgroundPNG = gfx.loadpng("Images/UserPage/manageaccount.png")
backgroundPNG:premultiply()
gfx.screen:copyfrom(backgroundPNG, nil, {x=0 , y=0, w=gfx.screen:get_width(), h=gfx.screen:get_height()})
backgroundPNG:destroy()
end
---Change position for the inputfield
--@param key is the key pressed by the user
function moveHighlightedInputField(key)
if(key == 'up')then
highlightPosY = highlightPosY - 1
if(highlightPosY < lowerBoundary) then
highlightPosY = upperBoundary
end
--Down
elseif(key == 'down')then
highlightPosY = highlightPosY + 1
if(highlightPosY > upperBoundary) then
highlightPosY = 1
end
end
displayHighlighter()
gfx.update()
end
---Updates screen, calling other functions that displays images and changes on screen
function updateScreen()
buildGUI()
gfx.update()
end
---When deleting a user a confirm image is shown.
function showConfirmDelete()
if not(#userTable == 0)then
local confirm = gfx.loadpng("Images/UserPage/notifydelete.png")
confirm:premultiply()
gfx.screen:copyfrom(confirm, nil, {x=0 , y=0, w=gfx.screen:get_width(), h=gfx.screen:get_height()},true)
confirm:destroy()
deleteMode = true
gfx.update()
end
end
---Deletes user from table
function deleteUser()
removeIndex = (4*(currentPage-1)+highlightPosY)
table.remove(userTable,removeIndex)
io.saveUserTable(userTable)
currentPage = 1
startingIndex = 1
tempCopy = nil
highlightPosY = 1
updateScreen()
end
---Destoys tempsurfaces
function destroyTempSurfaces()
if tempCopy ~= nil then
tempCopy:destroy()
end
end
--- Gets input from user and re-directs according to input
--@param key is the key the user presses
--@param state is the current state of the pressed key (up or down)
function onKey(key,state)
if(state == 'up') then
if(key == 'up')then
if checkTestMode() then
return key
end
if not deleteMode then
moveHighlightedInputField(key)
end
elseif(key == 'down')then
if checkTestMode() then
return key
end
if not deleteMode then
moveHighlightedInputField(key)
end
elseif(key == 'left')then
if checkTestMode() then
return key
end
if not deleteMode then
changeCurrentPage(key)
end
elseif(key == 'right')then
if checkTestMode() then
return key
end
changeCurrentPage(key)
elseif(key == 'green') then
--Go back to menu
pathName = dir .. "Menu.lua"
if checkTestMode() then
return pathName
else
if not(deleteMode)then
destroyTempSurfaces()
dofile(pathName)
end
end
elseif(key == 'blue') then
pathName = dir .. "RegistrationStep1.lua"
if checkTestMode() then
return pathName
else
if(deleteMode)then
updateScreen()
deleteMode = false
else
destroyTempSurfaces()
dofile(pathName)
end
end
elseif(key == 'yellow') then
pathName = dir .. "RegistrationStep1.lua"
if checkTestMode() then
return pathName
else
if(deleteMode)then
deleteUser()
deleteMode = false
else
newForm = getUser()
destroyTempSurfaces()
assert(loadfile(pathName))(newForm)
end
end
elseif(key == 'red') then
if not (deleteMode)then
showConfirmDelete()
end
end
end
end
--- Functions that returns some of the values on local variables to be used when testing
-- @return StartPosY Starting position of the marker for this page
-- @return HightlightPosY Current position of the marker
-- @return upperBoundary Value of the highest position the marker can go before going offscreen
-- @return lowerBoundary Value of the lowerst position the marker can go before going offscreen
function returnValuesForTesting(value)
if value == "startPosY" then
return startPosY
elseif value == "highlightPosY" then
return highlightPosY
elseif value == "upperBoundary" then
return upperBoundary
elseif value == "lowerBoundary" then
return lowerBoundary
end
end
--- Function that sets the markers position to a selected value
-- @param value Value that the user wants to set the marker on
function setValuesForTesting(value)
highlightPosY = value
end
---Main method
function onStart()
readUsers()
updateScreen()
end
onStart()
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5cc.lua | 13 | 1054 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: _5cc (Gate of Ice)
-- @pos -228 0 99 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(DOOR_FIRMLY_CLOSED);
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/hallowed_sword.lua | 42 | 1454 | -----------------------------------------
-- ID: 16550
-- Hallowed Sword
-- Additional Effect: Light Damage
-- Enchantment: "Enlight"
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 5;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(7,21);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_LIGHT, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
dmg = adjustForTarget(target,dmg,ELE_LIGHT);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_LIGHT,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_LIGHT_DAMAGE,message,dmg;
end
end;
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
return 0;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
local effect = EFFECT_ENLIGHT;
doEnspell(target,target,nil,effect);
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Lathuya.lua | 34 | 1032 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Lathuya
-- 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(0x0302);
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/prowess_killer.lua | 34 | 2257 | -----------------------------------
--
-- EFFECT_PROWESS : "Killer" effects bonus
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VERMIN_KILLER, effect:getPower());
target:addMod(MOD_BIRD_KILLER, effect:getPower());
target:addMod(MOD_AMORPH_KILLER, effect:getPower());
target:addMod(MOD_LIZARD_KILLER, effect:getPower());
target:addMod(MOD_AQUAN_KILLER, effect:getPower());
target:addMod(MOD_PLANTOID_KILLER, effect:getPower());
target:addMod(MOD_BEAST_KILLER, effect:getPower());
target:addMod(MOD_UNDEAD_KILLER, effect:getPower());
target:addMod(MOD_ARCANA_KILLER, effect:getPower());
target:addMod(MOD_DRAGON_KILLER, effect:getPower());
target:addMod(MOD_DEMON_KILLER, effect:getPower());
target:addMod(MOD_EMPTY_KILLER, effect:getPower());
-- target:addMod(MOD_HUMANOID_KILLER, effect:getPower());
target:addMod(MOD_LUMORIAN_KILLER, effect:getPower());
target:addMod(MOD_LUMINION_KILLER, effect:getPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VERMIN_KILLER, effect:getPower());
target:delMod(MOD_BIRD_KILLER, effect:getPower());
target:delMod(MOD_AMORPH_KILLER, effect:getPower());
target:delMod(MOD_LIZARD_KILLER, effect:getPower());
target:delMod(MOD_AQUAN_KILLER, effect:getPower());
target:delMod(MOD_PLANTOID_KILLER, effect:getPower());
target:delMod(MOD_BEAST_KILLER, effect:getPower());
target:delMod(MOD_UNDEAD_KILLER, effect:getPower());
target:delMod(MOD_ARCANA_KILLER, effect:getPower());
target:delMod(MOD_DRAGON_KILLER, effect:getPower());
target:delMod(MOD_DEMON_KILLER, effect:getPower());
target:delMod(MOD_EMPTY_KILLER, effect:getPower());
-- target:delMod(MOD_HUMANOID_KILLER, effect:getPower());
target:delMod(MOD_LUMORIAN_KILLER, effect:getPower());
target:delMod(MOD_LUMINION_KILLER, effect:getPower());
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Waters/npcs/Naiko-Paneiko.lua | 17 | 3519 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Naiko-Paneiko
-- Involved In Quest: Making Headlines, Riding on the Clouds
-- @zone 238
-- @pos -246 -5 -308
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 2) then
if(trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
function testflag(set,flag)
return (set % (2*flag) >= flag)
end
MakingHeadlines = player:getQuestStatus(WINDURST,MAKING_HEADLINES);
if(MakingHeadlines == 0) then
player:startEvent(0x0299); -- Quest Start
elseif(MakingHeadlines == 1) then
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),1) == false or testflag(tonumber(prog),2) == false or testflag(tonumber(prog),4) == false or testflag(tonumber(prog),8) == false) then
rand = math.random(1,2);
if(rand == 1) then
player:startEvent(0x029a); -- Quest Reminder 1
else
player:startEvent(0x029f); -- Quest Reminder 2
end
elseif(testflag(tonumber(prog),8) == true and testflag(tonumber(prog),16) == false) then
player:startEvent(0x02a1); -- Advises to validate story
elseif(prog == 31) then
rand = math.random(1,2);
if(rand == 1) then
player:startEvent(0x02a2); -- Quest finish 1
elseif(scoop == 4 and door == 1) then
player:startEvent(0x029e); -- Quest finish 2
end
end
else
player:startEvent(0x0297); -- 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 == 0x0299) then
player:addQuest(WINDURST,MAKING_HEADLINES);
elseif (csid == 0x029e or csid == 0x02a2) then
player:addTitle(EDITORS_HATCHET_MAN);
player:addGil(GIL_RATE*560);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*560);
player:delKeyItem(WINDURST_WOODS_SCOOP);
player:delKeyItem(WINDURST_WALLS_SCOOP);
player:delKeyItem(WINDURST_WATERS_SCOOP);
player:delKeyItem(PORT_WINDURST_SCOOP);
player:setVar("QuestMakingHeadlines_var",0);
player:addFame(WINDURST,WIN_FAME*30);
player:completeQuest(WINDURST,MAKING_HEADLINES);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Engelhart.lua | 31 | 3561 | -----------------------------------
-- Area: Bastok Markets (S)
-- NPC: Engelhart
-- Quest NPC
-- pos -79 -4 -125
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
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,BETTER_PART_OF_VALOR) == QUEST_ACCEPTED) then
if (player:getVar("BetterPartOfValProg") == 0) then
player:startEvent(0x0074);
elseif (player:getVar("BetterPartOfValProg") == 4) then
player:startEvent(0x0076);
else
player:startEvent(0x0075);
end
elseif (player:getQuestStatus(CRYSTAL_WAR,BETTER_PART_OF_VALOR) == QUEST_COMPLETED and player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_AVAILABLE) then
player:startEvent(0x0078);
elseif (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then
if (player:getVar("FiresOfDiscProg") < 2) then
player:startEvent(0x0079);
elseif (player:getVar("FiresOfDiscProg") == 2) then
player:startEvent(0x007C);
elseif (player:getVar("FiresOfDiscProg") == 3) then
player:startEvent(0x007D);
elseif (player:getVar("FiresOfDiscProg") == 4) then
player:startEvent(0x007E);
elseif (player:getVar("FiresOfDiscProg") == 5) then
player:startEvent(0x007F);
elseif (player:getVar("FiresOfDiscProg") == 6) then
player:startEvent(0x00A4);
end
elseif (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_COMPLETED) then
player:startEvent(0x00A5);
else
player:startEvent(0x0068);
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 == 0x0074) then
player:setVar("BetterPartOfValProg",1);
player:delKeyItem(CLUMP_OF_ANIMAL_HAIR);
elseif (csid == 0x0076) then
player:delKeyItem(XHIFHUT);
player:completeQuest(CRYSTAL_WAR,BETTER_PART_OF_VALOR);
player:addKeyItem(WARNING_LETTER);
player:messageSpecial(KEYITEM_OBTAINED,WARNING_LETTER);
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000);
player:setVar("BetterPartOfValProg",0);
player:needToZone(true);
elseif (csid == 0x0078) then
player:addQuest(CRYSTAL_WAR,FIRES_OF_DISCONTENT);
player:delKeyItem(WARNING_LETTER);
elseif (csid == 0x007C) then
player:setVar("FiresOfDiscProg",3);
elseif (csid == 0x007E) then
player:setVar("FiresOfDiscProg",5);
elseif (csid == 0x00A4) then
player:completeQuest(CRYSTAL_WAR,FIRES_OF_DISCONTENT);
player:addGil(GIL_RATE*10000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000);
player:setVar("FiresOfDiscProg",0);
end
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Quicksand_Caves/mobs/Triarius_IV-XIV.lua | 10 | 1501 | -----------------------------------
-- Area: Quicksand Caves
-- MOB: Tribunus_IV-XIV
-- Pops in Bastok mission 8-1 "The Chains that Bind Us"
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Quicksand_Caves/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath Action
-----------------------------------
function onMobDeath(mob,killer)
if(killer:getCurrentMission(BASTOK) == THE_CHAINS_THAT_BIND_US) and (killer:getVar("MissionStatus") == 1) then
SetServerVariable("Bastok8-1LastClear", os.time());
end
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob, target)
end;
-----------------------------------
-- onMobDisengage Action
-----------------------------------
function onMobDisengage(mob)
-- printf("Disengaging Triarius");
local self = mob:getID();
DespawnMob(self, 120);
end;
-----------------------------------
-- onMobDespawn Action
-----------------------------------
function onMobDespawn(mob)
-- printf("Despawning Triarius");
local mobsup = GetServerVariable("BastokFight8_1");
SetServerVariable("BastokFight8_1",mobsup - 1);
if(GetServerVariable("BastokFight8_1") == 0) then
local npc = GetNPCByID(17629731); -- qm6
npc:setStatus(0); -- Reappear
end
end;
| gpl-3.0 |
akdor1154/awesome | lib/awful/widget/common.lua | 1 | 3638 | ---------------------------------------------------------------------------
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @classmod awful.widget.common
---------------------------------------------------------------------------
-- Grab environment we need
local type = type
local ipairs = ipairs
local capi = { button = button }
local wibox = require("wibox")
local dpi = require("beautiful").xresources.apply_dpi
--- Common utilities for awful widgets
local common = {}
--- Common method to create buttons.
-- @tab buttons
-- @param object
-- @treturn table
function common.create_buttons(buttons, object)
if buttons then
local btns = {}
for _, b in ipairs(buttons) do
-- Create a proxy button object: it will receive the real
-- press and release events, and will propagate them to the
-- button object the user provided, but with the object as
-- argument.
local btn = capi.button { modifiers = b.modifiers, button = b.button }
btn:connect_signal("press", function () b:emit_signal("press", object) end)
btn:connect_signal("release", function () b:emit_signal("release", object) end)
btns[#btns + 1] = btn
end
return btns
end
end
--- Common update method.
-- @param w The widget.
-- @tab buttons
-- @func label Function to generate label parameters from an object.
-- The function gets passed an object from `objects`, and
-- has to return `text`, `bg`, `bg_image`, `icon`.
-- @tab data Current data/cache, indexed by objects.
-- @tab objects Objects to be displayed / updated.
function common.list_update(w, buttons, label, data, objects)
-- update the widgets, creating them if needed
w:reset()
for i, o in ipairs(objects) do
local cache = data[o]
local ib, tb, bgb, tbm, ibm, l
if cache then
ib = cache.ib
tb = cache.tb
bgb = cache.bgb
tbm = cache.tbm
ibm = cache.ibm
else
ib = wibox.widget.imagebox()
tb = wibox.widget.textbox()
bgb = wibox.widget.background()
tbm = wibox.layout.margin(tb, dpi(4), dpi(4))
ibm = wibox.layout.margin(ib, dpi(4))
l = wibox.layout.fixed.horizontal()
-- All of this is added in a fixed widget
l:fill_space(true)
l:add(ibm)
l:add(tbm)
-- And all of this gets a background
bgb:set_widget(l)
bgb:buttons(common.create_buttons(buttons, o))
data[o] = {
ib = ib,
tb = tb,
bgb = bgb,
tbm = tbm,
ibm = ibm,
}
end
local text, bg, bg_image, icon = label(o, tb)
-- The text might be invalid, so use pcall.
if text == nil or text == "" then
tbm:set_margins(0)
else
if not tb:set_markup_silently(text) then
tb:set_markup("<i><Invalid text></i>")
end
end
bgb:set_bg(bg)
if type(bg_image) == "function" then
-- TODO: Why does this pass nil as an argument?
bg_image = bg_image(tb,o,nil,objects,i)
end
bgb:set_bgimage(bg_image)
if icon then
ib:set_image(icon)
else
ibm:set_margins(0)
end
w:add(bgb)
end
end
return common
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
FailcoderAddons/supervillain-ui | SVUI_!Core/libs/AceVillain-1.0/widgets/shared/SoundWidget.lua | 3 | 8375 | -- Widget is based on the AceGUIWidget-DropDown.lua supplied with AceGUI-3.0
-- Widget created by Yssaril
local AceGUI = LibStub("AceGUI-3.0")
local Media = LibStub("LibSharedMedia-3.0")
local AceVillain = LibStub("AceVillain-1.0")
do
local widgetType = "LSM30_Sound"
local widgetVersion = 999999
local contentFrameCache = {}
local function ReturnSelf(self)
self:ClearAllPoints()
self:Hide()
self.check:Hide()
table.insert(contentFrameCache, self)
end
local function ContentOnClick(this, button)
local self = this.obj
self:Fire("OnValueChanged", this.text:GetText())
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function ContentSpeakerOnClick(this, button)
local self = this.frame.obj
local sound = this.frame.text:GetText()
PlaySoundFile(self.list[sound] ~= sound and self.list[sound] or Media:Fetch('sound',sound), "Master")
end
local function GetContentLine()
local frame
if next(contentFrameCache) then
frame = table.remove(contentFrameCache)
else
frame = CreateFrame("Button", nil, UIParent)
--frame:SetWidth(320)
frame:SetHeight(18)
frame:SetHighlightTexture([[Interface\AddOns\SVUI_!Core\assets\textures\TITLE-HIGHLIGHT]], "ADD")
frame:SetScript("OnClick", ContentOnClick)
local check = frame:CreateTexture("OVERLAY")
check:SetWidth(16)
check:SetHeight(16)
check:SetPoint("LEFT",frame,"LEFT",1,-1)
check:SetTexture("Interface\\Buttons\\UI-CheckBox-Check")
check:Hide()
frame.check = check
local soundbutton = CreateFrame("Button", nil, frame)
soundbutton:SetWidth(16)
soundbutton:SetHeight(16)
soundbutton:SetPoint("RIGHT",frame,"RIGHT",-1,0)
soundbutton.frame = frame
soundbutton:SetScript("OnClick", ContentSpeakerOnClick)
frame.soundbutton = soundbutton
local speaker = soundbutton:CreateTexture(nil, "BACKGROUND")
speaker:SetTexture("Interface\\Common\\VoiceChat-Speaker")
speaker:SetAllPoints(soundbutton)
frame.speaker = speaker
local speakeron = soundbutton:CreateTexture(nil, "HIGHLIGHT")
speakeron:SetTexture("Interface\\Common\\VoiceChat-On")
speakeron:SetAllPoints(soundbutton)
frame.speakeron = speakeron
local text = frame:CreateFontString(nil,"OVERLAY","GameFontWhite")
text:SetWordWrap(false)
text:SetPoint("LEFT", check, "RIGHT", 1, 0)
text:SetPoint("RIGHT", soundbutton, "LEFT", -2, 0)
text:SetJustifyH("LEFT")
text:SetText("Test Test Test Test Test Test Test")
frame.text = text
frame.ReturnSelf = ReturnSelf
end
frame:Show()
return frame
end
local function OnAcquire(self)
self:SetHeight(44)
self:SetWidth(320)
end
local function OnRelease(self)
self:SetText("")
self:SetLabel("")
self:SetDisabled(false)
self.value = nil
self.list = nil
self.open = nil
self.hasClose = nil
self.frame:ClearAllPoints()
self.frame:Hide()
end
local function SetValue(self, value) -- Set the value to an item in the List.
if self.list then
self:SetText(value or "")
end
self.value = value
end
local function GetValue(self)
return self.value
end
local function SetList(self, list) -- Set the list of values for the dropdown (key => value pairs)
self.list = list or Media:HashTable("sound")
end
local function SetText(self, text) -- Set the text displayed in the box.
self.frame.text:SetText(text or "")
end
local function SetLabel(self, text) -- Set the text for the label.
self.frame.label:SetText(text or "")
end
local function AddItem(self, key, value) -- Add an item to the list.
self.list = self.list or {}
self.list[key] = value
end
local SetItemValue = AddItem -- Set the value of a item in the list. <<same as adding a new item>>
local function SetMultiselect(self, flag) end -- Toggle multi-selecting. <<Dummy function to stay inline with the dropdown API>>
local function GetMultiselect() return false end-- Query the multi-select flag. <<Dummy function to stay inline with the dropdown API>>
local function SetItemDisabled(self, key) end-- Disable one item in the list. <<Dummy function to stay inline with the dropdown API>>
local function SetDisabled(self, disabled) -- Disable the widget.
self.disabled = disabled
if disabled then
self.frame:Disable()
self.speaker:SetDesaturated(true)
self.speakeron:SetDesaturated(true)
else
self.frame:Enable()
self.speaker:SetDesaturated(false)
self.speakeron:SetDesaturated(false)
end
end
local function textSort(a,b)
return string.upper(a) < string.upper(b)
end
local sortedlist = {}
local function ToggleDrop(this)
local self = this.obj
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
AceGUI:ClearFocus()
else
AceGUI:SetFocus(self)
self.dropdown = AceVillain:GetDropDownFrame()
local width = self.frame:GetWidth()
self.dropdown:SetPoint("TOPLEFT", self.frame, "BOTTOMLEFT")
self.dropdown:SetPoint("TOPRIGHT", self.frame, "BOTTOMRIGHT", width < 160 and (160 - width) or 0, 0)
for k, v in pairs(self.list) do
sortedlist[#sortedlist+1] = k
end
table.sort(sortedlist, textSort)
for i, k in ipairs(sortedlist) do
local f = GetContentLine()
f.text:SetText(k)
if k == self.value then
f.check:Show()
end
f.obj = self
self.dropdown:AddFrame(f)
end
wipe(sortedlist)
end
end
local function ClearFocus(self)
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function OnHide(this)
local self = this.obj
if self.dropdown then
self.dropdown = AceVillain:ReturnDropDownFrame(self.dropdown)
end
end
local function Drop_OnEnter(this)
this.obj:Fire("OnEnter")
end
local function Drop_OnLeave(this)
this.obj:Fire("OnLeave")
end
local function WidgetPlaySound(this)
local self = this.obj
local sound = self.frame.text:GetText()
PlaySoundFile(self.list[sound] ~= sound and self.list[sound] or Media:Fetch('sound',sound), "Master")
end
local function SetDropDownStyle(self, xTopleft, yTopleft, xBottomright, yBottomright)
self:RemoveTextures()
self:SetStyle("Frame", "Transparent")
self.Panel:SetPoint("TOPLEFT", self, "TOPLEFT", xTopleft, yTopleft)
self.Panel:SetPoint("BOTTOMRIGHT", self, "BOTTOMRIGHT", xBottomright, yBottomright)
end
local function Constructor()
local frame = AceVillain:GetBaseFrame()
local self = {}
self.type = widgetType
self.frame = frame
frame.obj = self
frame.dropButton.obj = self
frame.dropButton:SetScript("OnEnter", Drop_OnEnter)
frame.dropButton:SetScript("OnLeave", Drop_OnLeave)
frame.dropButton:SetScript("OnClick",ToggleDrop)
frame:SetScript("OnHide", OnHide)
if(frame.SetStyle) then
SetDropDownStyle(frame, 2, -20, -2, 0)
frame.dropButton:ClearAllPoints()
frame.dropButton:SetPoint("BOTTOMRIGHT", frame, "BOTTOMRIGHT", -2, 0)
if(SVUI and SVUI.API) then
SVUI.API:Set("PageButton", frame.dropButton, true)
end
frame.dropButton:SetParent(frame.Panel)
end
local soundbutton = CreateFrame("Button", nil, frame)
soundbutton:SetWidth(16)
soundbutton:SetHeight(16)
soundbutton:SetPoint("LEFT",frame.DLeft,"LEFT",26,1)
soundbutton:SetScript("OnClick", WidgetPlaySound)
soundbutton.obj = self
self.soundbutton = soundbutton
frame.text:SetPoint("LEFT",soundbutton,"RIGHT",2,0)
local speaker = soundbutton:CreateTexture(nil, "BACKGROUND")
speaker:SetTexture("Interface\\Common\\VoiceChat-Speaker")
speaker:SetAllPoints(soundbutton)
self.speaker = speaker
local speakeron = soundbutton:CreateTexture(nil, "HIGHLIGHT")
speakeron:SetTexture("Interface\\Common\\VoiceChat-On")
speakeron:SetAllPoints(soundbutton)
self.speakeron = speakeron
self.alignoffset = 31
self.OnRelease = OnRelease
self.OnAcquire = OnAcquire
self.ClearFocus = ClearFocus
self.SetText = SetText
self.SetValue = SetValue
self.GetValue = GetValue
self.SetList = SetList
self.SetLabel = SetLabel
self.SetDisabled = SetDisabled
self.AddItem = AddItem
self.SetMultiselect = SetMultiselect
self.GetMultiselect = GetMultiselect
self.SetItemValue = SetItemValue
self.SetItemDisabled = SetItemDisabled
self.ToggleDrop = ToggleDrop
AceGUI:RegisterAsWidget(self)
return self
end
AceGUI:RegisterWidgetType(widgetType, Constructor, widgetVersion)
end
| mit |
Cycloneteam/CycloneTg | plugins/serverfile.lua | 1 | 2352 | do
local function run(msg, matches)
if not is_admin(msg) then
return "شما دسترسی لازم ندارید"
end
local receiver = get_receiver(msg)
if matches[1] == 'send' then
local file = matches[3]
if matches[2] == 'sticker' and not matches[4] then
send_document(receiver, "./media/"..file..".webp", ok_cb, false)
end
if matches[2] == 'file' then
local extension = matches[4]
send_document(receiver, "./media/"..file..'.'..extension, ok_cb, false)
end
if matches[2] == 'plugin' then
send_document(receiver, "./plugins/"..file..".lua", ok_cb, false)
end
if matches[2] == 'dev' or matches[2] == 'm4ster' or matches[2] == 'master' or matches[2] == 'developer' or matches[2] == 'creator'then
local extension = matches[4]
if matches[3] == 'file' then
send_document(receiver, "./media/M4STER.png", ok_cb, false)
elseif matches[3] ~= 'file' or not matches[3] then
send_photo(receiver, "./media/M4STER.png", ok_cb, false)
end
end
if matches[2] == 'manual' and is_admin(msg) then
local ruta = matches[3]
local document = matches[4]
send_document(receiver, "./"..ruta.."/"..document, ok_cb, false)
end
end
if matches[1] == 'extensions' then
return 'No disponible actualmente'
end
if matches[1] == 'list' and matches[2] == 'files' then
return 'No disponible actualmente'
—send_document(receiver, "./media/files/files.txt", ok_cb, false)
end
end
return {
description = "Kicking ourself (bot) from unmanaged groups.",
usage = {
"!list files : Envía un archivo con los nombres de todo lo que se puede enviar",
"!extensions : Envía un mensaje con las extensiones para cada tipo de archivo permitidas",
"➖➖➖➖➖➖➖➖➖➖",
"!send file <nombre del archivo> <extension del archivo> : Envía ese archivo del servidor",
"!send plugin <Nombre del plugin> : Envía ese archivo del servidor",
"!send manual <Ruta de archivo> <Nombre del plugin> : Envía un archivo desde el directorio TeleSeed",
"!send dev : Envía una foto del desarrollador"
},
patterns = {
"^([Ss]end) (.*) (.*) (.*)$",
"^([Ss]end) (.*) (.*)$",
"^([Ss]end) (.*)$",
"^([Ll]ist) (files)$",
"^([Ee]xtensions)$"
},
run = run
}
end
| gpl-2.0 |
nesstea/darkstar | scripts/zones/LaLoff_Amphitheater/npcs/qm0_4.lua | 13 | 1160 | -----------------------------------
-- Area: LaLoff_Amphitheater
-- NPC: qm0 (warp player outside after they win fight)
-------------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-------------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0C);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if (csid == 0x0C and option == 1) then
player:setPos(-471.738,-42.088,153.268,11,130);
end
end; | gpl-3.0 |
Mashape/kong | kong/plugins/bot-detection/rules.lua | 13 | 3575 | -- List taken from https://github.com/ua-parser/uap-core/blob/master/regexes.yaml
return {
bots = {
[[(Pingdom.com_bot_version_)(\d+)\.(\d+)]], -- Pingdom
[[(facebookexternalhit)/(\d+)\.(\d+)]], -- Facebook
[[Google.*/\+/web/snippet]], -- Google Plus
[[(Twitterbot)/(\d+)\.(\d+)]], -- Twitter
[[/((?:Ant-)?Nutch|[A-z]+[Bb]ot|[A-z]+[Ss]pider|Axtaris|fetchurl|Isara|ShopSalad|Tailsweep)[ \-](\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots Pattern '/name-0.0'
[[(008|Altresium|Argus|BaiduMobaider|BoardReader|DNSGroup|DataparkSearch|EDI|Goodzer|Grub|INGRID|Infohelfer|LinkedInBot|LOOQ|Nutch|PathDefender|Peew|PostPost|Steeler|Twitterbot|VSE|WebCrunch|WebZIP|Y!J-BR[A-Z]|YahooSeeker|envolk|sproose|wminer)/(\d+)(?:\.(\d+)(?:\.(\d+))?)?]], --Bots Pattern 'name/0.0'
[[(MSIE) (\d+)\.(\d+)([a-z]\d?)?;.* MSIECrawler]], --MSIECrawler
[[(Google-HTTP-Java-Client|Apache-HttpClient|http%20client|Python-urllib|HttpMonitor|TLSProber|WinHTTP|JNLP)(?:[ /](\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]], -- Downloader ...
[[(1470\.net crawler|50\.nu|8bo Crawler Bot|Aboundex|Accoona-[A-z]+-Agent|AdsBot-Google(?:-[a-z]+)?|altavista|AppEngine-Google|archive.*?\.org_bot|archiver|Ask Jeeves|[Bb]ai[Dd]u[Ss]pider(?:-[A-Za-z]+)*|bingbot|BingPreview|blitzbot|BlogBridge|BoardReader(?: [A-Za-z]+)*|boitho.com-dc|BotSeer|\b\w*favicon\w*\b|\bYeti(?:-[a-z]+)?|Catchpoint bot|[Cc]harlotte|Checklinks|clumboot|Comodo HTTP\(S\) Crawler|Comodo-Webinspector-Crawler|ConveraCrawler|CRAWL-E|CrawlConvera|Daumoa(?:-feedfetcher)?|Feed Seeker Bot|findlinks|Flamingo_SearchEngine|FollowSite Bot|furlbot|Genieo|gigabot|GomezAgent|gonzo1|(?:[a-zA-Z]+-)?Googlebot(?:-[a-zA-Z]+)?|Google SketchUp|grub-client|gsa-crawler|heritrix|HiddenMarket|holmes|HooWWWer|htdig|ia_archiver|ICC-Crawler|Icarus6j|ichiro(?:/mobile)?|IconSurf|IlTrovatore(?:-Setaccio)?|InfuzApp|Innovazion Crawler|InternetArchive|IP2[a-z]+Bot|jbot\b|KaloogaBot|Kraken|Kurzor|larbin|LEIA|LesnikBot|Linguee Bot|LinkAider|LinkedInBot|Lite Bot|Llaut|lycos|Mail\.RU_Bot|masidani_bot|Mediapartners-Google|Microsoft .*? Bot|mogimogi|mozDex|MJ12bot|msnbot(?:-media *)?|msrbot|netresearch|Netvibes|NewsGator[^/]*|^NING|Nutch[^/]*|Nymesis|ObjectsSearch|Orbiter|OOZBOT|PagePeeker|PagesInventory|PaxleFramework|Peeplo Screenshot Bot|PlantyNet_WebRobot|Pompos|Read%20Later|Reaper|RedCarpet|Retreiver|Riddler|Rival IQ|scooter|Scrapy|Scrubby|searchsight|seekbot|semanticdiscovery|Simpy|SimplePie|SEOstats|SimpleRSS|SiteCon|Slurp|snappy|Speedy Spider|Squrl Java|TheUsefulbot|ThumbShotsBot|Thumbshots\.ru|TwitterBot|URL2PNG|Vagabondo|VoilaBot|^vortex|Votay bot|^voyager|WASALive.Bot|Web-sniffer|WebThumb|WeSEE:[A-z]+|WhatWeb|WIRE|WordPress|Wotbox|www\.almaden\.ibm\.com|Xenu(?:.s)? Link Sleuth|Xerka [A-z]+Bot|yacy(?:bot)?|Yahoo[a-z]*Seeker|Yahoo! Slurp|Yandex\w+|YodaoBot(?:-[A-z]+)?|YottaaMonitor|Yowedo|^Zao|^Zao-Crawler|ZeBot_www\.ze\.bz|ZooShot|ZyBorg)(?:[ /]v?(\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]], -- Bots
[[(?:\/[A-Za-z0-9\.]+)? *([A-Za-z0-9 \-_\!\[\]:]*(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]*))/(\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots General matcher 'name/0.0'
[[(?:\/[A-Za-z0-9\.]+)? *([A-Za-z0-9 _\!\[\]:]*(?:[Aa]rchiver|[Ii]ndexer|[Ss]craper|[Bb]ot|[Ss]pider|[Cc]rawl[a-z]*)) (\d+)(?:\.(\d+)(?:\.(\d+))?)?]], -- Bots General matcher 'name 0.0'
[[((?:[A-z0-9]+|[A-z\-]+ ?)?(?: the )?(?:[Ss][Pp][Ii][Dd][Ee][Rr]|[Ss]crape|[A-Za-z0-9-]*(?:[^C][^Uu])[Bb]ot|[Cc][Rr][Aa][Ww][Ll])[A-z0-9]*)(?:(?:[ /]| v)(\d+)(?:\.(\d+)(?:\.(\d+))?)?)?]] -- Bots containing spider|scrape|bot(but not CUBOT)|Crawl
}
}
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/items/tiger_cod.lua | 17 | 1318 | -----------------------------------------
-- ID: 4483
-- Item: tiger_cod
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 2
-- Mind -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4483);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 2);
target:addMod(MOD_MND, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 2);
target:delMod(MOD_MND, -4);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sharin-Garin.lua | 13 | 1992 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sharin-Garin
-- Type: Adventurer's Assistant
-- @pos 122.658 -1.315 33.001 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/besieged");
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local runicpass = 0;
if (player:hasKeyItem(RUNIC_PORTAL_USE_PERMIT)) then
runicpass = 1;
end
local cost = 200 -- 200 IS to get a permit
if (getMercenaryRank(player) == 11) then
captain = 1;
else
captain = 0;
end;
local merc = 2 -- Probably could be done, but not really important atm
player:startEvent(0x008C,0,merc,runicpass,player:getCurrency("imperial_standing"),getAstralCandescence(),cost,captain);
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 == 0x008C and option == 1) then
player:addKeyItem(RUNIC_PORTAL_USE_PERMIT);
player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT);
player:delCurrency("imperial_standing", 200);
elseif (csid == 0x008C and option == 2) then
player:addKeyItem(RUNIC_PORTAL_USE_PERMIT);
player:messageSpecial(KEYITEM_OBTAINED,RUNIC_PORTAL_USE_PERMIT);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Windurst_Walls/npcs/Scavnix.lua | 13 | 1183 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Scavnix
-- Standard merchant, though he acts like a guild merchant
-- @pos 17.731 0.106 239.626 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Windurst_Walls/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(60418,11,22,6)) then
player:showText(npc,SCAVNIX_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Batallia_Downs/npcs/qm2.lua | 13 | 1495 | -----------------------------------
-- Area: Batallia Downs
-- NPC: qm2 (???)
-- Pop for the quest "Chasing Quotas"
-----------------------------------
package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Batallia_Downs/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
local Sturmtiger = player:getVar("SturmtigerKilled");
if (player:getVar("ChasingQuotas_Progress") == 5 and Sturmtiger == 0) then
SpawnMob(17207696,300):updateClaim(player);
elseif (Sturmtiger == 1) then
player:addKeyItem(RANCHURIOMES_LEGACY);
player:messageSpecial(KEYITEM_OBTAINED,RANCHURIOMES_LEGACY);
player:setVar("ChasingQuotas_Progress",6);
player:setVar("SturmtigerKilled",0);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
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/zones/The_Eldieme_Necropolis/TextIDs.lua | 5 | 2300 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6541; -- Obtained: <item>
GIL_OBTAINED = 6542; -- Obtained <number> gil
KEYITEM_OBTAINED = 6544; -- Obtained key item: <keyitem>
SOLID_STONE = 7361; -- This door is made of solid stone.
-- Treasure Coffer/Chest Dialog
CHEST_UNLOCKED = 7380; -- You unlock the chest!
CHEST_FAIL = 7381; -- Fails to open the chest.
CHEST_TRAP = 7382; -- The chest was trapped!
CHEST_WEAK = 7383; -- You cannot open the chest when you are in a weakened state.
CHEST_MIMIC = 7384; -- The chest was a mimic!
CHEST_MOOGLE = 7385; -- You cannot open the chest while participating in the moogle event.
CHEST_ILLUSION = 7386; -- The chest was but an illusion...
CHEST_LOCKED = 7387; -- The chest appears to be locked.
-- Quests
NOTHING_OUT_OF_ORDINARY = 6555; -- There is nothing out of the ordinary here.
SENSE_OF_FOREBODING = 6556; -- You are suddenly overcome with a sense of foreboding...
NOTHING_HAPPENED = 7321; -- Nothing happened...
RETURN_RIBBON_TO_HER = 7334; -- You can hear a voice from somewhere. (...return...ribbon to...her...)
THE_BRAZIER_IS_LIT = 7348; -- The brazier is lit.
REFUSE_TO_LIGHT = 7349; -- Unexpectedly, therefuses to light.
LANTERN_GOES_OUT = 7350; -- For some strange reason, the light of thegoes out...
THE_LIGHT_DIMLY = 7351; -- lights dimly. It doesn't look like this will be effective yet.?Prompt?
THE_LIGHT_HAS_INTENSIFIED = 7352; -- The light of thehas intensified.
THE_LIGHT_IS_FULLY_LIT = 7353; -- is fully lit!
SPIRIT_INCENSE_EMITS_PUTRID_ODOR = 7390; -- emits a putrid odor and burns up. Your attempt this time has failed...?Prompt?
SARCOPHAGUS_CANNOT_BE_OPENED = 7407; -- It is a stone sarcophagus with the lid sealed tight. It cannot be opened.
-- conquest Base
CONQUEST_BASE = 0;
-- Strange Apparatus
DEVICE_NOT_WORKING = 7297; -- The device is not working.
SYS_OVERLOAD = 7306; -- arning! Sys...verload! Enterin...fety mode. ID eras...d
YOU_LOST_THE = 7311; -- You lost the #.
| gpl-3.0 |
jj918160/cocos2d-x-samples | samples/FantasyWarrior3D/src/cocos/ui/DeprecatedUIEnum.lua | 39 | 4928 |
LAYOUT_COLOR_NONE = ccui.LayoutBackGroundColorType.none
LAYOUT_COLOR_SOLID = ccui.LayoutBackGroundColorType.solid
LAYOUT_COLOR_GRADIENT = ccui.LayoutBackGroundColorType.gradient
LAYOUT_ABSOLUTE = ccui.LayoutType.ABSOLUTE
LAYOUT_LINEAR_VERTICAL = ccui.LayoutType.VERTICAL
LAYOUT_LINEAR_HORIZONTAL = ccui.LayoutType.HORIZONTAL
LAYOUT_RELATIVE = ccui.LayoutType.RELATIVE
BRIGHT_NONE = ccui.BrightStyle.none
BRIGHT_NORMAL = ccui.BrightStyle.normal
BRIGHT_HIGHLIGHT = ccui.BrightStyle.highlight
UI_TEX_TYPE_LOCAL = ccui.TextureResType.localType
UI_TEX_TYPE_PLIST = ccui.TextureResType.plistType
TOUCH_EVENT_BEGAN = ccui.TouchEventType.began
TOUCH_EVENT_MOVED = ccui.TouchEventType.moved
TOUCH_EVENT_ENDED = ccui.TouchEventType.ended
TOUCH_EVENT_CANCELED = ccui.TouchEventType.canceled
SIZE_ABSOLUTE = ccui.SizeType.absolute
SIZE_PERCENT = ccui.SizeType.percent
POSITION_ABSOLUTE = ccui.PositionType.absolute
POSITION_PERCENT = ccui.PositionType.percent
CHECKBOX_STATE_EVENT_SELECTED = ccui.CheckBoxEventType.selected
CHECKBOX_STATE_EVENT_UNSELECTED = ccui.CheckBoxEventType.unselected
CHECKBOX_STATE_EVENT_SELECTED = ccui.CheckBoxEventType.selected
CHECKBOX_STATE_EVENT_UNSELECTED = ccui.CheckBoxEventType.unselected
LoadingBarTypeLeft = ccui.LoadingBarDirection.LEFT
LoadingBarTypeRight = ccui.LoadingBarDirection.RIGHT
LoadingBarTypeRight = ccui.SliderEventType.percent_changed
TEXTFIELD_EVENT_ATTACH_WITH_IME = ccui.TextFiledEventType.attach_with_ime
TEXTFIELD_EVENT_DETACH_WITH_IME = ccui.TextFiledEventType.detach_with_ime
TEXTFIELD_EVENT_INSERT_TEXT = ccui.TextFiledEventType.insert_text
TEXTFIELD_EVENT_DELETE_BACKWARD = ccui.TextFiledEventType.delete_backward
SCROLLVIEW_EVENT_SCROLL_TO_TOP = ccui.ScrollViewDir.none
SCROLLVIEW_DIR_VERTICAL = ccui.ScrollViewDir.vertical
SCROLLVIEW_DIR_HORIZONTAL = ccui.ScrollViewDir.horizontal
SCROLLVIEW_DIR_BOTH = ccui.ScrollViewDir.both
SCROLLVIEW_EVENT_SCROLL_TO_TOP = ccui.ScrollviewEventType.scrollToTop
SCROLLVIEW_EVENT_SCROLL_TO_BOTTOM = ccui.ScrollviewEventType.scrollToBottom
SCROLLVIEW_EVENT_SCROLL_TO_LEFT = ccui.ScrollviewEventType.scrollToLeft
SCROLLVIEW_EVENT_SCROLL_TO_RIGHT = ccui.ScrollviewEventType.scrollToRight
SCROLLVIEW_EVENT_SCROLLING = ccui.ScrollviewEventType.scrolling
SCROLLVIEW_EVENT_BOUNCE_TOP = ccui.ScrollviewEventType.bounceTop
SCROLLVIEW_EVENT_BOUNCE_BOTTOM = ccui.ScrollviewEventType.bounceBottom
SCROLLVIEW_EVENT_BOUNCE_LEFT = ccui.ScrollviewEventType.bounceLeft
SCROLLVIEW_EVENT_BOUNCE_RIGHT = ccui.ScrollviewEventType.bounceRight
PAGEVIEW_EVENT_TURNING = ccui.PageViewEventType.turning
PAGEVIEW_TOUCHLEFT = ccui.PVTouchDir.touch_left
PAGEVIEW_TOUCHRIGHT = ccui.PVTouchDir.touch_right
LISTVIEW_DIR_NONE = ccui.ListViewDirection.none
LISTVIEW_DIR_VERTICAL = ccui.ListViewDirection.vertical
LISTVIEW_DIR_HORIZONTAL = ccui.ListViewDirection.horizontal
LISTVIEW_MOVE_DIR_NONE = ccui.ListViewMoveDirection.none
LISTVIEW_MOVE_DIR_UP = ccui.ListViewMoveDirection.up
LISTVIEW_MOVE_DIR_DOWN = ccui.ListViewMoveDirection.down
LISTVIEW_MOVE_DIR_LEFT = ccui.ListViewMoveDirection.left
LISTVIEW_MOVE_DIR_RIGHT = ccui.ListViewMoveDirection.right
LISTVIEW_EVENT_INIT_CHILD = ccui.ListViewEventType.init_child
LISTVIEW_EVENT_UPDATE_CHILD = ccui.ListViewEventType.update_child
LAYOUT_PARAMETER_NONE = ccui.LayoutParameterType.none
LAYOUT_PARAMETER_LINEAR = ccui.LayoutParameterType.linear
LAYOUT_PARAMETER_RELATIVE = ccui.LayoutParameterType.relative
ccui.LoadingBarType = ccui.LoadingBarDirection
ccui.LoadingBarType.left = ccui.LoadingBarDirection.LEFT
ccui.LoadingBarType.right = ccui.LoadingBarDirection.RIGHT
ccui.LayoutType.absolute = ccui.LayoutType.ABSOLUTE
ccui.LayoutType.linearVertical = ccui.LayoutType.VERTICAL
ccui.LayoutType.linearHorizontal = ccui.LayoutType.HORIZONTAL
ccui.LayoutType.relative = ccui.LayoutType.RELATIVE
ccui.ListViewEventType.onsSelectedItem = ccui.ListViewEventType.ONSELECTEDITEM_START
| mit |
niessner/Matterport | tasks/region_classification/utils.lua | 1 | 1287 |
-- Check if a file exists
function fileExists(file)
local f = io.open(file, "rb")
if f then f:close() end
return f ~= nil
end
-- Get all lines from a file, returns an empty list/table if the file does not exist
function getLinesFromFile(file)
if not fileExists(file) then return {} end
lines = {}
for line in io.lines(file) do
lines[#lines + 1] = line
end
return lines
end
-- Shuffle table
function shuffleTable(t,n)
while n > 2 do -- only run if the table has more than 1 element
local k = math.random(n) -- get a random number
t[n], t[k] = t[k], t[n]
n = n - 1
end
return t
end
-- Lookup filenames in directory (with search query string)
function scanDir(directory,query)
local i, t, popen = 0, {}, io.popen
local pfile = popen('ls -a "'..directory..'"')
for filename in pfile:lines() do
if filename == '.' or filename == '..' then
else
if query then
if string.find(filename,query) then
i = i+1
t[i] = filename
end
else
print(filename)
i = i+1
t[i] = filename
end
end
end
pfile:close()
return t
end | mit |
UnfortunateFruit/darkstar | scripts/zones/Port_San_dOria/npcs/Gournaie.lua | 36 | 1374 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Gournaie
-- 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(0x2cb);
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/zones/Windurst_Waters_[S]/Zone.lua | 28 | 1331 | -----------------------------------
--
-- Zone: Windurst_Waters_[S] (94)
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Windurst_Waters_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(-39.996,-7.64,235,64);
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 |
nesstea/darkstar | scripts/zones/Windurst_Woods/npcs/Matata.lua | 13 | 1820 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Matata
-- Type: Standard NPC
-- @zone: 241
-- @pos 131 -5 -109
-- Involved in quest: In a Stew
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
CB = player:getQuestStatus(WINDURST,CHOCOBILIOUS);
IAS = player:getQuestStatus(WINDURST,IN_A_STEW);
IASvar = player:getVar("IASvar");
if (IAS == QUEST_ACCEPTED and IASvar == 1) then
player:startEvent(0x00E9,0,0,4545); -- In a Stew in progress
elseif (IAS == QUEST_ACCEPTED and IASvar == 2) then
player:startEvent(0x00ED); -- In a Stew reminder
elseif (IAS == QUEST_COMPLETED) then
player:startEvent(0x00F1); -- new dialog after In a Stew
elseif (CB == QUEST_COMPLETED) then
player:startEvent(0x00E2); -- Chocobilious complete
else
-- Standard Dialog
player:startEvent(0xdf);
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);
-- In a Stew
if (csid == 0x00E9) then
player:setVar("IASvar",2);
end
end;
| gpl-3.0 |
bowlofstew/Macaroni | Main/Generators/VCpp/VCpp10.lua | 2 | 13009 | require "Macaroni.IO.GeneratedFileWriter"
require "Macaroni.IO.Path"
Path = Macaroni.IO.Path
function checkArgs(args, name, description)
if args[name] == nil then
msg = 'Missing argument "' .. name;
if description ~= nil then
msg = msg .. " Description:" .. description;
end
error(msg)
end
end
function Generate(library, sources, outputPath)
end
function Build(library, sources, outputPath, installPath, extraArgs)
-- Creates a Visual C++ project.
local proj = ProjectFileWriter.new(extraArgs, library, sources, outputPath)
proj:WriteFile()
end
ProjectFileWriter = {
new = function(args, library, sources, outputPath)
if args == nil then error("Must include extraArgs.") end
checkArgs(args, "ProjectFile",
"The path to put the generated project file.");
checkArgs(args, "ProjectGUID");
checkArgs(args, "RootNamespace");
if args.Name == nil then
args.Name = library.Name
end
checkArgs(args, "AdditionalIncludePaths");
checkArgs(args, "AdditionalLibraryPaths");
checkArgs(args, "SourcePaths");
if args.AdditionalIncludePaths == nil then
args.AdditionalIncludePaths = {}
end
if args.AdditionalLibraryPaths == nil then
args.AdditionalLibraryPaths = {}
end
if args.AdditionalSourcePaths == nil then
args.AdditionalSourcePaths = {}
end
if args.SourceExcludePatterns == nil then
args.SourceExcludePatterns = {}
end
if args.Configurations == nil then
args.Configurations = {
{
Name="Debug|Win32",
Configuration="Debug",
Platform="Win32",
--PreprocessorDefinitions="WIN32;_DEBUG;_CONSOLE"
}
};
end
args.library = library
args.sources = {}
for i, v in ipairs(args.SourcePaths) do
args.sources[#args.sources + 1] = Path.New(v)
end
for i, v in ipairs(args.AdditionalSourcePaths) do
args.sources[#args.sources + 1] = Path.New(v)
end
args.outputPath = outputPath
self = args
self.writer = Path.New(self.ProjectFile):CreateFile()
setmetatable(self, {["__index"]=ProjectFileWriter});
return self
end,
-- function librarySourcePath(d)
-- local success, path = pcall(d.FindInstallPath, d);
-- if (success and path ~= nil) then
-- local pathText = path.AbsolutePathForceSlash;
-- local sourceFolder = path:NewPathForceSlash('Cpp');
-- if (sourceFolder.Exists) then
-- return sourceFolder;
-- end
-- end
-- return nil;
-- end,
WriteFile = function(self)
self:writeBegin();
self:writeConfigurations();
self.writer:Write([[
<PropertyGroup Label="Globals">
<ProjectGuid>{]] .. self.ProjectGUID .. [[}</ProjectGuid>
<Keyword>Win32Proj</Keyword>
<RootNamespace>]] .. self.RootNamespace .. [[</RootNamespace>
</PropertyGroup>
]])
self.writer:Write([[
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
<WholeProgramOptimization>true</WholeProgramOptimization>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" />
<ImportGroup Label="ExtensionSettings">
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<PropertyGroup Label="UserMacros" />
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<LinkIncremental>true</LinkIncremental>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<LinkIncremental>false</LinkIncremental>
</PropertyGroup>
]]);
self.writer:Write([[
<PropertyGroup>
<LinkIncremental>true</LinkIncremental>
<IncludePath>]]);
-- for i, source in ipairs(self.sources) do
-- self.writer:Write('"' .. source.AbsolutePath .. '";')
-- end
-- self.writer:Write('"' .. self.outputPath.AbsolutePath .. '";')
self.writer:Write([[$(IncludePath)</IncludePath>
</PropertyGroup>
]])
self.writer:Write([[
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<ClCompile>
<PrecompiledHeader>
</PrecompiledHeader>
<WarningLevel>Level3</WarningLevel>
<Optimization>Disabled</Optimization>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<AdditionalIncludeDirectories>]]);
for i, source in ipairs(self.sources) do
self.writer:Write('"' .. source.AbsolutePath .. '";')
end
self.writer:Write('"' .. self.outputPath.AbsolutePath .. '";')
for i, dir in ipairs(self.AdditionalIncludePaths) do
self.writer:Write('"' .. Path.New(dir).AbsolutePath .. '";')
end
self.writer:Write([[%(AdditionalIncludeDirectories)</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<AdditionalLibraryDirectories>]]);
for i, dir in ipairs(self.AdditionalLibraryPaths) do
self.writer:Write('"' .. Path.New(dir).AbsolutePath .. '";')
end
self.writer:Write([[%(AdditionalLibraryDirectories)
</AdditionalLibraryDirectories>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<PrecompiledHeader>
</PrecompiledHeader>
<Optimization>MaxSpeed</Optimization>
<FunctionLevelLinking>true</FunctionLevelLinking>
<IntrinsicFunctions>true</IntrinsicFunctions>
<PreprocessorDefinitions>WIN32;NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
<EnableCOMDATFolding>true</EnableCOMDATFolding>
<OptimizeReferences>true</OptimizeReferences>
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<None Include="ReadMe.txt" />
</ItemGroup>
]]);
self:writeFiles();
self.writer:Write([[
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">
</ImportGroup>
]]);
-- TODO: References?
-- self:writeFiles();
self:writeEnd();
end,
writeBegin = function(self)
self.writer:Write([[
<Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
]]);
end,
writeConfiguration = function(self, config)
self.writer:Write([[
<ProjectConfiguration Include="]] .. config.Name .. [[">
<Configuration>]] .. config.Configuration .. [[</Configuration>
<Platform>]] .. config.Platform .. [[</Platform>
</ProjectConfiguration>
]]);
end,
writeConfigurations = function(self)
self.writer:Write([[
<ItemGroup Label="ProjectConfigurations">
]]);
for i, v in ipairs(self.Configurations) do
self:writeConfiguration(v);
end
self.writer:Write([[
</ItemGroup>
]]);
end,
filePathExclude = function(self, fp)
-- Returns true if the given file path should be excluded.
for i, v in ipairs(self.SourceExcludePatterns) do
if string.sub(fp.AbsolutePath, - string.len(v)) == v then
return true
end
end
return false
end,
writeFiles = function(self)
local writeDirFiles = function(elementName, src, regex)
local filePaths = src:GetPaths(regex)
for i = 1, #filePaths do
local fp = filePaths[i];
if not self:filePathExclude(fp) then
if elementName == "None" then
self.writer:Write([[<None Include="]] ..
fp.AbsolutePath ..
[[">
<FileType>Document</FileType>
</None>]])
else
self.writer:Write([[<]] .. elementName ..[[ Include="]])
self.writer:Write(fp.AbsolutePath .. [[" />]] .. '\n')
end
end
end
end
self.writer:Write([[<ItemGroup>]]);
for i, v in ipairs(self.sources) do
writeDirFiles("None", v, [[\.(mcpp)?$]])
end
self.writer:Write([[</ItemGroup>]]);
self.writer:Write([[<ItemGroup>]]);
for i, v in ipairs(self.sources) do
writeDirFiles("ClCompile", v, [[\.(c|cc|cpp)?$]])
end
writeDirFiles("ClCompile", self.outputPath, [[\.(c|cpp)?$]])
self.writer:Write([[</ItemGroup>]]);
self.writer:Write([[<ItemGroup>]]);
for i, v in ipairs(self.sources) do
writeDirFiles("ClInclude", v, [[\.(h|hpp)?$]])
end
writeDirFiles("ClInclude", self.outputPath, [[\.(h|hpp)?$]])
self.writer:Write([[</ItemGroup>]]);
end,
writeEnd = function(self)
self.writer:Write("\n" .. [[
</Project>
]]);
self.writer:Close();
end,
writeIncludeDirectories = function(self, seperator)
local rtn = ""
for i, v in ipairs(self.sources) do
rtn = rtn .. v.AbsolutePath .. seperator
end
rtn = rtn .. self.outputPath.AbsolutePath .. seperator
for i, v in ipairs(self.library.Dependencies) do
local dir = guessIncludeLocation(v)
if dir ~= nil then
rtn = rtn .. dir .. seperator
end
end
return rtn;
end,
writeLibraryDirectories = function(self, seperator)
rtn = ""
for i, v in ipairs(self.sources) do
rtn = rtn .. v.AbsolutePath .. seperator
end
rtn = rtn .. self.outputPath.AbsolutePath .. seperator
for i, v in ipairs(self.library.Dependencies) do
local dir = guessBoostBuildLibraryLocation(v)
if dir ~= nil then
rtn = rtn .. dir .. seperator
end
end
return rtn;
end,
writePlatforms = function(self)
self.writer:Write("<Platforms>")
for i, n in ipairs(self.PlatformNames) do
self.writer:Write('<Platform Name="' .. n .. '" />')
end
self.writer:Write("</Platforms>")
end,
};
function guessIncludeLocation(d)
-- Given a dependency library, estimates where the included source is.
local success, path = pcall(d.FindInstallPath, d);
if (success and path ~= nil) then
local pathText = path.AbsolutePathForceSlash;
local includeDir = path:NewPathForceSlash('Cpp');
if (includeDir.Exists) then
return includeDir.AbsolutePath;
end
end
return nil;
end
function guessBoostBuildLibraryLocation(d)
-- Given a dependency library, estimates where Boost Build might have stored
-- its library files.
-- Clearly this is an insane hack, because a better solution would have to
-- solve for the multitude of possible configurations in a C++ project
-- and where they all might live.
local success, path = pcall(d.FindInstallPath, d);
if (success and path ~= nil) then
local pathText = path.AbsolutePathForceSlash;
-- local link_static = "Cpp/bin/msvc-9.0/debug/link-static"
local libDir = path:NewPathForceSlash('Cpp/bin/msvc-9.0/debug/threading-multi');
if (libDir.Exists) then
return libDir.AbsolutePath;
end
end
return nil;
end
| apache-2.0 |
zuzuf/TA3D | src/ta3d/mods/ta3d/scripts/corcrash.lua | 2 | 9119 | createUnitScript("corcrash")
__this:piece( "firept1", "firept2", "turret", "gunbase", "pelvis", "lleg", "rleg", "gun1",
"gun2", "ground")
local firept1 = __this.firept1
local firept2 = __this.firept2
local turret = __this.turret
local gunbase = __this.gunbase
local pelvis = __this.pelvis
local lleg = __this.lleg
local rleg = __this.rleg
local gun1 = __this.gun1
local gun2 = __this.gun2
local ground = __this.ground
__this.SMOKEPIECE1 = torso
#include "sfxtype.lh"
#include "exptype.lh"
#include "smokeunit.lh"
-- Signal definitions
local SIG_MOVE = 2
__this.walk = function(this)
while true do
this:move_piece_now(pelvis, y_axis, 0.0)
this:move_piece_now(lleg, y_axis, 0.0)
this:move_piece_now(lleg, z_axis, 0.875)
this:move_piece_now(rleg, y_axis, 0.0)
this:move_piece_now(rleg, z_axis, -0.8)
this:turn_piece_now(pelvis, x_axis, 6.0)
this:turn_piece_now(lleg, x_axis, -6.0)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.06)
this:move_piece_now(pelvis, y_axis, -0.25)
this:move_piece_now(lleg, y_axis, 0.25)
this:move_piece_now(rleg, y_axis, 0.25)
this:turn_piece_now(pelvis, x_axis, 4.917582)
this:turn_piece_now(lleg, x_axis, -4.917582)
this:turn_piece_now(rleg, x_axis, 1.049451)
this:sleep(0.03)
this:move_piece_now(pelvis, y_axis, -0.15)
this:move_piece_now(lleg, y_axis, 0.15)
this:move_piece_now(rleg, y_axis, 0.15)
this:turn_piece_now(pelvis, x_axis, 2.098901)
this:turn_piece_now(lleg, x_axis, -2.098901)
this:turn_piece_now(rleg, x_axis, 2.807692)
this:sleep(0.02)
this:move_piece_now(pelvis, y_axis, -0.05)
this:move_piece_now(lleg, y_axis, 0.05)
this:move_piece_now(rleg, y_axis, 0.05)
this:turn_piece_now(pelvis, x_axis, 1.049451)
this:turn_piece_now(lleg, x_axis, -1.038462)
this:turn_piece_now(rleg, x_axis, 3.159341)
this:sleep(0.01)
this:move_piece_now(pelvis, y_axis, 0.0)
this:move_piece_now(lleg, y_axis, 0.0)
this:move_piece_now(rleg, y_axis, 0.55)
this:move_piece_now(rleg, z_axis, -0.925)
this:turn_piece_now(pelvis, x_axis, 0.0)
this:turn_piece_now(lleg, x_axis, 0.0)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.06)
this:move_piece_now(lleg, z_axis, 0.5)
this:move_piece_now(rleg, z_axis, -0.175)
this:sleep(0.06)
this:move_piece_now(lleg, y_axis, 0.0)
this:move_piece_now(lleg, z_axis, 0.0)
this:move_piece_now(rleg, z_axis, 0.0)
this:turn_piece_now(pelvis, x_axis, 0.0)
this:turn_piece_now(lleg, x_axis, 0.0)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.06)
this:move_piece_now(lleg, z_axis, -0.3)
this:move_piece_now(rleg, z_axis, 0.425)
this:turn_piece_now(rleg, x_axis, -9.137363)
this:sleep(0.1)
this:move_piece_now(lleg, z_axis, -0.6)
this:move_piece_now(rleg, y_axis, 0.0)
this:turn_piece_now(pelvis, x_axis, 6.000000)
this:turn_piece_now(rleg, x_axis, -6.000000)
this:sleep(0.06)
this:move_piece_now(pelvis, y_axis, -0.244998)
this:move_piece_now(lleg, y_axis, 0.25)
this:move_piece_now(rleg, y_axis, 0.25)
this:turn_piece_now(pelvis, x_axis, 4.565934)
this:turn_piece_now(lleg, x_axis, 0.697802)
this:turn_piece_now(rleg, x_axis, -4.917582)
this:sleep(0.03)
this:move_piece_now(pelvis, y_axis, -0.1399995)
this:move_piece_now(lleg, y_axis, 0.15)
this:move_piece_now(rleg, y_axis, 0.15)
this:turn_piece_now(pelvis, x_axis, 2.098901)
this:turn_piece_now(lleg, x_axis, 2.807692)
this:turn_piece_now(rleg, x_axis, -2.098901)
this:sleep(0.02)
this:move_piece_now(pelvis, y_axis, -0.05)
this:move_piece_now(lleg, y_axis, 0.05)
this:move_piece_now(rleg, y_axis, 0.05)
this:turn_piece_now(pelvis, x_axis, 1.049451)
this:turn_piece_now(lleg, x_axis, 2.456044)
this:turn_piece_now(rleg, x_axis, -1.038462)
this:sleep(0.01)
this:move_piece_now(lleg, y_axis, 0.55)
this:move_piece_now(lleg, z_axis, -0.775)
this:move_piece_now(rleg, y_axis, 0.25)
this:turn_piece_now(pelvis, x_axis, 0.0)
this:turn_piece_now(lleg, x_axis, 0.0)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.06)
this:move_piece_now(lleg, z_axis, -0.35)
this:move_piece_now(rleg, z_axis, 0.1)
this:sleep(0.06)
this:move_piece_now(lleg, z_axis, 0.225)
this:move_piece_now(rleg, y_axis, 0.0)
this:move_piece_now(rleg, z_axis, -0.15)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.06)
this:move_piece_now(lleg, z_axis, 0.5)
this:move_piece_now(rleg, y_axis, 0.0)
this:move_piece_now(rleg, z_axis, -0.65)
this:turn_piece_now(lleg, x_axis, -10.192308)
this:turn_piece_now(rleg, x_axis, 0.0)
this:sleep(0.1)
end
end
__this.StartMoving = function(this)
this:signal(SIG_MOVE)
this:set_signal_mask(SIG_MOVE)
this:walk()
end
__this.StopMoving = function(this)
this:signal(SIG_MOVE)
this:set_signal_mask(SIG_MOVE)
end
__this.Create = function(this)
this.gun_3 = 0
this.restore_delay = 3.0
this.bAiming = false
this.restoreCount = 0
this:start_script( this.StopMoving, this )
this:start_script( this.SmokeUnit, this )
end
__this.SetMaxReloadTime = function(this, t)
this.restore_delay = t * 0.005
end
__this.SweetSpot = function(this)
return pelvis
end
__this.AimFromPrimary = function(this)
return turret
end
__this.QueryPrimary = function(this)
if this.gun_3 == 0 then
return firept1
end
if this.gun_3 == 1 then
return firept2
end
end
__this.RestoreAfterDelay = function(this)
this.restoreCount = this.restoreCount + 1
local ncall = this.restoreCount
this:sleep(this.restore_delay)
if ncall ~= this.restoreCount or this.bAiming then
return
end
this:turn(turret, y_axis, 0.0, 90.0)
this:turn(gunbase, x_axis, 0.0, 90.0)
end
__this.AimPrimary = function(this, heading, pitch)
this:set_script_value("AimPrimary", false)
heading = heading * TA2DEG
pitch = pitch * TA2DEG
this:turn(turret, y_axis, heading, 225.0)
this:turn(gunbase, x_axis, -pitch, 45.010989)
if this.bAiming then
return
end
this.bAiming = true
while this:is_turning(turret, y_axis) or this:is_turning(gunbase, x_axis) do
this:yield()
end
this.bAiming = false
this:start_script(this.RestoreAfterDelay, this)
this:set_script_value("AimPrimary", true)
end
__this.FirePrimary = function(this)
if this.gun_3 == 0 then
this.gun_3 = 1
this:move(gun1, z_axis, -0.75, 12.5)
this:wait_for_move(gun1, z_axis)
this:move(gun1, z_axis, 0.0, 1.5)
return
end
if this.gun_3 == 1 then
this.gun_3 = 0
this:move(gun2, z_axis, -0.75, 12.5)
this:wait_for_move(gun2, z_axis)
this:move(gun2, z_axis, 0.0, 1.5)
end
end
__this.Killed = function(this, severity)
if severity <= 25 then
this:explode(firept1, BITMAPONLY + BITMAP1)
this:explode(firept2, BITMAPONLY + BITMAP2)
this:explode(ground, BITMAPONLY + BITMAP3)
this:explode(gun1, BITMAPONLY + BITMAP4)
this:explode(gun2, BITMAPONLY + BITMAP5)
this:explode(gunbase, BITMAPONLY + BITMAP1)
this:explode(lleg, BITMAPONLY + BITMAP2)
this:explode(pelvis, BITMAPONLY + BITMAP3)
this:explode(rleg, BITMAPONLY + BITMAP4)
this:explode(turret, BITMAPONLY + BITMAP5)
return 1
end
if severity <= 50 then
this:explode(firept1, FALL + BITMAP1)
this:explode(firept2, FALL + BITMAP2)
this:explode(ground, FALL + BITMAP3)
this:explode(gun1, FALL + BITMAP4)
this:explode(gun2, FALL + BITMAP5)
this:explode(gunbase, BITMAPONLY + BITMAP1)
this:explode(lleg, FALL + BITMAP2)
this:explode(pelvis, BITMAPONLY + BITMAP3)
this:explode(rleg, FALL + BITMAP4)
this:explode(turret, BITMAPONLY + BITMAP5)
return 2
end
if severity <= 99 then
this:explode(firept1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP1)
this:explode(firept2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP2)
this:explode(ground, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP3)
this:explode(gun1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP4)
this:explode(gun2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP5)
this:explode(gunbase, BITMAPONLY + BITMAP1)
this:explode(lleg, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP2)
this:explode(pelvis, BITMAPONLY + BITMAP3)
this:explode(rleg, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP4)
this:explode(turret, BITMAPONLY + BITMAP5)
return 3
end
this:explode(firept1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP1)
this:explode(firept2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP2)
this:explode(ground, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP3)
this:explode(gun1, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP4)
this:explode(gun2, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP5)
this:explode(gunbase, SHATTER + EXPLODE_ON_HIT + BITMAP1)
this:explode(lleg, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP2)
this:explode(pelvis, BITMAPONLY + BITMAP3)
this:explode(rleg, FALL + SMOKE + FIRE + EXPLODE_ON_HIT + BITMAP4)
this:explode(turret, BITMAPONLY + BITMAP5)
return 3
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/effects/saber_dance.lua | 17 | 1745 | -----------------------------------
--
-- EFFECT_SABER_DANCE
--
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE);
if (saberDanceMerits>5) then
target:addMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5));
end
-- Does not stack with warrior Double Attack trait, so disable it
if(target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK
target:delMod(MOD_DOUBLE_ATTACK, 10);
end
target:addMod(MOD_DOUBLE_ATTACK,effect:getPower());
target:delStatusEffect(EFFECT_FAN_DANCE);
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
local power = effect:getPower();
local decayby = 0;
-- Double attack rate decays until 20% then stays there
if (power > 20) then
decayby = 3;
effect:setPower(power-decayby);
target:delMod(MOD_DOUBLE_ATTACK,decayby);
end
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local saberDanceMerits = target:getMerit(MERIT_SABER_DANCE);
if (saberDanceMerits>1) then
target:delMod(MOD_SAMBA_PDURATION, (saberDanceMerits -5));
end
if(target:hasTrait(15)) then --TRAIT_DOUBLE_ATTACK
-- put Double Attack trait back on.
target:addMod(MOD_DOUBLE_ATTACK, 10);
end
target:delMod(MOD_DOUBLE_ATTACK,effect:getPower());
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Bastok_Mines/npcs/Parraggoh.lua | 36 | 2331 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Parraggoh
-- Finishes Quest: Beauty and the Galka
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
BeautyAndTheGalka = player:getQuestStatus(BASTOK,BEAUTY_AND_THE_GALKA);
BeautyAndTheGalkaDenied = player:getVar("BeautyAndTheGalkaDenied");
PalboroughMinesLogs = player:hasKeyItem(2);
if (PalboroughMinesLogs == true) then
player:startEvent(0x000a);
elseif (BeautyAndTheGalka == QUEST_ACCEPTED) then
Message = math.random(0,1);
if (Message == 1) then
player:startEvent(0x0008);
else
player:startEvent(0x0009);
end
elseif (BeautyAndTheGalkaDenied == 1) then
player:startEvent(0x0007);
elseif (BeautyAndTheGalka == QUEST_COMPLETED) then
player:startEvent(0x000c);
else
player:startEvent(0x000b);
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 == 0x0007 and option == 0) then
player:addQuest(BASTOK,BEAUTY_AND_THE_GALKA);
elseif (csid == 0x000a) then
FreeSlots = player:getFreeSlotsCount();
if (FreeSlots >= 1) then
player:completeQuest(BASTOK,BEAUTY_AND_THE_GALKA);
player:setVar("BeautyAndTheGalkaDenied",0);
player:delKeyItem(PALBOROUGH_MINES_LOGS);
player:addFame(BASTOK,BAS_FAME*75);
player:addItem(16465);
player:messageSpecial(ITEM_OBTAINED,16465);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16465);
end
end
end;
| gpl-3.0 |
Mashape/kong | spec/02-integration/04-admin_api/04-plugins_routes_spec.lua | 1 | 10239 | local helpers = require "spec.helpers"
local admin_api = require "spec.fixtures.admin_api"
local utils = require "kong.tools.utils"
local cjson = require "cjson"
for _, strategy in helpers.each_strategy() do
describe("Admin API #" .. strategy, function()
local db
local client
lazy_setup(function()
_, db = helpers.get_db_utils(strategy, {
"services",
"routes",
"plugins",
}, {
"key-auth"
})
assert(helpers.start_kong({
database = strategy,
}))
end)
lazy_teardown(function()
helpers.stop_kong(nil, true)
end)
before_each(function()
client = helpers.admin_client()
end)
after_each(function()
if client then
client:close()
end
end)
describe("/plugins/enabled", function()
it("returns a list of enabled plugins on this node", function()
local res = assert(client:send {
method = "GET",
path = "/plugins/enabled",
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.is_table(json.enabled_plugins)
assert.True(#json.enabled_plugins > 0)
end)
end)
describe("/plugins", function()
local services = {}
local plugins = {}
lazy_setup(function()
for i = 1, 3 do
local service, err, err_t = db.services:insert {
name = "service-" .. i,
protocol = "http",
host = "127.0.0.1",
port = 15555,
}
assert.is_nil(err_t)
assert.is_nil(err)
db.routes:insert({
service = { id = service.id },
hosts = { "route_" .. tostring(i) .. ".test" }
})
services[i] = service
plugins[i] = assert(db.plugins:insert({
name = "key-auth",
service = { id = service.id },
config = {
key_names = { "testkey" },
}
}, { nulls = true }))
end
end)
describe("GET", function()
it("retrieves all plugins configured", function()
local res = assert(client:send {
method = "GET",
path = "/plugins"
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(3, #json.data)
end)
end)
it("returns 405 on invalid method", function()
local methods = {"DELETE", "PATCH"}
for i = 1, #methods do
local res = assert(client:send {
method = methods[i],
path = "/plugins",
body = {}, -- tmp: body to allow POST/PUT to work
headers = {["Content-Type"] = "application/json"}
})
local body = assert.response(res).has.status(405)
local json = cjson.decode(body)
assert.same({ message = "Method not allowed" }, json)
end
end)
describe("/plugins/{plugin}", function()
describe("GET", function()
it("retrieves a plugin by id", function()
local res = assert(client:send {
method = "GET",
path = "/plugins/" .. plugins[1].id
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.same(plugins[1], json)
end)
it("returns 404 if not found", function()
local res = assert(client:send {
method = "GET",
path = "/plugins/f4aecadc-05c7-11e6-8d41-1f3b3d5fa15c"
})
assert.res_status(404, res)
end)
end)
describe("PUT", function()
it("can create a plugin", function()
local service = admin_api.services:insert()
admin_api.routes:insert({
paths = { "/mypath" },
service = { id = service.id },
})
local res = assert(client:send {
method = "PUT",
path = "/plugins/" .. utils.uuid(),
body = {
name = "key-auth",
service = {
id = service.id,
}
},
headers = {["Content-Type"] = "application/json"}
})
assert.res_status(200, res)
end)
end)
describe("PATCH", function()
it("updates a plugin", function()
local res = assert(client:send {
method = "PATCH",
path = "/plugins/" .. plugins[1].id,
body = {enabled = false},
headers = {["Content-Type"] = "application/json"}
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.False(json.enabled)
local in_db = assert(db.plugins:select({ id = plugins[1].id }, { nulls = true }))
assert.same(json, in_db)
end)
it("updates a plugin bis", function()
local plugin = assert(db.plugins:select({ id = plugins[2].id }, { nulls = true }))
plugin.enabled = not plugin.enabled
plugin.created_at = nil
local res = assert(client:send {
method = "PATCH",
path = "/plugins/" .. plugin.id,
body = plugin,
headers = {["Content-Type"] = "application/json"}
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.equal(plugin.enabled, json.enabled)
end)
it("updates a plugin (removing foreign key reference)", function()
assert.equal(services[2].id, plugins[2].service.id)
local res = assert(client:send {
method = "PATCH",
path = "/plugins/" .. plugins[2].id,
body = {
service = cjson.null,
},
headers = { ["Content-Type"] = "application/json" }
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.same(ngx.null, json.service)
local in_db = assert(db.plugins:select({ id = plugins[2].id }, { nulls = true }))
assert.same(json, in_db)
end)
it("does not infer json input", function()
local res = assert(client:send {
method = "PATCH",
path = "/plugins/" .. plugins[2].id,
body = {
tags = cjson.null,
},
headers = { ["Content-Type"] = "application/json" }
})
assert.res_status(200, res)
end)
describe("errors", function()
it("handles invalid input", function()
local before = assert(db.plugins:select({ id = plugins[1].id }, { nulls = true }))
local res = assert(client:send {
method = "PATCH",
path = "/plugins/" .. plugins[1].id,
body = { foo = "bar" },
headers = {["Content-Type"] = "application/json"}
})
local body = cjson.decode(assert.res_status(400, res))
assert.same({
message = "schema violation (foo: unknown field)",
name = "schema violation",
fields = {
foo = "unknown field",
},
code = 2,
}, body)
local after = assert(db.plugins:select({ id = plugins[1].id }, { nulls = true }))
assert.same(before, after)
assert.same({"testkey"}, after.config.key_names)
end)
it("returns 404 if not found", function()
local res = assert(client:send {
method = "PATCH",
path = "/plugins/f4aecadc-05c7-11e6-8d41-1f3b3d5fa15c",
body = {enabled = false},
headers = {["Content-Type"] = "application/json"}
})
assert.res_status(404, res)
end)
end)
end)
describe("DELETE", function()
it("deletes by id", function()
local res = assert(client:send {
method = "DELETE",
path = "/plugins/" .. plugins[3].id
})
assert.res_status(204, res)
end)
describe("errors", function()
it("returns 204 if not found", function()
local res = assert(client:send {
method = "DELETE",
path = "/plugins/f4aecadc-05c7-11e6-8d41-1f3b3d5fa15c"
})
assert.res_status(204, res)
end)
end)
end)
end)
end)
describe("/plugins/schema/{plugin}", function()
describe("GET", function()
it("returns the schema of all bundled plugins", function()
for plugin, _ in pairs(helpers.test_conf.loaded_plugins) do
local res = assert(client:send {
method = "GET",
path = "/plugins/schema/" .. plugin,
})
local body = assert.res_status(200, res)
local json = cjson.decode(body)
assert.is_table(json.fields)
end
end)
it("returns nested records and empty array defaults as arrays", function()
local res = assert(client:send {
method = "GET",
path = "/plugins/schema/request-transformer",
})
local body = assert.res_status(200, res)
assert.match('{"fields":[{', body, 1, true)
assert.not_match('"fields":{', body, 1, true)
assert.match('"default":[]', body, 1, true)
assert.not_match('"default":{}', body, 1, true)
end)
it("returns 404 on invalid plugin", function()
local res = assert(client:send {
method = "GET",
path = "/plugins/schema/foobar",
})
local body = assert.res_status(404, res)
local json = cjson.decode(body)
assert.same({ message = "No plugin named 'foobar'" }, json)
end)
end)
end)
end)
end
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Ranguemont_Pass/npcs/Perchond.lua | 19 | 1576 | -----------------------------------
-- Area: Ranguemont Pass
-- NPC: Perchond
-- @pos -182.844 4 -164.948 166
-----------------------------------
package.loaded["scripts/zones/Ranguemont_Pass/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (SinHunting == 2) then
player:startEvent(0x0005);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SinHunting = player:getVar("sinHunting"); -- RNG AF1
if (SinHunting == 1) then
player:startEvent(0x0003, 0, 1107);
else
player:startEvent(0x0002);
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 == 3) then
player:setVar("sinHunting",2);
elseif(csid == 5) then
player:tradeComplete();
player:addKeyItem(PERCHONDS_ENVELOPE);
player:messageSpecial(KEYITEM_OBTAINED,PERCHONDS_ENVELOPE);
player:setVar("sinHunting",3);
end
end;
| gpl-3.0 |
abasshacker/extreme | bot/utils.lua | 494 | 23873 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
local user_info = redis:hgetall('user:'..v)
if user_info and user_info.print_name then
text = text..k.." - "..string.gsub(user_info.print_name, "_", " ").." ["..v.."]\n"
else
text = text..k.." - "..v.."\n"
end
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
vonflynee/opencomputersserver | world/opencomputers/4f2775bd-9dcb-42e6-8318-1837ede27e76/lib/term.lua | 15 | 12816 | local component = require("component")
local computer = require("computer")
local event = require("event")
local keyboard = require("keyboard")
local text = require("text")
local unicode = require("unicode")
local term = {}
local cursorX, cursorY = 1, 1
local cursorBlink = nil
local function toggleBlink()
if term.isAvailable() then
cursorBlink.state = not cursorBlink.state
if cursorBlink.state then
cursorBlink.alt = component.gpu.get(cursorX, cursorY) or cursorBlink.alt
component.gpu.set(cursorX, cursorY, string.rep(unicode.char(0x2588), unicode.charWidth(cursorBlink.alt))) -- solid block
else
component.gpu.set(cursorX, cursorY, cursorBlink.alt)
end
end
end
-------------------------------------------------------------------------------
function term.clear()
if term.isAvailable() then
local w, h = component.gpu.getResolution()
component.gpu.fill(1, 1, w, h, " ")
end
cursorX, cursorY = 1, 1
end
function term.clearLine()
if term.isAvailable() then
local w = component.gpu.getResolution()
component.gpu.fill(1, cursorY, w, 1, " ")
end
cursorX = 1
end
function term.getCursor()
return cursorX, cursorY
end
function term.setCursor(col, row)
checkArg(1, col, "number")
checkArg(2, row, "number")
if cursorBlink and cursorBlink.state then
toggleBlink()
end
local wide, right = term.isWide(cursorX, cursorY)
if wide and right then
cursorX = cursorX - 1
end
cursorX = math.floor(col)
cursorY = math.floor(row)
end
function term.getCursorBlink()
return cursorBlink ~= nil
end
function term.setCursorBlink(enabled)
checkArg(1, enabled, "boolean")
if enabled then
if not cursorBlink then
cursorBlink = {}
cursorBlink.id = event.timer(0.5, toggleBlink, math.huge)
cursorBlink.state = false
elseif not cursorBlink.state then
toggleBlink()
end
elseif cursorBlink then
event.cancel(cursorBlink.id)
if cursorBlink.state then
toggleBlink()
end
cursorBlink = nil
end
end
function term.isWide(x, y)
if not term.isAvailable() then
return false
end
local w, h = component.gpu.getResolution()
if x < 1 or x > w or y < 1 or y > h then
return false
end
local char = component.gpu.get(x, y)
if unicode.isWide(char) then
-- The char at the specified position is a wide char.
return true
end
if char == " " and x > 1 then
local charLeft = component.gpu.get(x - 1, y)
if charLeft and unicode.isWide(charLeft) then
-- The char left to the specified position is a wide char.
return true, true
end
end
-- Not a wide char.
return false
end
function term.isAvailable()
if component.isAvailable("gpu") and component.isAvailable("screen") then
-- Ensure our primary GPU is bound to our primary screen.
if component.gpu.getScreen() ~= component.screen.address then
component.gpu.bind(component.screen.address)
end
return true
end
return false
end
function term.read(history, dobreak, hint, pwchar, filter)
checkArg(1, history, "table", "nil")
checkArg(3, hint, "function", "table", "nil")
checkArg(4, pwchar, "string", "nil")
checkArg(5, filter, "string", "function", "nil")
history = history or {}
table.insert(history, "")
local offset = term.getCursor() - 1
local scrollX, scrollY = 0, #history - 1
local cursorX = 1
if type(hint) == "table" then
local hintTable = hint
hint = function()
return hintTable
end
end
local hintCache, hintIndex
if pwchar and unicode.len(pwchar) > 0 then
pwchar = unicode.sub(pwchar, 1, 1)
end
if type(filter) == "string" then
local pattern = filter
filter = function(line)
return line:match(pattern)
end
end
local function masktext(str)
return pwchar and pwchar:rep(unicode.len(str)) or str
end
local function getCursor()
return cursorX, 1 + scrollY
end
local function line()
local _, cby = getCursor()
return history[cby]
end
local function clearHint()
hintCache = nil
end
local function setCursor(nbx, nby)
local w, h = component.gpu.getResolution()
local cx, cy = term.getCursor()
scrollY = nby - 1
nbx = math.max(1, math.min(unicode.len(history[nby]) + 1, nbx))
local ncx = nbx + offset - scrollX
if ncx > w then
local sx = nbx - (w - offset)
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + offset + dx, cy, w - offset - dx, 1, -dx, 0)
local str = masktext(unicode.sub(history[nby], nbx - (dx - 1), nbx))
str = text.padRight(str, dx)
component.gpu.set(1 + math.max(offset, w - dx), cy, unicode.sub(str, 1 + math.max(0, dx - (w - offset))))
elseif ncx < 1 + offset then
local sx = nbx - 1
local dx = math.abs(scrollX - sx)
scrollX = sx
component.gpu.copy(1 + offset, cy, w - offset - dx, 1, dx, 0)
local str = masktext(unicode.sub(history[nby], nbx, nbx + dx))
--str = text.padRight(str, dx)
component.gpu.set(1 + offset, cy, str)
end
cursorX = nbx
term.setCursor(nbx - scrollX + offset, cy)
clearHint()
end
local function copyIfNecessary()
local cbx, cby = getCursor()
if cby ~= #history then
history[#history] = line()
setCursor(cbx, #history)
end
end
local function redraw()
local cx, cy = term.getCursor()
local bx, by = 1 + scrollX, 1 + scrollY
local w, h = component.gpu.getResolution()
local l = w - offset
local str = masktext(unicode.sub(history[by], bx, bx + l))
str = text.padRight(str, l)
component.gpu.set(1 + offset, cy, str)
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
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(math.min(be, cbx + n), cby)
end
end
local function up()
local cbx, cby = getCursor()
if cby > 1 then
setCursor(1, cby - 1)
redraw()
ende()
end
end
local function down()
local cbx, cby = getCursor()
if cby < #history then
setCursor(1, cby + 1)
redraw()
ende()
end
end
local function delete()
copyIfNecessary()
clearHint()
local cbx, cby = getCursor()
if cbx <= unicode.len(line()) then
local cw = unicode.charWidth(unicode.sub(line(), cbx))
history[cby] = unicode.sub(line(), 1, cbx - 1) ..
unicode.sub(line(), cbx + 1)
local cx, cy = term.getCursor()
local w, h = component.gpu.getResolution()
component.gpu.copy(cx + cw, cy, w - cx, 1, -cw, 0)
local br = cbx + (w - cx)
local char = masktext(unicode.sub(line(), br, br))
if not char or unicode.wlen(char) == 0 then
char = " "
end
component.gpu.set(w, cy, char)
end
end
local function insert(value)
copyIfNecessary()
clearHint()
local cx, cy = term.getCursor()
local cbx, cby = getCursor()
local w, h = component.gpu.getResolution()
history[cby] = unicode.sub(line(), 1, cbx - 1) ..
value ..
unicode.sub(line(), cbx)
local len = unicode.wlen(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, masktext(value))
right(unicode.len(value))
end
local function tab(direction)
local cbx, cby = getCursor()
if not hintCache then -- hint is never nil, see onKeyDown
hintCache = hint(line(), cbx)
hintIndex = 0
if type(hintCache) == "string" then
hintCache = {hintCache}
end
if type(hintCache) ~= "table" or #hintCache < 1 then
hintCache = nil -- invalid hint
end
end
if hintCache then
hintIndex = (hintIndex + direction + #hintCache - 1) % #hintCache + 1
history[cby] = tostring(hintCache[hintIndex])
-- because all other cases of the cursor being moved will result
-- in the hint cache getting invalidated we do that in setCursor,
-- so we have to back it up here to restore it after moving.
local savedCache = hintCache
redraw()
ende()
if #savedCache > 1 then -- stop if only one hint exists.
hintCache = savedCache
end
end
end
local function onKeyDown(char, code)
term.setCursorBlink(false)
if code == keyboard.keys.back then
if left() then delete() end
elseif code == keyboard.keys.delete then
delete()
elseif code == keyboard.keys.left then
left()
elseif code == keyboard.keys.right then
right()
elseif code == keyboard.keys.home then
home()
elseif code == keyboard.keys["end"] then
ende()
elseif code == keyboard.keys.up then
up()
elseif code == keyboard.keys.down then
down()
elseif code == keyboard.keys.tab and hint then
tab(keyboard.isShiftDown() and -1 or 1)
elseif code == keyboard.keys.enter then
if not filter or filter(line() or "") then
local cbx, cby = getCursor()
if cby ~= #history then -- bring entry to front
history[#history] = line()
table.remove(history, cby)
end
return true, history[#history] .. "\n"
else
computer.beep(2000, 0.1)
end
elseif keyboard.isControlDown() and code == keyboard.keys.d then
if line() == "" then
history[#history] = ""
return true, nil
end
elseif not keyboard.isControl(char) then
insert(unicode.char(char))
end
term.setCursorBlink(true)
term.setCursorBlink(true) -- force toggle to caret
end
local function onClipboard(value)
copyIfNecessary()
term.setCursorBlink(false)
local cbx, cby = getCursor()
local l = value:find("\n", 1, true)
if l then
history[cby] = unicode.sub(line(), 1, cbx - 1)
redraw()
insert(unicode.sub(value, 1, l - 1))
return true, line() .. "\n"
else
insert(value)
term.setCursorBlink(true)
term.setCursorBlink(true) -- force toggle to caret
end
end
local function cleanup()
if history[#history] == "" then
table.remove(history)
end
term.setCursorBlink(false)
if term.getCursor() > 1 and dobreak ~= false then
term.write("\n")
end
end
term.setCursorBlink(true)
while term.isAvailable() do
local ocx, ocy = getCursor()
local ok, name, address, charOrValue, code = pcall(event.pull)
if not ok then
cleanup()
error("interrupted", 0)
end
if name == "interrupted" then
cleanup()
return nil
end
local ncx, ncy = getCursor()
if ocx ~= ncx or ocy ~= ncy then
cleanup()
return "" -- soft fail the read if someone messes with the term
end
if term.isAvailable() and -- may have changed since pull
type(address) == "string" and
component.isPrimary(address)
then
local done, result
if name == "key_down" then
done, result = onKeyDown(charOrValue, code)
elseif name == "clipboard" then
done, result = onClipboard(charOrValue)
end
if done then
cleanup()
return result
end
end
end
cleanup()
return nil -- fail the read if term becomes unavailable
end
function term.write(value, wrap)
if not term.isAvailable() then
return
end
value = text.detab(tostring(value))
if unicode.wlen(value) == 0 then
return
end
do
local noBell = value:gsub("\a", "")
if #noBell ~= #value then
value = noBell
computer.beep()
end
end
local w, h = component.gpu.getResolution()
if not w then
return -- gpu lost its screen but the signal wasn't processed yet.
end
local blink = term.getCursorBlink()
term.setCursorBlink(false)
local line, nl
repeat
local wrapAfter, margin = math.huge, math.huge
if wrap then
wrapAfter, margin = w - (cursorX - 1), w
end
line, value, nl = text.wrap(value, wrapAfter, margin)
component.gpu.set(cursorX, cursorY, line)
cursorX = cursorX + unicode.wlen(line)
if nl or (cursorX > w and wrap) then
cursorX = 1
cursorY = cursorY + 1
end
if cursorY > h then
component.gpu.copy(1, 1, w, h, 0, -1)
component.gpu.fill(1, h, w, 1, " ")
cursorY = h
end
until not value
term.setCursorBlink(blink)
end
-------------------------------------------------------------------------------
return term
| mit |
ruisebastiao/nodemcu-firmware | lua_examples/webap_toggle_pin.lua | 70 | 1202 | wifi.setmode(wifi.SOFTAP);
wifi.ap.config({ssid="test",pwd="12345678"});
gpio.mode(1, gpio.OUTPUT)
srv=net.createServer(net.TCP)
srv:listen(80,function(conn)
conn:on("receive", function(client,request)
local buf = "";
local _, _, method, path, vars = string.find(request, "([A-Z]+) (.+)?(.+) HTTP");
if(method == nil)then
_, _, method, path = string.find(request, "([A-Z]+) (.+) HTTP");
end
local _GET = {}
if (vars ~= nil)then
for k, v in string.gmatch(vars, "(%w+)=(%w+)&*") do
_GET[k] = v
end
end
buf = buf.."<h1> Hello, NodeMcu.</h1><form src=\"/\">Turn PIN1 <select name=\"pin\" onchange=\"form.submit()\">";
local _on,_off = "",""
if(_GET.pin == "ON")then
_on = " selected=true";
gpio.write(1, gpio.HIGH);
elseif(_GET.pin == "OFF")then
_off = " selected=\"true\"";
gpio.write(1, gpio.LOW);
end
buf = buf.."<option".._on..">ON</opton><option".._off..">OFF</option></select></form>";
client:send(buf);
client:close();
collectgarbage();
end)
end)
| mit |
PUMpITapp/instantpizza | src/qrencode.lua | 2 | 56594 | --- The qrcode library is licensed under the 3-clause BSD license (aka "new BSD")
--- To get in contact with the author, mail to <gundlach@speedata.de>.
---
--- Please report bugs on the [github project page](http://speedata.github.com/luaqrcode/).
-- Copyright (c) 2012, Patrick Gundlach
-- All rights reserved.
--
-- Redistribution and use in source and binary forms, with or without
-- modification, are permitted provided that the following conditions are met:
-- * Redistributions of source code must retain the above copyright
-- notice, this list of conditions and the following disclaimer.
-- * Redistributions in binary form must reproduce the above copyright
-- notice, this list of conditions and the following disclaimer in the
-- documentation and/or other materials provided with the distribution.
-- * Neither the name of the <organization> nor the
-- names of its contributors may be used to endorse or promote products
-- derived from this software without specific prior written permission.
--
-- THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
-- ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
-- WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-- DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY
-- DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
-- (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
-- LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
-- ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
-- (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
-- SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
--- Overall workflow
--- ================
--- The steps to generate the qrcode, assuming we already have the codeword:
---
--- 1. Determine version, ec level and mode (=encoding) for codeword
--- 1. Encode data
--- 1. Arrange data and calculate error correction code
--- 1. Generate 8 matrices with different masks and calculate the penalty
--- 1. Return qrcode with least penalty
---
--- Each step is of course more or less complex and needs further description
--- Helper functions
--- ================
---
--- We start with some helper functions
-- To calculate xor we need to do that bitwise. This helper table speeds up the num-to-bit
-- part a bit (no pun intended)
local cclxvi = {[0] = {0,0,0,0,0,0,0,0}, {1,0,0,0,0,0,0,0}, {0,1,0,0,0,0,0,0}, {1,1,0,0,0,0,0,0},
{0,0,1,0,0,0,0,0}, {1,0,1,0,0,0,0,0}, {0,1,1,0,0,0,0,0}, {1,1,1,0,0,0,0,0},
{0,0,0,1,0,0,0,0}, {1,0,0,1,0,0,0,0}, {0,1,0,1,0,0,0,0}, {1,1,0,1,0,0,0,0},
{0,0,1,1,0,0,0,0}, {1,0,1,1,0,0,0,0}, {0,1,1,1,0,0,0,0}, {1,1,1,1,0,0,0,0},
{0,0,0,0,1,0,0,0}, {1,0,0,0,1,0,0,0}, {0,1,0,0,1,0,0,0}, {1,1,0,0,1,0,0,0},
{0,0,1,0,1,0,0,0}, {1,0,1,0,1,0,0,0}, {0,1,1,0,1,0,0,0}, {1,1,1,0,1,0,0,0},
{0,0,0,1,1,0,0,0}, {1,0,0,1,1,0,0,0}, {0,1,0,1,1,0,0,0}, {1,1,0,1,1,0,0,0},
{0,0,1,1,1,0,0,0}, {1,0,1,1,1,0,0,0}, {0,1,1,1,1,0,0,0}, {1,1,1,1,1,0,0,0},
{0,0,0,0,0,1,0,0}, {1,0,0,0,0,1,0,0}, {0,1,0,0,0,1,0,0}, {1,1,0,0,0,1,0,0},
{0,0,1,0,0,1,0,0}, {1,0,1,0,0,1,0,0}, {0,1,1,0,0,1,0,0}, {1,1,1,0,0,1,0,0},
{0,0,0,1,0,1,0,0}, {1,0,0,1,0,1,0,0}, {0,1,0,1,0,1,0,0}, {1,1,0,1,0,1,0,0},
{0,0,1,1,0,1,0,0}, {1,0,1,1,0,1,0,0}, {0,1,1,1,0,1,0,0}, {1,1,1,1,0,1,0,0},
{0,0,0,0,1,1,0,0}, {1,0,0,0,1,1,0,0}, {0,1,0,0,1,1,0,0}, {1,1,0,0,1,1,0,0},
{0,0,1,0,1,1,0,0}, {1,0,1,0,1,1,0,0}, {0,1,1,0,1,1,0,0}, {1,1,1,0,1,1,0,0},
{0,0,0,1,1,1,0,0}, {1,0,0,1,1,1,0,0}, {0,1,0,1,1,1,0,0}, {1,1,0,1,1,1,0,0},
{0,0,1,1,1,1,0,0}, {1,0,1,1,1,1,0,0}, {0,1,1,1,1,1,0,0}, {1,1,1,1,1,1,0,0},
{0,0,0,0,0,0,1,0}, {1,0,0,0,0,0,1,0}, {0,1,0,0,0,0,1,0}, {1,1,0,0,0,0,1,0},
{0,0,1,0,0,0,1,0}, {1,0,1,0,0,0,1,0}, {0,1,1,0,0,0,1,0}, {1,1,1,0,0,0,1,0},
{0,0,0,1,0,0,1,0}, {1,0,0,1,0,0,1,0}, {0,1,0,1,0,0,1,0}, {1,1,0,1,0,0,1,0},
{0,0,1,1,0,0,1,0}, {1,0,1,1,0,0,1,0}, {0,1,1,1,0,0,1,0}, {1,1,1,1,0,0,1,0},
{0,0,0,0,1,0,1,0}, {1,0,0,0,1,0,1,0}, {0,1,0,0,1,0,1,0}, {1,1,0,0,1,0,1,0},
{0,0,1,0,1,0,1,0}, {1,0,1,0,1,0,1,0}, {0,1,1,0,1,0,1,0}, {1,1,1,0,1,0,1,0},
{0,0,0,1,1,0,1,0}, {1,0,0,1,1,0,1,0}, {0,1,0,1,1,0,1,0}, {1,1,0,1,1,0,1,0},
{0,0,1,1,1,0,1,0}, {1,0,1,1,1,0,1,0}, {0,1,1,1,1,0,1,0}, {1,1,1,1,1,0,1,0},
{0,0,0,0,0,1,1,0}, {1,0,0,0,0,1,1,0}, {0,1,0,0,0,1,1,0}, {1,1,0,0,0,1,1,0},
{0,0,1,0,0,1,1,0}, {1,0,1,0,0,1,1,0}, {0,1,1,0,0,1,1,0}, {1,1,1,0,0,1,1,0},
{0,0,0,1,0,1,1,0}, {1,0,0,1,0,1,1,0}, {0,1,0,1,0,1,1,0}, {1,1,0,1,0,1,1,0},
{0,0,1,1,0,1,1,0}, {1,0,1,1,0,1,1,0}, {0,1,1,1,0,1,1,0}, {1,1,1,1,0,1,1,0},
{0,0,0,0,1,1,1,0}, {1,0,0,0,1,1,1,0}, {0,1,0,0,1,1,1,0}, {1,1,0,0,1,1,1,0},
{0,0,1,0,1,1,1,0}, {1,0,1,0,1,1,1,0}, {0,1,1,0,1,1,1,0}, {1,1,1,0,1,1,1,0},
{0,0,0,1,1,1,1,0}, {1,0,0,1,1,1,1,0}, {0,1,0,1,1,1,1,0}, {1,1,0,1,1,1,1,0},
{0,0,1,1,1,1,1,0}, {1,0,1,1,1,1,1,0}, {0,1,1,1,1,1,1,0}, {1,1,1,1,1,1,1,0},
{0,0,0,0,0,0,0,1}, {1,0,0,0,0,0,0,1}, {0,1,0,0,0,0,0,1}, {1,1,0,0,0,0,0,1},
{0,0,1,0,0,0,0,1}, {1,0,1,0,0,0,0,1}, {0,1,1,0,0,0,0,1}, {1,1,1,0,0,0,0,1},
{0,0,0,1,0,0,0,1}, {1,0,0,1,0,0,0,1}, {0,1,0,1,0,0,0,1}, {1,1,0,1,0,0,0,1},
{0,0,1,1,0,0,0,1}, {1,0,1,1,0,0,0,1}, {0,1,1,1,0,0,0,1}, {1,1,1,1,0,0,0,1},
{0,0,0,0,1,0,0,1}, {1,0,0,0,1,0,0,1}, {0,1,0,0,1,0,0,1}, {1,1,0,0,1,0,0,1},
{0,0,1,0,1,0,0,1}, {1,0,1,0,1,0,0,1}, {0,1,1,0,1,0,0,1}, {1,1,1,0,1,0,0,1},
{0,0,0,1,1,0,0,1}, {1,0,0,1,1,0,0,1}, {0,1,0,1,1,0,0,1}, {1,1,0,1,1,0,0,1},
{0,0,1,1,1,0,0,1}, {1,0,1,1,1,0,0,1}, {0,1,1,1,1,0,0,1}, {1,1,1,1,1,0,0,1},
{0,0,0,0,0,1,0,1}, {1,0,0,0,0,1,0,1}, {0,1,0,0,0,1,0,1}, {1,1,0,0,0,1,0,1},
{0,0,1,0,0,1,0,1}, {1,0,1,0,0,1,0,1}, {0,1,1,0,0,1,0,1}, {1,1,1,0,0,1,0,1},
{0,0,0,1,0,1,0,1}, {1,0,0,1,0,1,0,1}, {0,1,0,1,0,1,0,1}, {1,1,0,1,0,1,0,1},
{0,0,1,1,0,1,0,1}, {1,0,1,1,0,1,0,1}, {0,1,1,1,0,1,0,1}, {1,1,1,1,0,1,0,1},
{0,0,0,0,1,1,0,1}, {1,0,0,0,1,1,0,1}, {0,1,0,0,1,1,0,1}, {1,1,0,0,1,1,0,1},
{0,0,1,0,1,1,0,1}, {1,0,1,0,1,1,0,1}, {0,1,1,0,1,1,0,1}, {1,1,1,0,1,1,0,1},
{0,0,0,1,1,1,0,1}, {1,0,0,1,1,1,0,1}, {0,1,0,1,1,1,0,1}, {1,1,0,1,1,1,0,1},
{0,0,1,1,1,1,0,1}, {1,0,1,1,1,1,0,1}, {0,1,1,1,1,1,0,1}, {1,1,1,1,1,1,0,1},
{0,0,0,0,0,0,1,1}, {1,0,0,0,0,0,1,1}, {0,1,0,0,0,0,1,1}, {1,1,0,0,0,0,1,1},
{0,0,1,0,0,0,1,1}, {1,0,1,0,0,0,1,1}, {0,1,1,0,0,0,1,1}, {1,1,1,0,0,0,1,1},
{0,0,0,1,0,0,1,1}, {1,0,0,1,0,0,1,1}, {0,1,0,1,0,0,1,1}, {1,1,0,1,0,0,1,1},
{0,0,1,1,0,0,1,1}, {1,0,1,1,0,0,1,1}, {0,1,1,1,0,0,1,1}, {1,1,1,1,0,0,1,1},
{0,0,0,0,1,0,1,1}, {1,0,0,0,1,0,1,1}, {0,1,0,0,1,0,1,1}, {1,1,0,0,1,0,1,1},
{0,0,1,0,1,0,1,1}, {1,0,1,0,1,0,1,1}, {0,1,1,0,1,0,1,1}, {1,1,1,0,1,0,1,1},
{0,0,0,1,1,0,1,1}, {1,0,0,1,1,0,1,1}, {0,1,0,1,1,0,1,1}, {1,1,0,1,1,0,1,1},
{0,0,1,1,1,0,1,1}, {1,0,1,1,1,0,1,1}, {0,1,1,1,1,0,1,1}, {1,1,1,1,1,0,1,1},
{0,0,0,0,0,1,1,1}, {1,0,0,0,0,1,1,1}, {0,1,0,0,0,1,1,1}, {1,1,0,0,0,1,1,1},
{0,0,1,0,0,1,1,1}, {1,0,1,0,0,1,1,1}, {0,1,1,0,0,1,1,1}, {1,1,1,0,0,1,1,1},
{0,0,0,1,0,1,1,1}, {1,0,0,1,0,1,1,1}, {0,1,0,1,0,1,1,1}, {1,1,0,1,0,1,1,1},
{0,0,1,1,0,1,1,1}, {1,0,1,1,0,1,1,1}, {0,1,1,1,0,1,1,1}, {1,1,1,1,0,1,1,1},
{0,0,0,0,1,1,1,1}, {1,0,0,0,1,1,1,1}, {0,1,0,0,1,1,1,1}, {1,1,0,0,1,1,1,1},
{0,0,1,0,1,1,1,1}, {1,0,1,0,1,1,1,1}, {0,1,1,0,1,1,1,1}, {1,1,1,0,1,1,1,1},
{0,0,0,1,1,1,1,1}, {1,0,0,1,1,1,1,1}, {0,1,0,1,1,1,1,1}, {1,1,0,1,1,1,1,1},
{0,0,1,1,1,1,1,1}, {1,0,1,1,1,1,1,1}, {0,1,1,1,1,1,1,1}, {1,1,1,1,1,1,1,1}}
-- Return a number that is the result of interpreting the table tbl (msb first)
local function tbl_to_number(tbl)
local n = #tbl
local rslt = 0
local power = 1
for i = 1, n do
rslt = rslt + tbl[i]*power
power = power*2
end
return rslt
end
-- Calculate bitwise xor of bytes m and n. 0 <= m,n <= 256.
local function bit_xor(m, n)
local tbl_m = cclxvi[m]
local tbl_n = cclxvi[n]
local tbl = {}
for i = 1, 8 do
if(tbl_m[i] ~= tbl_n[i]) then
tbl[i] = 1
else
tbl[i] = 0
end
end
return tbl_to_number(tbl)
end
-- Return the binary representation of the number x with the width of `digits`.
local function binary(x,digits)
local s=string.format("%o",x)
local a={["0"]="000",["1"]="001", ["2"]="010",["3"]="011",
["4"]="100",["5"]="101", ["6"]="110",["7"]="111"}
s=string.gsub(s,"(.)",function (d) return a[d] end)
-- remove leading 0s
s = string.gsub(s,"^0*(.*)$","%1")
local fmtstring = string.format("%%%ds",digits)
local ret = string.format(fmtstring,s)
return string.gsub(ret," ","0")
end
-- A small helper function for add_typeinfo_to_matrix() and add_version_information()
-- Add a 2 (black by default) / -2 (blank by default) to the matrix at position x,y
-- depending on the bitstring (size 1!) where "0"=blank and "1"=black.
local function fill_matrix_position(matrix,bitstring,x,y)
if bitstring == "1" then
matrix[x][y] = 2
else
matrix[x][y] = -2
end
end
--- Step 1: Determine version, ec level and mode for codeword
--- ========================================================
---
--- First we need to find out the version (= size) of the QR code. This depends on
--- the input data (the mode to be used), the requested error correction level
--- (normally we use the maximum level that fits into the minimal size).
-- Return the mode for the given string `str`.
-- See table 2 of the spec. We only support mode 1, 2 and 4.
-- That is: numeric, alaphnumeric and binary.
local function get_mode( str )
local mode
if string.match(str,"^[0-9]+$") then
return 1
elseif string.match(str,"^[0-9A-Z $%%*./:+-]+$") then
return 2
else
return 4
end
assert(false,"never reached")
return nil
end
--- Capacity of QR codes
--- --------------------
--- The capacity is calculated as follow: \\(\text{Number of data bits} = \text{number of codewords} * 8\\).
--- The number of data bits is now reduced by 4 (the mode indicator) and the length string,
--- that varies between 8 and 16, depending on the version and the mode (see method `get_length()`). The
--- remaining capacity is multiplied by the amount of data per bit string (numeric: 3, alphanumeric: 2, other: 1)
--- and divided by the length of the bit string (numeric: 10, alphanumeric: 11, binary: 8, kanji: 13).
--- Then the floor function is applied to the result:
--- $$\Big\lfloor \frac{( \text{#data bits} - 4 - \text{length string}) * \text{data per bit string}}{\text{length of the bit string}} \Big\rfloor$$
---
--- There is one problem remaining. The length string depends on the version,
--- and the version depends on the length string. But we take this into account when calculating the
--- the capacity, so this is not really a problem here.
-- The capacity (number of codewords) of each version (1-40) for error correction levels 1-4 (LMQH).
-- The higher the ec level, the lower the capacity of the version. Taken from spec, tables 7-11.
local capacity = {
{ 19, 16, 13, 9},{ 34, 28, 22, 16},{ 55, 44, 34, 26},{ 80, 64, 48, 36},
{ 108, 86, 62, 46},{ 136, 108, 76, 60},{ 156, 124, 88, 66},{ 194, 154, 110, 86},
{ 232, 182, 132, 100},{ 274, 216, 154, 122},{ 324, 254, 180, 140},{ 370, 290, 206, 158},
{ 428, 334, 244, 180},{ 461, 365, 261, 197},{ 523, 415, 295, 223},{ 589, 453, 325, 253},
{ 647, 507, 367, 283},{ 721, 563, 397, 313},{ 795, 627, 445, 341},{ 861, 669, 485, 385},
{ 932, 714, 512, 406},{1006, 782, 568, 442},{1094, 860, 614, 464},{1174, 914, 664, 514},
{1276, 1000, 718, 538},{1370, 1062, 754, 596},{1468, 1128, 808, 628},{1531, 1193, 871, 661},
{1631, 1267, 911, 701},{1735, 1373, 985, 745},{1843, 1455, 1033, 793},{1955, 1541, 1115, 845},
{2071, 1631, 1171, 901},{2191, 1725, 1231, 961},{2306, 1812, 1286, 986},{2434, 1914, 1354, 1054},
{2566, 1992, 1426, 1096},{2702, 2102, 1502, 1142},{2812, 2216, 1582, 1222},{2956, 2334, 1666, 1276}}
--- Return the smallest version for this codeword. If `requested_ec_level` is supplied,
--- then the ec level (LMQH - 1,2,3,4) must be at least the requested level.
-- mode = 1,2,4,8
local function get_version_eclevel(len,mode,requested_ec_level)
local local_mode = mode
if mode == 4 then
local_mode = 3
elseif mode == 8 then
local_mode = 4
end
assert( local_mode <= 4 )
local bytes, bits, digits, modebits, c
local tab = { {10,9,8,8},{12,11,16,10},{14,13,16,12} }
local minversion = 40
local maxec_level = 1
for ec_level=1,4 do
if requested_ec_level == nil or ec_level >= requested_ec_level then
for version=1,#capacity do
bits = capacity[version][ec_level] * 8
bits = bits - 4 -- the mode indicator
if version < 10 then
digits = tab[1][local_mode]
elseif version < 27 then
digits = tab[2][local_mode]
elseif version <= 40 then
digits = tab[3][local_mode]
end
modebits = bits - digits
if local_mode == 1 then -- numeric
c = math.floor(modebits * 3 / 10)
elseif local_mode == 2 then -- alphanumeric
c = math.floor(modebits * 2 / 11)
elseif local_mode == 3 then -- binary
c = math.floor(modebits * 1 / 8)
else
c = math.floor(modebits * 1 / 13)
end
if c >= len then
if version <= minversion then
minversion = version
maxec_level = ec_level
end
break
end
end
end
end
return minversion, maxec_level
end
-- Return a bit string of 0s and 1s that includes the length of the code string.
-- The modes are numeric = 1, alphanumeric = 2, binary = 4, and japanese = 8
local function get_length(str,version,mode)
local i = mode
if mode == 4 then
i = 3
elseif mode == 8 then
i = 4
end
assert( i <= 4 )
local tab = { {10,9,8,8},{12,11,16,10},{14,13,16,12} }
local digits
if version < 10 then
digits = tab[1][i]
elseif version < 27 then
digits = tab[2][i]
elseif version <= 40 then
digits = tab[3][i]
else
assert(false, "get_length, version > 40 not supported")
end
local len = binary(#str,digits)
return len
end
--- If the `requested_ec_level` or the `mode` are provided, this will be used if possible.
--- The mode depends on the characters used in the string `str`. It seems to be
--- possible to split the QR code to handle multiple modes, but we don't do that.
local function get_version_eclevel_mode_bistringlength(str,requested_ec_level,mode)
local local_mode
if mode then
assert(false,"not implemented")
-- check if the mode is OK for the string
local_mode = mode
else
local_mode = get_mode(str)
end
local version, ec_level
version, ec_level = get_version_eclevel(#str,local_mode,requested_ec_level)
local length_string = get_length(str,version,local_mode)
return version,ec_level,binary(local_mode,4),local_mode,length_string
end
--- Step 2: Encode data
--- ===================
--- There are several ways to encode the data. We currently support only numeric, alphanumeric and binary.
--- We already chose the encoding (a.k.a. mode) in the first step, so we need to apply the mode to the
--- codeword.
---
--- **Numeric**: take three digits and encode them in 10 bits
--- **Alphanumeric**: take two characters and encode them in 11 bits
--- **Binary**: take one octet and encode it in 8 bits
local asciitbl = {
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -- 0x01-0x0f
-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -- 0x10-0x1f
36, -1, -1, -1, 37, 38, -1, -1, -1, -1, 39, 40, -1, 41, 42, 43, -- 0x20-0x2f
0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 44, -1, -1, -1, -1, -1, -- 0x30-0x3f
-1, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, -- 0x40-0x4f
25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, -1, -1, -1, -1, -1, -- 0x50-0x5f
}
-- Return a binary representation of the numeric string `str`. This must contain only digits 0-9.
local function encode_string_numeric(str)
local bitstring = ""
local int
string.gsub(str,"..?.?",function(a)
int = tonumber(a)
if #a == 3 then
bitstring = bitstring .. binary(int,10)
elseif #a == 2 then
bitstring = bitstring .. binary(int,7)
else
bitstring = bitstring .. binary(int,4)
end
end)
return bitstring
end
-- Return a binary representation of the alphanumeric string `str`. This must contain only
-- digits 0-9, uppercase letters A-Z, space and the following chars: $%*./:+-.
local function encode_string_ascii(str)
local bitstring = ""
local int
local b1, b2
string.gsub(str,"..?",function(a)
if #a == 2 then
b1 = asciitbl[string.byte(string.sub(a,1,1))]
b2 = asciitbl[string.byte(string.sub(a,2,2))]
int = b1 * 45 + b2
bitstring = bitstring .. binary(int,11)
else
int = asciitbl[string.byte(a)]
bitstring = bitstring .. binary(int,6)
end
end)
return bitstring
end
-- Return a bitstring representing string str in binary mode.
-- We don't handle UTF-8 in any special way because we assume the
-- scanner recognizes UTF-8 and displays it correctly.
local function encode_string_binary(str)
local ret = {}
string.gsub(str,".",function(x)
ret[#ret + 1] = binary(string.byte(x),8)
end)
return table.concat(ret)
end
-- Return a bitstring representing string str in the given mode.
local function encode_data(str,mode)
if mode == 1 then
return encode_string_numeric(str)
elseif mode == 2 then
return encode_string_ascii(str)
elseif mode == 4 then
return encode_string_binary(str)
else
assert(false,"not implemented yet")
end
end
-- Encoding the codeword is not enough. We need to make sure that
-- the length of the binary string is equal to the number of codewords of the version.
local function add_pad_data(version,ec_level,data)
local count_to_pad, missing_digits
local cpty = capacity[version][ec_level] * 8
count_to_pad = math.min(4,cpty - #data)
if count_to_pad > 0 then
data = data .. string.rep("0",count_to_pad)
end
if math.fmod(#data,8) ~= 0 then
missing_digits = 8 - math.fmod(#data,8)
data = data .. string.rep("0",missing_digits)
end
assert(math.fmod(#data,8) == 0)
-- add "11101100" and "00010001" until enough data
while #data < cpty do
data = data .. "11101100"
if #data < cpty then
data = data .. "00010001"
end
end
return data
end
--- Step 3: Organize data and calculate error correction code
--- =======================================================
--- The data in the qrcode is not encoded linearly. For example code 5-H has four blocks, the first two blocks
--- contain 11 codewords and 22 error correction codes each, the second block contain 12 codewords and 22 ec codes each.
--- We just take the table from the spec and don't calculate the blocks ourself. The table `ecblocks` contains this info.
---
--- During the phase of splitting the data into codewords, we do the calculation for error correction codes. This step involves
--- polynomial division. Find a math book from school and follow the code here :)
--- ### Reed Solomon error correction
--- Now this is the slightly ugly part of the error correction. We start with log/antilog tables
local alpha_int = {
[0] = 0,
2, 4, 8, 16, 32, 64, 128, 29, 58, 116, 232, 205, 135, 19, 38, 76,
152, 45, 90, 180, 117, 234, 201, 143, 3, 6, 12, 24, 48, 96, 192, 157,
39, 78, 156, 37, 74, 148, 53, 106, 212, 181, 119, 238, 193, 159, 35, 70,
140, 5, 10, 20, 40, 80, 160, 93, 186, 105, 210, 185, 111, 222, 161, 95,
190, 97, 194, 153, 47, 94, 188, 101, 202, 137, 15, 30, 60, 120, 240, 253,
231, 211, 187, 107, 214, 177, 127, 254, 225, 223, 163, 91, 182, 113, 226, 217,
175, 67, 134, 17, 34, 68, 136, 13, 26, 52, 104, 208, 189, 103, 206, 129,
31, 62, 124, 248, 237, 199, 147, 59, 118, 236, 197, 151, 51, 102, 204, 133,
23, 46, 92, 184, 109, 218, 169, 79, 158, 33, 66, 132, 21, 42, 84, 168,
77, 154, 41, 82, 164, 85, 170, 73, 146, 57, 114, 228, 213, 183, 115, 230,
209, 191, 99, 198, 145, 63, 126, 252, 229, 215, 179, 123, 246, 241, 255, 227,
219, 171, 75, 150, 49, 98, 196, 149, 55, 110, 220, 165, 87, 174, 65, 130,
25, 50, 100, 200, 141, 7, 14, 28, 56, 112, 224, 221, 167, 83, 166, 81,
162, 89, 178, 121, 242, 249, 239, 195, 155, 43, 86, 172, 69, 138, 9, 18,
36, 72, 144, 61, 122, 244, 245, 247, 243, 251, 235, 203, 139, 11, 22, 44,
88, 176, 125, 250, 233, 207, 131, 27, 54, 108, 216, 173, 71, 142, 1
}
local int_alpha = {
[0] = 0,
255, 1, 25, 2, 50, 26, 198, 3, 223, 51, 238, 27, 104, 199, 75, 4,
100, 224, 14, 52, 141, 239, 129, 28, 193, 105, 248, 200, 8, 76, 113, 5,
138, 101, 47, 225, 36, 15, 33, 53, 147, 142, 218, 240, 18, 130, 69, 29,
181, 194, 125, 106, 39, 249, 185, 201, 154, 9, 120, 77, 228, 114, 166, 6,
191, 139, 98, 102, 221, 48, 253, 226, 152, 37, 179, 16, 145, 34, 136, 54,
208, 148, 206, 143, 150, 219, 189, 241, 210, 19, 92, 131, 56, 70, 64, 30,
66, 182, 163, 195, 72, 126, 110, 107, 58, 40, 84, 250, 133, 186, 61, 202,
94, 155, 159, 10, 21, 121, 43, 78, 212, 229, 172, 115, 243, 167, 87, 7,
112, 192, 247, 140, 128, 99, 13, 103, 74, 222, 237, 49, 197, 254, 24, 227,
165, 153, 119, 38, 184, 180, 124, 17, 68, 146, 217, 35, 32, 137, 46, 55,
63, 209, 91, 149, 188, 207, 205, 144, 135, 151, 178, 220, 252, 190, 97, 242,
86, 211, 171, 20, 42, 93, 158, 132, 60, 57, 83, 71, 109, 65, 162, 31,
45, 67, 216, 183, 123, 164, 118, 196, 23, 73, 236, 127, 12, 111, 246, 108,
161, 59, 82, 41, 157, 85, 170, 251, 96, 134, 177, 187, 204, 62, 90, 203,
89, 95, 176, 156, 169, 160, 81, 11, 245, 22, 235, 122, 117, 44, 215, 79,
174, 213, 233, 230, 231, 173, 232, 116, 214, 244, 234, 168, 80, 88, 175
}
-- We only need the polynomial generators for block sizes 7, 10, 13, 15, 16, 17, 18, 20, 22, 24, 26, 28, and 30. Version
-- 2 of the qr codes don't need larger ones (as opposed to version 1). The table has the format x^1*ɑ^21 + x^2*a^102 ...
local generator_polynomial = {
[7] = { 21, 102, 238, 149, 146, 229, 87, 0},
[10] = { 45, 32, 94, 64, 70, 118, 61, 46, 67, 251, 0 },
[13] = { 78, 140, 206, 218, 130, 104, 106, 100, 86, 100, 176, 152, 74, 0 },
[15] = {105, 99, 5, 124, 140, 237, 58, 58, 51, 37, 202, 91, 61, 183, 8, 0},
[16] = {120, 225, 194, 182, 169, 147, 191, 91, 3, 76, 161, 102, 109, 107, 104, 120, 0},
[17] = {136, 163, 243, 39, 150, 99, 24, 147, 214, 206, 123, 239, 43, 78, 206, 139, 43, 0},
[18] = {153, 96, 98, 5, 179, 252, 148, 152, 187, 79, 170, 118, 97, 184, 94, 158, 234, 215, 0},
[20] = {190, 188, 212, 212, 164, 156, 239, 83, 225, 221, 180, 202, 187, 26, 163, 61, 50, 79, 60, 17, 0},
[22] = {231, 165, 105, 160, 134, 219, 80, 98, 172, 8, 74, 200, 53, 221, 109, 14, 230, 93, 242, 247, 171, 210, 0},
[24] = { 21, 227, 96, 87, 232, 117, 0, 111, 218, 228, 226, 192, 152, 169, 180, 159, 126, 251, 117, 211, 48, 135, 121, 229, 0},
[26] = { 70, 218, 145, 153, 227, 48, 102, 13, 142, 245, 21, 161, 53, 165, 28, 111, 201, 145, 17, 118, 182, 103, 2, 158, 125, 173, 0},
[28] = {123, 9, 37, 242, 119, 212, 195, 42, 87, 245, 43, 21, 201, 232, 27, 205, 147, 195, 190, 110, 180, 108, 234, 224, 104, 200, 223, 168, 0},
[30] = {180, 192, 40, 238, 216, 251, 37, 156, 130, 224, 193, 226, 173, 42, 125, 222, 96, 239, 86, 110, 48, 50, 182, 179, 31, 216, 152, 145, 173, 41, 0}}
-- Turn a binary string of length 8*x into a table size x of numbers.
local function convert_bitstring_to_bytes(data)
local msg = {}
local tab = string.gsub(data,"(........)",function(x)
msg[#msg+1] = tonumber(x,2)
end)
return msg
end
-- Return a table that has 0's in the first entries and then the alpha
-- representation of the generator polynominal
function get_generator_polynominal_adjusted(num_ec_codewords,highest_exponent)
local gp_alpha = {[0]=0}
for i=0,highest_exponent - num_ec_codewords - 1 do
gp_alpha[i] = 0
end
local gp = generator_polynomial[num_ec_codewords]
for i=1,num_ec_codewords + 1 do
gp_alpha[highest_exponent - num_ec_codewords + i - 1] = gp[i]
end
return gp_alpha
end
--- These converter functions use the log/antilog table above.
--- We could have created the table programatically, but I like fixed tables.
-- Convert polynominal in int notation to alpha notation.
local function convert_to_alpha( tab )
local new_tab = {}
for i=0,#tab do
new_tab[i] = int_alpha[tab[i]]
end
return new_tab
end
-- Convert polynominal in alpha notation to int notation.
local function convert_to_int(tab,len_message)
local new_tab = {}
for i=0,#tab do
new_tab[i] = alpha_int[tab[i]]
end
return new_tab
end
-- That's the heart of the error correction calculation.
local function calculate_error_correction(data,num_ec_codewords)
local mp
if type(data)=="string" then
mp = convert_bitstring_to_bytes(data)
elseif type(data)=="table" then
mp = data
else
assert(false,"Unknown type for data: %s",type(data))
end
local len_message = #mp
local highest_exponent = len_message + num_ec_codewords - 1
local gp_alpha,tmp
local he
local gp_int = {}
local mp_int,mp_alpha = {},{}
-- create message shifted to left (highest exponent)
for i=1,len_message do
mp_int[highest_exponent - i + 1] = mp[i]
end
for i=1,highest_exponent - len_message do
mp_int[i] = 0
end
mp_int[0] = 0
mp_alpha = convert_to_alpha(mp_int)
while highest_exponent >= num_ec_codewords do
gp_alpha = get_generator_polynominal_adjusted(num_ec_codewords,highest_exponent)
-- Multiply generator polynomial by first coefficient of the above polynomial
-- take the highest exponent from the message polynom (alpha) and add
-- it to the generator polynom
local exp = mp_alpha[highest_exponent]
for i=highest_exponent,highest_exponent - num_ec_codewords,-1 do
if gp_alpha[i] + exp > 255 then
gp_alpha[i] = math.fmod(gp_alpha[i] + exp,255)
else
gp_alpha[i] = gp_alpha[i] + exp
end
end
for i=highest_exponent - num_ec_codewords - 1,0,-1 do
gp_alpha[i] = 0
end
gp_int = convert_to_int(gp_alpha)
mp_int = convert_to_int(mp_alpha)
tmp = {}
for i=highest_exponent,0,-1 do
tmp[i] = bit_xor(gp_int[i],mp_int[i])
end
-- remove leading 0's
he = highest_exponent
for i=he,0,-1 do
-- We need to stop if the length of the codeword is matched
if i < num_ec_codewords then break end
if tmp[i] == 0 then
tmp[i] = nil
highest_exponent = highest_exponent - 1
else
break
end
end
mp_int = tmp
mp_alpha = convert_to_alpha(mp_int)
end
local ret = {}
-- reverse data
for i=#mp_int,0,-1 do
ret[#ret + 1] = mp_int[i]
end
return ret
end
--- #### Arranging the data
--- Now we arrange the data into smaller chunks. This table is taken from the spec.
-- ecblocks has 40 entries, one for each version. Each version entry has 4 entries, for each LMQH
-- ec level. Each entry has two or four fields, the odd files are the number of repetitions for the
-- folowing block info. The first entry of the block is the total number of codewords in the block,
-- the second entry is the number of data codewords. The third is not important.
local ecblocks = {
{{ 1,{ 26, 19, 2} }, { 1,{26,16, 4}}, { 1,{26,13, 6}}, { 1, {26, 9, 8} }},
{{ 1,{ 44, 34, 4} }, { 1,{44,28, 8}}, { 1,{44,22,11}}, { 1, {44,16,14} }},
{{ 1,{ 70, 55, 7} }, { 1,{70,44,13}}, { 2,{35,17, 9}}, { 2, {35,13,11} }},
{{ 1,{100, 80,10} }, { 2,{50,32, 9}}, { 2,{50,24,13}}, { 4, {25, 9, 8} }},
{{ 1,{134,108,13} }, { 2,{67,43,12}}, { 2,{33,15, 9}, 2,{34,16, 9}}, { 2, {33,11,11}, 2,{34,12,11}}},
{{ 2,{ 86, 68, 9} }, { 4,{43,27, 8}}, { 4,{43,19,12}}, { 4, {43,15,14} }},
{{ 2,{ 98, 78,10} }, { 4,{49,31, 9}}, { 2,{32,14, 9}, 4,{33,15, 9}}, { 4, {39,13,13}, 1,{40,14,13}}},
{{ 2,{121, 97,12} }, { 2,{60,38,11}, 2,{61,39,11}}, { 4,{40,18,11}, 2,{41,19,11}}, { 4, {40,14,13}, 2,{41,15,13}}},
{{ 2,{146,116,15} }, { 3,{58,36,11}, 2,{59,37,11}}, { 4,{36,16,10}, 4,{37,17,10}}, { 4, {36,12,12}, 4,{37,13,12}}},
{{ 2,{ 86, 68, 9}, 2,{ 87, 69, 9}}, { 4,{69,43,13}, 1,{70,44,13}}, { 6,{43,19,12}, 2,{44,20,12}}, { 6, {43,15,14}, 2,{44,16,14}}},
{{ 4,{101, 81,10} }, { 1,{80,50,15}, 4,{81,51,15}}, { 4,{50,22,14}, 4,{51,23,14}}, { 3, {36,12,12}, 8,{37,13,12}}},
{{ 2,{116, 92,12}, 2,{117, 93,12}}, { 6,{58,36,11}, 2,{59,37,11}}, { 4,{46,20,13}, 6,{47,21,13}}, { 7, {42,14,14}, 4,{43,15,14}}},
{{ 4,{133,107,13} }, { 8,{59,37,11}, 1,{60,38,11}}, { 8,{44,20,12}, 4,{45,21,12}}, { 12, {33,11,11}, 4,{34,12,11}}},
{{ 3,{145,115,15}, 1,{146,116,15}}, { 4,{64,40,12}, 5,{65,41,12}}, { 11,{36,16,10}, 5,{37,17,10}}, { 11, {36,12,12}, 5,{37,13,12}}},
{{ 5,{109, 87,11}, 1,{110, 88,11}}, { 5,{65,41,12}, 5,{66,42,12}}, { 5,{54,24,15}, 7,{55,25,15}}, { 11, {36,12,12}, 7,{37,13,12}}},
{{ 5,{122, 98,12}, 1,{123, 99,12}}, { 7,{73,45,14}, 3,{74,46,14}}, { 15,{43,19,12}, 2,{44,20,12}}, { 3, {45,15,15}, 13,{46,16,15}}},
{{ 1,{135,107,14}, 5,{136,108,14}}, { 10,{74,46,14}, 1,{75,47,14}}, { 1,{50,22,14}, 15,{51,23,14}}, { 2, {42,14,14}, 17,{43,15,14}}},
{{ 5,{150,120,15}, 1,{151,121,15}}, { 9,{69,43,13}, 4,{70,44,13}}, { 17,{50,22,14}, 1,{51,23,14}}, { 2, {42,14,14}, 19,{43,15,14}}},
{{ 3,{141,113,14}, 4,{142,114,14}}, { 3,{70,44,13}, 11,{71,45,13}}, { 17,{47,21,13}, 4,{48,22,13}}, { 9, {39,13,13}, 16,{40,14,13}}},
{{ 3,{135,107,14}, 5,{136,108,14}}, { 3,{67,41,13}, 13,{68,42,13}}, { 15,{54,24,15}, 5,{55,25,15}}, { 15, {43,15,14}, 10,{44,16,14}}},
{{ 4,{144,116,14}, 4,{145,117,14}}, { 17,{68,42,13}}, { 17,{50,22,14}, 6,{51,23,14}}, { 19, {46,16,15}, 6,{47,17,15}}},
{{ 2,{139,111,14}, 7,{140,112,14}}, { 17,{74,46,14}}, { 7,{54,24,15}, 16,{55,25,15}}, { 34, {37,13,12} }},
{{ 4,{151,121,15}, 5,{152,122,15}}, { 4,{75,47,14}, 14,{76,48,14}}, { 11,{54,24,15}, 14,{55,25,15}}, { 16, {45,15,15}, 14,{46,16,15}}},
{{ 6,{147,117,15}, 4,{148,118,15}}, { 6,{73,45,14}, 14,{74,46,14}}, { 11,{54,24,15}, 16,{55,25,15}}, { 30, {46,16,15}, 2,{47,17,15}}},
{{ 8,{132,106,13}, 4,{133,107,13}}, { 8,{75,47,14}, 13,{76,48,14}}, { 7,{54,24,15}, 22,{55,25,15}}, { 22, {45,15,15}, 13,{46,16,15}}},
{{ 10,{142,114,14}, 2,{143,115,14}}, { 19,{74,46,14}, 4,{75,47,14}}, { 28,{50,22,14}, 6,{51,23,14}}, { 33, {46,16,15}, 4,{47,17,15}}},
{{ 8,{152,122,15}, 4,{153,123,15}}, { 22,{73,45,14}, 3,{74,46,14}}, { 8,{53,23,15}, 26,{54,24,15}}, { 12, {45,15,15}, 28,{46,16,15}}},
{{ 3,{147,117,15}, 10,{148,118,15}}, { 3,{73,45,14}, 23,{74,46,14}}, { 4,{54,24,15}, 31,{55,25,15}}, { 11, {45,15,15}, 31,{46,16,15}}},
{{ 7,{146,116,15}, 7,{147,117,15}}, { 21,{73,45,14}, 7,{74,46,14}}, { 1,{53,23,15}, 37,{54,24,15}}, { 19, {45,15,15}, 26,{46,16,15}}},
{{ 5,{145,115,15}, 10,{146,116,15}}, { 19,{75,47,14}, 10,{76,48,14}}, { 15,{54,24,15}, 25,{55,25,15}}, { 23, {45,15,15}, 25,{46,16,15}}},
{{ 13,{145,115,15}, 3,{146,116,15}}, { 2,{74,46,14}, 29,{75,47,14}}, { 42,{54,24,15}, 1,{55,25,15}}, { 23, {45,15,15}, 28,{46,16,15}}},
{{ 17,{145,115,15} }, { 10,{74,46,14}, 23,{75,47,14}}, { 10,{54,24,15}, 35,{55,25,15}}, { 19, {45,15,15}, 35,{46,16,15}}},
{{ 17,{145,115,15}, 1,{146,116,15}}, { 14,{74,46,14}, 21,{75,47,14}}, { 29,{54,24,15}, 19,{55,25,15}}, { 11, {45,15,15}, 46,{46,16,15}}},
{{ 13,{145,115,15}, 6,{146,116,15}}, { 14,{74,46,14}, 23,{75,47,14}}, { 44,{54,24,15}, 7,{55,25,15}}, { 59, {46,16,15}, 1,{47,17,15}}},
{{ 12,{151,121,15}, 7,{152,122,15}}, { 12,{75,47,14}, 26,{76,48,14}}, { 39,{54,24,15}, 14,{55,25,15}}, { 22, {45,15,15}, 41,{46,16,15}}},
{{ 6,{151,121,15}, 14,{152,122,15}}, { 6,{75,47,14}, 34,{76,48,14}}, { 46,{54,24,15}, 10,{55,25,15}}, { 2, {45,15,15}, 64,{46,16,15}}},
{{ 17,{152,122,15}, 4,{153,123,15}}, { 29,{74,46,14}, 14,{75,47,14}}, { 49,{54,24,15}, 10,{55,25,15}}, { 24, {45,15,15}, 46,{46,16,15}}},
{{ 4,{152,122,15}, 18,{153,123,15}}, { 13,{74,46,14}, 32,{75,47,14}}, { 48,{54,24,15}, 14,{55,25,15}}, { 42, {45,15,15}, 32,{46,16,15}}},
{{ 20,{147,117,15}, 4,{148,118,15}}, { 40,{75,47,14}, 7,{76,48,14}}, { 43,{54,24,15}, 22,{55,25,15}}, { 10, {45,15,15}, 67,{46,16,15}}},
{{ 19,{148,118,15}, 6,{149,119,15}}, { 18,{75,47,14}, 31,{76,48,14}}, { 34,{54,24,15}, 34,{55,25,15}}, { 20, {45,15,15}, 61,{46,16,15}}}
}
-- The bits that must be 0 if the version does fill the complete matrix.
-- Example: for version 1, no bits need to be added after arranging the data, for version 2 we need to add 7 bits at the end.
local remainder = {0, 7, 7, 7, 7, 7, 0, 0, 0, 0, 0, 0, 0, 3, 3, 3, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3, 3, 3, 3, 3, 0, 0, 0, 0, 0, 0}
-- This is the formula for table 1 in the spec:
-- function get_capacity_remainder( version )
-- local len = version * 4 + 17
-- local size = len^2
-- local function_pattern_modules = 192 + 2 * len - 32 -- Position Adjustment pattern + timing pattern
-- local count_alignemnt_pattern = #alignment_pattern[version]
-- if count_alignemnt_pattern > 0 then
-- -- add 25 for each aligment pattern
-- function_pattern_modules = function_pattern_modules + 25 * ( count_alignemnt_pattern^2 - 3 )
-- -- but substract the timing pattern occupied by the aligment pattern on the top and left
-- function_pattern_modules = function_pattern_modules - ( count_alignemnt_pattern - 2) * 10
-- end
-- size = size - function_pattern_modules
-- if version > 6 then
-- size = size - 67
-- else
-- size = size - 31
-- end
-- return math.floor(size/8),math.fmod(size,8)
-- end
--- Example: Version 5-H has four data and four error correction blocks. The table above lists
--- `2, {33,11,11}, 2,{34,12,11}` for entry [5][4]. This means we take two blocks with 11 codewords
--- and two blocks with 12 codewords, and two blocks with 33 - 11 = 22 ec codes and another
--- two blocks with 34 - 12 = 22 ec codes.
--- Block 1: D1 D2 D3 ... D11
--- Block 2: D12 D13 D14 ... D22
--- Block 3: D23 D24 D25 ... D33 D34
--- Block 4: D35 D36 D37 ... D45 D46
--- Then we place the data like this in the matrix: D1, D12, D23, D35, D2, D13, D24, D36 ... D45, D34, D46. The same goes
--- with error correction codes.
-- The given data can be a string of 0's and 1' (with #string mod 8 == 0).
-- Alternatively the data can be a table of codewords. The number of codewords
-- must match the capacity of the qr code.
local function arrange_codewords_and_calculate_ec( version,ec_level,data )
if type(data)=="table" then
local tmp = ""
for i=1,#data do
tmp = tmp .. binary(data[i],8)
end
data = tmp
end
-- If the size of the data is not enough for the codeword, we add 0's and two special bytes until finished.
local blocks = ecblocks[version][ec_level]
local size_datablock_bytes, size_ecblock_bytes
local datablocks = {}
local ecblocks = {}
local count = 1
local pos = 0
local cpty_ec_bits = 0
for i=1,#blocks/2 do
for j=1,blocks[2*i - 1] do
size_datablock_bytes = blocks[2*i][2]
size_ecblock_bytes = blocks[2*i][1] - blocks[2*i][2]
cpty_ec_bits = cpty_ec_bits + size_ecblock_bytes * 8
datablocks[#datablocks + 1] = string.sub(data, pos * 8 + 1,( pos + size_datablock_bytes)*8)
tmp_tab = calculate_error_correction(datablocks[#datablocks],size_ecblock_bytes)
tmp_str = ""
for x=1,#tmp_tab do
tmp_str = tmp_str .. binary(tmp_tab[x],8)
end
ecblocks[#ecblocks + 1] = tmp_str
pos = pos + size_datablock_bytes
count = count + 1
end
end
local arranged_data = ""
pos = 1
repeat
for i=1,#datablocks do
if pos < #datablocks[i] then
arranged_data = arranged_data .. string.sub(datablocks[i],pos, pos + 7)
end
end
pos = pos + 8
until #arranged_data == #data
-- ec
local arranged_ec = ""
pos = 1
repeat
for i=1,#ecblocks do
if pos < #ecblocks[i] then
arranged_ec = arranged_ec .. string.sub(ecblocks[i],pos, pos + 7)
end
end
pos = pos + 8
until #arranged_ec == cpty_ec_bits
return arranged_data .. arranged_ec
end
--- Step 4: Generate 8 matrices with different masks and calculate the penalty
--- ==========================================================================
---
--- Prepare matrix
--- --------------
--- The first step is to prepare an _empty_ matrix for a given size/mask. The matrix has a
--- few predefined areas that must be black or blank. We encode the matrix with a two
--- dimensional field where the numbers determine which pixel is blank or not.
---
--- The following code is used for our matrix:
--- 0 = not in use yet,
--- -2 = blank by mandatory pattern,
--- 2 = black by mandatory pattern,
--- -1 = blank by data,
--- 1 = black by data
---
---
--- To prepare the _empty_, we add positioning, alingment and timing patters.
--- ### Positioning patterns ###
local function add_position_detection_patterns(tab_x)
local size = #tab_x
-- allocate quite zone in the matrix area
for i=1,8 do
for j=1,8 do
tab_x[i][j] = -2
tab_x[size - 8 + i][j] = -2
tab_x[i][size - 8 + j] = -2
end
end
-- draw the detection pattern (outer)
for i=1,7 do
-- top left
tab_x[1][i]=2
tab_x[7][i]=2
tab_x[i][1]=2
tab_x[i][7]=2
-- top right
tab_x[size][i]=2
tab_x[size - 6][i]=2
tab_x[size - i + 1][1]=2
tab_x[size - i + 1][7]=2
-- bottom left
tab_x[1][size - i + 1]=2
tab_x[7][size - i + 1]=2
tab_x[i][size - 6]=2
tab_x[i][size]=2
end
-- draw the detection pattern (inner)
for i=1,3 do
for j=1,3 do
-- top left
tab_x[2+j][i+2]=2
-- top right
tab_x[size - j - 1][i+2]=2
-- bottom left
tab_x[2 + j][size - i - 1]=2
end
end
end
--- ### Timing patterns ###
-- The timing patterns (two) are the dashed lines between two adjacent positioning patterns on row/column 7.
local function add_timing_pattern(tab_x)
local line,col
line = 7
col = 9
for i=col,#tab_x - 8 do
if math.fmod(i,2) == 1 then
tab_x[i][line] = 2
else
tab_x[i][line] = -2
end
end
for i=col,#tab_x - 8 do
if math.fmod(i,2) == 1 then
tab_x[line][i] = 2
else
tab_x[line][i] = -2
end
end
end
--- ### Alignment patterns ###
--- The alignment patterns must be added to the matrix for versions > 1. The amount and positions depend on the versions and are
--- given by the spec. Beware: the patterns must not be placed where we have the positioning patterns
--- (that is: top left, top right and bottom left.)
-- For each version, where should we place the alignment patterns? See table E.1 of the spec
local alignment_pattern = {
{},{6,18},{6,22},{6,26},{6,30},{6,34}, -- 1-6
{6,22,38},{6,24,42},{6,26,46},{6,28,50},{6,30,54},{6,32,58},{6,34,62}, -- 7-13
{6,26,46,66},{6,26,48,70},{6,26,50,74},{6,30,54,78},{6,30,56,82},{6,30,58,86},{6,34,62,90}, -- 14-20
{6,28,50,72,94},{6,26,50,74,98},{6,30,54,78,102},{6,28,54,80,106},{6,32,58,84,110},{6,30,58,86,114},{6,34,62,90,118}, -- 21-27
{6,26,50,74,98 ,122},{6,30,54,78,102,126},{6,26,52,78,104,130},{6,30,56,82,108,134},{6,34,60,86,112,138},{6,30,58,86,114,142},{6,34,62,90,118,146}, -- 28-34
{6,30,54,78,102,126,150}, {6,24,50,76,102,128,154},{6,28,54,80,106,132,158},{6,32,58,84,110,136,162},{6,26,54,82,110,138,166},{6,30,58,86,114,142,170} -- 35 - 40
}
--- The alignment pattern has size 5x5 and looks like this:
--- XXXXX
--- X X
--- X X X
--- X X
--- XXXXX
local function add_alignment_pattern( tab_x )
local version = (#tab_x - 17) / 4
local ap = alignment_pattern[version]
local pos_x, pos_y
for x=1,#ap do
for y=1,#ap do
-- we must not put an alignment pattern on top of the positioning pattern
if not (x == 1 and y == 1 or x == #ap and y == 1 or x == 1 and y == #ap ) then
pos_x = ap[x] + 1
pos_y = ap[y] + 1
tab_x[pos_x][pos_y] = 2
tab_x[pos_x+1][pos_y] = -2
tab_x[pos_x-1][pos_y] = -2
tab_x[pos_x+2][pos_y] = 2
tab_x[pos_x-2][pos_y] = 2
tab_x[pos_x ][pos_y - 2] = 2
tab_x[pos_x+1][pos_y - 2] = 2
tab_x[pos_x-1][pos_y - 2] = 2
tab_x[pos_x+2][pos_y - 2] = 2
tab_x[pos_x-2][pos_y - 2] = 2
tab_x[pos_x ][pos_y + 2] = 2
tab_x[pos_x+1][pos_y + 2] = 2
tab_x[pos_x-1][pos_y + 2] = 2
tab_x[pos_x+2][pos_y + 2] = 2
tab_x[pos_x-2][pos_y + 2] = 2
tab_x[pos_x ][pos_y - 1] = -2
tab_x[pos_x+1][pos_y - 1] = -2
tab_x[pos_x-1][pos_y - 1] = -2
tab_x[pos_x+2][pos_y - 1] = 2
tab_x[pos_x-2][pos_y - 1] = 2
tab_x[pos_x ][pos_y + 1] = -2
tab_x[pos_x+1][pos_y + 1] = -2
tab_x[pos_x-1][pos_y + 1] = -2
tab_x[pos_x+2][pos_y + 1] = 2
tab_x[pos_x-2][pos_y + 1] = 2
end
end
end
end
--- ### Type information ###
--- Let's not forget the type information that is in column 9 next to the left positioning patterns and on row 9 below
--- the top positioning patterns. This type information is not fixed, it depends on the mask and the error correction.
-- The first index is ec level (LMQH,1-4), the second is the mask (0-7). This bitstring of length 15 is to be used
-- as mandatory pattern in the qrcode. Mask -1 is for debugging purpose only and is the 'noop' mask.
local typeinfo = {
{ [-1]= "111111111111111", [0] = "111011111000100", "111001011110011", "111110110101010", "111100010011101", "110011000101111", "110001100011000", "110110001000001", "110100101110110" },
{ [-1]= "111111111111111", [0] = "101010000010010", "101000100100101", "101111001111100", "101101101001011", "100010111111001", "100000011001110", "100111110010111", "100101010100000" },
{ [-1]= "111111111111111", [0] = "011010101011111", "011000001101000", "011111100110001", "011101000000110", "010010010110100", "010000110000011", "010111011011010", "010101111101101" },
{ [-1]= "111111111111111", [0] = "001011010001001", "001001110111110", "001110011100111", "001100111010000", "000011101100010", "000001001010101", "000110100001100", "000100000111011" }
}
-- The typeinfo is a mixture of mask and ec level information and is
-- added twice to the qr code, one horizontal, one vertical.
local function add_typeinfo_to_matrix( matrix,ec_level,mask )
local ec_mask_type = typeinfo[ec_level][mask]
local bit
-- vertical from bottom to top
for i=1,7 do
bit = string.sub(ec_mask_type,i,i)
fill_matrix_position(matrix, bit, 9, #matrix - i + 1)
end
for i=8,9 do
bit = string.sub(ec_mask_type,i,i)
fill_matrix_position(matrix,bit,9,17-i)
end
for i=10,15 do
bit = string.sub(ec_mask_type,i,i)
fill_matrix_position(matrix,bit,9,16 - i)
end
-- horizontal, left to right
for i=1,6 do
bit = string.sub(ec_mask_type,i,i)
fill_matrix_position(matrix,bit,i,9)
end
bit = string.sub(ec_mask_type,7,7)
fill_matrix_position(matrix,bit,8,9)
for i=8,15 do
bit = string.sub(ec_mask_type,i,i)
fill_matrix_position(matrix,bit,#matrix - 15 + i,9)
end
end
-- Bits for version information 7-40
local version_information = {"001010010011111000", "000111101101000100", "100110010101100100","011001011001010100",
"011011111101110100", "001000110111001100", "111000100001101100", "010110000011011100", "000101001001111100",
"000111101101000010", "010111010001100010", "111010000101010010", "001001100101110010", "011001011001001010",
"011000001011101010", "100100110001011010", "000110111111111010", "001000110111000110", "000100001111100110",
"110101011111010110", "000001110001110110", "010110000011001110", "001111110011101110", "101011101011011110",
"000000101001111110", "101010111001000001", "000001111011100001", "010111010001010001", "011111001111110001",
"110100001101001001", "001110100001101001", "001001100101011001", "010000010101111001", "100101100011000101" }
-- Versions 7 and above need two bitfields with version information added to the code
local function add_version_information(matrix,version)
if version < 7 then return end
local size = #matrix
local bitstring = version_information[version - 6]
local x,y, bit
local start_x, start_y
-- first top right
start_x = #matrix - 10
start_y = 1
for i=1,#bitstring do
bit = string.sub(bitstring,i,i)
x = start_x + math.fmod(i - 1,3)
y = start_y + math.floor( (i - 1) / 3 )
fill_matrix_position(matrix,bit,x,y)
end
-- now bottom left
start_x = 1
start_y = #matrix - 10
for i=1,#bitstring do
bit = string.sub(bitstring,i,i)
x = start_x + math.floor( (i - 1) / 3 )
y = start_y + math.fmod(i - 1,3)
fill_matrix_position(matrix,bit,x,y)
end
end
--- Now it's time to use the methods above to create a prefilled matrix for the given mask
local function prepare_matrix_with_mask( version,ec_level, mask )
local size
local tab_x = {}
size = version * 4 + 17
for i=1,size do
tab_x[i]={}
for j=1,size do
tab_x[i][j] = 0
end
end
add_position_detection_patterns(tab_x)
add_timing_pattern(tab_x)
add_version_information(tab_x,version)
-- black pixel above lower left position detection pattern
tab_x[9][size - 7] = 2
add_alignment_pattern(tab_x)
add_typeinfo_to_matrix(tab_x,ec_level, mask)
return tab_x
end
--- Finally we come to the place where we need to put the calculated data (remember step 3?) into the qr code.
--- We do this for each mask. BTW speaking of mask, this is what we find in the spec:
--- Mask Pattern Reference Condition
--- 000 (y + x) mod 2 = 0
--- 001 y mod 2 = 0
--- 010 x mod 3 = 0
--- 011 (y + x) mod 3 = 0
--- 100 ((y div 2) + (x div 3)) mod 2 = 0
--- 101 (y x) mod 2 + (y x) mod 3 = 0
--- 110 ((y x) mod 2 + (y x) mod 3) mod 2 = 0
--- 111 ((y x) mod 3 + (y+x) mod 2) mod 2 = 0
-- Return 1 (black) or -1 (blank) depending on the mask, value and position.
-- Parameter mask is 0-7 (-1 for 'no mask'). x and y are 1-based coordinates,
-- 1,1 = upper left. tonumber(value) must be 0 or 1.
local function get_pixel_with_mask( mask, x,y,value )
x = x - 1
y = y - 1
local invert = false
-- test purpose only:
if mask == -1 then
-- ignore, no masking applied
elseif mask == 0 then
if math.fmod(x + y,2) == 0 then invert = true end
elseif mask == 1 then
if math.fmod(y,2) == 0 then invert = true end
elseif mask == 2 then
if math.fmod(x,3) == 0 then invert = true end
elseif mask == 3 then
if math.fmod(x + y,3) == 0 then invert = true end
elseif mask == 4 then
if math.fmod(math.floor(y / 2) + math.floor(x / 3),2) == 0 then invert = true end
elseif mask == 5 then
if math.fmod(x * y,2) + math.fmod(x * y,3) == 0 then invert = true end
elseif mask == 6 then
if math.fmod(math.fmod(x * y,2) + math.fmod(x * y,3),2) == 0 then invert = true end
elseif mask == 7 then
if math.fmod(math.fmod(x * y,3) + math.fmod(x + y,2),2) == 0 then invert = true end
else
assert(false,"This can't happen (mask must be <= 7)")
end
if invert then
-- value = 1? -> -1, value = 0? -> 1
return 1 - 2 * tonumber(value)
else
-- value = 1? -> 1, value = 0? -> -1
return -1 + 2*tonumber(value)
end
end
-- We need up to 8 positions in the matrix. Only the last few bits may be less then 8.
-- The function returns a table of (up to) 8 entries with subtables where
-- the x coordinate is the first and the y coordinate is the second entry.
function get_next_free_positions(matrix,x,y,dir,byte)
local ret = {}
local count = 1
local mode = "right"
while count <= #byte do
if mode == "right" and matrix[x][y] == 0 then
ret[#ret + 1] = {x,y}
mode = "left"
count = count + 1
elseif mode == "left" and matrix[x-1][y] == 0 then
ret[#ret + 1] = {x-1,y}
mode = "right"
count = count + 1
if dir == "up" then
y = y - 1
else
y = y + 1
end
elseif mode == "right" and matrix[x-1][y] == 0 then
ret[#ret + 1] = {x-1,y}
count = count + 1
if dir == "up" then
y = y - 1
else
y = y + 1
end
else
if dir == "up" then
y = y - 1
else
y = y + 1
end
end
if y < 1 or y > #matrix then
x = x - 2
-- don't overwrite the timing pattern
if x == 7 then x = 6 end
if dir == "up" then
dir = "down"
y = 1
else
dir = "up"
y = #matrix
end
end
end
return ret,x,y,dir
end
-- Add the data string (0's and 1's) to the matrix for the given mask.
local function add_data_to_matrix(matrix,data,mask)
size = #matrix
local x,y,positions
local _x,_y,m
local dir = "up"
local byte_number = 0
x,y = size,size
string.gsub(data,".?.?.?.?.?.?.?.?",function ( byte )
byte_number = byte_number + 1
positions,x,y,dir = get_next_free_positions(matrix,x,y,dir,byte,mask)
for i=1,#byte do
_x = positions[i][1]
_y = positions[i][2]
m = get_pixel_with_mask(mask,_x,_y,string.sub(byte,i,i))
if debugging then
matrix[_x][_y] = m * (i + 10)
else
matrix[_x][_y] = m
end
end
end)
end
--- The total penalty of the matrix is the sum of four steps. The following steps are taken into account:
---
--- 1. Adjacent modules in row/column in same color
--- 1. Block of modules in same color
--- 1. 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column
--- 1. Proportion of dark modules in entire symbol
---
--- This all is done to avoid bad patterns in the code that prevent the scanner from
--- reading the code.
-- Return the penalty for the given matrix
local function calculate_penalty(matrix)
local penalty1, penalty2, penalty3, penalty4 = 0,0,0,0
local size = #matrix
-- this is for penalty 4
local number_of_dark_cells = 0
-- 1: Adjacent modules in row/column in same color
-- --------------------------------------------
-- No. of modules = (5+i) -> 3 + i
local last_bit_blank -- < 0: blank, > 0: black
local is_blank
local number_of_consecutive_bits
-- first: vertical
for x=1,size do
number_of_consecutive_bits = 0
last_bit_blank = nil
for y = 1,size do
if matrix[x][y] > 0 then
-- small optimization: this is for penalty 4
number_of_dark_cells = number_of_dark_cells + 1
is_blank = false
else
is_blank = true
end
is_blank = matrix[x][y] < 0
if last_bit_blank == is_blank then
number_of_consecutive_bits = number_of_consecutive_bits + 1
else
if number_of_consecutive_bits >= 5 then
penalty1 = penalty1 + number_of_consecutive_bits - 2
end
number_of_consecutive_bits = 1
end
last_bit_blank = is_blank
end
if number_of_consecutive_bits >= 5 then
penalty1 = penalty1 + number_of_consecutive_bits - 2
end
end
-- now horizontal
for y=1,size do
number_of_consecutive_bits = 0
last_bit_blank = nil
for x = 1,size do
is_blank = matrix[x][y] < 0
if last_bit_blank == is_blank then
number_of_consecutive_bits = number_of_consecutive_bits + 1
else
if number_of_consecutive_bits >= 5 then
penalty1 = penalty1 + number_of_consecutive_bits - 2
end
number_of_consecutive_bits = 1
end
last_bit_blank = is_blank
end
if number_of_consecutive_bits >= 5 then
penalty1 = penalty1 + number_of_consecutive_bits - 2
end
end
for x=1,size do
for y=1,size do
-- 2: Block of modules in same color
-- -----------------------------------
-- Blocksize = m × n -> 3 × (m-1) × (n-1)
if (y < size - 1) and ( x < size - 1) and ( (matrix[x][y] < 0 and matrix[x+1][y] < 0 and matrix[x][y+1] < 0 and matrix[x+1][y+1] < 0) or (matrix[x][y] > 0 and matrix[x+1][y] > 0 and matrix[x][y+1] > 0 and matrix[x+1][y+1] > 0) ) then
penalty2 = penalty2 + 3
end
-- 3: 1:1:3:1:1 ratio (dark:light:dark:light:dark) pattern in row/column
-- ------------------------------------------------------------------
-- Gives 40 points each
--
-- I have no idea why we need the extra 0000 on left or right side. The spec doesn't mention it,
-- other sources do mention it. This is heavily inspired by zxing.
if (y + 6 < size and
matrix[x][y] > 0 and
matrix[x][y + 1] < 0 and
matrix[x][y + 2] > 0 and
matrix[x][y + 3] > 0 and
matrix[x][y + 4] > 0 and
matrix[x][y + 5] < 0 and
matrix[x][y + 6] > 0 and
((y + 10 < size and
matrix[x][y + 7] < 0 and
matrix[x][y + 8] < 0 and
matrix[x][y + 9] < 0 and
matrix[x][y + 10] < 0) or
(y - 4 >= 1 and
matrix[x][y - 1] < 0 and
matrix[x][y - 2] < 0 and
matrix[x][y - 3] < 0 and
matrix[x][y - 4] < 0))) then penalty3 = penalty3 + 40 end
if (x + 6 <= size and
matrix[x][y] > 0 and
matrix[x + 1][y] < 0 and
matrix[x + 2][y] > 0 and
matrix[x + 3][y] > 0 and
matrix[x + 4][y] > 0 and
matrix[x + 5][y] < 0 and
matrix[x + 6][y] > 0 and
((x + 10 <= size and
matrix[x + 7][y] < 0 and
matrix[x + 8][y] < 0 and
matrix[x + 9][y] < 0 and
matrix[x + 10][y] < 0) or
(x - 4 >= 1 and
matrix[x - 1][y] < 0 and
matrix[x - 2][y] < 0 and
matrix[x - 3][y] < 0 and
matrix[x - 4][y] < 0))) then penalty3 = penalty3 + 40 end
end
end
-- 4: Proportion of dark modules in entire symbol
-- ----------------------------------------------
-- 50 ± (5 × k)% to 50 ± (5 × (k + 1))% -> 10 × k
local dark_ratio = number_of_dark_cells / ( size * size )
penalty4 = math.floor(math.abs(dark_ratio * 100 - 50)) * 2
return penalty1 + penalty2 + penalty3 + penalty4
end
-- Create a matrix for the given parameters and calculate the penalty score.
-- Return both (matrix and penalty)
local function get_matrix_and_penalty(version,ec_level,data,mask)
local tab = prepare_matrix_with_mask(version,ec_level,mask)
add_data_to_matrix(tab,data,mask)
local penalty = calculate_penalty(tab)
return tab, penalty
end
-- Return the matrix with the smallest penalty. To to this
-- we try out the matrix for all 8 masks and determine the
-- penalty (score) each.
local function get_matrix_with_lowest_penalty(version,ec_level,data)
local tab, penalty
local tab_min_penalty, min_penalty
-- try masks 0-7
tab_min_penalty, min_penalty = get_matrix_and_penalty(version,ec_level,data,0)
for i=1,7 do
tab, penalty = get_matrix_and_penalty(version,ec_level,data,i)
if penalty < min_penalty then
tab_min_penalty = tab
min_penalty = penalty
end
end
return tab_min_penalty
end
--- The main function. We connect everything together. Remember from above:
---
--- 1. Determine version, ec level and mode (=encoding) for codeword
--- 1. Encode data
--- 1. Arrange data and calculate error correction code
--- 1. Generate 8 matrices with different masks and calculate the penalty
--- 1. Return qrcode with least penalty
-- If ec_level or mode is given, use the ones for generating the qrcode. (mode is not implemented yet)
local function qrcode( str, ec_level, mode )
local arranged_data, version, ec_level, data_raw, mode, len_bitstring
version, ec_level, data_raw, mode, len_bitstring = get_version_eclevel_mode_bistringlength(str)
data_raw = data_raw .. len_bitstring
data_raw = data_raw .. encode_data(str,mode)
data_raw = add_pad_data(version,ec_level,data_raw)
arranged_data = arrange_codewords_and_calculate_ec(version,ec_level,data_raw)
if math.fmod(#arranged_data,8) ~= 0 then
return false, string.format("Arranged data %% 8 != 0: data length = %d, mod 8 = %d",#arranged_data, math.fmod(#arranged_data,8))
end
arranged_data = arranged_data .. string.rep("0",remainder[version])
local tab = get_matrix_with_lowest_penalty(version,ec_level,arranged_data)
return true, tab
end
if testing then
return {
encode_string_numeric = encode_string_numeric,
encode_string_ascii = encode_string_ascii,
qrcode = qrcode,
binary = binary,
get_mode = get_mode,
get_length = get_length,
add_pad_data = add_pad_data,
get_generator_polynome_adjusted = get_generator_polynome_adjusted,
get_matrix = get_matrix,
get_pixel_with_mask = get_pixel_with_mask,
print_pattern = print_pattern,
get_version_eclevel_mode_bistringlength = get_version_eclevel_mode_bistringlength,
remainder = remainder,
get_capacity_remainder = get_capacity_remainder,
arrange_codewords_and_calculate_ec = arrange_codewords_and_calculate_ec,
calculate_error_correction = calculate_error_correction,
convert_bitstring_to_bytes = convert_bitstring_to_bytes,
bit_xor = bit_xor,
}
end
return {
qrcode = qrcode
} | gpl-3.0 |
nesstea/darkstar | scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Gamygyn.lua | 2 | 1528 | -----------------------------------
-- Area: Dynamis Xarcabard
-- MOB: Marquis Gamygyn
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if (mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 8192;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if (Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330177); -- Dynamis Lord
GetMobByID(17330183):setSpawn(-364,-35.661,17.254); -- Set Ying and Yang's spawn points to their initial spawn point.
GetMobByID(17330184):setSpawn(-364,-35.974,24.254);
SpawnMob(17330183);
SpawnMob(17330184);
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if (Animate_Trigger == 32767) then
ally:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/weaponskills/detonator.lua | 11 | 1643 | -----------------------------------
-- Detonator
-- Marksmanship weapon skill
-- Skill Level: 250
-- Delivers a single-hit attack. Damage varies with TP.
-- In order to obtain Detonator, the quest Shoot First, Ask Questions Later must be completed.
-- Despite the lack of a STR weaponskill mod, STR is still the most potent stat for increasing this weaponskill's damage to the point at which fSTR2 is capped.
-- Aligned with the Flame Gorget & Light Gorget.
-- Aligned with the Flame Belt & Light Belt.
-- Element: None
-- Modifiers: AGI: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, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 1.5; params.ftp200 = 2; params.ftp300 = 2.5;
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.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.ftp100 = 1.5; params.ftp200 = 2.5; params.ftp300 = 5.0;
params.agi_wsc = 0.7;
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/spells/horde_lullaby.lua | 23 | 1097 | -----------------------------------------
-- Spell: Horde Lullaby
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local duration = 30;
local pCHR = caster:getStat(MOD_CHR);
local mCHR = target:getStat(MOD_CHR);
local dCHR = (pCHR - mCHR);
local resm = applyResistanceEffect(caster,spell,target,dCHR,SINGING_SKILL,0,EFFECT_LULLABY);
if (resm < 0.5) then
spell:setMsg(85);--resist message
else
local iBoost = caster:getMod(MOD_LULLABY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (target:addStatusEffect(EFFECT_LULLABY,1,0,duration)) then
spell:setMsg(237);
else
spell:setMsg(75);
end
end
return EFFECT_LULLABY;
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/San_dOria-Jeuno_Airship/TextIDs.lua | 22 | 1088 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6384; -- Obtained: <item>
GIL_OBTAINED = 6385; -- Obtained <number> gil
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>
-- Other
WILL_REACH_JEUNO = 7204; -- The airship will reach Jeuno in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
WILL_REACH_SANDORIA = 7205; -- The airship will reach San d'Oria in Multiple Choice (Parameter 1)[less than an hour/about 1 hour/about 2 hours/about 3 hours/about 4 hours/about 5 hours/about 6 hours/about 7 hours] ( Singular/Plural Choice (Parameter 0)[minute/minutes] in Earth time).
IN_JEUNO_MOMENTARILY = 7207; -- We will be arriving in Jeuno momentarily.
IN_SANDORIA_MOMENTARILY = 7208; -- We will be arriving in San d'Oria momentarily.
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Temenos/mobs/Enhanced_Vulture.lua | 17 | 1433 | -----------------------------------
-- Area: Temenos W T
-- NPC: Enhanced_Vulture
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
GetMobByID(16928959):updateEnmity(target);
GetMobByID(16928960):updateEnmity(target);
GetMobByID(16928961):updateEnmity(target);
GetMobByID(16928962):updateEnmity(target);
GetMobByID(16928963):updateEnmity(target);
GetMobByID(16928964):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
if(IsMobDead(16928959)==true and IsMobDead(16928960)==true and IsMobDead(16928961)==true
and IsMobDead(16928962)==true and IsMobDead(16928963)==true and IsMobDead(16928964)==true)then
GetNPCByID(16928768+17):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+17):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+470):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/libs/Plugins/oUF_WarlockShards/oUF_WarlockShards.lua | 2 | 3293 | --GLOBAL NAMESPACE
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
--MATH
local math = _G.math;
local floor = math.floor
--BLIZZARD API
local UnitPower = _G.UnitPower;
local UnitPowerMax = _G.UnitPowerMax;
local UnitHasVehicleUI = _G.UnitHasVehicleUI;
local GetSpecialization = _G.GetSpecialization;
if select(2, UnitClass('player')) ~= "WARLOCK" then return end
local _, ns = ...
local oUF = ns.oUF or oUF
assert(oUF, 'oUF_WarlockShards was unable to locate oUF install')
local shardColor = {
[1] = {0,0.72,0.1},
[2] = {0.57,0.08,1},
[3] = {1,0.25,0}
}
local Update = function(self, event, unit, powerType)
local bar = self.WarlockShards;
if(bar.PreUpdate) then bar:PreUpdate(unit) end
if UnitHasVehicleUI("player") then
bar:Hide()
else
bar:Show()
end
local spec = GetSpecialization()
if spec then
local colors = shardColor[spec]
local numShards = UnitPower("player", Enum.PowerType.SoulShards);
bar.MaxCount = UnitPowerMax("player", Enum.PowerType.SoulShards);
if not bar:IsShown() then
bar:Show()
end
if((not bar.CurrentSpec) or (bar.CurrentSpec ~= spec and bar.UpdateTextures)) then
bar:UpdateTextures(spec)
end
for i = 1, 5 do
if(i > bar.MaxCount) then
bar[i]:Hide()
else
bar[i]:Show()
bar[i]:SetStatusBarColor(unpack(colors))
bar[i]:SetMinMaxValues(0, 1)
local filled = (i <= numShards) and 1 or 0
bar[i]:SetValue(filled)
if(bar[i].Update) then
bar[i]:Update(filled)
end
end
end
else
if bar:IsShown() then bar:Hide() end;
end
if(bar.PostUpdate) then
return bar:PostUpdate(unit, spec)
end
end
local Path = function(self, ...)
return (self.WarlockShards.Override or Update) (self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate', element.__owner.unit, 'SOUL_SHARDS')
end
local function Enable(self, unit)
if(unit ~= 'player') then return end
local bar = self.WarlockShards
if(bar) then
bar.__owner = self
bar.ForceUpdate = ForceUpdate
self:RegisterEvent('UNIT_POWER_UPDATE', Path)
self:RegisterEvent("PLAYER_TALENT_UPDATE", Path)
self:RegisterEvent("PLAYER_ENTERING_WORLD", Path)
self:RegisterEvent('UNIT_DISPLAYPOWER', Path)
self:RegisterEvent("UNIT_POWER_FREQUENT", Path)
self:RegisterEvent("UNIT_MAXPOWER", Path)
self:RegisterUnitEvent('UNIT_DISPLAYPOWER', "player")
self:RegisterUnitEvent("UNIT_POWER_FREQUENT", "player")
self:RegisterUnitEvent("UNIT_MAXPOWER", "player")
for i = 1, 5 do
if not bar[i]:GetStatusBarTexture() then
bar[i]:SetStatusBarTexture([=[Interface\TargetingFrame\UI-StatusBar]=])
end
bar[i]:SetFrameLevel(bar:GetFrameLevel() + 1)
bar[i]:GetStatusBarTexture():SetHorizTile(false)
end
return true
end
end
local function Disable(self)
local bar = self.WarlockShards
if(bar) then
self:UnregisterEvent('UNIT_POWER_UPDATE', Path)
self:UnregisterEvent("PLAYER_TALENT_UPDATE", Path)
self:UnregisterEvent("PLAYER_ENTERING_WORLD", Path)
self:UnregisterEvent('UNIT_DISPLAYPOWER', Path)
self:UnregisterEvent("UNIT_POWER_FREQUENT", Path)
self:UnregisterEvent("UNIT_MAXPOWER", Path)
bar:Hide()
end
end
oUF:AddElement('WarlockShards', Path, Enable, Disable)
| mit |
plajjan/snabbswitch | lib/ljsyscall/syscall/methods.lua | 18 | 7907 | -- this creates types with methods
-- cannot do this in types as the functions have not been defined yet (as they depend on types)
-- well we could, by passing in the empty table for S, but this is more modular
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(S)
local abi = S.abi
local c = S.c
local types = S.types
local t, s, pt = types.t, types.s, types.pt
local bit = require "syscall.bit"
local ffi = require "ffi"
local h = require "syscall.helpers"
local getfd, istype, mktype = h.getfd, h.istype, h.mktype
local function metatype(tp, mt)
if abi.rumpfn then tp = abi.rumpfn(tp) end
return ffi.metatype(tp, mt)
end
-- easier interfaces to some functions that are in common use TODO new fcntl code should make easier
local function nonblock(fd)
local fl, err = S.fcntl(fd, c.F.GETFL)
if not fl then return nil, err end
fl, err = S.fcntl(fd, c.F.SETFL, c.O(fl, "nonblock"))
if not fl then return nil, err end
return true
end
local function block(fd)
local fl, err = S.fcntl(fd, c.F.GETFL)
if not fl then return nil, err end
fl, err = S.fcntl(fd, c.F.SETFL, c.O(fl, "~nonblock"))
if not fl then return nil, err end
return true
end
local function tell(fd) return S.lseek(fd, 0, c.SEEK.CUR) end
-- somewhat confusing now we have flock too. I think this comes from nixio.
local function lockf(fd, cmd, len)
cmd = c.LOCKF[cmd]
if cmd == c.LOCKF.LOCK then
return S.fcntl(fd, c.F.SETLKW, {l_type = c.FCNTL_LOCK.WRLCK, l_whence = c.SEEK.CUR, l_start = 0, l_len = len})
elseif cmd == c.LOCKF.TLOCK then
return S.fcntl(fd, c.F.SETLK, {l_type = c.FCNTL_LOCK.WRLCK, l_whence = c.SEEK.CUR, l_start = 0, l_len = len})
elseif cmd == c.LOCKF.ULOCK then
return S.fcntl(fd, c.F.SETLK, {l_type = c.FCNTL_LOCK.UNLCK, l_whence = c.SEEK.CUR, l_start = 0, l_len = len})
elseif cmd == c.LOCKF.TEST then
local ret, err = S.fcntl(fd, c.F.GETLK, {l_type = c.FCNTL_LOCK.WRLCK, l_whence = c.SEEK.CUR, l_start = 0, l_len = len})
if not ret then return nil, err end
return ret.l_type == c.FCNTL_LOCK.UNLCK
end
end
-- methods on an fd
-- note could split, so a socket does not have methods only appropriate for a file; sometimes you do not know what type an fd is
local fdmethods = {'dup', 'dup2', 'dup3', 'read', 'write', 'pread', 'pwrite',
'lseek', 'fchdir', 'fsync', 'fdatasync', 'fstat', 'fcntl', 'fchmod',
'bind', 'listen', 'connect', 'accept', 'getsockname', 'getpeername',
'send', 'sendto', 'recv', 'recvfrom', 'readv', 'writev', 'sendmsg',
'recvmsg', 'setsockopt', 'epoll_ctl', 'epoll_wait', 'sendfile', 'getdents',
'ftruncate', 'shutdown', 'getsockopt',
'inotify_add_watch', 'inotify_rm_watch', 'inotify_read', 'flistxattr',
'fsetxattr', 'fgetxattr', 'fremovexattr', 'fxattr', 'splice', 'vmsplice', 'tee',
'timerfd_gettime', 'timerfd_settime',
'fadvise', 'fallocate', 'posix_fallocate', 'readahead',
'sync_file_range', 'fstatfs', 'futimens', 'futimes',
'fstatat', 'unlinkat', 'mkdirat', 'mknodat', 'faccessat', 'fchmodat', 'fchown',
'fchownat', 'readlinkat', 'setns', 'openat', 'accept4',
'preadv', 'pwritev', 'epoll_pwait', 'ioctl', 'flock', 'fpathconf',
'grantpt', 'unlockpt', 'ptsname', 'tcgetattr', 'tcsetattr', 'isatty',
'tcsendbreak', 'tcdrain', 'tcflush', 'tcflow', 'tcgetsid',
'sendmmsg', 'recvmmsg', 'syncfs',
'fchflags', 'fchroot', 'fsync_range', 'kevent', 'paccept', 'fktrace', -- bsd only
'pdgetpid', 'pdkill' -- freebsd only
}
local fmeth = {}
for _, v in ipairs(fdmethods) do fmeth[v] = S[v] end
-- defined above
fmeth.block = block
fmeth.nonblock = nonblock
fmeth.tell = tell
fmeth.lockf = lockf
-- fd not first argument
fmeth.mmap = function(fd, addr, length, prot, flags, offset) return S.mmap(addr, length, prot, flags, fd, offset) end
if S.bindat then fmeth.bindat = function(s, dirfd, addr, addrlen) return S.bindat(dirfd, s, addr, addrlen) end end
if S.connectat then fmeth.connectat = function(s, dirfd, addr, addrlen) return S.connectat(dirfd, s, addr, addrlen) end end
-- allow calling without leading f
fmeth.stat = S.fstat
fmeth.chdir = S.fchdir
fmeth.sync = S.fsync
fmeth.datasync = S.fdatasync
fmeth.chmod = S.fchmod
fmeth.setxattr = S.fsetxattr
fmeth.getxattr = S.gsetxattr
fmeth.truncate = S.ftruncate
fmeth.statfs = S.fstatfs
fmeth.utimens = S.futimens
fmeth.utimes = S.futimes
fmeth.seek = S.lseek
fmeth.chown = S.fchown
fmeth.lock = S.flock
fmeth.pathconf = S.fpathconf
-- netbsd only
fmeth.chflags = S.fchflags
fmeth.chroot = S.fchroot
fmeth.sync_range = S.fsync_range
fmeth.ktrace = S.fktrace
-- no point having fd in name - bsd only
fmeth.extattr_get = S.extattr_get_fd
fmeth.extattr_set = S.extattr_set_fd
fmeth.extattr_delete = S.extattr_delete_fd
fmeth.extattr_list = S.extattr_list_fd
local function nogc(d) return ffi.gc(d, nil) end
fmeth.nogc = nogc
-- sequence number used by netlink messages
fmeth.seq = function(fd)
fd.sequence = fd.sequence + 1
return fd.sequence
end
-- TODO note this is not very friendly to user, as will just get EBADF from all calls
function fmeth.close(fd)
local fileno = getfd(fd)
if fileno == -1 then return true end -- already closed
local ok, err = S.close(fileno)
fd.filenum = -1 -- make sure cannot accidentally close this fd object again
return ok, err
end
fmeth.getfd = function(fd) return fd.filenum end
t.fd = metatype("struct {int filenum; int sequence;}", {
__index = fmeth,
__gc = fmeth.close,
__new = function(tp, i)
return istype(tp, i) or ffi.new(tp, i or -1)
end,
})
S.stdin = t.fd(c.STD.IN):nogc()
S.stdout = t.fd(c.STD.OUT):nogc()
S.stderr = t.fd(c.STD.ERR):nogc()
if S.mq_open then -- TODO better test. TODO support in BSD
local mqmeth = {
close = fmeth.close,
nogc = nogc,
getfd = function(fd) return fd.filenum end,
getattr = function(mqd, attr)
attr = attr or t.mq_attr()
local ok, err = S.mq_getsetattr(mqd, nil, attr)
if not ok then return nil, err end
return attr
end,
setattr = function(mqd, attr)
if type(attr) == "number" or type(attr) == "string" then attr = {flags = attr} end -- only flags can be set so allow this
attr = mktype(t.mq_attr, attr)
return S.mq_getsetattr(mqd, attr, nil)
end,
timedsend = S.mq_timedsend,
send = function(mqd, msg_ptr, msg_len, msg_prio) return S.mq_timedsend(mqd, msg_ptr, msg_len, msg_prio) end,
timedreceive = S.mq_timedreceive,
receive = function(mqd, msg_ptr, msg_len, msg_prio) return S.mq_timedreceive(mqd, msg_ptr, msg_len, msg_prio) end,
}
t.mqd = metatype("struct {mqd_t filenum;}", {
__index = mqmeth,
__gc = mqmeth.close,
__new = function(tp, i)
return istype(tp, i) or ffi.new(tp, i or -1)
end,
})
end
-- TODO deal with delete twice issue with delete and gc
t.timer = metatype("struct {timer_t timerid[1];}", {
__index = {
gettimerp = function(self) return self.timerid end,
gettimer = function(self) return self.timerid[0] end,
settime = S.timer_settime,
gettime = S.timer_gettime,
delete = S.timer_delete,
getoverrun = S.timer_getoverrun,
},
--__gc = S.timer_delete,
})
-- TODO reinstate this, more like fd is, hence changes to destroy
--[[
t.aio_context = metatype("struct {aio_context_t ctx;}", {
__index = {destroy = S.io_destroy, submit = S.io_submit, getevents = S.io_getevents, cancel = S.io_cancel, nogc = nogc},
__gc = S.io_destroy
})
]]
return S
end
return {init = init}
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/items/cobalt_jellyfish.lua | 17 | 1336 | -----------------------------------------
-- ID: 4443
-- Item: cobalt_jellyfish
-- Food Effect: 5 Min, Mithra only
-----------------------------------------
-- Dexterity 1
-- Mind -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4443);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_MND,-3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_MND,-3);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Waters/npcs/Fomina.lua | 36 | 1701 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Fomina
-- Only sells when Windurst controlls Elshimo Lowlands
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(ELSHIMOLOWLANDS);
if (RegionOwner ~= WINDURST) then
player:showText(npc,FOMINA_CLOSED_DIALOG);
else
player:showText(npc,FOMINA_OPEN_DIALOG);
stock = {
0x0264, 55, --Kazham Peppers
0x1150, 55, --Kazham Pineapple
0x1126, 36, --Mithran Tomato
0x0272, 234, --Black Pepper
0x0276, 88, --Ogre Pumpkin
0x0278, 110, --Kukuru Bean
0x0583, 1656 --Phalaenopsis
}
showShop(player,WINDURST,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Port_San_dOria/npcs/Liloune.lua | 13 | 1355 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Liloune
-- 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(0x252);
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 |
bowlofstew/Macaroni | Main/App/Source/test/lua/Macaroni/Parser/Pippy/Tests/PippyParserTests_Functions.lua | 2 | 6353 | --------------------------------------------------------------------------------
-- Copyright 2011 Tim Simpson
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
--------------------------------------------------------------------------------
-- require "Macaroni.Model.Context";
-- require "Macaroni.Environment.Messages";
-- require "Macaroni.Parser.Pippy.PippyParser";
-- require "Macaroni.Parser.Parser";
-- require "Macaroni.Parser.ParserException";
-- require "Macaroni.IO.Path";
-- require "Macaroni.Model.Source";
-- require "Macaroni.Model.Type";
-- require "Macaroni.Model.TypeArgument";
-- require "Macaroni.Model.TypeArgumentList";
-- require "Macaroni.Model.TypeList";
local Context = require "Macaroni.Model.Context";
local Messages = require "Macaroni.Environment.Messages";
local PippyParser = require "Macaroni.Parser.Pippy.PippyParser";
local Path = require "Macaroni.IO.Path";
local FileName = require "Macaroni.Model.FileName";
local Source = require "Macaroni.Model.Source";
local Type = require "Macaroni.Model.Type";
local TypeArgumentList = require "Macaroni.Model.TypeArgumentList";
local TypeList = require "Macaroni.Model.TypeList";
-- Convience method returns result of the parse, then status, and
-- finally an err message.
local tryParse = function(text)
local parser = PippyParser.Create();
local context = Context.New("{ROOT}");
local file = FileName.Create(Path.New("", "Blah1.mcpp"));
local src = Source.Create(file, 1, 1);
local result = nil;
local status, err = pcall(function()
result = parser:Read(context, src, text);
end
);
return status, err;
end
Test.register(
{
name = "PippyParser Tests :: Functions",
tests = {
{
name = "Creating an empty method.",
init = function(this)
this.parser = PippyParser.Create();
this.context = Context.New("{ROOT}");
this.target = this.context:Group("Tests")
:Project("PippyParserTests_Functions"):Version("9.5"):Target("hi");
this.file = FileName.Create(Path.New("", "Blah1.mcpp"));
this.root = this.context.Root;
this.src = Source.Create(this.file, 1, 1);
this.parser:Read(this.target, this.src, [[
void main(){}
]]);
this.funcNode = this.root.Children[2];
this.func = this.funcNode.Element;
this.fo1 = this.funcNode.Children[1].Element;
end,
tests = {
["Main is added."] = function(this)
Test.assertEquals(2, #this.root.Children);
Test.assertEquals("main", this.root.Children[2].Name);
end,
["Main's type is function."] = function(this)
Test.assertEquals("Function", this.func.TypeName);
end,
["Main has one overload."] = function(this)
Test.assertEquals(1, #(this.funcNode.Children));
end,
["Main.Overload#0 type is overload."] = function(this)
Test.assertEquals("FunctionOverload", this.fo1.TypeName);
end,
["Main.Overload#0 return type is void."] = function(this)
Test.assertEquals("void", this.fo1.ReturnType.Node.Name); --
end,
["Main.Overload#0 argument list is empty."] = function(this)
Test.assertEquals(0, #this.fo1.Arguments); --
end,
}
},
{
name = "Finding types in argument list.",
init = function(this)
this.parser = PippyParser.Create();
this.context = Context.New("{ROOT}");
this.target = this.context:Group("Tests")
:Project("ArgList_types"):Version("3.x"):Target("hi");
this.file = FileName.Create(Path.New("", "Blah1.mcpp"));
this.root = this.context.Root;
this.src = Source.Create(this.file, 1, 1);
this.parser:Read(this.target, this.src, [[
~import std::string;
void go(string blah){}
]]);
this.funcNode = this.root.Children[3];
this.func = this.funcNode.Element;
this.fo1 = this.funcNode.Children[1].Element;
end,
tests = {
["Function 'go' is added."] = function(this)
Test.assertEquals(3, #this.root.Children);
Test.assertEquals("go", this.root.Children[3].Name);
end,
["Go's type is function."] = function(this)
Test.assertEquals("Function", this.func.TypeName);
end,
["Go has one child."] = function(this)
Test.assertEquals(1, #(this.funcNode.Children));
end,
["Go.Overload#1 is type 'FunctionOverload'"] = function(this)
Test.assertEquals("FunctionOverload", this.fo1.TypeName);
end,
["Go.Overload#1's return type is void."] = function(this)
Test.assertEquals("void", this.fo1.ReturnType.Node.Name);
end,
["Go.Overload#1's argument list has one entry."] = function(this)
Test.assertEquals(1, #this.fo1.Arguments);
end,
["Go.Overload#1's argument #1 is std::string."] = function(this)
local args = this.fo1.Arguments;
local number = #args;
local arg1 = args[1];
local arg1Type = arg1.Element.Type;
local arg1TypeName = arg1Type.Node.FullName;
Test.assertEquals("std::string", arg1TypeName);
end,
}
},
} -- end of tests table ( I skipped some indentation way above here).
}); -- End of register call
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/kurayami_san.lua | 11 | 1139 | -----------------------------------------
-- Spell: Kurayami: San
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
-- Base Stats
local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT));
--Duration Calculation
local duration = 420 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0);
--Kurayami base power is 30 and is not affected by resistaces.
local power = 30;
--Calculates resist chanve from Reist Blind
if(math.random(0,100) >= target:getMod(MOD_BLINDRES)) then
if(duration >= 210) then
if(target:addStatusEffect(EFFECT_BLINDNESS,power,0,duration)) then
spell:setMsg(236);
else
spell:setMsg(75);
end
else
spell:setMsg(85);
end
else
spell:setMsg(284);
end
return EFFECT_BLINDNESS;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/homura_+1.lua | 16 | 1027 | -----------------------------------------
-- ID: 16986
-- Item: Homura +1
-- Additional Effect: Fire Damage
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 10;
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local dmg = math.random(6,23);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0);
dmg = adjustForTarget(target,dmg,ELE_FIRE);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg);
local message = 163;
if (dmg < 0) then
message = 167;
end
return SUBEFFECT_FIRE_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/plate_of_homemade_salad.lua | 35 | 1131 | -----------------------------------------
-- ID: 5227
-- Item: plate_of_homemade_salad
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Magic 10
-----------------------------------------
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,5227);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 10);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/bluemagic/tail_slap.lua | 28 | 1767 | -----------------------------------------
-- Spell: Tail Slap
-- Delivers an area attack. Additional effect: "Stun." Damage varies with TP
-- Spell cost: 77 MP
-- Monster Type: Beastmen
-- Spell Type: Physical (Blunt)
-- Blue Magic Points: 4
-- Stat Bonus: MND+2
-- Level: 69
-- Casting Time: 1 seconds
-- Recast Time: 28.5 seconds
-- Skillchain Element: Water (can open Impaction and Induration; can close Reverberation and Fragmentation)
-- Combos: Store TP
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.tpmod = TPMOD_ATTACK;
params.dmgtype = DMGTYPE_H2H;
params.scattr = SC_REVERBERATION;
params.numhits = 1;
params.multiplier = 1.625;
params.tp150 = 1.625;
params.tp300 = 1.625;
params.azuretp = 1.625;
params.duppercap = 75;
params.str_wsc = 0.2;
params.dex_wsc = 0.0;
params.vit_wsc = 0.5;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
damage = BluePhysicalSpell(caster, target, spell, params);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
return damage;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Port_Windurst/npcs/Aroro.lua | 34 | 1741 | -----------------------------------
-- Area: Port Windurst
-- NPC: Aroro
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ARORO_SHOP_DIALOG);
stock = {
0x12FE, 114,1, --Blind
0x12DC, 84,2, --Poison
0x12E6, 368,2, --Bio
0x12FD, 2300,2, --Sleep
0x129F, 62,3, --Stone
0x12A9, 143,3, --Water
0x129A, 331,3, --Aero
0x1290, 855,3, --Fire
0x1295, 1619,3, --Blizzard
0x12A4, 3334,3, --Thunder
0x12EB, 4747,3, --Burn
0x12EC, 3770,3, --Frost
0x12ED, 2300,3, --Choke
0x12EE, 1867,3, --Rasp
0x12EF, 1393,3, --Shock
0x12F0, 6508,3 --Drown
}
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/bluemagic/warm-up.lua | 9 | 1512 | -----------------------------------------
-- Spell: Warm-Up
-- Enhances accuracy and evasion
-- Spell cost: 59 MP
-- Monster Type: Beastmen
-- Spell Type: Magical (Earth)
-- Blue Magic Points: 4
-- Stat Bonus: VIT+1
-- Level: 68
-- Casting Time: 7 seconds
-- Recast Time: 120 seconds
-- Duration: 180 seconds
--
-- Combos: Clear Mind
-----------------------------------------
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 = 180;
if(caster:hasStatusEffect(EFFECT_DIFFUSION)) then
local diffMerit = caster:getMerit(MERIT_DIFFUSION);
if(diffMerit > 0) then
duration = duration + (duration/100)* diffMerit;
end
caster:delStatusEffect(EFFECT_DIFFUSION);
end
if(caster:hasStatusEffect(EFFECT_ACCURACY_BOOST) and caster:hasStatusEffect(EFFECT_EVASION_BOOST) == true) then
spell:setMsg(75);
else
caster:addStatusEffect(EFFECT_EVASION_BOOST,10,0,duration);
caster:addStatusEffect(EFFECT_ACCURACY_BOOST,10,0,duration);
end
return EFFECT_EVASION_BOOST;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/bowl_of_eyeball_soup.lua | 35 | 1403 | -----------------------------------------
-- ID: 4453
-- Item: Bowl of Eyeball Soup
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Charisma -10
-- Health Regen While Healing 4
-- Accuracy 12
-- Ranged ACC 12
-----------------------------------------
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,4453);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_CHR, -10);
target:addMod(MOD_HPHEAL, 4);
target:addMod(MOD_ACC, 12);
target:addMod(MOD_RACC, 12);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_CHR, -10);
target:delMod(MOD_HPHEAL, 4);
target:delMod(MOD_ACC, 12);
target:delMod(MOD_RACC, 12);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/abilities/blade_bash.lua | 10 | 1641 | -----------------------------------
-- Ability: Blade Bash
-- Deliver an attack that can stun the target and occasionally cause Plague.
-- Obtained: Samurai Level 75
-- Recast Time: 3:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (not player:isWeaponTwoHanded()) then
return MSGBASIC_NEEDS_2H_WEAPON,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Stun rate
if(math.random(1,100) < 99) then
target:addStatusEffect(EFFECT_STUN,1,0,6);
end
-- Yes, even Blade Bash deals damage dependant of Dark Knight level
local darkKnightLvl = 0;
local damage = 0;
if(player:getMainJob()==JOB_DRK) then
damage = math.floor(((player:getMainLvl() + 11) / 4) + player:getMod(MOD_WEAPON_BASH));
elseif(player:getSubJob()==JOB_DRK) then
damage = math.floor(((player:getSubLvl() + 11) / 4) + player:getMod(MOD_WEAPON_BASH));
end
-- Calculating and applying Blade Bash damage
target:delHP(damage);
target:updateEnmityFromDamage(player,damage);
-- Applying Plague based on merit level.
if(math.random(1,100) < 65) then
target:addStatusEffect(EFFECT_PLAGUE,5,0,15 + player:getMerit(MERIT_BLADE_BASH));
end
ability:setMsg(110)
return damage;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/LaLoff_Amphitheater/bcnms/ark_angels_1.lua | 13 | 3031 | -----------------------------------
-- Area: LaLoff Amphitheater
-- Name: Ark Angels 1 (Hume)
-----------------------------------
package.loaded["scripts/zones/LaLoff_Amphitheater/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/LaLoff_Amphitheater/TextIDs");
require("scripts/globals/missions");
require("scripts/globals/keyitems");
-----------------------------------
-- Death cutscenes:
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); -- Hume
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); -- taru
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,2,0); -- mithra
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); -- elvan
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0); -- galka
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,5,0); -- divine might
-- player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,6,0); -- skip ending cs
-- 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
if(player:hasCompletedMission(ZILART,ARK_ANGELS)) then
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,1); -- winning CS (allow player to skip)
else
player:startEvent(0x7d01,instance:getEntrance(),instance:getFastestTime(),1,instance:getTimeInside(),180,0,0); -- winning CS (allow player to skip)
end
elseif(leavecode == 4) then
player:startEvent(0x7d02, 0, 0, 0, 0, 0, instance:getEntrance(), 180); -- player lost
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);
local AAKeyitems = (player:hasKeyItem(SHARD_OF_ARROGANCE) and player:hasKeyItem(SHARD_OF_COWARDICE)
and player:hasKeyItem(SHARD_OF_ENVY) and player:hasKeyItem(SHARD_OF_RAGE));
if(csid == 0x7d01) then
if (player:getCurrentMission(ZILART) == ARK_ANGELS and player:getVar("ZilartStatus") == 1) then
player:addKeyItem(SHARD_OF_APATHY);
player:messageSpecial(KEYITEM_OBTAINED,SHARD_OF_APATHY);
if (AAKeyitems == true) then
player:completeMission(ZILART,ARK_ANGELS);
player:addMission(ZILART,THE_SEALED_SHRINE);
player:setVar("ZilartStatus",0);
end
end
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Bastok_Markets/npcs/Mjoll.lua | 17 | 1529 | -----------------------------------
-- Area: Batok Markets
-- NPC: Mjoll
-- Standard Merchant NPC
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MJOLL_SHOP_DIALOG);
stock = {
0x43A9, 16,1, --Silver Arrow
0x43A6, 3,2, --Wooden Arrow
0x43A8, 7,3, --Iron Arrow
0x13CD, 199,3, --Scroll of Dark Threnody
0x13C7, 1000,3, --Scroll of Ice Threnody
0x4340, 163,3, --Light Crossbow
0x4341, 2166,3, --Crossbow
0x43B8, 3,3, --Crossbow Bolt
0x43B9, 21,3, --Mythril Bolt
}
showNationShop(player, BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/effects/yonin.lua | 30 | 1281 | -----------------------------------
--
--
--
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect) --power=30 initially, subpower=20 for enmity
target:addMod(MOD_ACC,-effect:getPower());
target:addMod(MOD_NINJA_TOOL,effect:getPower());
target:addMod(MOD_ENMITY,effect:getSubPower());
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
--tick down the effect and reduce the overall power
effect:setPower(effect:getPower()-1);
target:delMod(MOD_ACC,-1);
target:delMod(MOD_NINJA_TOOL,1);
if (effect:getPower() % 2 == 0) then -- enmity+ decays from 20 to 10, so half as often as the rest.
effect:setSubPower(effect:getSubPower()-1);
target:delMod(MOD_ENMITY,1);
end;
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
--remove the remaining power
target:delMod(MOD_ACC,-effect:getPower());
target:delMod(MOD_NINJA_TOOL,effect:getPower());
target:delMod(MOD_ENMITY,effect:getSubPower());
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Bastok_Markets/npcs/Loulia.lua | 13 | 1091 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Loulia
-- Type: Room Renters
-- @zone: 235
-- @pos -176.212 -9 -25.049
--
-- Auto-Script: Requires Verification. Validated standard dialog - thrydwolf 12/8/2011
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01e7);
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_ikra_gunkan_+1.lua | 18 | 1730 | -----------------------------------------
-- ID: 5220
-- Item: plate_of_ikra_gunkan_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 30
-- Magic 12
-- Dexterity 3
-- Mind -1
-- Accuracy % 17
-- Accuracy Cap 30
-- Ranged ACC % 17
-- Ranged ACC Cap 30
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5220);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_MP, 12);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -1);
target:addMod(MOD_FOOD_ACCP, 17);
target:addMod(MOD_FOOD_ACC_CAP, 30);
target:addMod(MOD_FOOD_RACCP, 17);
target:addMod(MOD_FOOD_RACC_CAP, 30);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_MP, 12);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -1);
target:delMod(MOD_FOOD_ACCP, 17);
target:delMod(MOD_FOOD_ACC_CAP, 30);
target:delMod(MOD_FOOD_RACCP, 17);
target:delMod(MOD_FOOD_RACC_CAP, 30);
end;
| gpl-3.0 |
heyuqi/wxFormBuilder | build/premake/4.3/src/base/globals.lua | 8 | 2836 | --
-- globals.lua
-- Global tables and variables, replacements and extensions to Lua's global functions.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
-- A top-level namespace for support functions
premake = { }
-- The list of supported platforms; also update list in cmdline.lua
premake.platforms =
{
Native =
{
cfgsuffix = "",
},
x32 =
{
cfgsuffix = "32",
},
x64 =
{
cfgsuffix = "64",
},
Universal =
{
cfgsuffix = "univ",
},
Universal32 =
{
cfgsuffix = "univ32",
},
Universal64 =
{
cfgsuffix = "univ64",
},
PS3 =
{
cfgsuffix = "ps3",
iscrosscompiler = true,
nosharedlibs = true,
namestyle = "PS3",
},
Xbox360 =
{
cfgsuffix = "xbox360",
iscrosscompiler = true,
namestyle = "windows",
},
}
--
-- A replacement for Lua's built-in dofile() function, this one sets the
-- current working directory to the script's location, enabling script-relative
-- referencing of other files and resources.
--
local builtin_dofile = dofile
function dofile(fname)
-- remember the current working directory and file; I'll restore it shortly
local oldcwd = os.getcwd()
local oldfile = _SCRIPT
-- if the file doesn't exist, check the search path
if (not os.isfile(fname)) then
local path = os.pathsearch(fname, _OPTIONS["scripts"], os.getenv("PREMAKE_PATH"))
if (path) then
fname = path.."/"..fname
end
end
-- use the absolute path to the script file, to avoid any file name
-- ambiguity if an error should arise
_SCRIPT = path.getabsolute(fname)
-- switch the working directory to the new script location
local newcwd = path.getdirectory(_SCRIPT)
os.chdir(newcwd)
-- run the chunk. How can I catch variable return values?
local a, b, c, d, e, f = builtin_dofile(_SCRIPT)
-- restore the previous working directory when done
_SCRIPT = oldfile
os.chdir(oldcwd)
return a, b, c, d, e, f
end
--
-- "Immediate If" - returns one of the two values depending on the value of expr.
--
function iif(expr, trueval, falseval)
if (expr) then
return trueval
else
return falseval
end
end
--
-- A shortcut for including another "premake4.lua" file, often used for projects.
--
function include(fname)
return dofile(fname .. "/premake4.lua")
end
--
-- A shortcut for printing formatted output.
--
function printf(msg, ...)
print(string.format(msg, unpack(arg)))
end
--
-- An extension to type() to identify project object types by reading the
-- "__type" field from the metatable.
--
local builtin_type = type
function type(t)
local mt = getmetatable(t)
if (mt) then
if (mt.__type) then
return mt.__type
end
end
return builtin_type(t)
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Chamber_of_Oracles/bcnms/through_the_quicksand_caves.lua | 13 | 1875 | -----------------------------------
-- Area: Qu'Bia Arena
-- Name: Zilart Mission 6
-- @pos -221 -24 19 206
-----------------------------------
package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Sacrificial_Chamber/TextIDs");
-----------------------------------
-- 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
if(player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
end
elseif(leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if(csid == 0x7d01) then
if(player:getCurrentMission(ZILART) == THROUGH_THE_QUICKSAND_CAVES) then
player:completeMission(ZILART,THROUGH_THE_QUICKSAND_CAVES);
player:addMission(ZILART,THE_CHAMBER_OF_ORACLES);
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Jugner_Forest_[S]/npcs/Telepoint.lua | 18 | 1191 | -----------------------------------
-- 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 |
Lordlotter/AdvanSource | plugins/savefile.lua | 1 | 1244 | --Created by: @lordlotter3
--Powered by: @lordandroid_bot
--⚠️CopyRight all right reserved⚠️
local function savefile(extra, success, result)
local msg = extra.msg
local name = extra.name
local adress = extra.adress
local receiver = get_receiver(msg)
if success then
local file = './'..adress..'/'..name..''
print('File saving to:', result)
os.rename(result, file)
print('File moved to:', file)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function run(msg,matches)
local receiver = get_receiver(msg)
local group = msg.to.id
if msg.reply_id then
local adress = matches[2]
local name = matches[3]
if matches[1] == "file" and matches[2] and matches[3] and is_sudo(msg) then
load_document(msg.reply_id, savefile, {msg=msg,name=name,adress=adress})
return 'File '..name..' has been saved in: \n./'..adress
end
if not is_sudo(msg) then
return "only for sudo!"
end
end
end
return {
patterns = {
"^[!/#]([Ff]ile) (.*) (.*)$",
},
run = run,
}
--Created by: @lordlotter3
--Powered by: @lordandroid_bot
--⚠️CopyRight all right reserved⚠️
| gpl-2.0 |
luketwitter/cutorch | FFI.lua | 6 | 2877 | local ok, ffi = pcall(require, 'ffi')
if ok then
local unpack = unpack or table.unpack
local cdefs = [[
typedef struct CUstream_st *cudaStream_t;
struct cublasContext;
typedef struct cublasContext *cublasHandle_t;
typedef struct CUhandle_st *cublasHandle_t;
typedef struct _THCCudaResourcesPerDevice {
cudaStream_t* streams;
cublasHandle_t* blasHandles;
size_t scratchSpacePerStream;
void** devScratchSpacePerStream;
} THCCudaResourcesPerDevice;
typedef struct THCState
{
struct THCRNGState* rngState;
struct cudaDeviceProp* deviceProperties;
cudaStream_t currentStream;
cublasHandle_t currentBlasHandle;
THCCudaResourcesPerDevice* resourcesPerDevice;
int numDevices;
int numUserStreams;
int numUserBlasHandles;
int currentPerDeviceStream;
int currentPerDeviceBlasHandle;
struct THAllocator* cudaHostAllocator;
} THCState;
cudaStream_t THCState_getCurrentStream(THCState *state);
]]
local CudaTypes = {
{'float', ''},
{'unsigned char', 'Byte'},
{'char', 'Char'},
{'short', 'Short'},
{'int', 'Int'},
{'long','Long'},
{'double','Double'},
}
if cutorch.hasHalf then
table.insert(CudaTypes, {'half','Half'})
end
for _, typedata in ipairs(CudaTypes) do
local real, Real = unpack(typedata)
local ctype_def = [[
typedef struct THCStorage
{
real *data;
long size;
int refcount;
char flag;
THAllocator *allocator;
void *allocatorContext;
struct THCStorage *view;
} THCStorage;
typedef struct THCTensor
{
long *size;
long *stride;
int nDimension;
THCStorage *storage;
long storageOffset;
int refcount;
char flag;
} THCTensor;
]]
ctype_def = ctype_def:gsub('real',real):gsub('THCStorage','THCuda'..Real..'Storage'):gsub('THCTensor','THCuda'..Real..'Tensor')
cdefs = cdefs .. ctype_def
end
if cutorch.hasHalf then
ffi.cdef([[
typedef struct {
unsigned short x;
} __half;
typedef __half half;
]])
end
ffi.cdef(cdefs)
for _, typedata in ipairs(CudaTypes) do
local real, Real = unpack(typedata)
local Storage = torch.getmetatable('torch.Cuda' .. Real .. 'Storage')
local Storage_tt = ffi.typeof('THCuda' .. Real .. 'Storage**')
rawset(Storage, "cdata", function(self) return Storage_tt(self)[0] end)
rawset(Storage, "data", function(self) return Storage_tt(self)[0].data end)
-- Tensor
local Tensor = torch.getmetatable('torch.Cuda' .. Real .. 'Tensor')
local Tensor_tt = ffi.typeof('THCuda' .. Real .. 'Tensor**')
rawset(Tensor, "cdata", function(self) return Tensor_tt(self)[0] end)
rawset(Tensor, "data",
function(self)
self = Tensor_tt(self)[0]
return self.storage ~= nil and self.storage.data + self.storageOffset or nil
end
)
end
end
| bsd-3-clause |
NezzKryptic/Wire-Extras | lua/weapons/gmod_tool/stools/wire_pid.lua | 4 | 5576 | TOOL.Category = "Wire Extras/Other"
TOOL.Name = "PID"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
/* Con vars for this stool */
TOOL.ClientConVar[ "pgain" ] = "0"
TOOL.ClientConVar[ "igain" ] = "0"
TOOL.ClientConVar[ "dgain" ] = "0"
TOOL.ClientConVar[ "dcut" ] = "1000"
TOOL.ClientConVar[ "ilim" ] = "1000"
TOOL.ClientConVar[ "limit" ] = "1000"
TOOL.Model = "models/jaanus/wiretool/wiretool_siren.mdl"
/* If we're running on the client, setup the description strings */
if ( CLIENT ) then
language.Add( "Tool.wire_pid.name", "PID Tool (Wire)" )
language.Add( "Tool.wire_pid.desc", "Spawns a PID Loop." )
language.Add( "Tool.wire_pid.0", "Primary: Create/Update Controller Secondary: Copy Settings" )
language.Add( "undone_Wire PID", "Undone Wire PID" )
end
function TOOL:LeftClick( trace )
/* Everything is server except the trace */
if (!SERVER) then return true end
/* Setup all of our local variables */
local ply = self:GetOwner()
local pgain = self:GetClientNumber("pgain")
local igain = self:GetClientNumber("igain")
local dgain = self:GetClientNumber("dgain")
local dcut = self:GetClientNumber("dcut")
local ilim = self:GetClientNumber("ilim")
local limit = self:GetClientNumber("limit")
/* If we're just updating, call the PID's SetupGains and exit */
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_pid") then
trace.Entity:SetupGains(pgain, igain, dgain, dcut, ilim, limit)
return true
end
/* Don't want to put one on a player */
if (trace.Entity:IsPlayer()) then return end
/* Normal to hit surface */
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
/* Make the PID loop */
local ent = MakeWirePID(ply, self.Model, trace.HitPos, Ang, pgain, igain, dgain, dcut, ilim, limit)
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
/* Weld it to the surface, as long as it isn't the ground */
if (!trace.HitWorld) then
local const = WireLib.Weld(ent, trace.Entity, trace.PhysicsBone, true)
end
/* Add us to the undo list */
undo.Create("Wire PID")
undo.AddEntity(ent)
if (!(const == nil)) then
undo.AddEntity(const)
end
undo.SetPlayer(ply)
undo.Finish()
return true
end
function TOOL:RightClick( trace )
/* Get our player */
local ply = self:GetOwner()
/* If we hit a PID loop that's ours, get its settings and change the tool's to match */
if ( trace.Entity:IsValid() && trace.Entity:GetClass() == "gmod_wire_pid" && trace.Entity:GetPlayer() == ply ) then
local pgain, igain, dgain, dcut, ilim, limit = trace.Entity.p, trace.Entity.i, trace.Entity.d, trace.Entity.dcut, trace.Entity.ilim, trace.Entity.limit
local ply = self:GetOwner()
ply:ConCommand("wire_pid_pgain "..pgain)
ply:ConCommand("wire_pid_igain "..igain)
ply:ConCommand("wire_pid_dgain "..dgain)
ply:ConCommand("wire_pid_dcut "..dcut)
ply:ConCommand("wire_pid_ilim "..ilim)
ply:ConCommand("wire_pid_limit "..limit)
return true
end
end
if (SERVER) then
/* Makes a PID loop */
function MakeWirePID(pl, Model, Pos, Ang, p, i, d, dcut, ilim, limit, nocollide, Vel, aVel, frozen)
local ent = ents.Create("gmod_wire_pid")
ent:SetAngles(Ang)
ent:SetPos(Pos)
ent:SetModel(Model)
ent:Spawn()
ent:SetupGains(p, i, d, dcut, ilim, limit)
ent:SetPlayer(pl)
return ent
end
/* Register us for duplicator compatibility */
duplicator.RegisterEntityClass("gmod_wire_pid", MakeWirePID, "Model", "Pos", "Ang", "p", "i", "d", "dcut", "ilim", "limit", "nocollide", "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostWirePID( 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_pid" || 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:UpdateGhostWirePID( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel( panel )
panel:AddControl("Header", {
Text = "#Tool.wire_pid.name",
Description = "#Tool.wire_pid.desc"
})
panel:AddControl("Slider", {
Label = "P Gain",
Type = "Float",
Min = "0",
Max = "1000",
Command = "wire_pid_pgain"
})
panel:AddControl("Slider", {
Label = "I Gain",
Type = "Float",
Min = "0",
Max = "10",
Command = "wire_pid_igain"
})
panel:AddControl("Slider", {
Label = "D Gain",
Type = "Float",
Min = "0",
Max = "1000",
Command = "wire_pid_dgain"
})
panel:AddControl("Slider", {
Label = "D Cutoff for Integral",
Type = "Float",
Min = "0",
Max = "1000",
Command = "wire_pid_dcut"
})
panel:AddControl("Slider", {
Label = "Integral Limit",
Type = "Float",
Min = "0",
Max = "10000",
Command = "wire_pid_ilim"
})
panel:AddControl("Slider", {
Label = "Output Limit",
Type = "Float",
Min = "0",
Max = "10000",
Command = "wire_pid_limit"
})
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/bowl_of_mushroom_stew.lua | 35 | 1464 | -----------------------------------------
-- ID: 4544
-- Item: mushroom_stew
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Magic Points 40
-- Strength -1
-- Mind 4
-- MP Recovered While Healing 4
-- Enmity -4
-----------------------------------------
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,4544);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 40);
target:addMod(MOD_STR, -1);
target:addMod(MOD_MND, 4);
target:addMod(MOD_MPHEAL, 4);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 40);
target:delMod(MOD_STR, -1);
target:delMod(MOD_MND, 4);
target:delMod(MOD_MPHEAL, 4);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
dpino/snabbswitch | lib/ljsyscall/syscall/lfs.lua | 24 | 3075 | -- this is intended to be compatible with luafilesystem https://github.com/keplerproject/luafilesystem
-- currently does not implement locks
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
-- TODO allow use eg with rump kernel, needs an initialisation option
-- maybe return a table with a metatable that allows init or uses default if no init?
local S = require "syscall"
-- TODO not implemented
-- lfs.lock_dir
-- lfs.lock
-- unlock
local function lfswrap(f)
return function(...)
local ret, err = f(...)
if not ret then return nil, tostring(err) end
return ret
end
end
local lfs = {}
lfs._VERSION = "ljsyscall lfs 1"
local attributes = {
dev = "dev",
ino = "ino",
mode = "typename", -- not sure why lfs insists on calling this mode
nlink = "nlink",
uid = "uid",
gid = "gid",
rdev = "rdev",
access = "access",
modification = "modification",
change = "change",
size = "size",
blocks = "blocks",
blksize = "blksize",
}
local function attr(st, aname)
if aname then
aname = attributes[aname]
return st[aname]
end
local ret = {}
for k, v in pairs(attributes) do ret[k] = st[v] end
return ret
end
function lfs.attributes(filepath, aname)
local st, err = S.stat(filepath)
if not st then return nil, tostring(err) end
return attr(st, aname)
end
function lfs.symlinkattributes(filepath, aname)
local st, err = S.lstat(filepath)
if not st then return nil, tostring(err) end
return attr(st, aname)
end
lfs.chdir = lfswrap(S.chdir)
lfs.currentdir = lfswrap(S.getcwd)
lfs.rmdir = lfswrap(S.rmdir)
lfs.touch = lfswrap(S.utime)
function lfs.mkdir(path)
local ret, err = S.mkdir(path, "0777")
if not ret then return nil, tostring(err) end
return ret
end
local function dir_close(dir)
dir.fd:close()
dir.fd = nil
end
local function dir_next(dir)
if not dir.fd then error "dir ended" end
local d
repeat
if not dir.di then
local err
dir.di, err = dir.fd:getdents(dir.buf, dir.size)
if not dir.di then
dir_close(dir)
error(tostring(err)) -- not sure how we are suppose to handle errors
end
dir.first = true
end
d = dir.di()
if not d then
dir.di = nil
if dir.first then
dir_close(dir)
return nil
end
end
dir.first = false
until d
return d.name
end
function lfs.dir(path)
local size = 4096
local buf = S.t.buffer(size)
local fd, err = S.open(path, "directory, rdonly")
if err then return nil, tostring(err) end
return dir_next, {size = size, buf = buf, fd = fd, next = dir_next, close = dir_close}
end
local flink, fsymlink = lfswrap(S.link), lfswrap(S.symlink)
function lfs.link(old, new, symlink)
if symlink then
return fsymlink(old, new)
else
return flink(old, new)
end
end
function lfs.setmode(file, mode) return true, "binary" end
return lfs
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/spells/paralyze_ii.lua | 11 | 2285 | -----------------------------------------
-- Spell: Paralyze II
-- Spell accuracy is most highly affected by Enfeebling Magic Skill, Magic Accuracy, and MND.
-- caster:getMerit() returns a value which is equal to the number of merit points TIMES the value of each point
-- Paralyze II value per point is '1' This is a constant set in the table 'merits'
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
if(target:hasStatusEffect(EFFECT_PARALYSIS)) then --effect already on, do nothing
spell:setMsg(75);
else
-- Calculate duration.
local duration = 180;
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
-- Grabbing variables for paralyze potency
local pMND = caster:getStat(MOD_MND);
local mMND = target:getStat(MOD_MND);
local merits = caster:getMerit(MERIT_PARALYZE_II);
local dMND = (pMND - mMND);
-- Calculate potency.
local potency = (pMND + dMND)/5; --simplified from (2 * (pMND + dMND)) / 10
if (potency > 30) then
potency = 30;
end
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
potency = potency * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
potency = potency + merits; --similar to Slow II, merit potency bonus is added after the cap
--printf("Duration : %u",duration);
--printf("Potency : %u",potency);
local resist = applyResistanceEffect(caster,spell,target,dMND,35,merits*2,EFFECT_PARALYSIS);
if(resist >= 0.5) then --there are no quarter or less hits, if target resists more than .5 spell is resisted completely
if(target:addStatusEffect(EFFECT_PARALYSIS,potency,0,duration*resist)) then
spell:setMsg(236);
else
-- no effect
spell:setMsg(75);
end
else
-- resist
spell:setMsg(85);
end
end
return EFFECT_PARALYSIS;
end;
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.