repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
UnfortunateFruit/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Famad.lua | 30 | 3494 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Famad
-- Type: Assault Mission Giver
-- @pos 134.098 0.161 -43.759 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/besieged");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local rank = getMercenaryRank(player);
local haveimperialIDtag;
local assaultPoints = player:getAssaultPoint(LEBROS_ASSAULT_POINT);
if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then
haveimperialIDtag = 1;
else
haveimperialIDtag = 0;
end
if (rank > 0) then
player:startEvent(275,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault());
else
player:startEvent(281); -- no rank
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 275) then
local selectiontype = bit.band(option, 0xF);
if (selectiontype == 1) then
-- taken assault mission
player:addAssault(bit.rshift(option,4));
player:delKeyItem(IMPERIAL_ARMY_ID_TAG);
player:addKeyItem(LEBROS_ASSAULT_ORDERS);
player:messageSpecial(KEYITEM_OBTAINED,LEBROS_ASSAULT_ORDERS);
elseif (selectiontype == 2) then
-- purchased an item
local item = bit.rshift(option,14);
local itemID = 0;
local price = 0;
if (item == 1) then
itemID = 15972;
price = 3000;
elseif (item == 2) then
itemID = 15777;
price = 5000;
elseif (item == 3) then
itemID = 15523;
price = 8000;
elseif (item == 4) then
itemID = 15886;
price = 10000;
elseif (item == 5) then
itemID = 15492;
price = 10000;
elseif (item == 6) then
itemID = 18583;
price = 10000;
elseif (item == 7) then
itemID = 18388;
price = 15000;
elseif (item == 8) then
itemID = 18417;
price = 15000;
elseif (item == 9) then
itemID = 14940;
price = 15000;
elseif (item == 10) then
itemID = 15690;
price = 20000;
elseif (item == 11) then
itemID = 14525;
price = 20000;
else
return;
end
player:addItem(itemID);
player:messageSpecial(ITEM_OBTAINED,itemID);
player:delAssaultPoint(LEBROS_ASSAULT_POINT,price);
end
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Sacrarium/npcs/qm2.lua | 13 | 1803 | -----------------------------------
-- Area: Sacrarium
-- NPC: qm2 (???)
-- Notes: Used to spawn Old Prof. Mariselle
-- @pos 102.669 -3.111 127.279 28
-----------------------------------
package.loaded["scripts/zones/Sacrarium/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Sacrarium/TextIDs");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local OldProfessor = 16891970;
if (GetServerVariable("Old_Prof_Spawn_Location") == 2) then
if (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 3 and player:hasKeyItem(RELIQUIARIUM_KEY)==false and GetMobAction(OldProfessor) == 0) then
player:messageSpecial(EVIL_PRESENCE);
SpawnMob(OldProfessor,300):updateClaim(player);
GetMobByID(OldProfessor):setPos(npc:getXPos()+1, npc:getYPos(), npc:getZPos()+1); -- Set Prof. spawn x and z pos. +1 from NPC
else
player:messageSpecial(DRAWER_SHUT);
end
elseif (player:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and player:getVar("PromathiaStatus") == 4 and player:hasKeyItem(RELIQUIARIUM_KEY)==false) then
player:addKeyItem(RELIQUIARIUM_KEY);
player:messageSpecial(KEYITEM_OBTAINED,RELIQUIARIUM_KEY);
else
player:messageSpecial(DRAWER_OPEN);
player:messageSpecial(DRAWER_EMPTY);
end
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
xenodium/dotsies | hammerspoon/Spoons/Lunette.spoon/init.lua | 1 | 2343 | local obj = {}
obj.__index = obj
-- Metadata
obj.name = "Lunette"
obj.version = "0.1-beta"
obj.author = "Scott Hudson <scott.w.hudson@gmail.com>"
obj.license = "MIT"
obj.homepage = "https://github.com/scottwhudson/Lunette"
-- disable animation
hs.window.animationDuration = 0
-- Internal function used to find our location, so we know where to load files from
local function script_path()
local str = debug.getinfo(2, "S").source:sub(2)
return str:match("(.*/)")
end
obj.spoonPath = script_path()
Command = dofile(obj.spoonPath.."/command.lua")
history = dofile(obj.spoonPath.."/history.lua"):init()
DefaultMapping = {
leftHalf = {{"cmd", "alt"}, "left"},
rightHalf = {{"cmd", "alt"}, "right"},
topHalf = {{"cmd", "alt"}, "up"},
bottomHalf = {{"cmd", "alt"}, "down"},
-- topLeft = {{"ctrl", "cmd"}, "Left"},
-- topRight = {{"ctrl", "cmd"}, "Right"},
-- bottomLeft = {{"ctrl", "cmd", "shift"}, "Left"},
-- bottomRight = {{"ctrl", "cmd", "shift"}, "Right"},
-- fullScreen = {{"cmd", "alt"}, "F"},
-- center = {{"cmd", "alt"}, "C"},
-- nextThird = {{"ctrl", "alt"}, "Right"},
-- prevThird = {{"ctrl", "alt"}, "Left"},
-- enlarge = {{"ctrl", "alt", "shift"}, "Right"},
-- shrink = {{"ctrl", "alt", "shift"}, "Left"},
-- undo = {{"alt", "cmd"}, "Z"},
-- redo = {{"alt", "cmd", "shift"}, "Z"},
-- nextDisplay = {{"ctrl", "alt", "cmd"}, "Right"},
-- prevDisplay = {{"ctrl", "alt", "cmd"}, "Left"}
}
function obj:bindHotkeys(userMapping)
print("Lunette: Binding Hotkeys")
local userMapping = userMapping or {}
local mapping = DefaultMapping
for k, v in pairs(userMapping) do
mapping[k] = v
end
for k, v in pairs(mapping) do
if mapping[k] then
hs.hotkey.bind(v[1], v[2], function()
exec(k)
end)
end
end
end
function exec(commandName)
local window = hs.window.focusedWindow()
local windowFrame = window:frame()
local screen = window:screen()
local screenFrame = screen:frame()
local currentFrame = window:frame()
local newFrame
if commandName == "undo" then
newFrame = history:retrievePrevState()
elseif commandName == "redo" then
newFrame = history:retrieveNextState()
else
newFrame = Command[commandName](windowFrame, screenFrame)
history:push(currentFrame, newFrame)
end
window:setFrame(newFrame)
end
return obj
| bsd-2-clause |
dpino/snabbswitch | lib/ljndpi/ndpi/c.lua | 4 | 4682 | #! /usr/bin/env luajit
--
-- c.lua
-- Copyright (C) 2016-2017 Adrian Perez <aperez@igalia.com>
--
-- Distributed under terms of the Apache License 2.0.
--
local ffi = require "ffi"
--
-- Common definitions for all supported nDPI versions.
--
ffi.cdef [[
void* malloc(size_t size);
void free(void *ptr);
typedef enum {
NDPI_PROTOCOL_SAFE,
NDPI_PROTOCOL_ACCEPTABLE,
NDPI_PROTOCOL_FUN,
NDPI_PROTOCOL_UNSAFE,
NDPI_PROTOCOL_POTENTIALLY_DANGEROUS,
NDPI_PROTOCOL_UNRATED,
} ndpi_protocol_breed_t;
typedef struct ndpi_id_struct ndpi_id_t;
typedef struct ndpi_flow_struct ndpi_flow_t;
typedef struct ndpi_detection_module_struct ndpi_detection_module_t;
typedef struct ndpi_protocol_bitmask_struct ndpi_protocol_bitmask_t;
typedef struct { uint16_t master_protocol, protocol; } ndpi_protocol_t;
const char* ndpi_revision (void);
uint32_t ndpi_detection_get_sizeof_ndpi_flow_struct (void);
void ndpi_free_flow (ndpi_flow_t *flow);
uint32_t ndpi_detection_get_sizeof_ndpi_id_struct (void);
void ndpi_set_protocol_detection_bitmask2 (ndpi_detection_module_t *detection_module,
const ndpi_protocol_bitmask_t *bitmask);
ndpi_protocol_t ndpi_detection_process_packet (ndpi_detection_module_t *detection_module,
ndpi_flow_t *flow,
const uint8_t *packet,
unsigned short packetlen,
uint64_t current_tick,
ndpi_id_t *src,
ndpi_id_t *dst);
void ndpi_dump_protocols (ndpi_detection_module_t *detection_module);
int ndpi_load_protocols_file (ndpi_detection_module_t *detection_module,
const char *path);
ndpi_protocol_t ndpi_guess_undetected_protocol (ndpi_detection_module_t *detection_module,
uint8_t protocol,
uint32_t src_host, uint16_t src_port,
uint32_t dst_host, uint32_t dst_port);
ndpi_protocol_breed_t ndpi_get_proto_breed (ndpi_detection_module_t *detection_module,
uint16_t protocol);
const char* ndpi_get_proto_breed_name (ndpi_detection_module_t *detection_module,
ndpi_protocol_breed_t breed_id);
const char* ndpi_get_proto_name (ndpi_detection_module_t *detection_module,
uint16_t protocol_id);
int ndpi_get_protocol_id (ndpi_detection_module_t *detection_module, const char *name);
]]
local lib = ffi.load("ndpi")
local lib_version = (function ()
local string = ffi.string(lib.ndpi_revision())
local major, minor, patch = string.match(string, "^(%d+)%.(%d+)%.(%d+)")
return setmetatable({
major = tonumber(major);
minor = tonumber(minor);
patch = tonumber(patch);
}, {
__tostring = function (self) return string end;
})
end)()
-- Only nDPI 1.x versions above 1.7 are supported.
if lib_version.major ~= 1 or lib_version.minor < 7 then
error("Unsupported nDPI version: " .. tostring(lib_version))
end
if lib_version.minor == 7 then
-- nDPI 1.7
ffi.cdef [[
ndpi_detection_module_t* ndpi_init_detection_module (uint32_t ticks_per_second,
void *ndpi_malloc,
void *ndpi_free,
void *ndpi_debug);
void ndpi_exit_detection_module (ndpi_detection_module_t *detection_module,
void *ndpi_free__dummy);
ndpi_protocol_t ndpi_find_port_based_protocol (ndpi_detection_module_t *detection_module,
uint8_t protocol,
uint32_t src_host, uint16_t src_port,
uint32_t dst_host, uint32_t dst_port);
]]
elseif lib_version.minor == 8 then
-- nDPI 1.8
ffi.cdef [[
ndpi_detection_module_t* ndpi_init_detection_module (void);
void ndpi_exit_detection_module (ndpi_detection_module_t *detection_module);
ndpi_protocol_t ndpi_find_port_based_protocol (ndpi_detection_module_t *detection_module,
uint32_t src_host, uint16_t src_port,
uint32_t dst_host, uint32_t dst_port);
]]
end
return { version = lib_version, lib = lib }
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/globals/items/rabbit_pie.lua | 35 | 1859 | -----------------------------------------
-- ID: 5685
-- Item: rabbit_pie
-- Food Effect: 30minutes, All Races
-----------------------------------------
-- Strength 5
-- Vitality 5
-- Attack 25% (caps @ 100)
-- Ranged Attack 25% (caps @ 100)
-- Defense 25% (caps @ 100)
-- Intelligence -2
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5685);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 5);
target:addMod(MOD_VIT, 5);
target:addMod(MOD_FOOD_ATTP, 25);
target:addMod(MOD_FOOD_ATT_CAP, 100);
target:addMod(MOD_FOOD_RATTP, 25);
target:addMod(MOD_FOOD_RATT_CAP, 100);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 100);
target:addMod(MOD_INT, -2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 5);
target:delMod(MOD_VIT, 5);
target:delMod(MOD_FOOD_ATTP, 25);
target:delMod(MOD_FOOD_ATT_CAP, 100);
target:delMod(MOD_FOOD_RATTP, 25);
target:delMod(MOD_FOOD_RATT_CAP, 100);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 100);
target:delMod(MOD_INT, -2);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Kamihr_Drifts/npcs/LiseranDoorEntrance.lua | 16 | 1182 | -----------------------------------
-- Area: Kamihr Drifts
-- NPC: Liseran Door Entrance
-- Zones to Outer Ra'Kaznar (zone 274)
-- @zone 274
-- @pos -34.549 -181.334 -20.031
-----------------------------------
package.loaded["scripts/zones/Kamihr_Drifts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Kamihr_Drifts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0022);
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 == 0x0022 and option == 1)then
player:setPos(-39.846,-179.334,-19.921,131,274);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Chamber_of_Oracles/npcs/Pedestal_of_Water.lua | 12 | 2265 | -----------------------------------
-- Area: Chamber of Oracles
-- NPC: Pedestal of Water
-- Involved in Zilart Mission 7
-- @pos 199 -2 36 168
-------------------------------------
package.loaded["scripts/zones/Chamber_of_Oracles/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Chamber_of_Oracles/TextIDs");
-------------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ZilartStatus = player:getVar("ZilartStatus");
if(player:getCurrentMission(ZILART) == THE_CHAMBER_OF_ORACLES) then
if(player:hasKeyItem(WATER_FRAGMENT)) then
player:delKeyItem(WATER_FRAGMENT);
player:setVar("ZilartStatus",ZilartStatus + 64);
player:messageSpecial(YOU_PLACE_THE,WATER_FRAGMENT);
if(ZilartStatus == 255) then
player:startEvent(0x0001);
end
elseif (ZilartStatus == 255) then -- Execute cutscene if the player is interrupted.
player:startEvent(0x0001);
else
player:messageSpecial(IS_SET_IN_THE_PEDESTAL,WATER_FRAGMENT);
end
elseif(player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES)) then
player:messageSpecial(HAS_LOST_ITS_POWER,WATER_FRAGMENT);
else
player:messageSpecial(PLACED_INTO_THE_PEDESTAL);
end
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 == 0x0001) then
player:addTitle(LIGHTWEAVER);
player:setVar("ZilartStatus",2);
player:addKeyItem(PRISMATIC_FRAGMENT);
player:messageSpecial(KEYITEM_OBTAINED,PRISMATIC_FRAGMENT);
player:completeMission(ZILART,THE_CHAMBER_OF_ORACLES);
player:addMission(ZILART,RETURN_TO_DELKFUTTS_TOWER);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Ifrits_Cauldron/Zone.lua | 10 | 2582 | -----------------------------------
--
-- Zone: Ifrits_Cauldron (205)
--
-----------------------------------
package.loaded["scripts/zones/Ifrits_Cauldron/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local tomes = {17617263,17617264,17617265,17617266,17617267,17617268,17617269,17617270};
SetGroundsTome(tomes);
-- Mysticmaker Profblix
SetRespawnTime(17617147, 900, 10800);
UpdateTreasureSpawnPoint(17617220);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(-60.296,48.884,105.967,69);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onGameHour
-----------------------------------
function onGameHour()
local VanadielHour = VanadielHour();
local FlameSpout = 17617204;
if(VanadielHour % 3 == 0) then -- Opens flame spouts every 3 hours Vana'diel time
GetNPCByID(FlameSpout):openDoor(90); -- Ifrit's Cauldron flame spout (H-6) Map 1
GetNPCByID(FlameSpout+1):openDoor(90); -- Ifrit's Cauldron flame spout (H-6) Map 5
GetNPCByID(FlameSpout+2):openDoor(90); -- Ifrit's Cauldron flame spout (I-10) Map 8
GetNPCByID(FlameSpout+3):openDoor(90); -- Ifrit's Cauldron flame spout (E-7) Map 8
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 |
LordError/LordError1 | 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/zones/QuBia_Arena/mobs/Death_Clan_Destroyer.lua | 10 | 3599 | -----------------------------------
-- Area: QuBia_Arena
-- Mission 9-2 SANDO
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/missions");
require("scripts/zones/QuBia_Arena/TextIDs");
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobRoam
-----------------------------------
function onMobRoam(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
local allies= {{17621017,17621018,17621019,17621020,17621021,17621022,17621023,17621024,17621025,17621026},{17621031,17621032,17621033,17621034,17621035,17621036,17621037,17621038,17621039,17621040},{17621031,17621046,17621047,17621048,17621049,17621050,17621051,17621052,17621053,17621054}};
mob:setMP(9999);
if(mob:getID() == 17621027)then inst = 1
elseif(mob:getID() == 17621041) then inst = 2
elseif(mob:getID() == 17621055)then inst = 3
end
for i,v in ipairs(allies[inst]) do
-- printf("inst %u",inst);
-- printf("MP %u",mob:getMP());
if(GetMobAction(v) == 27)then
if(mob:actionQueueEmpty() == true)then
if(mob:getLocalVar("cooldown") == 0) then
mob:castSpell(8,GetMobByID(v));
mob:setLocalVar("cooldown",20);
end
elseif(mob:actionQueueEmpty() == false)then
mob:setLocalVar("cooldown",20);
end
end
end
if(mob:getLocalVar("cooldown") > 0) then
mob:setLocalVar("cooldown",mob:getLocalVar("cooldown")-1);
end
-- printf("cooldown %u",mob:getLocalVar("cooldown"));
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local mobs= {{17621017,17621018,17621019,17621020,17621021,17621022,17621023,17621024,17621025,17621026,17621027},{17621031,17621032,17621033,17621034,17621035,17621036,17621037,17621038,17621039,17621040,17621041},{17621031,17621046,17621047,17621048,17621049,17621050,17621051,17621052,17621053,17621054,17621055}};
local inst=killer:getBattlefield():getBattlefieldNumber();
mob:setLocalVar("cooldown",0);
local victory = true
for i,v in ipairs(mobs[inst]) do
local action = GetMobAction(v);
printf("action %u",action);
if not(action == 0 or (action >=21 and action <=23))then
victory = false
end
end
if victory == true then
killer:startEvent(0x7d04,0,0,4);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
printf("finishCSID: %u",csid);
printf("RESULT: %u",option);
if(csid == 0x7d04)then
if(player:getBattlefield():getBattlefieldNumber() == 1)then
SpawnMob(17621014);
SpawnMob(17621015);
SpawnMob(17621016);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-403,-201,413,58);
trion:spawn();
player:setPos(-400,-201,419,61);
elseif(player:getBattlefield():getBattlefieldNumber() == 2)then SpawnMob(17621028);
SpawnMob(17621029);
SpawnMob(17621030);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(-3,-1,4,61);
trion:spawn();
player:setPos(0,-1,10,61);
elseif(player:getBattlefield():getBattlefieldNumber() == 3)then SpawnMob(17621042);
SpawnMob(17621043);
SpawnMob(17621044);
local trion = player:getBattlefield():insertAlly(14183)
trion:setSpawn(397,198,-395,64);
trion:spawn();
player:setPos(399,198,-381,57);
end
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Xarcabard/npcs/Kaya_IM.lua | 13 | 3309 | -----------------------------------
-- Area: Xarcabard
-- NPC: Kaya, I.M.
-- Type: Outpost Conquest Guards
-- @pos 207.548 -24.795 -203.694 112
-----------------------------------
package.loaded["scripts/zones/Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Xarcabard/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VALDEAUNIA;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Vavegallet.lua | 36 | 1425 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Vavegallet
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(673);
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 |
Badboy30/badboy30 | plugins/stats.lua | 57 | 3698 | do
local NUM_MSG_MAX = 6
local TIME_CHECK = 4 -- seconds
local 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
-- Returns a table with `name` and `msgs`
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..'👤|'..user_id..'|🗣'
return user_info
end
local function chat_stats(chat_id)
-- Users on chat
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
-- Sort users by msgs number
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = ''
for k,user in pairs(users_info) do
text = text..user.name..' => '..user.msgs..'\n-----------'
end
return text
end
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
print('Service message')
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
-- Check flood
local kick = chat_del_user(chat_id , user_id, ok_cb, true)
vardump(kick)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
chat_del_user('chat#id'..msg.to.id,'user#id'..msg.from.id,ok_cb,false)
print('User '..msg.from.id..'is flooding '..msgs)
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function bot_stats()
local redis_scan = [[
local cursor = '0'
local count = 0
repeat
local r = redis.call("SCAN", cursor, "MATCH", KEYS[1])
cursor = r[1]
count = count + #r[2]
until cursor == '0'
return count]]
-- Users
local hash = 'msgs:*:'..our_id
local r = redis:eval(redis_scan, 1, hash)
local text = 'Users: '..r
hash = 'chat:*:users'
r = redis:eval(redis_scan, 1, hash)
text = text..'\nChats: '..r
return text
end
local function run(msg, matches)
if matches[1]:lower() == "stats" then
if not matches[2] then
if msg.to.type == 'chat' then
local chat_id = msg.to.id
return chat_stats(chat_id)
else
return 'Stats works only on chats'
end
end
if matches[2] == "bot" then
if not is_sudo(msg) then
return "Bot stats requires privileged user"
else
return bot_stats()
end
end
if matches[2] == "chat" then
if not is_sudo(msg) then
return "This command requires privileged user"
else
return chat_stats(matches[3])
end
end
end
end
return {
description = "Plugin to update user stats.",
usage = {
"!stats: Returns a list of Username [telegram_id]: msg_num",
"!stats chat <chat_id>: Show stats for chat_id",
"!stats bot: Shows bot stats (sudo users)"
},
patterns = {
"^!([Ss]tats)$",
"^!([Ss]tats) (chat) (%d+)",
"^!([Ss]tats) (bot)"
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fp.lua | 34 | 2568 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: West Plate
-- @pos 128 -34 20 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 24; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/pot_of_white_honey.lua | 35 | 1149 | -----------------------------------------
-- ID: 5562
-- Item: pot_of_white_honey
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Magic Regen While Healing 1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5562);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MPHEAL, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MPHEAL, 1);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/globals/items/mokusa.lua | 41 | 1064 | -----------------------------------------
-- ID: 18451
-- Item: Mokusa
-- Additional Effect: Wind Damage
-----------------------------------------
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(4,19);
local params = {};
params.bonusmab = 0;
params.includemab = false;
dmg = addBonusesAbility(player, ELE_WIND, target, dmg, params);
dmg = dmg * applyResistanceAddEffect(player,target,ELE_WIND,0);
dmg = adjustForTarget(target,dmg,ELE_WIND);
dmg = finalMagicNonSpellAdjustments(player,target,ELE_WIND,dmg);
local message = MSGBASIC_ADD_EFFECT_DMG;
if (dmg < 0) then
message = MSGBASIC_ADD_EFFECT_HEAL;
end
return SUBEFFECT_WIND_DAMAGE,message,dmg;
end
end; | gpl-3.0 |
mhmspm/z | plugins/msg-checks.lua | 15 | 11975 | --Begin msg_checks.lua By @SoLiD
local TIME_CHECK = 2
local function pre_process(msg)
local data = load_data(_config.moderation.data)
local chat = msg.to.id
local user = msg.from.id
local is_channel = msg.to.type == "channel"
local is_chat = msg.to.type == "chat"
local auto_leave = 'auto_leave_bot'
local hash = "gp_lang:"..chat
local lang = redis:get(hash)
if is_channel or is_chat then
if msg.text then
if msg.text:match("(.*)") then
if not data[tostring(msg.to.id)] and not redis:get(auto_leave) and not is_admin(msg) then
tdcli.sendMessage(msg.to.id, "", 0, "_This Is Not One Of My_ *Groups*", 0, "md")
tdcli.changeChatMemberStatus(chat, our_id, 'Left', dl_cb, nil)
end
end
end
if data[tostring(chat)] and data[tostring(chat)]['mutes'] then
mutes = data[tostring(chat)]['mutes']
else
return
end
if mutes.mute_all then
mute_all = mutes.mute_all
else
mute_all = 'no'
end
if mutes.mute_gif then
mute_gif = mutes.mute_gif
else
mute_gif = 'no'
end
if mutes.mute_photo then
mute_photo = mutes.mute_photo
else
mute_photo = 'no'
end
if mutes.mute_sticker then
mute_sticker = mutes.mute_sticker
else
mute_sticker = 'no'
end
if mutes.mute_contact then
mute_contact = mutes.mute_contact
else
mute_contact = 'no'
end
if mutes.mute_inline then
mute_inline = mutes.mute_inline
else
mute_inline = 'no'
end
if mutes.mute_game then
mute_game = mutes.mute_game
else
mute_game = 'no'
end
if mutes.mute_text then
mute_text = mutes.mute_text
else
mute_text = 'no'
end
if mutes.mute_keyboard then
mute_keyboard = mutes.mute_keyboard
else
mute_keyboard = 'no'
end
if mutes.mute_forward then
mute_forward = mutes.mute_forward
else
mute_forward = 'no'
end
if mutes.mute_location then
mute_location = mutes.mute_location
else
mute_location = 'no'
end
if mutes.mute_document then
mute_document = mutes.mute_document
else
mute_document = 'no'
end
if mutes.mute_voice then
mute_voice = mutes.mute_voice
else
mute_voice = 'no'
end
if mutes.mute_audio then
mute_audio = mutes.mute_audio
else
mute_audio = 'no'
end
if mutes.mute_video then
mute_video = mutes.mute_video
else
mute_video = 'no'
end
if mutes.mute_tgservice then
mute_tgservice = mutes.mute_tgservice
else
mute_tgservice = 'no'
end
if data[tostring(chat)] and data[tostring(chat)]['settings'] then
settings = data[tostring(chat)]['settings']
else
return
end
if settings.lock_link then
lock_link = settings.lock_link
else
lock_link = 'no'
end
if settings.lock_tag then
lock_tag = settings.lock_tag
else
lock_tag = 'no'
end
if settings.lock_pin then
lock_pin = settings.lock_pin
else
lock_pin = 'no'
end
if settings.lock_arabic then
lock_arabic = settings.lock_arabic
else
lock_arabic = 'no'
end
if settings.lock_mention then
lock_mention = settings.lock_mention
else
lock_mention = 'no'
end
if settings.lock_edit then
lock_edit = settings.lock_edit
else
lock_edit = 'no'
end
if settings.lock_spam then
lock_spam = settings.lock_spam
else
lock_spam = 'no'
end
if settings.flood then
lock_flood = settings.flood
else
lock_flood = 'no'
end
if settings.lock_markdown then
lock_markdown = settings.lock_markdown
else
lock_markdown = 'no'
end
if settings.lock_webpage then
lock_webpage = settings.lock_webpage
else
lock_webpage = 'no'
end
if msg.adduser or msg.joinuser or msg.deluser then
if mute_tgservice == "yes" then
del_msg(chat, tonumber(msg.id))
end
end
if msg.pinned and is_channel then
if lock_pin == "yes" then
if is_owner(msg) then
return
end
if tonumber(msg.from.id) == our_id then
return
end
local pin_msg = data[tostring(chat)]['pin']
if pin_msg then
tdcli.pinChannelMessage(msg.to.id, pin_msg, 1)
elseif not pin_msg then
tdcli.unpinChannelMessage(msg.to.id)
end
if lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>شما اجازه دسترسی به سنجاق پیام را ندارید، به همین دلیل پیام قبلی مجدد سنجاق میگردد</i>', 0, "html")
elseif not lang then
tdcli.sendMessage(msg.to.id, msg.id, 0, '<b>User ID :</b> <code>'..msg.from.id..'</code>\n<b>Username :</b> '..('@'..msg.from.username or '<i>No Username</i>')..'\n<i>You Have Not Permission To Pin Message, Last Message Has Been Pinned Again</i>', 0, "html")
end
end
end
if not is_mod(msg) then
if msg.edited and lock_edit == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.forward_info_ and mute_forward == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.photo_ and mute_photo == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.video_ and mute_video == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.document_ and mute_document == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.sticker_ and mute_sticker == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.animation_ and mute_gif == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.contact_ and mute_contact == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.location_ and mute_location == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.voice_ and mute_voice == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_ and mute_keyboard == "yes" then
if msg.reply_markup_ and msg.reply_markup_.ID == "ReplyMarkupInlineKeyboard" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if tonumber(msg.via_bot_user_id_) ~= 0 and mute_inline == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.game_ and mute_game == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.audio_ and mute_audio == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.media.caption then
local link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.media.caption:match("[Tt].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_caption
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_caption = msg.media.caption:match("@") or msg.media.caption:match("#")
if tag_caption and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.media.caption) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_caption = msg.media.caption:match("[\216-\219][\128-\191]")
if arabic_caption and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.text then
local _nl, ctrl_chars = string.gsub(msg.text, '%c', '')
local _nl, real_digits = string.gsub(msg.text, '%d', '')
if lock_spam == "yes" then
if string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
local link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Dd][Oo][Gg]/") or msg.text:match("[Tt].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/")
if link_msg
and lock_link == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local tag_msg = msg.text:match("@") or msg.text:match("#")
if tag_msg and lock_tag == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if is_filter(msg, msg.text) then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
local arabic_msg = msg.text:match("[\216-\219][\128-\191]")
if arabic_msg and lock_arabic == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.text:match("(.*)")
and mute_text == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if mute_all == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
if msg.content_.entities_ and msg.content_.entities_[0] then
if msg.content_.entities_[0].ID == "MessageEntityMentionName" then
if lock_mention == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityUrl" or msg.content_.entities_[0].ID == "MessageEntityTextUrl" then
if lock_webpage == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
if msg.content_.entities_[0].ID == "MessageEntityBold" or msg.content_.entities_[0].ID == "MessageEntityCode" or msg.content_.entities_[0].ID == "MessageEntityPre" or msg.content_.entities_[0].ID == "MessageEntityItalic" then
if lock_markdown == "yes" then
if is_channel then
del_msg(chat, tonumber(msg.id))
elseif is_chat then
kick_user(user, chat)
end
end
end
end
if msg.to.type ~= 'pv' then
if lock_flood == "yes" then
local hash = 'user:'..user..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local NUM_MSG_MAX = 5
if data[tostring(chat)] then
if data[tostring(chat)]['settings']['num_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(chat)]['settings']['num_msg_max'])
end
end
if msgs > NUM_MSG_MAX then
if is_mod(msg) then
return
end
if msg.adduser and msg.from.id then
return
end
if msg.from.username then
user_name = "@"..msg.from.username
else
user_name = msg.from.first_name
end
if redis:get('sender:'..user..':flood') then
return
else
del_msg(chat, msg.id)
kick_user(user, chat)
if not lang then
tdcli.sendMessage(chat, msg.id, 0, "_User_ "..user_name.." `[ "..user.." ]` _has been_ *kicked* _because of_ *flooding*", 0, "md")
elseif lang then
tdcli.sendMessage(chat, msg.id, 0, "_کاربر_ "..user_name.." `[ "..user.." ]` _به دلیل ارسال پیام های مکرر اخراج شد_", 0, "md")
end
redis:setex('sender:'..user..':flood', 30, true)
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
end
end
end
end
return {
patterns = {},
pre_process = pre_process
}
--End msg_checks.lua--
| gpl-3.0 |
olark/kubernetes-contrib | ingress/controllers/nginx/lua/error_page.lua | 45 | 1661 | http = require "resty.http"
def_backend = "upstream-default-backend"
local concat = table.concat
local upstream = require "ngx.upstream"
local get_servers = upstream.get_servers
local get_upstreams = upstream.get_upstreams
local random = math.random
local us = get_upstreams()
function openURL(status)
local httpc = http.new()
local random_backend = get_destination()
local res, err = httpc:request_uri(random_backend, {
path = "/",
method = "GET",
headers = {
["X-Code"] = status or "404",
["X-Format"] = ngx.var.httpAccept or "html",
}
})
if not res then
ngx.log(ngx.ERR, err)
ngx.exit(500)
end
if ngx.var.http_cookie then
ngx.header["Cookie"] = ngx.var.http_cookie
end
ngx.status = tonumber(status)
ngx.say(res.body)
end
function get_destination()
for _, u in ipairs(us) do
if u == def_backend then
local srvs, err = get_servers(u)
local us_table = {}
if not srvs then
return "http://127.0.0.1:8181"
else
for _, srv in ipairs(srvs) do
us_table[srv["name"]] = srv["weight"]
end
end
local destination = random_weight(us_table)
return "http://"..destination
end
end
end
function random_weight(tbl)
local total = 0
for k, v in pairs(tbl) do
total = total + v
end
local offset = random(0, total - 1)
for k1, v1 in pairs(tbl) do
if offset < v1 then
return k1
end
offset = offset - v1
end
end
| apache-2.0 |
nesstea/darkstar | scripts/zones/Phomiuna_Aqueducts/npcs/_0rp.lua | 13 | 1640 | -----------------------------------
-- Area: Phomiuna_Aqueducts
-- NPC: Oil lamp
-- @pos -60 -23 60 27
-----------------------------------
package.loaded["scripts/zones/Phomiuna_Aqueducts/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Phomiuna_Aqueducts/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local DoorOffset = npc:getID();
player:messageSpecial(LAMP_OFFSET+5); -- lighting lamp
npc:openDoor(7); -- lamp animation
local element = VanadielDayElement();
--printf("element: %u",element);
if (element == 5) then -- lightningday
if (GetNPCByID(DoorOffset-2):getAnimation() == 8) then -- lamp water open ?
GetNPCByID(DoorOffset-4):openDoor(15); -- Open Door _0rk
end
elseif (element == 1) then -- earthday
if (GetNPCByID(DoorOffset+2):getAnimation() == 8) then -- lamp earth open ?
GetNPCByID(DoorOffset-4):openDoor(15); -- Open Door _0rk
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm18.lua | 57 | 2138 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm18 (??? - Bomb Coal Fragments)
-- Involved in Quest: In Defiant Challenge
-- @pos -13.425,-1.176,191.669 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (OldSchoolG1 == false) then
if (player:hasItem(1090) == false and player:hasKeyItem(BOMB_COAL_FRAGMENT1) == false
and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then
player:addKeyItem(BOMB_COAL_FRAGMENT1);
player:messageSpecial(KEYITEM_OBTAINED,BOMB_COAL_FRAGMENT1);
end
if (player:hasKeyItem(BOMB_COAL_FRAGMENT1) and player:hasKeyItem(BOMB_COAL_FRAGMENT2) and player:hasKeyItem(BOMB_COAL_FRAGMENT3)) then
if (player:getFreeSlotsCount() >= 1) then
player:addItem(1090, 1);
player:messageSpecial(ITEM_OBTAINED, 1090);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1090);
end
end
if (player:hasItem(1090)) then
player:delKeyItem(BOMB_COAL_FRAGMENT1);
player:delKeyItem(BOMB_COAL_FRAGMENT2);
player:delKeyItem(BOMB_COAL_FRAGMENT3);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/items/sleep_bolt.lua | 26 | 1183 | -----------------------------------------
-- ID: 18149
-- Item: Sleep Bolt
-- Additional Effect: Sleep
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------
-- onAdditionalEffect Action
-----------------------------------
function onAdditionalEffect(player,target,damage)
local chance = 95;
if (target:getMainLvl() > player:getMainLvl()) then
chance = chance - 5 * (target:getMainLvl() - player:getMainLvl())
chance = utils.clamp(chance, 5, 95);
end
if (math.random(0,99) >= chance) then
return 0,0,0;
else
local duration = 25;
if (target:getMainLvl() > player:getMainLvl()) then
duration = duration - (target:getMainLvl() - player:getMainLvl())
end
duration = utils.clamp(duration,1,25);
duration = duration * applyResistanceAddEffect(player,target,ELE_LIGHT,0);
if (not target:hasStatusEffect(EFFECT_SLEEP_I)) then
target:addStatusEffect(EFFECT_SLEEP_I, 1, 0, duration);
end
return SUBEFFECT_SLEEP, MSGBASIC_ADD_EFFECT_STATUS, EFFECT_SLEEP_I;
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Dynamis-Bastok/bcnms/dynamis_bastok.lua | 22 | 1313 | -----------------------------------
-- Area: Dynamis Bastok
-- Name: Dynamis Bastok
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[DynaBastok]UniqueID",player:getDynamisUniqueID(1280));
SetServerVariable("[DynaBastok]Boss_Trigger",0);
SetServerVariable("[DynaBastok]Already_Received",0);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("DynamisID",GetServerVariable("[DynaBastok]UniqueID"));
local realDay = os.time();
if (DYNA_MIDNIGHT_RESET == true) then
realDay = getMidnight() - 86400;
end
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then
player:setVar("dynaWaitxDay",realDay);
end
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if (leavecode == 4) then
GetNPCByID(17539323):setStatus(2);
SetServerVariable("[DynaBastok]UniqueID",0);
end
end; | gpl-3.0 |
vonflynee/opencomputersserver | world/opencomputers/a3abb948-eba5-4c6b-9388-1bb1f150ed2b/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 |
UnfortunateFruit/darkstar | scripts/zones/Southern_San_dOria/npcs/Simmie.lua | 36 | 1432 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Simmie
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Southern_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(0x2A1);
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/Southern_San_dOria/npcs/Amutiyaal.lua | 17 | 4461 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Amutiyaal
-- Warp NPC (Aht Urhgan)
-- @pos 116 0.1 84 230
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/globals/missions");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
--[[
Bitmask Designations:
Southern San d'Oria (East to West)
00001 (K-5) Daggao (Lion Springs Tavern)
00002 (J-9) Authere (a small boy under a tree to the east of the Auction House)
00004 (I-8) Rouva (under a tree in west Victory Square)
00008 (I-8) Femitte (Rouva's attache)
00010 (G-8) Deraquien (guarding entrance to Watchdog Alley)
Northern San d'Oria (South to North)
00020 (I-9) Giaunne (west of the fountain)
00040 (J-8) Anilla (north of the fountain)
00080 (J-8) Maloquedil (east of Anilla, under a tree)
00100 (H-8) Phairupegiont (north of Windurstian Consul, looking into the moat)
00200 (E-4) Bertenont (upstairs outside the Royal Armoury)
Port San d'Oria (West to East)
00400 (G-7) Perdiouvilet (Rusty Anchor Pub)
00800 (H-8) Pomilla (outside the Rusty Anchor, watching Joulet fish)
01000 (H-8) Cherlodeau (just before the docks where two fisherman are having a contest)
02000 (H-10) Parcarin (on top of the Auction House)
04000 (J-8) Rugiette (Regine's Magicmart)
Chateau d'Oraguille (East to West)
08000 (I-9) Curilla (Temple Knights' Quarters)
10000 (I-9) Halver (main room)
20000 (H-9) Rahal (Royal Knights' Quarters)
40000 (H-7) Perfaumand (guarding Prince Royal Trion I d'Oraguille's Room)
80000 (F-7) Chalvatot (Her Majesty's garden)
--]]
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
if (trade:getGil() == 300 and trade:getItemCount() == 1 and player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_COMPLETED and player:getCurrentMission(TOAU) > IMMORTAL_SENTRIES) then
-- Needs a check for at least traded an invitation card to Naja Salaheem
player:startEvent(0x0371);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local LureSandy = player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA);
local WildcatSandy = player:getVar("WildcatSandy");
if (LureSandy ~= QUEST_COMPLETED and ENABLE_TOAU == 1) then
if (LureSandy == QUEST_AVAILABLE) then
player:startEvent(0x032c);
else
if (WildcatSandy == 0) then
player:startEvent(0x032d);
elseif (player:isMaskFull(WildcatSandy,20) == true) then
player:startEvent(0x032f);
else
player:startEvent(0x032e);
end
end
elseif(player:getCurrentMission(TOAU) >= 2)then
player:startEvent(0x0370);
else
player:startEvent(0x0330);
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 == 0x032c) then
player:addQuest(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA);
player:setVar("WildcatSandy",0);
player:addKeyItem(RED_SENTINEL_BADGE);
player:messageSpecial(KEYITEM_OBTAINED,RED_SENTINEL_BADGE);
elseif(csid == 0x032f) then
player:completeQuest(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA);
player:addFame(SANDORIA,150);
player:setVar("WildcatSandy",0);
player:delKeyItem(RED_SENTINEL_BADGE);
player:addKeyItem(RED_INVITATION_CARD);
player:messageSpecial(KEYITEM_LOST,RED_SENTINEL_BADGE);
player:messageSpecial(KEYITEM_OBTAINED,RED_INVITATION_CARD);
elseif(csid == 0x0371)then
player:tradeComplete();
toAhtUrhganWhitegate(player);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/abilities/healing_waltz.lua | 10 | 1626 | -----------------------------------
-- Ability: Healing Waltz
-- Removes one detrimental status effect from target party member.
-- Obtained: Dancer Level 35
-- TP Required: 20%
-- Recast Time: 00:15
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (target:getHP() == 0) then
return MSGBASIC_CANNOT_ON_THAT_TARG,0;
elseif(player:hasStatusEffect(EFFECT_SABER_DANCE)) then
return MSGBASIC_UNABLE_TO_USE_JA2, 0;
elseif (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 20) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
-- apply waltz recast modifiers
if(player:getMod(MOD_WALTZ_RECAST)~=0) then
local recastMod = -150 * (player:getMod(MOD_WALTZ_RECAST)); -- 750 ms or 5% per merit
if(recastMod <0) then
--TODO
end
end
return 0,0;
end;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(20);
end;
local effect = target:healingWaltz();
if(effect == EFFECT_NONE) then
ability:setMsg(283); -- no effect
else
ability:setMsg(123);
end
return effect;
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Jugner_Forest_[S]/mobs/Lobison.lua | 13 | 1678 | -----------------------------------
-- Area: Jugner Forest (S)
-- NPC: Lobison
-----------------------------------
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:setLocalVar("transformTime", os.time())
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
local changeTime = mob:getLocalVar("transformTime");
local roamChance = math.random(1,100);
local roamMoonPhase = VanadielMoonPhase();
if (roamChance > 100-roamMoonPhase) then
if (mob:AnimationSub() == 0 and os.time() - changeTime > 300) then
mob:AnimationSub(1);
mob:setLocalVar("transformTime", os.time());
elseif (mob:AnimationSub() == 1 and os.time() - changeTime > 300) then
mob:AnimationSub(0);
mob:setLocalVar("transformTime", os.time());
end
end
end;
-----------------------------------
-- onMobEngaged
-- Change forms every 60 seconds
-----------------------------------
function onMobEngaged(mob,target)
local changeTime = mob:getLocalVar("changeTime");
local chance = math.random(1,100);
local moonPhase = VanadielMoonPhase();
if (chance > 100-moonPhase) then
if (mob:AnimationSub() == 0 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(1);
mob:setLocalVar("changeTime", mob:getBattleTime());
elseif (mob:AnimationSub() == 1 and mob:getBattleTime() - changeTime > 45) then
mob:AnimationSub(0);
mob:setLocalVar("changeTime", mob:getBattleTime());
end
end
end; | gpl-3.0 |
VurtualRuler98/kswep2-NWI | lua/ins_sounds/sounds_fal.lua | 1 | 1868 | if (SERVER) then
AddCSLuaFile()
end
--FnFAL
sound.Add({
name="Weapon_FnFAL.Single",
volume = 1.0,
pitch = {100,105},
sound = "weapons/FnFal/FnFAL_fp.wav",
level = 156,
channel = CHAN_STATIC
})
sound.Add({
name="Weapon_FnFAL.SingleSilenced",
volume = 1.0,
pitch = {100,105},
sound = "weapons/FnFal/FnFAL_suppressed_fp.wav",
level = 140,
channel = CHAN_STATIC
})
sound.Add({
name="Weapon_FnFAL.Magrelease",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_magrelease.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.MagHitrelease",
volume = 0.3,
sound = "weapons/FnFal/handling/fnfal_maghitrelease.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Magin",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_magin.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Magout",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_magout.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Boltback",
volume = 0.3,
sound = "weapons/FnFal/handling/fnfal_boltback.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Boltrelease",
volume = 0.3,
sound = "weapons/FnFal/handling/fnfal_boltrelease.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Hit",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_hit.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.MagoutRattle",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_magout_rattle.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.Rattle",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_rattle.wav",
level = 65,
channel = CHAN_ITEM
})
sound.Add({
name="Weapon_FnFAL.ROF",
volume = 0.2,
sound = "weapons/FnFal/handling/fnfal_fireselect_1.wav",
level = 65,
channel = CHAN_ITEM
})
| apache-2.0 |
jj918160/cocos2d-x-samples | samples/FantasyWarrior3D/src/cocos/cocos2d/DeprecatedCocos2dFunc.lua | 94 | 39158 |
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of CCDirector will be deprecated,begin
local CCDirectorDeprecated = { }
function CCDirectorDeprecated.sharedDirector()
deprecatedTip("CCDirector:sharedDirector","cc.Director:getInstance")
return cc.Director:getInstance()
end
CCDirector.sharedDirector = CCDirectorDeprecated.sharedDirector
--functions of CCDirector will be deprecated,end
--functions of CCTextureCache will be deprecated begin
local TextureCacheDeprecated = {}
function TextureCacheDeprecated.getInstance(self)
deprecatedTip("cc.TextureCache:getInstance","cc.Director:getInstance():getTextureCache")
return cc.Director:getInstance():getTextureCache()
end
cc.TextureCache.getInstance = TextureCacheDeprecated.getInstance
function TextureCacheDeprecated.destroyInstance(self)
deprecatedTip("cc.TextureCache:destroyInstance","cc.Director:getInstance():destroyTextureCache")
return cc.Director:getInstance():destroyTextureCache()
end
cc.TextureCache.destroyInstance = TextureCacheDeprecated.destroyInstance
function TextureCacheDeprecated.dumpCachedTextureInfo(self)
deprecatedTip("self:dumpCachedTextureInfo","self:getCachedTextureInfo")
return print(self:getCachedTextureInfo())
end
cc.TextureCache.dumpCachedTextureInfo = TextureCacheDeprecated.dumpCachedTextureInfo
local CCTextureCacheDeprecated = { }
function CCTextureCacheDeprecated.sharedTextureCache()
deprecatedTip("CCTextureCache:sharedTextureCache","CCTextureCache:getInstance")
return cc.TextureCache:getInstance()
end
rawset(CCTextureCache,"sharedTextureCache",CCTextureCacheDeprecated.sharedTextureCache)
function CCTextureCacheDeprecated.purgeSharedTextureCache()
deprecatedTip("CCTextureCache:purgeSharedTextureCache","CCTextureCache:destroyInstance")
return cc.TextureCache:destroyInstance()
end
rawset(CCTextureCache,"purgeSharedTextureCache",CCTextureCacheDeprecated.purgeSharedTextureCache)
function CCTextureCacheDeprecated.addUIImage(self, image, key)
deprecatedTip("CCTextureCache:addUIImage","CCTextureCache:addImage")
return self:addImage(image,key)
end
CCTextureCache.addUIImage = CCTextureCacheDeprecated.addUIImage
--functions of CCTextureCache will be deprecated end
--functions of CCAnimation will be deprecated begin
local CCAnimationDeprecated = {}
function CCAnimationDeprecated.addSpriteFrameWithFileName(self,...)
deprecatedTip("CCAnimationDeprecated:addSpriteFrameWithFileName","cc.Animation:addSpriteFrameWithFile")
return self:addSpriteFrameWithFile(...)
end
CCAnimation.addSpriteFrameWithFileName = CCAnimationDeprecated.addSpriteFrameWithFileName
--functions of CCAnimation will be deprecated end
--functions of CCAnimationCache will be deprecated begin
local CCAnimationCacheDeprecated = { }
function CCAnimationCacheDeprecated.sharedAnimationCache()
deprecatedTip("CCAnimationCache:sharedAnimationCache","CCAnimationCache:getInstance")
return CCAnimationCache:getInstance()
end
CCAnimationCache.sharedAnimationCache = CCAnimationCacheDeprecated.sharedAnimationCache
function CCAnimationCacheDeprecated.purgeSharedAnimationCache()
deprecatedTip("CCAnimationCache:purgeSharedAnimationCache","CCAnimationCache:destroyInstance")
return CCAnimationCache:destroyInstance()
end
CCAnimationCache.purgeSharedAnimationCache = CCAnimationCacheDeprecated.purgeSharedAnimationCache
function CCAnimationCacheDeprecated.addAnimationsWithFile(self,...)
deprecatedTip("CCAnimationCache:addAnimationsWithFile","cc.AnimationCache:addAnimations")
return self:addAnimations(...)
end
CCAnimationCache.addAnimationsWithFile = CCAnimationCacheDeprecated.addAnimationsWithFile
function CCAnimationCacheDeprecated.animationByName(self,...)
deprecatedTip("CCAnimationCache:animationByName","cc.AnimationCache:getAnimation")
return self:getAnimation(...)
end
CCAnimationCache.animationByName = CCAnimationCacheDeprecated.animationByName
function CCAnimationCacheDeprecated.removeAnimationByName(self)
deprecatedTip("CCAnimationCache:removeAnimationByName","cc.AnimationCache:removeAnimation")
return self:removeAnimation()
end
CCAnimationCache.removeAnimationByName = CCAnimationCacheDeprecated.removeAnimationByName
--functions of CCAnimationCache will be deprecated end
--functions of CCFileUtils will be deprecated end
local CCFileUtilsDeprecated = { }
function CCFileUtilsDeprecated.sharedFileUtils()
deprecatedTip("CCFileUtils:sharedFileUtils","CCFileUtils:getInstance")
return cc.FileUtils:getInstance()
end
CCFileUtils.sharedFileUtils = CCFileUtilsDeprecated.sharedFileUtils
function CCFileUtilsDeprecated.purgeFileUtils()
deprecatedTip("CCFileUtils:purgeFileUtils","CCFileUtils:destroyInstance")
return cc.FileUtils:destroyInstance()
end
CCFileUtils.purgeFileUtils = CCFileUtilsDeprecated.purgeFileUtils
--functions of CCFileUtils will be deprecated end
--functions of CCMenu will be deprecated begin
local CCMenuDeprecated = { }
function CCMenuDeprecated.createWithItem(self,...)
deprecatedTip("CCMenuDeprecated:createWithItem","cc.Menu:createWithItem")
return self:create(...)
end
CCMenu.createWithItem = CCMenuDeprecated.createWithItem
function CCMenuDeprecated.setHandlerPriority(self)
print("\n********** \n".."setHandlerPriority was deprecated in 3.0. \n**********")
end
CCMenu.setHandlerPriority = CCMenuDeprecated.setHandlerPriority
--functions of CCMenu will be deprecated end
--functions of CCNode will be deprecated begin
local CCNodeDeprecated = { }
function CCNodeDeprecated.boundingBox(self)
deprecatedTip("CCNode:boundingBox","cc.Node:getBoundingBox")
return self:getBoundingBox()
end
CCNode.boundingBox = CCNodeDeprecated.boundingBox
function CCNodeDeprecated.numberOfRunningActions(self)
deprecatedTip("CCNode:numberOfRunningActions","cc.Node:getNumberOfRunningActions")
return self:getNumberOfRunningActions()
end
CCNode.numberOfRunningActions = CCNodeDeprecated.numberOfRunningActions
function CCNodeDeprecated.removeFromParentAndCleanup(self,...)
deprecatedTip("CCNode:removeFromParentAndCleanup","cc.Node:removeFromParent")
return self:removeFromParent(...)
end
CCNode.removeFromParentAndCleanup = CCNodeDeprecated.removeFromParentAndCleanup
--functions of CCNode will be deprecated end
--CCDrawPrimitives will be deprecated begin
local function CCDrawPrimitivesClassDeprecated()
deprecatedTip("CCDrawPrimitives","cc.DrawPrimitives")
return cc.DrawPrimitives
end
_G.CCDrawPrimitives = CCDrawPrimitivesClassDeprecated()
--functions of CCDrawPrimitives will be deprecated begin
local CCDrawPrimitivesDeprecated = { }
function CCDrawPrimitivesDeprecated.ccDrawPoint(pt)
deprecatedTip("ccDrawPoint","cc.DrawPrimitives.drawPoint")
return cc.DrawPrimitives.drawPoint(pt)
end
_G.ccDrawPoint = CCDrawPrimitivesDeprecated.ccDrawPoint
function CCDrawPrimitivesDeprecated.ccDrawLine(origin,destination)
deprecatedTip("ccDrawLine","cc.DrawPrimitives.drawLine")
return cc.DrawPrimitives.drawLine(origin,destination)
end
_G.ccDrawLine = CCDrawPrimitivesDeprecated.ccDrawLine
function CCDrawPrimitivesDeprecated.ccDrawRect(origin,destination)
deprecatedTip("ccDrawRect","cc.DrawPrimitives.drawRect")
return cc.DrawPrimitives.drawRect(origin,destination)
end
_G.ccDrawRect = CCDrawPrimitivesDeprecated.ccDrawRect
function CCDrawPrimitivesDeprecated.ccDrawSolidRect(origin,destination,color)
deprecatedTip("ccDrawSolidRect","cc.DrawPrimitives.drawSolidRect")
return cc.DrawPrimitives.drawSolidRect(origin,destination,color)
end
_G.ccDrawSolidRect = CCDrawPrimitivesDeprecated.ccDrawSolidRect
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawCircle(center,radius,angle,segments,drawLineToCenter,...)
deprecatedTip("ccDrawCircle","cc.DrawPrimitives.drawCircle")
return cc.DrawPrimitives.drawCircle(center,radius,angle,segments,drawLineToCenter,...)
end
_G.ccDrawCircle = CCDrawPrimitivesDeprecated.ccDrawCircle
-- params:... may represent two param(xScale,yScale) or nil
function CCDrawPrimitivesDeprecated.ccDrawSolidCircle(center,radius,angle,segments,...)
deprecatedTip("ccDrawSolidCircle","cc.DrawPrimitives.drawSolidCircle")
return cc.DrawPrimitives.drawSolidCircle(center,radius,angle,segments,...)
end
_G.ccDrawSolidCircle = CCDrawPrimitivesDeprecated.ccDrawSolidCircle
function CCDrawPrimitivesDeprecated.ccDrawQuadBezier(origin,control,destination,segments)
deprecatedTip("ccDrawQuadBezier","cc.DrawPrimitives.drawQuadBezier")
return cc.DrawPrimitives.drawQuadBezier(origin,control,destination,segments)
end
_G.ccDrawQuadBezier = CCDrawPrimitivesDeprecated.ccDrawQuadBezier
function CCDrawPrimitivesDeprecated.ccDrawCubicBezier(origin,control1,control2,destination,segments)
deprecatedTip("ccDrawCubicBezier","cc.DrawPrimitives.drawCubicBezier")
return cc.DrawPrimitives.drawCubicBezier(origin,control1,control2,destination,segments)
end
_G.ccDrawCubicBezier = CCDrawPrimitivesDeprecated.ccDrawCubicBezier
function CCDrawPrimitivesDeprecated.ccDrawCatmullRom(arrayOfControlPoints,segments)
deprecatedTip("ccDrawCatmullRom","cc.DrawPrimitives.drawCatmullRom")
return cc.DrawPrimitives.drawCatmullRom(arrayOfControlPoints,segments)
end
_G.ccDrawCatmullRom = CCDrawPrimitivesDeprecated.ccDrawCatmullRom
function CCDrawPrimitivesDeprecated.ccDrawCardinalSpline(config,tension,segments)
deprecatedTip("ccDrawCardinalSpline","cc.DrawPrimitives.drawCardinalSpline")
return cc.DrawPrimitives.drawCardinalSpline(config,tension,segments)
end
_G.ccDrawCardinalSpline = CCDrawPrimitivesDeprecated.ccDrawCardinalSpline
function CCDrawPrimitivesDeprecated.ccDrawColor4B(r,g,b,a)
deprecatedTip("ccDrawColor4B","cc.DrawPrimitives.drawColor4B")
return cc.DrawPrimitives.drawColor4B(r,g,b,a)
end
_G.ccDrawColor4B = CCDrawPrimitivesDeprecated.ccDrawColor4B
function CCDrawPrimitivesDeprecated.ccDrawColor4F(r,g,b,a)
deprecatedTip("ccDrawColor4F","cc.DrawPrimitives.drawColor4F")
return cc.DrawPrimitives.drawColor4F(r,g,b,a)
end
_G.ccDrawColor4F = CCDrawPrimitivesDeprecated.ccDrawColor4F
function CCDrawPrimitivesDeprecated.ccPointSize(pointSize)
deprecatedTip("ccPointSize","cc.DrawPrimitives.setPointSize")
return cc.DrawPrimitives.setPointSize(pointSize)
end
_G.ccPointSize = CCDrawPrimitivesDeprecated.ccPointSize
--functions of CCDrawPrimitives will be deprecated end
--CCDrawPrimitives will be deprecated end
local CCProgressTimerDeprecated = {}
function CCProgressTimerDeprecated.setReverseProgress(self,...)
deprecatedTip("CCProgressTimer","CCProgressTimer:setReverseDirection")
return self:setReverseDirection(...)
end
CCProgressTimer.setReverseProgress = CCProgressTimerDeprecated.setReverseProgress
--functions of CCSpriteFrameCache will be deprecated begin
local CCSpriteFrameCacheDeprecated = { }
function CCSpriteFrameCacheDeprecated.spriteFrameByName(self,szName)
deprecatedTip("CCSpriteFrameCache:spriteFrameByName","CCSpriteFrameCache:getSpriteFrameByName")
return self:getSpriteFrameByName(szName)
end
CCSpriteFrameCache.spriteFrameByName = CCSpriteFrameCacheDeprecated.spriteFrameByName
function CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:sharedSpriteFrameCache","CCSpriteFrameCache:getInstance")
return CCSpriteFrameCache:getInstance()
end
CCSpriteFrameCache.sharedSpriteFrameCache = CCSpriteFrameCacheDeprecated.sharedSpriteFrameCache
function CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache()
deprecatedTip("CCSpriteFrameCache:purgeSharedSpriteFrameCache","CCSpriteFrameCache:destroyInstance")
return CCSpriteFrameCache:destroyInstance()
end
CCSpriteFrameCache.purgeSharedSpriteFrameCache = CCSpriteFrameCacheDeprecated.purgeSharedSpriteFrameCache
function CCSpriteFrameCacheDeprecated.addSpriteFramesWithFile(self,...)
deprecatedTip("CCSpriteFrameCache:addSpriteFramesWithFile","CCSpriteFrameCache:addSpriteFrames")
return self:addSpriteFrames(...)
end
rawset(CCSpriteFrameCache,"addSpriteFramesWithFile",CCSpriteFrameCacheDeprecated.addSpriteFramesWithFile)
function CCSpriteFrameCacheDeprecated.getSpriteFrameByName(self,...)
deprecatedTip("CCSpriteFrameCache:getSpriteFrameByName","CCSpriteFrameCache:getSpriteFrame")
return self:getSpriteFrame(...)
end
CCSpriteFrameCache.getSpriteFrameByName = CCSpriteFrameCacheDeprecated.getSpriteFrameByName
--functions of CCSpriteFrameCache will be deprecated end
--functions of CCLabelAtlas will be deprecated begin
local CCLabelAtlasDeprecated = {}
function CCLabelAtlasDeprecated.create(self,...)
deprecatedTip("CCLabelAtlas:create","CCLabelAtlas:_create")
return self:_create(...)
end
CCLabelAtlas.create = CCLabelAtlasDeprecated.create
--functions of CCLabelAtlas will be deprecated end
---------------------------
--global functions wil be deprecated, begin
local function CCRectMake(x,y,width,height)
deprecatedTip("CCRectMake(x,y,width,height)","cc.rect(x,y,width,height) in lua")
return cc.rect(x,y,width,height)
end
_G.CCRectMake = CCRectMake
local function ccc3(r,g,b)
deprecatedTip("ccc3(r,g,b)","cc.c3b(r,g,b)")
return cc.c3b(r,g,b)
end
_G.ccc3 = ccc3
local function ccp(x,y)
deprecatedTip("ccp(x,y)","cc.p(x,y)")
return cc.p(x,y)
end
_G.ccp = ccp
local function CCSizeMake(width,height)
deprecatedTip("CCSizeMake(width,height)","cc.size(width,height)")
return cc.size(width,height)
end
_G.CCSizeMake = CCSizeMake
local function ccc4(r,g,b,a)
deprecatedTip("ccc4(r,g,b,a)","cc.c4b(r,g,b,a)")
return cc.c4b(r,g,b,a)
end
_G.ccc4 = ccc4
local function ccc4FFromccc3B(color3B)
deprecatedTip("ccc4FFromccc3B(color3B)","cc.c4f(color3B.r / 255.0,color3B.g / 255.0,color3B.b / 255.0,1.0)")
return cc.c4f(color3B.r/255.0, color3B.g/255.0, color3B.b/255.0, 1.0)
end
_G.ccc4FFromccc3B = ccc4FFromccc3B
local function ccc4f(r,g,b,a)
deprecatedTip("ccc4f(r,g,b,a)","cc.c4f(r,g,b,a)")
return cc.c4f(r,g,b,a)
end
_G.ccc4f = ccc4f
local function ccc4FFromccc4B(color4B)
deprecatedTip("ccc4FFromccc4B(color4B)","cc.c4f(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)")
return cc.c4f(color4B.r/255.0, color4B.g/255.0, color4B.b/255.0, color4B.a/255.0)
end
_G.ccc4FFromccc4B = ccc4FFromccc4B
local function ccc4FEqual(a,b)
deprecatedTip("ccc4FEqual(a,b)","a:equals(b)")
return a:equals(b)
end
_G.ccc4FEqual = ccc4FEqual
--global functions wil be deprecated, end
--functions of _G will be deprecated begin
local function ccpLineIntersect(a,b,c,d,s,t)
deprecatedTip("ccpLineIntersect","cc.pIsLineIntersect")
return cc.pIsLineIntersect(a,b,c,d,s,t)
end
_G.ccpLineIntersect = ccpLineIntersect
local function CCPointMake(x,y)
deprecatedTip("CCPointMake(x,y)","cc.p(x,y)")
return cc.p(x,y)
end
_G.CCPointMake = CCPointMake
local function ccpNeg(pt)
deprecatedTip("ccpNeg","cc.pSub")
return cc.pSub({x = 0,y = 0}, pt)
end
_G.ccpNeg = ccpNeg
local function ccpAdd(pt1,pt2)
deprecatedTip("ccpAdd","cc.pAdd")
return cc.pAdd(pt1,pt2)
end
_G.ccpAdd = ccpAdd
local function ccpSub(pt1,pt2)
deprecatedTip("ccpSub","cc.pSub")
return cc.pSub(pt1,pt2)
end
_G.ccpSub = ccpSub
local function ccpMult(pt,factor)
deprecatedTip("ccpMult","cc.pMul")
return cc.pMul(pt,factor)
end
_G.ccpMult = ccpMult
local function ccpMidpoint(pt1,pt2)
deprecatedTip("ccpMidpoint","cc.pMidpoint")
return cc.pMidpoint(pt1,pt2)
end
_G.ccpMidpoint = ccpMidpoint
local function ccpDot(pt1,pt2)
deprecatedTip("ccpDot","cc.pDot")
return cc.pDot(pt1,pt2)
end
_G.ccpDot = ccpDot
local function ccpCross(pt1,pt2)
deprecatedTip("ccpCross","cc.pCross")
return cc.pCross(pt1, pt2)
end
_G.ccpCross = ccpCross
local function ccpPerp(pt)
deprecatedTip("ccpPerp","cc.pPerp")
return cc.pPerp(pt)
end
_G.ccpPerp = ccpPerp
local function ccpRPerp(pt)
deprecatedTip("ccpRPerp","cc.RPerp")
return cc.RPerp(pt)
end
_G.ccpRPerp = ccpRPerp
local function ccpProject(pt1,pt2)
deprecatedTip("ccpProject","cc.pProject")
return cc.pProject(pt1,pt2)
end
_G.ccpProject = ccpProject
local function ccpRotate(pt1,pt2)
deprecatedTip("ccpRotate","cc.pRotate")
return cc.pRotate(pt1,pt2)
end
_G.ccpRotate = ccpRotate
local function ccpUnrotate(pt1,pt2)
deprecatedTip("ccpUnrotate","cc.pUnrotate")
return cc.pUnrotate(pt1,pt2)
end
_G.ccpUnrotate = ccpUnrotate
local function ccpLengthSQ(pt)
deprecatedTip("ccpLengthSQ","cc.pLengthSQ")
return cc.pLengthSQ(pt)
end
_G.ccpLengthSQ = ccpLengthSQ
local function ccpDistanceSQ(pt1,pt2)
deprecatedTip("ccpDistanceSQ","cc.pDistanceSQ")
return cc.pDistanceSQ(pt1,pt2)
end
_G.ccpDistanceSQ = ccpDistanceSQ
local function ccpLength(pt)
deprecatedTip("ccpLength","cc.pGetLength")
return cc.pGetLength(pt)
end
_G.ccpLength = ccpLength
local function ccpDistance(pt1,pt2)
deprecatedTip("ccpDistance","cc.pGetDistance")
return cc.pGetDistance(pt1, pt2)
end
_G.ccpDistance = ccpDistance
local function ccpNormalize(pt)
deprecatedTip("ccpNormalize","cc.pNormalize")
return cc.pNormalize(pt)
end
_G.ccpNormalize = ccpNormalize
local function ccpForAngle(angle)
deprecatedTip("ccpForAngle","cc.pForAngle")
return cc.pForAngle(angle)
end
_G.ccpForAngle = ccpForAngle
local function ccpToAngle(pt)
deprecatedTip("ccpToAngle","cc.pToAngleSelf")
return cc.pToAngleSelf(pt)
end
_G.ccpToAngle = ccpToAngle
local function ccpClamp(pt1,pt2,pt3)
deprecatedTip("ccpClamp","cc.pGetClampPoint")
return cc.pGetClampPoint(pt1,pt2,pt3)
end
_G.ccpClamp = ccpClamp
local function ccpFromSize(sz)
deprecatedTip("ccpFromSize(sz)","cc.pFromSize")
return cc.pFromSize(sz)
end
_G.ccpFromSize = ccpFromSize
local function ccpLerp(pt1,pt2,alpha)
deprecatedTip("ccpLerp","cc.pLerp")
return cc.pLerp(pt1,pt2,alpha)
end
_G.ccpLerp = ccpLerp
local function ccpFuzzyEqual(pt1,pt2,variance)
deprecatedTip("ccpFuzzyEqual","cc.pFuzzyEqual")
return cc.pFuzzyEqual(pt1,pt2,variance)
end
_G.ccpFuzzyEqual = ccpFuzzyEqual
local function ccpCompMult(pt1,pt2)
deprecatedTip("ccpCompMult","cc.p")
return cc.p(pt1.x * pt2.x , pt1.y * pt2.y)
end
_G.ccpCompMult = ccpCompMult
local function ccpAngleSigned(pt1,pt2)
deprecatedTip("ccpAngleSigned","cc.pGetAngle")
return cc.pGetAngle(pt1, pt2)
end
_G.ccpAngleSigned = ccpAngleSigned
local function ccpAngle(pt1,pt2)
deprecatedTip("ccpAngle","cc.pGetAngle")
return cc.pGetAngle(pt1,ptw)
end
_G.ccpAngle = ccpAngle
local function ccpRotateByAngle(pt1,pt2,angle)
deprecatedTip("ccpRotateByAngle","cc.pRotateByAngle")
return cc.pRotateByAngle(pt1, pt2, angle)
end
_G.ccpRotateByAngle = ccpRotateByAngle
local function ccpSegmentIntersect(pt1,pt2,pt3,pt4)
deprecatedTip("ccpSegmentIntersect","cc.pIsSegmentIntersect")
return cc.pIsSegmentIntersect(pt1,pt2,pt3,pt4)
end
_G.ccpSegmentIntersect = ccpSegmentIntersect
local function ccpIntersectPoint(pt1,pt2,pt3,pt4)
deprecatedTip("ccpIntersectPoint","cc.pGetIntersectPoint")
return cc.pGetIntersectPoint(pt1,pt2,pt3,pt4)
end
_G.ccpIntersectPoint = ccpIntersectPoint
local function vertex2(x,y)
deprecatedTip("vertex2(x,y)","cc.vertex2F(x,y)")
return cc.vertex2F(x,y)
end
_G.vertex2 = vertex2
local function vertex3(x,y,z)
deprecatedTip("vertex3(x,y,z)","cc.Vertex3F(x,y,z)")
return cc.Vertex3F(x,y,z)
end
_G.vertex3 = vertex3
local function tex2(u,v)
deprecatedTip("tex2(u,v)","cc.tex2f(u,v)")
return cc.tex2f(u,v)
end
_G.tex2 = tex2
local function ccc4BFromccc4F(color4F)
deprecatedTip("ccc4BFromccc4F(color4F)","Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)")
return Color4B(color4F.r * 255.0, color4F.g * 255.0, color4F.b * 255.0, color4B.a * 255.0)
end
_G.ccc4BFromccc4F = ccc4BFromccc4F
local function ccColor3BDeprecated()
deprecatedTip("ccColor3B","cc.c3b(0,0,0)")
return cc.c3b(0,0,0)
end
_G.ccColor3B = ccColor3BDeprecated
local function ccColor4BDeprecated()
deprecatedTip("ccColor4B","cc.c4b(0,0,0,0)")
return cc.c4b(0,0,0,0)
end
_G.ccColor4B = ccColor4BDeprecated
local function ccColor4FDeprecated()
deprecatedTip("ccColor4F","cc.c4f(0.0,0.0,0.0,0.0)")
return cc.c4f(0.0,0.0,0.0,0.0)
end
_G.ccColor4F = ccColor4FDeprecated
local function ccVertex2FDeprecated()
deprecatedTip("ccVertex2F","cc.vertex2F(0.0,0.0)")
return cc.vertex2F(0.0,0.0)
end
_G.ccVertex2F = ccVertex2FDeprecated
local function ccVertex3FDeprecated()
deprecatedTip("ccVertex3F","cc.Vertex3F(0.0, 0.0, 0.0)")
return cc.Vertex3F(0.0, 0.0, 0.0)
end
_G.ccVertex3F = ccVertex3FDeprecated
local function ccTex2FDeprecated()
deprecatedTip("ccTex2F","cc.tex2F(0.0, 0.0)")
return cc.tex2F(0.0, 0.0)
end
_G.ccTex2F = ccTex2FDeprecated
local function ccPointSpriteDeprecated()
deprecatedTip("ccPointSprite","cc.PointSprite(cc.vertex2F(0.0, 0.0),cc.c4b(0.0, 0.0, 0.0),0)")
return cc.PointSprite(cc.vertex2F(0.0, 0.0),cc.c4b(0.0, 0.0, 0.0),0)
end
_G.ccPointSprite = ccPointSpriteDeprecated
local function ccQuad2Deprecated()
deprecatedTip("ccQuad2","cc.Quad2(cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0))")
return cc.Quad2(cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0), cc.vertex2F(0.0, 0.0))
end
_G.ccQuad2 = ccQuad2Deprecated
local function ccQuad3Deprecated()
deprecatedTip("ccQuad3","cc.Quad3(cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0))")
return cc.Quad3(cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0), cc.Vertex3F(0.0, 0.0 ,0.0))
end
_G.ccQuad3 = ccQuad3Deprecated
local function ccV2FC4BT2FDeprecated()
deprecatedTip("ccV2F_C4B_T2F","cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0))")
return cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0))
end
_G.ccV2F_C4B_T2F = ccV2FC4BT2FDeprecated
local function ccV2FC4FT2FDeprecated()
deprecatedTip("ccV2F_C4F_T2F","cc.V2F_C4F_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0 , 0.0 , 0.0 ), cc.tex2F(0.0, 0.0))")
return cc.V2F_C4F_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0 , 0.0 , 0.0), cc.tex2F(0.0, 0.0))
end
_G.ccV2F_C4F_T2F = ccV2FC4FT2FDeprecated
local function ccV3FC4BT2FDeprecated()
deprecatedTip("ccV3F_C4B_T2F","cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0 , 0, 0 ), cc.tex2F(0.0, 0.0))")
return cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0 , 0, 0 ), cc.tex2F(0.0, 0.0))
end
_G.ccV3F_C4B_T2F = ccV3FC4BT2FDeprecated
local function ccV2FC4BT2FQuadDeprecated()
deprecatedTip("ccV2F_C4B_T2F_Quad","cc.V2F_C4B_T2F_Quad(cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)))")
return cc.V2F_C4B_T2F_Quad(cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)))
end
_G.ccV2F_C4B_T2F_Quad = ccV2FC4BT2FQuadDeprecated
local function ccV3FC4BT2FQuadDeprecated()
deprecatedTip("ccV3F_C4B_T2F_Quad","cc.V3F_C4B_T2F_Quad(_tl, _bl, _tr, _br)")
return cc.V3F_C4B_T2F_Quad(cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)), cc.V3F_C4B_T2F(cc.vertex3F(0.0, 0.0, 0.0), cc.c4b(0 , 0, 0, 0 ), cc.tex2F(0.0, 0.0)))
end
_G.ccV3F_C4B_T2F_Quad = ccV3FC4BT2FQuadDeprecated
local function ccV2FC4FT2FQuadDeprecated()
deprecatedTip("ccV2F_C4F_T2F_Quad","cc.V2F_C4F_T2F_Quad(_bl, _br, _tl, _tr)")
return cc.V2F_C4F_T2F_Quad(cc.V2F_C4F_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0, 0.0, 0.0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4F_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0, 0.0, 0.0 ), cc.tex2F(0.0, 0.0)), cc.V3F_C4B_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0, 0.0, 0.0 ), cc.tex2F(0.0, 0.0)), cc.V2F_C4F_T2F(cc.vertex2F(0.0, 0.0), cc.c4f(0.0 , 0.0, 0.0, 0.0 ), cc.tex2F(0.0, 0.0)))
end
_G.ccV2F_C4F_T2F_Quad = ccV2FC4FT2FQuadDeprecated
local function ccT2FQuadDeprecated()
deprecatedTip("ccT2F_Quad","cc.T2F_Quad(_bl, _br, _tl, _tr)")
return cc.T2F_Quad(cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0))
end
_G.ccT2F_Quad = ccT2FQuadDeprecated
local function ccAnimationFrameDataDeprecated()
deprecatedTip("ccAnimationFrameData","cc.AnimationFrameData( _texCoords, _delay, _size)")
return cc.AnimationFrameData(cc.T2F_Quad(cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0), cc.tex2F(0.0,0.0)), 0, cc.size(0,0))
end
_G.ccAnimationFrameData = ccAnimationFrameDataDeprecated
local function tex2(u,v)
deprecatedTip("tex2(u,v)","cc.tex2f(u,v)")
return cc.tex2f(u,v)
end
_G.tex2 = tex2
--functions of CCApplication will be deprecated end
local CCApplicationDeprecated = { }
function CCApplicationDeprecated.sharedApplication()
deprecatedTip("CCApplication:sharedApplication","CCApplication:getInstance")
return CCApplication:getInstance()
end
CCApplication.sharedApplication = CCApplicationDeprecated.sharedApplication
--functions of CCApplication will be deprecated end
--functions of CCDirector will be deprecated end
local CCDirectorDeprecated = { }
function CCDirectorDeprecated.sharedDirector()
deprecatedTip("CCDirector:sharedDirector","CCDirector:getInstance")
return CCDirector:getInstance()
end
CCDirector.sharedDirector = CCDirectorDeprecated.sharedDirector
--functions of CCDirector will be deprecated end
--functions of CCUserDefault will be deprecated end
local CCUserDefaultDeprecated = { }
function CCUserDefaultDeprecated.sharedUserDefault()
deprecatedTip("CCUserDefault:sharedUserDefault","CCUserDefault:getInstance")
return CCUserDefault:getInstance()
end
CCUserDefault.sharedUserDefault = CCUserDefaultDeprecated.sharedUserDefault
function CCUserDefaultDeprecated.purgeSharedUserDefault()
deprecatedTip("CCUserDefault:purgeSharedUserDefault","CCUserDefault:destroyInstance")
return CCUserDefault:destroyInstance()
end
CCUserDefault.purgeSharedUserDefault = CCUserDefaultDeprecated.purgeSharedUserDefault
--functions of CCUserDefault will be deprecated end
--functions of CCGrid3DAction will be deprecated begin
local CCGrid3DActionDeprecated = { }
function CCGrid3DActionDeprecated.vertex(self,pt)
deprecatedTip("vertex","CCGrid3DAction:getVertex")
return self:getVertex(pt)
end
CCGrid3DAction.vertex = CCGrid3DActionDeprecated.vertex
function CCGrid3DActionDeprecated.originalVertex(self,pt)
deprecatedTip("originalVertex","CCGrid3DAction:getOriginalVertex")
return self:getOriginalVertex(pt)
end
CCGrid3DAction.originalVertex = CCGrid3DActionDeprecated.originalVertex
--functions of CCGrid3DAction will be deprecated end
--functions of CCTiledGrid3DAction will be deprecated begin
local CCTiledGrid3DActionDeprecated = { }
function CCTiledGrid3DActionDeprecated.tile(self,pt)
deprecatedTip("tile","CCTiledGrid3DAction:getTile")
return self:getTile(pt)
end
CCTiledGrid3DAction.tile = CCTiledGrid3DActionDeprecated.tile
function CCTiledGrid3DActionDeprecated.originalTile(self,pt)
deprecatedTip("originalTile","CCTiledGrid3DAction:getOriginalTile")
return self:getOriginalTile(pt)
end
CCTiledGrid3DAction.originalTile = CCTiledGrid3DActionDeprecated.originalTile
--functions of CCTiledGrid3DAction will be deprecated end
--functions of CCTexture2D will be deprecated begin
local CCTexture2DDeprecated = { }
function CCTexture2DDeprecated.stringForFormat(self)
deprecatedTip("Texture2D:stringForFormat","Texture2D:getStringForFormat")
return self:getStringForFormat()
end
CCTexture2D.stringForFormat = CCTexture2DDeprecated.stringForFormat
function CCTexture2DDeprecated.bitsPerPixelForFormat(self)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat()
end
CCTexture2D.bitsPerPixelForFormat = CCTexture2DDeprecated.bitsPerPixelForFormat
function CCTexture2DDeprecated.bitsPerPixelForFormat(self,pixelFormat)
deprecatedTip("Texture2D:bitsPerPixelForFormat","Texture2D:getBitsPerPixelForFormat")
return self:getBitsPerPixelForFormat(pixelFormat)
end
CCTexture2D.bitsPerPixelForFormat = CCTexture2DDeprecated.bitsPerPixelForFormat
function CCTexture2DDeprecated.defaultAlphaPixelFormat(self)
deprecatedTip("Texture2D:defaultAlphaPixelFormat","Texture2D:getDefaultAlphaPixelFormat")
return self:getDefaultAlphaPixelFormat()
end
CCTexture2D.defaultAlphaPixelFormat = CCTexture2DDeprecated.defaultAlphaPixelFormat
--functions of CCTexture2D will be deprecated end
--functions of CCTimer will be deprecated begin
local CCTimerDeprecated = { }
function CCTimerDeprecated.timerWithScriptHandler(handler,seconds)
deprecatedTip("CCTimer:timerWithScriptHandler","CCTimer:createWithScriptHandler")
return CCTimer:createWithScriptHandler(handler,seconds)
end
CCTimer.timerWithScriptHandler = CCTimerDeprecated.timerWithScriptHandler
function CCTimerDeprecated.numberOfRunningActionsInTarget(self,target)
deprecatedTip("CCActionManager:numberOfRunningActionsInTarget","CCActionManager:getNumberOfRunningActionsInTarget")
return self:getNumberOfRunningActionsInTarget(target)
end
CCTimer.numberOfRunningActionsInTarget = CCTimerDeprecated.numberOfRunningActionsInTarget
--functions of CCTimer will be deprecated end
--functions of CCMenuItemFont will be deprecated begin
local CCMenuItemFontDeprecated = { }
function CCMenuItemFontDeprecated.fontSize()
deprecatedTip("CCMenuItemFont:fontSize","CCMenuItemFont:getFontSize")
return CCMenuItemFont:getFontSize()
end
CCMenuItemFont.fontSize = CCMenuItemFontDeprecated.fontSize
function CCMenuItemFontDeprecated.fontName()
deprecatedTip("CCMenuItemFont:fontName","CCMenuItemFont:getFontName")
return CCMenuItemFont:getFontName()
end
CCMenuItemFont.fontName = CCMenuItemFontDeprecated.fontName
function CCMenuItemFontDeprecated.fontSizeObj(self)
deprecatedTip("CCMenuItemFont:fontSizeObj","CCMenuItemFont:getFontSizeObj")
return self:getFontSizeObj()
end
CCMenuItemFont.fontSizeObj = CCMenuItemFontDeprecated.fontSizeObj
function CCMenuItemFontDeprecated.fontNameObj(self)
deprecatedTip("CCMenuItemFont:fontNameObj","CCMenuItemFont:getFontNameObj")
return self:getFontNameObj()
end
CCMenuItemFont.fontNameObj = CCMenuItemFontDeprecated.fontNameObj
--functions of CCMenuItemFont will be deprecated end
--functions of CCMenuItemToggle will be deprecated begin
local CCMenuItemToggleDeprecated = { }
function CCMenuItemToggleDeprecated.selectedItem(self)
deprecatedTip("CCMenuItemToggle:selectedItem","CCMenuItemToggle:getSelectedItem")
return self:getSelectedItem()
end
CCMenuItemToggle.selectedItem = CCMenuItemToggleDeprecated.selectedItem
--functions of CCMenuItemToggle will be deprecated end
--functions of CCTileMapAtlas will be deprecated begin
local CCTileMapAtlasDeprecated = { }
function CCTileMapAtlasDeprecated.tileAt(self,pos)
deprecatedTip("CCTileMapAtlas:tileAt","CCTileMapAtlas:getTileAt")
return self:getTileAt(pos)
end
CCTileMapAtlas.tileAt = CCTileMapAtlasDeprecated.tileAt
--functions of CCTileMapAtlas will be deprecated end
--functions of CCTMXLayer will be deprecated begin
local CCTMXLayerDeprecated = { }
function CCTMXLayerDeprecated.tileAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileAt","CCTMXLayer:getTileAt")
return self:getTileAt(tileCoordinate)
end
CCTMXLayer.tileAt = CCTMXLayerDeprecated.tileAt
function CCTMXLayerDeprecated.tileGIDAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:tileGIDAt","CCTMXLayer:getTileGIDAt")
return self:getTileGIDAt(tileCoordinate)
end
CCTMXLayer.tileGIDAt = CCTMXLayerDeprecated.tileGIDAt
function CCTMXLayerDeprecated.positionAt(self,tileCoordinate)
deprecatedTip("CCTMXLayer:positionAt","CCTMXLayer:getPositionAt")
return self:getPositionAt(tileCoordinate)
end
CCTMXLayer.positionAt = CCTMXLayerDeprecated.positionAt
function CCTMXLayerDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXLayer:propertyNamed","CCTMXLayer:getProperty")
return self:getProperty(propertyName)
end
CCTMXLayer.propertyNamed = CCTMXLayerDeprecated.propertyNamed
--functions of CCTMXLayer will be deprecated end
--functions of CCTMXTiledMap will be deprecated begin
local CCTMXTiledMapDeprecated = { }
function CCTMXTiledMapDeprecated.layerNamed(self,layerName)
deprecatedTip("CCTMXTiledMap:layerNamed","CCTMXTiledMap:getLayer")
return self:getLayer(layerName)
end
CCTMXTiledMap.layerNamed = CCTMXTiledMapDeprecated.layerNamed
function CCTMXTiledMapDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXTiledMap:propertyNamed","CCTMXTiledMap:getProperty")
return self:getProperty(propertyName)
end
CCTMXTiledMap.propertyNamed = CCTMXTiledMapDeprecated.propertyNamed
function CCTMXTiledMapDeprecated.propertiesForGID(self,GID)
deprecatedTip("CCTMXTiledMap:propertiesForGID","CCTMXTiledMap:getPropertiesForGID")
return self:getPropertiesForGID(GID)
end
CCTMXTiledMap.propertiesForGID = CCTMXTiledMapDeprecated.propertiesForGID
function CCTMXTiledMapDeprecated.objectGroupNamed(self,groupName)
deprecatedTip("CCTMXTiledMap:objectGroupNamed","CCTMXTiledMap:getObjectGroup")
return self:getObjectGroup(groupName)
end
CCTMXTiledMap.objectGroupNamed = CCTMXTiledMapDeprecated.objectGroupNamed
--functions of CCTMXTiledMap will be deprecated end
--functions of CCTMXMapInfo will be deprecated begin
local CCTMXMapInfoDeprecated = { }
function CCTMXMapInfoDeprecated.getStoringCharacters(self)
deprecatedTip("CCTMXMapInfo:getStoringCharacters","CCTMXMapInfo:isStoringCharacters")
return self:isStoringCharacters()
end
CCTMXMapInfo.getStoringCharacters = CCTMXMapInfoDeprecated.getStoringCharacters
function CCTMXMapInfoDeprecated.formatWithTMXFile(infoTable,tmxFile)
deprecatedTip("CCTMXMapInfo:formatWithTMXFile","CCTMXMapInfo:create")
return CCTMXMapInfo:create(tmxFile)
end
CCTMXMapInfo.formatWithTMXFile = CCTMXMapInfoDeprecated.formatWithTMXFile
function CCTMXMapInfoDeprecated.formatWithXML(infoTable,tmxString,resourcePath)
deprecatedTip("CCTMXMapInfo:formatWithXML","TMXMapInfo:createWithXML")
return CCTMXMapInfo:createWithXML(tmxString,resourcePath)
end
CCTMXMapInfo.formatWithXML = CCTMXMapInfoDeprecated.formatWithXML
--functions of CCTMXMapInfo will be deprecated end
--functions of CCTMXObject will be deprecated begin
local CCTMXObjectGroupDeprecated = { }
function CCTMXObjectGroupDeprecated.propertyNamed(self,propertyName)
deprecatedTip("CCTMXObjectGroup:propertyNamed","CCTMXObjectGroup:getProperty")
return self:getProperty(propertyName)
end
CCTMXObjectGroup.propertyNamed = CCTMXObjectGroupDeprecated.propertyNamed
function CCTMXObjectGroupDeprecated.objectNamed(self, objectName)
deprecatedTip("CCTMXObjectGroup:objectNamed","CCTMXObjectGroup:getObject")
return self:getObject(objectName)
end
CCTMXObjectGroup.objectNamed = CCTMXObjectGroupDeprecated.objectNamed
--functions of CCTMXObject will be deprecated end
--functions of CCRenderTexture will be deprecated begin
local CCRenderTextureDeprecated = { }
function CCRenderTextureDeprecated.newCCImage(self)
deprecatedTip("CCRenderTexture:newCCImage","CCRenderTexture:newImage")
return self:newImage()
end
CCRenderTexture.newCCImage = CCRenderTextureDeprecated.newCCImage
--functions of CCRenderTexture will be deprecated end
--functions of Sprite will be deprecated begin
local CCSpriteDeprecated = { }
function CCSpriteDeprecated.setFlipX(self,flag)
deprecatedTip("CCSpriteDeprecated:setFlipX","CCSpriteDeprecated:setFlippedX")
return self:setFlippedX(flag)
end
cc.Sprite.setFlipX = CCSpriteDeprecated.setFlipX
function CCSpriteDeprecated.setFlipY(self,flag)
deprecatedTip("CCSpriteDeprecated:setFlipY","CCSpriteDeprecated:setFlippedY")
return self:setFlippedY(flag)
end
cc.Sprite.setFlipY = CCSpriteDeprecated.setFlipY
--functions of Sprite will be deprecated end
--functions of Layer will be deprecated begin
local CCLayerDeprecated = {}
function CCLayerDeprecated.setKeypadEnabled( self, enabled)
return self:setKeyboardEnabled(enabled)
end
cc.Layer.setKeypadEnabled = CCLayerDeprecated.setKeypadEnabled
function CCLayerDeprecated.isKeypadEnabled(self)
return self:isKeyboardEnabled()
end
cc.Layer.isKeypadEnabled = CCLayerDeprecated.isKeypadEnabled
--functions of Layer will be deprecated end
--functions of cc.Node will be deprecated begin
local NodeDeprecated = { }
function NodeDeprecated.setZOrder(self,zOrder)
deprecatedTip("cc.Node:setZOrder","cc.Node:setLocalZOrder")
return self:setLocalZOrder(zOrder)
end
cc.Node.setZOrder = NodeDeprecated.setZOrder
function NodeDeprecated.getZOrder(self)
deprecatedTip("cc.Node:getZOrder","cc.Node:getLocalZOrder")
return self:getLocalZOrder()
end
cc.Node.getZOrder = NodeDeprecated.getZOrder
function NodeDeprecated.setVertexZ(self,vertexZ)
deprecatedTip("cc.Node:setVertexZ", "cc.Node:setPositionZ")
return self:setPositionZ(vertexZ)
end
cc.Node.setVertexZ = NodeDeprecated.setVertexZ
function NodeDeprecated.getVertexZ(self)
deprecatedTip("cc.Node:getVertexZ", "cc.Node:getPositionZ")
return self:getPositionZ()
end
cc.Node.getVertexZ = NodeDeprecated.getVertexZ
--functions of cc.Node will be deprecated end
--functions of cc.GLProgram will be deprecated begin
local GLProgram = { }
function GLProgram.initWithVertexShaderByteArray(self,vShaderByteArray, fShaderByteArray)
deprecatedTip("cc.GLProgram:initWithVertexShaderByteArray","cc.GLProgram:initWithByteArrays")
return self:initWithByteArrays(vShaderByteArray, fShaderByteArray)
end
cc.GLProgram.initWithVertexShaderByteArray = GLProgram.initWithVertexShaderByteArray
function GLProgram.initWithVertexShaderFilename(self,vShaderByteArray, fShaderByteArray)
deprecatedTip("cc.GLProgram:initWithVertexShaderFilename","cc.GLProgram:initWithFilenames")
return self:initWithFilenames(vShaderByteArray, fShaderByteArray)
end
cc.GLProgram.initWithVertexShaderFilename = GLProgram.initWithVertexShaderFilename
function GLProgram.addAttribute(self, attributeName, index)
deprecatedTip("cc.GLProgram:addAttribute","cc.GLProgram:bindAttribLocation")
return self:bindAttribLocation(attributeName, index)
end
cc.GLProgram.addAttribute = GLProgram.addAttribute
--functions of cc.GLProgram will be deprecated end
| mit |
dpino/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 |
nesstea/darkstar | scripts/zones/Metalworks/npcs/Lexun-Marixun_WW.lua | 13 | 5592 | -----------------------------------
-- Area: Metalworks
-- NPC: Lexun-Maxirun, W.W.
-- @pos 28 -16 28 237
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Metalworks/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
local guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border
local size = table.getn(WindInv);
local inventory = WindInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
local region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
local Menu1 = getArg1(guardnation,player);
local Menu2 = getExForceAvailable(guardnation,player);
local Menu3 = conquestRanking();
local Menu4 = getSupplyAvailable(guardnation,player);
local Menu5 = player:getNationTeleport(guardnation);
local Menu6 = getArg6(player);
local Menu7 = player:getCP();
local Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("onUpdateCSID: %u",csid);
-- printf("onUpdateOPTION: %u",option);
if (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
CPVerify = 1;
if (player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break
end
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("onFinishCSID: %u",csid);
-- printf("onFinishOPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if (option == inventory[Item]) then
if (player:getFreeSlotsCount() >= 1) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if (player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if (inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end
end
if (player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end
break
end
end
elseif (option >= 65541 and option <= 65565) then -- player chose supply quest.
local region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Stellar_Fulcrum/npcs/_4z3.lua | 36 | 1313 | -----------------------------------
-- Area: Stellar Fulcrum
-- NPC: Qe'Lov Gate
-------------------------------------
require("scripts/globals/status");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x7d03);
return 1;
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);
local pZone = player:getZoneID();
if(csid == 0x7d03 and option == 4) then
if(player:getVar(tostring(pZone) .. "_Fight") == 100) then
player:setVar("BCNM_Killed",0);
player:setVar("BCNM_Timer",0);
end
player:setVar(tostring(pZone) .. "_Runaway",1);
player:delStatusEffect(EFFECT_BATTLEFIELD);
player:setVar(tostring(pZone) .. "_Runaway",0)
end
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Mulaujeant.lua | 24 | 2325 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Mulaujeant
-- Involved in Quests: Missionary Man
-- @zone 231
-- @pos -175 0 181
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
starttime = player:getVar("MissionaryMan_date");
MissionaryManVar = player:getVar("MissionaryManVar");
if(MissionaryManVar == 2) then
player:startEvent(0x02ba,0,1146); -- Start statue creation
elseif(MissionaryManVar == 3 and (starttime == realday or player:needToZone() == true)) then
player:startEvent(0x02bb); -- During statue creation
elseif(MissionaryManVar == 3 and starttime ~= realday and player:needToZone() == false) then
player:startEvent(0x02bc); -- End of statue creation
elseif(MissionaryManVar == 4) then
player:startEvent(0x02bd); -- During quest (after creation)
else
player:startEvent(0x02b9); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x02ba) then
player:setVar("MissionaryManVar",3);
player:setVar("MissionaryMan_date", os.date("%j")); -- %M for next minute, %j for next day
player:delKeyItem(RAUTEINOTS_PARCEL);
player:needToZone(true);
elseif(csid == 0x02bc) then
player:setVar("MissionaryManVar",4);
player:setVar("MissionaryMan_date", 0);
player:addKeyItem(SUBLIME_STATUE_OF_THE_GODDESS);
player:messageSpecial(KEYITEM_OBTAINED,SUBLIME_STATUE_OF_THE_GODDESS);
end
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Woods/npcs/Pulonono.lua | 38 | 1045 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Pulonono
-- Type: VCS Chocobo Trainer
-- @zone: 241
-- @pos 130.124 -6.35 -119.341
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02e5);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Apollyon/bcnms/NW_Apollyon.lua | 13 | 1064 | -----------------------------------
-- Area: Appolyon
-- Name:
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
SetServerVariable("[NW_Apollyon]UniqueID",GenerateLimbusKey());
HideArmouryCrates(GetInstanceRegion(1290),APPOLLYON_NW_SW);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
player:setVar("limbusbitmap",0);
player:setVar("characterLimbusKey",GetServerVariable("[NW_Apollyon]UniqueID"));
player:setVar("LimbusID",1290);
player:delKeyItem(COSMOCLEANSE);
player:delKeyItem(RED_CARD);
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish
function onBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if(leavecode == 4) then
player:setPos(-668,0.1,-666);
ResetPlayerLimbusVariable(player)
end
end; | gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/libs/oUF/elements/maintank.lua | 4 | 1503 | --GLOBAL NAMESPACE
local _G = _G;
--LUA
local unpack = _G.unpack;
local select = _G.select;
local assert = _G.assert;
--BLIZZARD API
local UnitInRaid = _G.UnitInRaid;
local GetRaidRosterInfo = _G.GetRaidRosterInfo;
local UnitHasVehicleUI = _G.UnitHasVehicleUI;
local parent, ns = ...
local oUF = ns.oUF
local Update = function(self, event)
local raidID = UnitInRaid(self.unit)
if(not raidID) then return end
local maintank = self.MainTank
if(maintank.PreUpdate) then
maintank:PreUpdate()
end
local _, _, _, _, _, _, _, _, _, rinfo = GetRaidRosterInfo(raidID)
if(rinfo == 'MAINTANK' and not UnitHasVehicleUI(self.unit)) then
self.MainTank:Show()
else
self.MainTank:Hide()
end
if(maintank.PostUpdate) then
return maintank:PostUpdate(rinfo)
end
end
local Path = function(self, ...)
return (self.MainTank.Override or Update)(self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate')
end
local Enable = function(self)
local mt = self.MainTank
if(mt) then
mt.__owner = self
mt.ForceUpdate = ForceUpdate
self:RegisterEvent('GROUP_ROSTER_UPDATE', Path, true)
if(mt:IsObjectType'Texture' and not mt:GetTexture()) then
mt:SetTexture[[Interface\GROUPFRAME\UI-GROUP-MAINTANKICON]]
end
return true
end
end
local Disable = function(self)
local mt = self.MainTank
if (mt) then
self:UnregisterEvent('GROUP_ROSTER_UPDATE', Path)
end
end
oUF:AddElement('MainTank', Path, Enable, Disable)
| mit |
dpino/snabbswitch | lib/luajit/dynasm/dynasm.lua | 36 | 30989 | ------------------------------------------------------------------------------
-- DynASM. A dynamic assembler for code generation engines.
-- Originally designed and implemented for LuaJIT.
--
-- Copyright (C) 2005-2017 Mike Pall. All rights reserved.
-- See below for full copyright notice.
------------------------------------------------------------------------------
-- Application information.
local _info = {
name = "DynASM",
description = "A dynamic assembler for code generation engines",
version = "1.4.0",
vernum = 10400,
release = "2015-10-18",
author = "Mike Pall",
url = "http://luajit.org/dynasm.html",
license = "MIT",
copyright = [[
Copyright (C) 2005-2017 Mike Pall. All rights reserved.
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
[ MIT license: http://www.opensource.org/licenses/mit-license.php ]
]],
}
-- Cache library functions.
local type, pairs, ipairs = type, pairs, ipairs
local pcall, error, assert = pcall, error, assert
local _s = string
local sub, match, gmatch, gsub = _s.sub, _s.match, _s.gmatch, _s.gsub
local format, rep, upper = _s.format, _s.rep, _s.upper
local _t = table
local insert, remove, concat, sort = _t.insert, _t.remove, _t.concat, _t.sort
local exit = os.exit
local io = io
local stdin, stdout, stderr = io.stdin, io.stdout, io.stderr
------------------------------------------------------------------------------
-- Program options.
local g_opt = {}
-- Global state for current file.
local g_fname, g_curline, g_indent, g_lineno, g_synclineno, g_arch
local g_errcount = 0
-- Write buffer for output file.
local g_wbuffer, g_capbuffer
------------------------------------------------------------------------------
-- Write an output line (or callback function) to the buffer.
local function wline(line, needindent)
local buf = g_capbuffer or g_wbuffer
buf[#buf+1] = needindent and g_indent..line or line
g_synclineno = g_synclineno + 1
end
-- Write assembler line as a comment, if requestd.
local function wcomment(aline)
if g_opt.comment then
wline(g_opt.comment..aline..g_opt.endcomment, true)
end
end
-- Resync CPP line numbers.
local function wsync()
if g_synclineno ~= g_lineno and g_opt.cpp then
wline("#line "..g_lineno..' "'..g_fname..'"')
g_synclineno = g_lineno
end
end
-- Dummy action flush function. Replaced with arch-specific function later.
local function wflush(term)
end
-- Dump all buffered output lines.
local function wdumplines(out, buf)
for _,line in ipairs(buf) do
if type(line) == "string" then
assert(out:write(line, "\n"))
else
-- Special callback to dynamically insert lines after end of processing.
line(out)
end
end
end
------------------------------------------------------------------------------
-- Emit an error. Processing continues with next statement.
local function werror(msg)
error(format("%s:%s: error: %s:\n%s", g_fname, g_lineno, msg, g_curline), 0)
end
-- Emit a fatal error. Processing stops.
local function wfatal(msg)
g_errcount = "fatal"
werror(msg)
end
-- Print a warning. Processing continues.
local function wwarn(msg)
stderr:write(format("%s:%s: warning: %s:\n%s\n",
g_fname, g_lineno, msg, g_curline))
end
-- Print caught error message. But suppress excessive errors.
local function wprinterr(...)
if type(g_errcount) == "number" then
-- Regular error.
g_errcount = g_errcount + 1
if g_errcount < 21 then -- Seems to be a reasonable limit.
stderr:write(...)
elseif g_errcount == 21 then
stderr:write(g_fname,
":*: warning: too many errors (suppressed further messages).\n")
end
else
-- Fatal error.
stderr:write(...)
return true -- Stop processing.
end
end
------------------------------------------------------------------------------
-- Map holding all option handlers.
local opt_map = {}
local opt_current
-- Print error and exit with error status.
local function opterror(...)
stderr:write("dynasm.lua: ERROR: ", ...)
stderr:write("\n")
exit(1)
end
-- Get option parameter.
local function optparam(args)
local argn = args.argn
local p = args[argn]
if not p then
opterror("missing parameter for option `", opt_current, "'.")
end
args.argn = argn + 1
return p
end
------------------------------------------------------------------------------
-- Core pseudo-opcodes.
local map_coreop = {}
-- Dummy opcode map. Replaced by arch-specific map.
local map_op = {}
-- Forward declarations.
local dostmt
local readfile
------------------------------------------------------------------------------
-- Map for defines (initially empty, chains to arch-specific map).
local map_def = {}
-- Pseudo-opcode to define a substitution.
map_coreop[".define_2"] = function(params, nparams)
if not params then return nparams == 1 and "name" or "name, subst" end
local name, def = params[1], params[2] or "1"
if not match(name, "^[%a_][%w_]*$") then werror("bad or duplicate define") end
map_def[name] = def
end
map_coreop[".define_1"] = map_coreop[".define_2"]
-- Define a substitution on the command line.
function opt_map.D(args)
local namesubst = optparam(args)
local name, subst = match(namesubst, "^([%a_][%w_]*)=(.*)$")
if name then
map_def[name] = subst
elseif match(namesubst, "^[%a_][%w_]*$") then
map_def[namesubst] = "1"
else
opterror("bad define")
end
end
-- Undefine a substitution on the command line.
function opt_map.U(args)
local name = optparam(args)
if match(name, "^[%a_][%w_]*$") then
map_def[name] = nil
else
opterror("bad define")
end
end
-- Helper for definesubst.
local gotsubst
local function definesubst_one(word)
local subst = map_def[word]
if subst then gotsubst = word; return subst else return word end
end
-- Iteratively substitute defines.
local function definesubst(stmt)
-- Limit number of iterations.
for i=1,100 do
gotsubst = false
stmt = gsub(stmt, "#?[%w_]+", definesubst_one)
if not gotsubst then break end
end
if gotsubst then wfatal("recursive define involving `"..gotsubst.."'") end
return stmt
end
-- Dump all defines.
local function dumpdefines(out, lvl)
local t = {}
for name in pairs(map_def) do
t[#t+1] = name
end
sort(t)
out:write("Defines:\n")
for _,name in ipairs(t) do
local subst = map_def[name]
if g_arch then subst = g_arch.revdef(subst) end
out:write(format(" %-20s %s\n", name, subst))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Support variables for conditional assembly.
local condlevel = 0
local condstack = {}
-- Evaluate condition with a Lua expression. Substitutions already performed.
local function cond_eval(cond)
local func, err
if setfenv then
func, err = loadstring("return "..cond, "=expr")
else
-- No globals. All unknown identifiers evaluate to nil.
func, err = load("return "..cond, "=expr", "t", {})
end
if func then
if setfenv then
setfenv(func, {}) -- No globals. All unknown identifiers evaluate to nil.
end
local ok, res = pcall(func)
if ok then
if res == 0 then return false end -- Oh well.
return not not res
end
err = res
end
wfatal("bad condition: "..err)
end
-- Skip statements until next conditional pseudo-opcode at the same level.
local function stmtskip()
local dostmt_save = dostmt
local lvl = 0
dostmt = function(stmt)
local op = match(stmt, "^%s*(%S+)")
if op == ".if" then
lvl = lvl + 1
elseif lvl ~= 0 then
if op == ".endif" then lvl = lvl - 1 end
elseif op == ".elif" or op == ".else" or op == ".endif" then
dostmt = dostmt_save
dostmt(stmt)
end
end
end
-- Pseudo-opcodes for conditional assembly.
map_coreop[".if_1"] = function(params)
if not params then return "condition" end
local lvl = condlevel + 1
local res = cond_eval(params[1])
condlevel = lvl
condstack[lvl] = res
if not res then stmtskip() end
end
map_coreop[".elif_1"] = function(params)
if not params then return "condition" end
if condlevel == 0 then wfatal(".elif without .if") end
local lvl = condlevel
local res = condstack[lvl]
if res then
if res == "else" then wfatal(".elif after .else") end
else
res = cond_eval(params[1])
if res then
condstack[lvl] = res
return
end
end
stmtskip()
end
map_coreop[".else_0"] = function(params)
if condlevel == 0 then wfatal(".else without .if") end
local lvl = condlevel
local res = condstack[lvl]
condstack[lvl] = "else"
if res then
if res == "else" then wfatal(".else after .else") end
stmtskip()
end
end
map_coreop[".endif_0"] = function(params)
local lvl = condlevel
if lvl == 0 then wfatal(".endif without .if") end
condlevel = lvl - 1
end
-- Check for unfinished conditionals.
local function checkconds()
if g_errcount ~= "fatal" and condlevel ~= 0 then
wprinterr(g_fname, ":*: error: unbalanced conditional\n")
end
end
------------------------------------------------------------------------------
-- Search for a file in the given path and open it for reading.
local function pathopen(path, name)
local dirsep = package and match(package.path, "\\") and "\\" or "/"
for _,p in ipairs(path) do
local fullname = p == "" and name or p..dirsep..name
local fin = io.open(fullname, "r")
if fin then
g_fname = fullname
return fin
end
end
end
-- Include a file.
map_coreop[".include_1"] = function(params)
if not params then return "filename" end
local name = params[1]
-- Save state. Ugly, I know. but upvalues are fast.
local gf, gl, gcl, gi = g_fname, g_lineno, g_curline, g_indent
-- Read the included file.
local fatal = readfile(pathopen(g_opt.include, name) or
wfatal("include file `"..name.."' not found"))
-- Restore state.
g_synclineno = -1
g_fname, g_lineno, g_curline, g_indent = gf, gl, gcl, gi
if fatal then wfatal("in include file") end
end
-- Make .include and conditionals initially available, too.
map_op[".include_1"] = map_coreop[".include_1"]
map_op[".if_1"] = map_coreop[".if_1"]
map_op[".elif_1"] = map_coreop[".elif_1"]
map_op[".else_0"] = map_coreop[".else_0"]
map_op[".endif_0"] = map_coreop[".endif_0"]
------------------------------------------------------------------------------
-- Support variables for macros.
local mac_capture, mac_lineno, mac_name
local mac_active = {}
local mac_list = {}
-- Pseudo-opcode to define a macro.
map_coreop[".macro_*"] = function(mparams)
if not mparams then return "name [, params...]" end
-- Split off and validate macro name.
local name = remove(mparams, 1)
if not name then werror("missing macro name") end
if not (match(name, "^[%a_][%w_%.]*$") or match(name, "^%.[%w_%.]*$")) then
wfatal("bad macro name `"..name.."'")
end
-- Validate macro parameter names.
local mdup = {}
for _,mp in ipairs(mparams) do
if not match(mp, "^[%a_][%w_]*$") then
wfatal("bad macro parameter name `"..mp.."'")
end
if mdup[mp] then wfatal("duplicate macro parameter name `"..mp.."'") end
mdup[mp] = true
end
-- Check for duplicate or recursive macro definitions.
local opname = name.."_"..#mparams
if map_op[opname] or map_op[name.."_*"] then
wfatal("duplicate macro `"..name.."' ("..#mparams.." parameters)")
end
if mac_capture then wfatal("recursive macro definition") end
-- Enable statement capture.
local lines = {}
mac_lineno = g_lineno
mac_name = name
mac_capture = function(stmt) -- Statement capture function.
-- Stop macro definition with .endmacro pseudo-opcode.
if not match(stmt, "^%s*.endmacro%s*$") then
lines[#lines+1] = stmt
return
end
mac_capture = nil
mac_lineno = nil
mac_name = nil
mac_list[#mac_list+1] = opname
-- Add macro-op definition.
map_op[opname] = function(params)
if not params then return mparams, lines end
-- Protect against recursive macro invocation.
if mac_active[opname] then wfatal("recursive macro invocation") end
mac_active[opname] = true
-- Setup substitution map.
local subst = {}
for i,mp in ipairs(mparams) do subst[mp] = params[i] end
local mcom
if g_opt.maccomment and g_opt.comment then
mcom = " MACRO "..name.." ("..#mparams..")"
wcomment("{"..mcom)
end
-- Loop through all captured statements
for _,stmt in ipairs(lines) do
-- Substitute macro parameters.
local st = gsub(stmt, "[%w_]+", subst)
st = definesubst(st)
st = gsub(st, "%s*%.%.%s*", "") -- Token paste a..b.
if mcom and sub(st, 1, 1) ~= "|" then wcomment(st) end
-- Emit statement. Use a protected call for better diagnostics.
local ok, err = pcall(dostmt, st)
if not ok then
-- Add the captured statement to the error.
wprinterr(err, "\n", g_indent, "| ", stmt,
"\t[MACRO ", name, " (", #mparams, ")]\n")
end
end
if mcom then wcomment("}"..mcom) end
mac_active[opname] = nil
end
end
end
-- An .endmacro pseudo-opcode outside of a macro definition is an error.
map_coreop[".endmacro_0"] = function(params)
wfatal(".endmacro without .macro")
end
-- Dump all macros and their contents (with -PP only).
local function dumpmacros(out, lvl)
sort(mac_list)
out:write("Macros:\n")
for _,opname in ipairs(mac_list) do
local name = sub(opname, 1, -3)
local params, lines = map_op[opname]()
out:write(format(" %-20s %s\n", name, concat(params, ", ")))
if lvl > 1 then
for _,line in ipairs(lines) do
out:write(" |", line, "\n")
end
out:write("\n")
end
end
out:write("\n")
end
-- Check for unfinished macro definitions.
local function checkmacros()
if mac_capture then
wprinterr(g_fname, ":", mac_lineno,
": error: unfinished .macro `", mac_name ,"'\n")
end
end
------------------------------------------------------------------------------
-- Support variables for captures.
local cap_lineno, cap_name
local cap_buffers = {}
local cap_used = {}
-- Start a capture.
map_coreop[".capture_1"] = function(params)
if not params then return "name" end
wflush()
local name = params[1]
if not match(name, "^[%a_][%w_]*$") then
wfatal("bad capture name `"..name.."'")
end
if cap_name then
wfatal("already capturing to `"..cap_name.."' since line "..cap_lineno)
end
cap_name = name
cap_lineno = g_lineno
-- Create or continue a capture buffer and start the output line capture.
local buf = cap_buffers[name]
if not buf then buf = {}; cap_buffers[name] = buf end
g_capbuffer = buf
g_synclineno = 0
end
-- Stop a capture.
map_coreop[".endcapture_0"] = function(params)
wflush()
if not cap_name then wfatal(".endcapture without a valid .capture") end
cap_name = nil
cap_lineno = nil
g_capbuffer = nil
g_synclineno = 0
end
-- Dump a capture buffer.
map_coreop[".dumpcapture_1"] = function(params)
if not params then return "name" end
wflush()
local name = params[1]
if not match(name, "^[%a_][%w_]*$") then
wfatal("bad capture name `"..name.."'")
end
cap_used[name] = true
wline(function(out)
local buf = cap_buffers[name]
if buf then wdumplines(out, buf) end
end)
g_synclineno = 0
end
-- Dump all captures and their buffers (with -PP only).
local function dumpcaptures(out, lvl)
out:write("Captures:\n")
for name,buf in pairs(cap_buffers) do
out:write(format(" %-20s %4s)\n", name, "("..#buf))
if lvl > 1 then
local bar = rep("=", 76)
out:write(" ", bar, "\n")
for _,line in ipairs(buf) do
out:write(" ", line, "\n")
end
out:write(" ", bar, "\n\n")
end
end
out:write("\n")
end
-- Check for unfinished or unused captures.
local function checkcaptures()
if cap_name then
wprinterr(g_fname, ":", cap_lineno,
": error: unfinished .capture `", cap_name,"'\n")
return
end
for name in pairs(cap_buffers) do
if not cap_used[name] then
wprinterr(g_fname, ":*: error: missing .dumpcapture ", name ,"\n")
end
end
end
------------------------------------------------------------------------------
-- Sections names.
local map_sections = {}
-- Pseudo-opcode to define code sections.
-- TODO: Data sections, BSS sections. Needs extra C code and API.
map_coreop[".section_*"] = function(params)
if not params then return "name..." end
if #map_sections > 0 then werror("duplicate section definition") end
wflush()
for sn,name in ipairs(params) do
local opname = "."..name.."_0"
if not match(name, "^[%a][%w_]*$") or
map_op[opname] or map_op["."..name.."_*"] then
werror("bad section name `"..name.."'")
end
map_sections[#map_sections+1] = name
wline(format("#define DASM_SECTION_%s\t%d", upper(name), sn-1))
map_op[opname] = function(params) g_arch.section(sn-1) end
end
wline(format("#define DASM_MAXSECTION\t\t%d", #map_sections))
end
-- Dump all sections.
local function dumpsections(out, lvl)
out:write("Sections:\n")
for _,name in ipairs(map_sections) do
out:write(format(" %s\n", name))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Replacement for customized Lua, which lacks the package library.
local prefix = ""
if not require then
function require(name)
local fp = assert(io.open(prefix..name..".lua"))
local s = fp:read("*a")
assert(fp:close())
return assert(loadstring(s, "@"..name..".lua"))()
end
end
-- Load architecture-specific module.
local function loadarch(arch)
if not match(arch, "^[%w_]+$") then return "bad arch name" end
local ok, m_arch = pcall(require, "dasm_"..arch)
if not ok then return "cannot load module: "..m_arch end
g_arch = m_arch
wflush = m_arch.passcb(wline, werror, wfatal, wwarn)
m_arch.setup(arch, g_opt)
map_op, map_def = m_arch.mergemaps(map_coreop, map_def)
end
-- Dump architecture description.
function opt_map.dumparch(args)
local name = optparam(args)
if not g_arch then
local err = loadarch(name)
if err then opterror(err) end
end
local t = {}
for name in pairs(map_coreop) do t[#t+1] = name end
for name in pairs(map_op) do t[#t+1] = name end
sort(t)
local out = stdout
local _arch = g_arch._info
out:write(format("%s version %s, released %s, %s\n",
_info.name, _info.version, _info.release, _info.url))
g_arch.dumparch(out)
local pseudo = true
out:write("Pseudo-Opcodes:\n")
for _,sname in ipairs(t) do
local name, nparam = match(sname, "^(.+)_([0-9%*])$")
if name then
if pseudo and sub(name, 1, 1) ~= "." then
out:write("\nOpcodes:\n")
pseudo = false
end
local f = map_op[sname]
local s
if nparam ~= "*" then nparam = nparam + 0 end
if nparam == 0 then
s = ""
elseif type(f) == "string" then
s = map_op[".template__"](nil, f, nparam)
else
s = f(nil, nparam)
end
if type(s) == "table" then
for _,s2 in ipairs(s) do
out:write(format(" %-12s %s\n", name, s2))
end
else
out:write(format(" %-12s %s\n", name, s))
end
end
end
out:write("\n")
exit(0)
end
-- Pseudo-opcode to set the architecture.
-- Only initially available (map_op is replaced when called).
map_op[".arch_1"] = function(params)
if not params then return "name" end
local err = loadarch(params[1])
if err then wfatal(err) end
wline(format("#if DASM_VERSION != %d", _info.vernum))
wline('#error "Version mismatch between DynASM and included encoding engine"')
wline("#endif")
end
-- Dummy .arch pseudo-opcode to improve the error report.
map_coreop[".arch_1"] = function(params)
if not params then return "name" end
wfatal("duplicate .arch statement")
end
------------------------------------------------------------------------------
-- Dummy pseudo-opcode. Don't confuse '.nop' with 'nop'.
map_coreop[".nop_*"] = function(params)
if not params then return "[ignored...]" end
end
-- Pseudo-opcodes to raise errors.
map_coreop[".error_1"] = function(params)
if not params then return "message" end
werror(params[1])
end
map_coreop[".fatal_1"] = function(params)
if not params then return "message" end
wfatal(params[1])
end
-- Dump all user defined elements.
local function dumpdef(out)
local lvl = g_opt.dumpdef
if lvl == 0 then return end
dumpsections(out, lvl)
dumpdefines(out, lvl)
if g_arch then g_arch.dumpdef(out, lvl) end
dumpmacros(out, lvl)
dumpcaptures(out, lvl)
end
------------------------------------------------------------------------------
-- Helper for splitstmt.
local splitlvl
local function splitstmt_one(c)
if c == "(" then
splitlvl = ")"..splitlvl
elseif c == "[" then
splitlvl = "]"..splitlvl
elseif c == "{" then
splitlvl = "}"..splitlvl
elseif c == ")" or c == "]" or c == "}" then
if sub(splitlvl, 1, 1) ~= c then werror("unbalanced (), [] or {}") end
splitlvl = sub(splitlvl, 2)
elseif splitlvl == "" then
return " \0 "
end
return c
end
-- Split statement into (pseudo-)opcode and params.
local function splitstmt(stmt)
-- Convert label with trailing-colon into .label statement.
local label = match(stmt, "^%s*(.+):%s*$")
if label then return ".label", {label} end
-- Split at commas and equal signs, but obey parentheses and brackets.
splitlvl = ""
stmt = gsub(stmt, "[,%(%)%[%]{}]", splitstmt_one)
if splitlvl ~= "" then werror("unbalanced () or []") end
-- Split off opcode.
local op, other = match(stmt, "^%s*([^%s%z]+)%s*(.*)$")
if not op then werror("bad statement syntax") end
-- Split parameters.
local params = {}
for p in gmatch(other, "%s*(%Z+)%z?") do
params[#params+1] = gsub(p, "%s+$", "")
end
if #params > 16 then werror("too many parameters") end
params.op = op
return op, params
end
-- Process a single statement.
dostmt = function(stmt)
-- Ignore empty statements.
if match(stmt, "^%s*$") then return end
-- Capture macro defs before substitution.
if mac_capture then return mac_capture(stmt) end
stmt = definesubst(stmt)
-- Emit C code without parsing the line.
if sub(stmt, 1, 1) == "|" then
local tail = sub(stmt, 2)
wflush()
if sub(tail, 1, 2) == "//" then wcomment(tail) else wline(tail, true) end
return
end
-- Split into (pseudo-)opcode and params.
local op, params = splitstmt(stmt)
-- Get opcode handler (matching # of parameters or generic handler).
local f = map_op[op.."_"..#params] or map_op[op.."_*"]
if not f then
if not g_arch then wfatal("first statement must be .arch") end
-- Improve error report.
for i=0,9 do
if map_op[op.."_"..i] then
werror("wrong number of parameters for `"..op.."'")
end
end
werror("unknown statement `"..op.."'")
end
-- Call opcode handler or special handler for template strings.
if type(f) == "string" then
map_op[".template__"](params, f)
else
f(params)
end
end
-- Process a single line.
local function doline(line)
if g_opt.flushline then wflush() end
-- Assembler line?
local indent, aline = match(line, "^(%s*)%|(.*)$")
if not aline then
-- No, plain C code line, need to flush first.
wflush()
wsync()
wline(line, false)
return
end
g_indent = indent -- Remember current line indentation.
-- Emit C code (even from macros). Avoids echo and line parsing.
if sub(aline, 1, 1) == "|" then
if not mac_capture then
wsync()
elseif g_opt.comment then
wsync()
wcomment(aline)
end
dostmt(aline)
return
end
-- Echo assembler line as a comment.
if g_opt.comment then
wsync()
wcomment(aline)
end
-- Strip assembler comments.
aline = gsub(aline, "//.*$", "")
-- Split line into statements at semicolons.
if match(aline, ";") then
for stmt in gmatch(aline, "[^;]+") do dostmt(stmt) end
else
dostmt(aline)
end
end
------------------------------------------------------------------------------
-- Write DynASM header.
local function dasmhead(out)
out:write(format([[
/*
** This file has been pre-processed with DynASM.
** %s
** DynASM version %s, DynASM %s version %s
** DO NOT EDIT! The original file is in "%s".
*/
]], _info.url,
_info.version, g_arch._info.arch, g_arch._info.version,
g_fname))
end
-- Read input file.
readfile = function(fin)
g_indent = ""
g_lineno = 0
g_synclineno = -1
-- Process all lines.
for line in fin:lines() do
g_lineno = g_lineno + 1
g_curline = line
local ok, err = pcall(doline, line)
if not ok and wprinterr(err, "\n") then return true end
end
wflush()
-- Close input file.
assert(fin == stdin or fin:close())
end
-- Write output file.
local function writefile(outfile)
local fout
-- Open output file.
if outfile == nil or outfile == "-" then
fout = stdout
else
fout = assert(io.open(outfile, "w"))
end
-- Write all buffered lines
wdumplines(fout, g_wbuffer)
-- Close output file.
assert(fout == stdout or fout:close())
-- Optionally dump definitions.
dumpdef(fout == stdout and stderr or stdout)
end
-- Translate an input file to an output file.
local function translate(infile, outfile)
g_wbuffer = {}
g_indent = ""
g_lineno = 0
g_synclineno = -1
-- Put header.
wline(dasmhead)
-- Read input file.
local fin
if infile == "-" then
g_fname = "(stdin)"
fin = stdin
else
g_fname = infile
fin = assert(io.open(infile, "r"))
end
readfile(fin)
-- Check for errors.
if not g_arch then
wprinterr(g_fname, ":*: error: missing .arch directive\n")
end
checkconds()
checkmacros()
checkcaptures()
if g_errcount ~= 0 then
stderr:write(g_fname, ":*: info: ", g_errcount, " error",
(type(g_errcount) == "number" and g_errcount > 1) and "s" or "",
" in input file -- no output file generated.\n")
dumpdef(stderr)
exit(1)
end
-- Write output file.
writefile(outfile)
end
------------------------------------------------------------------------------
-- Print help text.
function opt_map.help()
stdout:write("DynASM -- ", _info.description, ".\n")
stdout:write("DynASM ", _info.version, " ", _info.release, " ", _info.url, "\n")
stdout:write[[
Usage: dynasm [OPTION]... INFILE.dasc|-
-h, --help Display this help text.
-V, --version Display version and copyright information.
-o, --outfile FILE Output file name (default is stdout).
-I, --include DIR Add directory to the include search path.
-c, --ccomment Use /* */ comments for assembler lines.
-C, --cppcomment Use // comments for assembler lines (default).
-N, --nocomment Suppress assembler lines in output.
-M, --maccomment Show macro expansions as comments (default off).
-L, --nolineno Suppress CPP line number information in output.
-F, --flushline Flush action list for every line.
-D NAME[=SUBST] Define a substitution.
-U NAME Undefine a substitution.
-P, --dumpdef Dump defines, macros, etc. Repeat for more output.
-A, --dumparch ARCH Load architecture ARCH and dump description.
]]
exit(0)
end
-- Print version information.
function opt_map.version()
stdout:write(format("%s version %s, released %s\n%s\n\n%s",
_info.name, _info.version, _info.release, _info.url, _info.copyright))
exit(0)
end
-- Misc. options.
function opt_map.outfile(args) g_opt.outfile = optparam(args) end
function opt_map.include(args) insert(g_opt.include, 1, optparam(args)) end
function opt_map.ccomment() g_opt.comment = "/*|"; g_opt.endcomment = " */" end
function opt_map.cppcomment() g_opt.comment = "//|"; g_opt.endcomment = "" end
function opt_map.nocomment() g_opt.comment = false end
function opt_map.maccomment() g_opt.maccomment = true end
function opt_map.nolineno() g_opt.cpp = false end
function opt_map.flushline() g_opt.flushline = true end
function opt_map.dumpdef() g_opt.dumpdef = g_opt.dumpdef + 1 end
------------------------------------------------------------------------------
-- Short aliases for long options.
local opt_alias = {
h = "help", ["?"] = "help", V = "version",
o = "outfile", I = "include",
c = "ccomment", C = "cppcomment", N = "nocomment", M = "maccomment",
L = "nolineno", F = "flushline",
P = "dumpdef", A = "dumparch",
}
-- Parse single option.
local function parseopt(opt, args)
opt_current = #opt == 1 and "-"..opt or "--"..opt
local f = opt_map[opt] or opt_map[opt_alias[opt]]
if not f then
opterror("unrecognized option `", opt_current, "'. Try `--help'.\n")
end
f(args)
end
-- Parse arguments.
local function parseargs(args)
-- Default options.
g_opt.comment = "//|"
g_opt.endcomment = ""
g_opt.cpp = true
g_opt.dumpdef = 0
g_opt.include = { "" }
-- Process all option arguments.
args.argn = 1
repeat
local a = args[args.argn]
if not a then break end
local lopt, opt = match(a, "^%-(%-?)(.+)")
if not opt then break end
args.argn = args.argn + 1
if lopt == "" then
-- Loop through short options.
for o in gmatch(opt, ".") do parseopt(o, args) end
else
-- Long option.
parseopt(opt, args)
end
until false
-- Check for proper number of arguments.
local nargs = #args - args.argn + 1
if nargs ~= 1 then
if nargs == 0 then
if g_opt.dumpdef > 0 then return dumpdef(stdout) end
end
opt_map.help()
end
-- Translate a single input file to a single output file
-- TODO: Handle multiple files?
translate(args[args.argn], g_opt.outfile)
end
------------------------------------------------------------------------------
-- Add the directory dynasm.lua resides in to the Lua module search path.
local arg = arg
if arg and arg[0] then
prefix = match(arg[0], "^(.*[/\\])")
if package and prefix then package.path = prefix.."?.lua;"..package.path end
end
-- Start DynASM.
parseargs{...}
------------------------------------------------------------------------------
| apache-2.0 |
nesstea/darkstar | scripts/zones/Kazham/npcs/Bhi_Telifahgo.lua | 15 | 1053 | -----------------------------------
-- Area: Kazham
-- NPC: Bhi Telifahgo
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Kazham/TextIDs"] = nil;
require("scripts/zones/Kazham/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("BathedInScent") == 1) then
player:startEvent(0x00B7); -- scent from Blue Rafflesias
else
player:startEvent(0x005D);
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 |
UnfortunateFruit/darkstar | scripts/zones/West_Sarutabaruta/npcs/Harvesting_Point.lua | 29 | 1125 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Harvesting Point
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/harvesting");
require("scripts/zones/West_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
startHarvesting(player,player:getZoneID(),npc,trade,0x0385);
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(HARVESTING_IS_POSSIBLE_HERE,1020);
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_bream_risotto.lua | 18 | 1639 | -----------------------------------------
-- ID: 4550
-- Item: plate_of_bream_risotto
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 40
-- Dexterity 6
-- Agility 3
-- Mind -4
-- Health Regen While Healing 1
-- Accuracy % 6
-- Accuracy Cap 15
-----------------------------------------
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,4550);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 40);
target:addMod(MOD_DEX, 6);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_MND, -4);
target:addMod(MOD_HPHEAL, 1);
target:addMod(MOD_FOOD_ACCP, 6);
target:addMod(MOD_FOOD_ACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 40);
target:delMod(MOD_DEX, 6);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_MND, -4);
target:delMod(MOD_HPHEAL, 1);
target:delMod(MOD_FOOD_ACCP, 6);
target:delMod(MOD_FOOD_ACC_CAP, 15);
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Port_Jeuno/npcs/Challoux.lua | 13 | 1114 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Challoux
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,CHALLOUX_SHOP_DIALOG);
stock = {0x11C1,62, --Gysahl Greens
0x0348,4, --Chocobo Feather
0x439B,9} --Dart
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 |
alirezanile/LaSt-GaMfg | plugins/join.lua | 26 | 1488 | --[[
Bot can join into a group by replying a message contain an invite link or by
typing !join [invite link].
URL.parse cannot parsing complicated message. So, this plugin only works for
single [invite link] in a post.
[invite link] may be preceeded but must not followed by another characters.
--]]
do
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
i = 0
for k,segment in pairs(parsed_path) do
i = i + 1
if segment == 'joinchat' then
invite_link = string.gsub(parsed_path[i+1], '[ %c].+$', '')
break
end
end
return invite_link
end
local function action_by_reply(extra, success, result)
local hash = parsed_url(result.text)
join = import_chat_link(hash, ok_cb, false)
end
function run(msg, matches)
if is_sudo(msg.from.id) then
if msg.reply_id then
msgr = get_message(msg.reply_id, action_by_reply, {msg=msg})
elseif matches[1] then
local hash = parsed_url(matches[1])
join = import_chat_link(hash, ok_cb, false)
end
end
end
return {
description = 'Invite the bot into a group chat via its invite link.',
usage = {
'!join : Join a group by replying a message containing invite link.',
'!join [invite_link] : Join into a group by providing their [invite_link].'
},
patterns = {
'^!join$',
'^!join (.*)$'
},
run = run
}
end
| gpl-2.0 |
nesstea/darkstar | scripts/zones/Lower_Jeuno/npcs/Bki_Tbujhja.lua | 11 | 4299 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Bki Tbujhja
-- Involved in Quest: The Old Monument
-- Starts and Finishes Quests: Path of the Bard (just start), The Requiem (BARD AF2)
-- @zone 245
-- @pos -22 0 -60
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,THE_REQUIEM) == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 2) then
if (trade:hasItemQty(4154,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x0097); -- After trade Holy water for "The Requiem"
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
PainfulMemory = player:getQuestStatus(JEUNO,PAINFUL_MEMORY);
TheRequiem = player:getQuestStatus(JEUNO,THE_REQUIEM);
if (player:getVar("TheOldMonument_Event") == 1) then
player:startEvent(0x00b5); -- For the quest "The Old Monument"
elseif (player:getQuestStatus(JEUNO,A_MINSTREL_IN_DESPAIR) == QUEST_COMPLETED and player:getVar("PathOfTheBard_Event") == 0) then
player:startEvent(0x00b6); -- Start Quest "Path of the Bard" (with var)
elseif (player:getMainJob() == 10 and player:getMainLvl() >= 50 and PainfulMemory == QUEST_COMPLETED and TheRequiem == QUEST_AVAILABLE) then
if (player:getVar("TheRequiemCS") == 0) then
player:startEvent(0x0091); -- Long dialog & Start Quest "The Requiem"
else
player:startEvent(0x0094); -- Shot dialog & Start Quest "The Requiem"
end
elseif (TheRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 2) then
player:startEvent(0x0092); -- During Quest "The Requiem" (before trading Holy Water)
elseif (TheRequiem == QUEST_ACCEPTED and player:getVar("TheRequiemCS") == 3 and player:hasKeyItem(STAR_RING1) == false) then
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x0093); -- During Quest "The Requiem" (after trading Holy Water)
else
player:startEvent(0x0095); -- During Quest "The Requiem" (after trading Holy Water)
end
elseif (TheRequiem == QUEST_ACCEPTED and player:hasKeyItem(STAR_RING1) == true) then
player:startEvent(0x0096); -- Finish Quest "The Requiem"
elseif (TheRequiem == QUEST_COMPLETED) then
player:startEvent(0x0086); -- Standard dialog after "The Requiem"
else
player:startEvent(0x00b4);
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 == 0x00b5) then
player:setVar("TheOldMonument_Event",2);
elseif (csid == 0x00b6 and option == 0) then
player:setVar("PathOfTheBard_Event",1);
elseif (csid == 0x0091 and option == 1 or csid == 0x0094 and option == 1) then
player:addQuest(JEUNO,THE_REQUIEM);
player:setVar("TheRequiemCS",2);
elseif (csid == 0x0091 and option == 0) then
player:setVar("TheRequiemCS",1);
elseif (csid == 0x0097) then
player:setVar("TheRequiemCS",3);
player:messageSpecial(ITEM_OBTAINED,4154); -- Holy Water (just message)
elseif (csid == 0x0096) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14098);
else
player:addItem(14098);
player:messageSpecial(ITEM_OBTAINED,14098); -- Choral Slippers
player:addFame(JEUNO, 30);
player:completeQuest(JEUNO,THE_REQUIEM);
end
end
end;
| gpl-3.0 |
dpino/snabbswitch | src/apps/lwaftr/loadgen.lua | 9 | 2163 | module(...,package.seeall)
local app = require("core.app")
local packet = require("core.packet")
local link = require("core.link")
local transmit, receive = link.transmit, link.receive
local clone = packet.clone
--- ### `RateLimitedRepeater` app: A repeater that can limit flow rate
RateLimitedRepeater = {
config = {
-- rate: by default, limit to 10 Mbps, just to have a default.
rate = {default=10e6},
-- bucket_capacity: by default, allow for 255 standard packets in the
-- queue.
bucket_capacity = {default=255*1500*8},
initial_capacity = {}
}
}
function RateLimitedRepeater:new (conf)
conf.initial_capacity = conf.initial_capacity or conf.bucket_capacity
local o = {
index = 1,
packets = {},
rate = conf.rate,
bucket_capacity = conf.bucket_capacity,
bucket_content = conf.initial_capacity
}
return setmetatable(o, {__index=RateLimitedRepeater})
end
function RateLimitedRepeater:set_rate (bit_rate)
self.rate = math.max(bit_rate, 0)
end
function RateLimitedRepeater:push ()
local i, o = self.input.input, self.output.output
for _ = 1, link.nreadable(i) do
local p = receive(i)
table.insert(self.packets, p)
end
do
local cur_now = tonumber(app.now())
local last_time = self.last_time or cur_now
self.bucket_content = math.min(
self.bucket_content + self.rate * (cur_now - last_time),
self.bucket_capacity
)
self.last_time = cur_now
end
-- 7 bytes preamble, 1 start-of-frame, 4 CRC, 12 interpacket gap.
local overhead = 7 + 1 + 4 + 12
local npackets = #self.packets
if npackets > 0 and self.rate > 0 then
for _ = 1, engine.pull_npackets do
local p = self.packets[self.index]
local bits = (p.length + overhead) * 8
if bits > self.bucket_content then break end
self.bucket_content = self.bucket_content - bits
transmit(o, clone(p))
self.index = (self.index % npackets) + 1
end
end
end
function RateLimitedRepeater:stop ()
for i = 1, #self.packets do
packet.free(self.packets[i])
end
end
| apache-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Porter_Moogle.lua | 41 | 1547 | -----------------------------------
-- Area: Bastok Markets [S]
-- NPC: Porter Moogle
-- Type: Storage Moogle
-- @zone 87
-- @pos TODO
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/porter_moogle_util");
local e =
{
TALK_EVENT_ID = 601,
STORE_EVENT_ID = 602,
RETRIEVE_EVENT_ID = 603,
ALREADY_STORED_ID = 604,
MAGIAN_TRIAL_ID = 605
};
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
porterMoogleTrade(player, trade, e);
end
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- No idea what the params are, other than event ID and gil.
player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8);
end
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED);
end
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL);
end | gpl-3.0 |
nesstea/darkstar | scripts/zones/Behemoths_Dominion/Zone.lua | 12 | 1901 | -----------------------------------
--
-- Zone: Behemoths_Dominion (127)
--
-----------------------------------
package.loaded["scripts/zones/Behemoths_Dominion/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/zone");
require("scripts/zones/Behemoths_Dominion/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
local manuals = {17297490};
SetFieldManual(manuals);
-- Behemoth
SetRespawnTime(17297440, 900, 10800);
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(358.134,24.806,-60.001,123);
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/globals/items/bibiki_slug.lua | 18 | 1416 | -----------------------------------------
-- ID: 5122
-- Item: Bibiki Slug
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 4
-- defense % 16
-----------------------------------------
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,5122);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_DEFP, 16);
end;
| gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/libs/oUF/oUF_core.lua | 4 | 31790 | local parent, ns = ...
local oUF = {}
local global = GetAddOnMetadata(parent, 'X-oUF')
local _VERSION = GetAddOnMetadata(parent, 'version')
local upper = string.upper
local split = string.split
local tinsert, tremove = table.insert, table.remove
local styles, style = {}
local callback, objects = {}, {}
local elements = {}
local activeElements = {}
--[[
/$$$$$$$ /$$ /$$
| $$__ $$ |__/ | $$
| $$ \ $$/$$$$$$ /$$ /$$ /$$/$$$$$$ /$$$$$$ /$$$$$$
| $$$$$$$/$$__ $$| $$| $$ /$$/____ $$|_ $$_/ /$$__ $$
| $$____/ $$ \__/| $$ \ $$/$$/ /$$$$$$$ | $$ | $$$$$$$$
| $$ | $$ | $$ \ $$$/ /$$__ $$ | $$ /$$| $$_____/
| $$ | $$ | $$ \ $/ | $$$$$$$ | $$$$/| $$$$$$$
|__/ |__/ |__/ \_/ \_______/ \___/ \_______/
--]]
local Private = {}
local match = string.match
local format = string.format
function Private.argcheck(value, num, ...)
assert(type(num) == 'number', "Bad argument #2 to 'argcheck' (number expected, got "..type(num)..")")
for i=1,select("#", ...) do
if type(value) == select(i, ...) then return end
end
local types = strjoin(", ", ...)
local name = match(debugstack(2,2,0), ": in function [`<](.-)['>]")
error(("Bad argument #%d to '%s' (%s expected, got %s"):format(num, name, types, type(value)), 3)
end
function Private.print(...)
print("|cff33ff99oUF:|r", ...)
end
function Private.error(...)
Private.print("|cffff0000Error:|r "..format(...))
end
local argcheck = Private.argcheck
local error = Private.error
local print = Private.print
local frame_metatable = Private.frame_metatable
--[[
/$$ /$$ /$$$$$$$$
| $$ | $$| $$_____/
/$$$$$$ | $$ | $$| $$
/$$__ $$| $$ | $$| $$$$$
| $$ \ $$| $$ | $$| $$__/
| $$ | $$| $$ | $$| $$
| $$$$$$/| $$$$$$/| $$
\______/ \______/ |__/
--]]
-- updating of "invalid" units.
local enableTargetUpdate = function(object)
object.onUpdateFrequency = object.onUpdateFrequency or .5
object.__eventless = true
local total = 0
object:SetScript('OnUpdate', function(self, elapsed)
if(not self.unit) then
return
elseif(total > self.onUpdateFrequency) then
self:UpdateAllElements'OnUpdate'
total = 0
end
total = total + elapsed
end)
end
Private.enableTargetUpdate = enableTargetUpdate
local updateActiveUnit = function(self, event, unit)
-- Calculate units to work with
local realUnit, modUnit = SecureButton_GetUnit(self), SecureButton_GetModifiedUnit(self)
-- _GetUnit() doesn't rewrite playerpet -> pet like _GetModifiedUnit does.
if(realUnit == 'playerpet') then
realUnit = 'pet'
elseif(realUnit == 'playertarget') then
realUnit = 'target'
end
if(modUnit == "pet" and realUnit ~= "pet") then
modUnit = "vehicle"
end
-- Drop out if the event unit doesn't match any of the frame units.
if(not UnitExists(modUnit) or unit and unit ~= realUnit and unit ~= modUnit) then return end
-- Change the active unit and run a full update.
if Private.UpdateUnits(self, modUnit, realUnit) then
self:UpdateAllElements('RefreshUnit')
return true
end
end
local iterateChildren = function(...)
for l = 1, select("#", ...) do
local obj = select(l, ...)
if(type(obj) == 'table' and obj.isChild) then
updateActiveUnit(obj, "iterateChildren")
end
end
end
local OnAttributeChanged = function(self, name, value)
if(name == "unit" and value) then
if(self.hasChildren) then
iterateChildren(self:GetChildren())
end
if(not self:GetAttribute'oUF-onlyProcessChildren') then
updateActiveUnit(self, "OnAttributeChanged")
end
end
end
local frame_metatable = {
__index = CreateFrame"Button"
}
Private.frame_metatable = frame_metatable
for k, v in pairs{
UpdateElement = function(self, name)
local unit = self.unit
if(not unit or not UnitExists(unit)) then return end
local element = elements[name]
if(not element or not self:IsElementEnabled(name) or not activeElements[self]) then return end
if(element.update) then
element.update(self, 'OnShow', unit)
end
end,
EnableElement = function(self, name, unit)
argcheck(name, 2, 'string')
argcheck(unit, 3, 'string', 'nil')
local element = elements[name]
if(not element or self:IsElementEnabled(name) or not activeElements[self]) then return end
if(element.enable(self, unit or self.unit)) then
activeElements[self][name] = true
if(element.update) then
tinsert(self.__elements, element.update)
end
end
end,
DisableElement = function(self, name)
argcheck(name, 2, 'string')
local enable = self:IsElementEnabled(name)
if(not enable) then return end
local update = elements[name].update
for k, func in next, self.__elements do
if(func == update) then
tremove(self.__elements, k)
break
end
end
activeElements[self][name] = nil
-- We need to run a new update cycle in-case we knocked ourself out of sync.
-- The main reason we do this is to make sure the full update is completed
-- if an element for some reason removes itself _during_ the update
-- progress.
self:UpdateAllElements('DisableElement', name)
return elements[name].disable(self)
end,
IsElementEnabled = function(self, name)
argcheck(name, 2, 'string')
local element = elements[name]
if(not element) then return end
local active = activeElements[self]
return active and active[name]
end,
Enable = RegisterUnitWatch,
Disable = function(self)
UnregisterUnitWatch(self)
self:Hide()
end,
UpdateAllElements = function(self, event)
local unit = self.unit
if(not unit or not UnitExists(unit)) then return end
if(self.PreUpdate) then
self:PreUpdate(event)
end
for _, func in next, self.__elements do
func(self, event, unit)
end
if(self.PostUpdate) then
self:PostUpdate(event)
end
end,
} do
frame_metatable.__index[k] = v
end
local OnShow = function(self)
if(not updateActiveUnit(self, 'OnShow')) then
return self:UpdateAllElements'OnShow'
end
end
local UpdatePet = function(self, event, unit)
local petUnit
if(unit == 'target') then
return
elseif(unit == 'player') then
petUnit = 'pet'
else
-- Convert raid26 -> raidpet26
petUnit = unit:gsub('^(%a+)(%d+)', '%1pet%2')
end
if(self.unit ~= petUnit) then return end
if(not updateActiveUnit(self, event)) then
return self:UpdateAllElements(event)
end
end
local initObject = function(unit, style, styleFunc, header, ...)
local num = select('#', ...)
for i=1, num do
local object = select(i, ...)
local objectUnit = object:GetAttribute'oUF-guessUnit' or unit
local suffix = object:GetAttribute'unitsuffix'
object.__elements = {}
object.style = style
object = setmetatable(object, frame_metatable)
-- Expose the frame through oUF.objects.
tinsert(objects, object)
-- We have to force update the frames when PEW fires.
object:RegisterEvent("PLAYER_ENTERING_WORLD", object.UpdateAllElements)
-- Handle the case where someone has modified the unitsuffix attribute in
-- oUF-initialConfigFunction.
if(suffix and objectUnit and not objectUnit:match(suffix)) then
objectUnit = objectUnit .. suffix
end
if(not (suffix == 'target' or objectUnit and objectUnit:match'target')) then
object:RegisterEvent('UNIT_ENTERED_VEHICLE', updateActiveUnit)
object:RegisterEvent('UNIT_EXITED_VEHICLE', updateActiveUnit)
-- We don't need to register UNIT_PET for the player unit. We register it
-- mainly because UNIT_EXITED_VEHICLE and UNIT_ENTERED_VEHICLE doesn't always
-- have pet information when they fire for party and raid units.
if(objectUnit ~= 'player') then
object:RegisterEvent('UNIT_PET', UpdatePet)
end
end
if(not header) then
-- No header means it's a frame created through :Spawn().
object:SetAttribute("*type1", "target")
object:SetAttribute('*type2', 'togglemenu')
-- No need to enable this for *target frames.
if(not (unit:match'target' or suffix == 'target')) then
object:SetAttribute('toggleForVehicle', true)
end
-- Other boss and target units are handled by :HandleUnit().
if(suffix == 'target') then
enableTargetUpdate(object)
else
oUF:HandleUnit(object)
end
else
-- Used to update frames when they change position in a group.
object:RegisterEvent('GROUP_ROSTER_UPDATE', object.UpdateAllElements)
if(num > 1) then
if(object:GetParent() == header) then
object.hasChildren = true
else
object.isChild = true
end
end
if(suffix == 'target') then
enableTargetUpdate(object)
end
end
Private.UpdateUnits(object, objectUnit)
styleFunc(object, objectUnit, not header)
object:SetScript("OnAttributeChanged", OnAttributeChanged)
object:SetScript("OnShow", OnShow)
activeElements[object] = {}
for element in next, elements do
object:EnableElement(element, objectUnit)
end
for _, func in next, callback do
func(object)
end
-- Make Clique happy
_G.ClickCastFrames = ClickCastFrames or {}
ClickCastFrames[object] = true
end
end
local walkObject = function(object, unit)
local parent = object:GetParent()
local style = parent.style or style
local styleFunc = styles[style]
local header = parent:GetAttribute'oUF-headerType' and parent
-- Check if we should leave the main frame blank.
if(object:GetAttribute'oUF-onlyProcessChildren') then
object.hasChildren = true
object:SetScript('OnAttributeChanged', OnAttributeChanged)
return initObject(unit, style, styleFunc, header, object:GetChildren())
end
return initObject(unit, style, styleFunc, header, object, object:GetChildren())
end
function oUF:RegisterInitCallback(func)
tinsert(callback, func)
end
function oUF:RegisterMetaFunction(name, func)
argcheck(name, 2, 'string')
argcheck(func, 3, 'function', 'table')
if(frame_metatable.__index[name]) then
return
end
frame_metatable.__index[name] = func
end
function oUF:RegisterStyle(name, func)
argcheck(name, 2, 'string')
argcheck(func, 3, 'function', 'table')
if(styles[name]) then return error("Style [%s] already registered.", name) end
if(not style) then style = name end
styles[name] = func
end
function oUF:SetActiveStyle(name)
argcheck(name, 2, 'string')
if(not styles[name]) then return error("Style [%s] does not exist.", name) end
style = name
end
do
local function iter(_, n)
-- don't expose the style functions.
return (next(styles, n))
end
function oUF.IterateStyles()
return iter, nil, nil
end
end
local getCondition
do
local conditions = {
raid40 = '[@raid26,exists] show;',
raid25 = '[@raid11,exists] show;',
raid10 = '[@raid6,exists] show;',
raid = '[group:raid] show;',
party = '[group:party,nogroup:raid] show;',
solo = '[@player,exists,nogroup:party] show;',
}
function getCondition(...)
local cond = ''
for i=1, select('#', ...) do
local short = select(i, ...)
local condition = conditions[short]
if(condition) then
cond = cond .. condition
end
end
return cond .. 'hide'
end
end
local generateName = function(unit, ...)
local name = 'oUF_' .. style:gsub('[^%a%d_]+', '')
local raid, party, groupFilter
for i=1, select('#', ...), 2 do
local att, val = select(i, ...)
if(att == 'showRaid') then
raid = true
elseif(att == 'showParty') then
party = true
elseif(att == 'groupFilter') then
groupFilter = val
end
end
local append
if(raid) then
if(groupFilter) then
if(type(groupFilter) == 'number' and groupFilter > 0) then
append = groupFilter
elseif(groupFilter:match'TANK') then
append = 'MainTank'
elseif(groupFilter:match'ASSIST') then
append = 'MainAssist'
else
local _, count = groupFilter:gsub(',', '')
if(count == 0) then
append = 'Raid' .. groupFilter
else
append = 'Raid'
end
end
else
append = 'Raid'
end
elseif(party) then
append = 'Party'
elseif(unit) then
append = unit:gsub("^%l", upper)
end
if(append) then
name = name .. append
end
-- Change oUF_LilyRaidRaid into oUF_LilyRaid
name = name:gsub('(%u%l+)([%u%l]*)%1', '%1')
-- Change oUF_LilyTargettarget into oUF_LilyTargetTarget
name = name:gsub('t(arget)', 'T%1')
local base = name
local i = 2
while(_G[name]) do
name = base .. i
i = i + 1
end
return name
end
do
local styleProxy = function(self, frame, ...)
return walkObject(_G[frame])
end
-- There has to be an easier way to do this.
local initialConfigFunction = [[
local header = self:GetParent()
local frames = table.new()
table.insert(frames, self)
self:GetChildList(frames)
for i=1, #frames do
local frame = frames[i]
local unit
-- There's no need to do anything on frames with onlyProcessChildren
if(not frame:GetAttribute'oUF-onlyProcessChildren') then
RegisterUnitWatch(frame)
-- Attempt to guess what the header is set to spawn.
local groupFilter = header:GetAttribute'groupFilter'
if(type(groupFilter) == 'string' and groupFilter:match('MAIN[AT]')) then
local role = groupFilter:match('MAIN([AT])')
if(role == 'T') then
unit = 'maintank'
else
unit = 'mainassist'
end
elseif(header:GetAttribute'showRaid') then
unit = 'raid'
elseif(header:GetAttribute'showParty') then
unit = 'party'
end
local headerType = header:GetAttribute'oUF-headerType'
local suffix = frame:GetAttribute'unitsuffix'
if(unit and suffix) then
if(headerType == 'pet' and suffix == 'target') then
unit = unit .. headerType .. suffix
else
unit = unit .. suffix
end
elseif(unit and headerType == 'pet') then
unit = unit .. headerType
end
frame:SetAttribute('*type1', 'target')
frame:SetAttribute('*type2', 'togglemenu')
frame:SetAttribute('toggleForVehicle', true)
frame:SetAttribute('oUF-guessUnit', unit)
end
local body = header:GetAttribute'oUF-initialConfigFunction'
if(body) then
frame:Run(body, unit)
end
end
header:CallMethod('styleFunction', self:GetName())
local clique = header:GetFrameRef("clickcast_header")
if(clique) then
clique:SetAttribute("clickcast_button", self)
clique:RunAttribute("clickcast_register")
end
]]
function oUF:SpawnHeader(overrideName, template, visibility, ...)
if(not style) then return error("Unable to create frame. No styles have been registered.") end
template = (template or 'SecureGroupHeaderTemplate')
local isPetHeader = template:match'PetHeader'
local name = overrideName or generateName(nil, ...)
local header = CreateFrame('Frame', name, UIParent, template)
header:SetAttribute("template", "oUF_ClickCastUnitTemplate")
for i=1, select("#", ...), 2 do
local att, val = select(i, ...)
if(not att) then break end
header:SetAttribute(att, val)
end
header.style = style
header.styleFunction = styleProxy
-- We set it here so layouts can't directly override it.
header:SetAttribute('initialConfigFunction', initialConfigFunction)
header:SetAttribute('oUF-headerType', isPetHeader and 'pet' or 'group')
if(Clique) then
SecureHandlerSetFrameRef(header, 'clickcast_header', Clique.header)
end
if(header:GetAttribute'showParty') then
self:DisableBlizzard'party'
end
if(visibility) then
local type, list = split(' ', visibility, 2)
if(list and type == 'custom') then
RegisterAttributeDriver(header, 'state-visibility', list)
else
local condition = getCondition(split(',', visibility))
RegisterAttributeDriver(header, 'state-visibility', condition)
end
end
return header
end
end
function oUF:Spawn(unit, overrideName, overrideTemplate)
argcheck(unit, 2, 'string')
if(not style) then return error("Unable to create frame. No styles have been registered.") end
unit = unit:lower()
local name = overrideName or generateName(unit)
local object = CreateFrame("Button", name, UIParent, overrideTemplate or "SecureUnitButtonTemplate")
Private.UpdateUnits(object, unit)
self:DisableBlizzard(unit)
walkObject(object, unit)
object:SetAttribute("unit", unit)
RegisterUnitWatch(object)
return object
end
function oUF:AddElement(name, update, enable, disable)
argcheck(name, 2, 'string')
argcheck(update, 3, 'function', 'nil')
argcheck(enable, 4, 'function', 'nil')
argcheck(disable, 5, 'function', 'nil')
if(elements[name]) then return error('Element [%s] is already registered.', name) end
elements[name] = {
update = update;
enable = enable;
disable = disable;
}
end
oUF.version = _VERSION
oUF.objects = objects
if(global) then
if(parent ~= 'oUF' and global == 'oUF') then
error("%s is doing it wrong and setting its global to oUF.", parent)
else
_G[global] = oUF
end
end
--[[
/$$$$$$$$ /$$
| $$_____/ | $$
| $$ /$$ /$$/$$$$$$ /$$$$$$$ /$$$$$$ /$$$$$$$
| $$$$$| $$ /$$/$$__ $$| $$__ $$|_ $$_/ /$$_____/
| $$__/ \ $$/$$/ $$$$$$$$| $$ \ $$ | $$ | $$$$$$
| $$ \ $$$/| $$_____/| $$ | $$ | $$ /$$\____ $$
| $$$$$$$$\ $/ | $$$$$$$| $$ | $$ | $$$$//$$$$$$$/
|________/ \_/ \_______/|__/ |__/ \___/ |_______/
--]]
local RegisterEvent, UnregisterEvent, IsEventRegistered
do
local eventFrame = CreateFrame("Frame")
local registry = {}
local framesForUnit = {}
local alternativeUnits = {
['player'] = 'vehicle',
['pet'] = 'player',
['party1'] = 'partypet1',
['party2'] = 'partypet2',
['party3'] = 'partypet3',
['party4'] = 'partypet4',
}
local RegisterFrameForUnit = function(frame, unit)
if not unit then return end
if framesForUnit[unit] then
framesForUnit[unit][frame] = true
else
framesForUnit[unit] = { [frame] = true }
end
end
local UnregisterFrameForUnit = function(frame, unit)
if not unit then return end
local frames = framesForUnit[unit]
if frames and frames[frame] then
frames[frame] = nil
if not next(frames) then
framesForUnit[unit] = nil
end
end
end
Private.UpdateUnits = function(frame, unit, realUnit)
if unit == realUnit then
realUnit = nil
end
if frame.unit ~= unit or frame.realUnit ~= realUnit then
if not frame:GetScript('OnUpdate') then
UnregisterFrameForUnit(frame, frame.unit)
UnregisterFrameForUnit(frame, frame.realUnit)
RegisterFrameForUnit(frame, unit)
RegisterFrameForUnit(frame, realUnit)
end
frame.alternativeUnit = alternativeUnits[unit]
frame.unit = unit
frame.realUnit = realUnit
frame.id = unit:match'^.-(%d+)'
return true
end
end
-- Holds true for every event, where the first (unit) argument should be ignored.
local sharedUnitEvents = {
UNIT_ENTERED_VEHICLE = true,
UNIT_EXITED_VEHICLE = true,
UNIT_PET = true,
}
eventFrame:SetScript('OnEvent', function(_, event, arg1, ...)
local listeners = registry[event]
if arg1 and not sharedUnitEvents[event] then
local frames = framesForUnit[arg1]
if frames then
for frame in next, frames do
if listeners[frame] and frame:IsVisible() then
frame[event](frame, event, arg1, ...)
end
end
end
else
for frame in next, listeners do
if frame:IsVisible() then
frame[event](frame, event, arg1, ...)
end
end
end
end)
function RegisterEvent(self, event, unitless)
if(unitless) then
sharedUnitEvents[event] = true
end
if not registry[event] then
registry[event] = { [self] = true }
eventFrame:RegisterEvent(event)
else
registry[event][self] = true
end
end
function UnregisterEvent(self, event)
if registry[event] then
registry[event][self] = nil
if not next(registry[event]) then
registry[event] = nil
eventFrame:UnregisterEvent(event)
end
end
end
function IsEventRegistered(self, event)
return registry[event] and registry[event][self]
end
end
local event_metatable = {
__call = function(funcs, self, ...)
for _, func in next, funcs do
func(self, ...)
end
end,
}
function frame_metatable.__index:RegisterEvent(event, func, unitless)
-- Block OnUpdate polled frames from registering events.
if(self.__eventless) then return end
argcheck(event, 2, 'string')
if(type(func) == 'string' and type(self[func]) == 'function') then
func = self[func]
end
local curev = self[event]
local kind = type(curev)
if(curev and func) then
if(kind == 'function' and curev ~= func) then
self[event] = setmetatable({curev, func}, event_metatable)
elseif(kind == 'table') then
for _, infunc in next, curev do
if(infunc == func) then return end
end
tinsert(curev, func)
end
elseif(IsEventRegistered(self, event)) then
return
else
if(type(func) == 'function') then
self[event] = func
elseif(not self[event]) then
return error("Style [%s] attempted to register event [%s] on unit [%s] with a handler that doesn't exist.", self.style, event, self.unit or 'unknown')
end
RegisterEvent(self, event, unitless)
end
end
function frame_metatable.__index:UnregisterEvent(event, func)
argcheck(event, 2, 'string')
local curev = self[event]
if(type(curev) == 'table' and func) then
for k, infunc in next, curev do
if(infunc == func) then
tremove(curev, k)
local n = #curev
if(n == 1) then
local _, handler = next(curev)
self[event] = handler
elseif(n == 0) then
UnregisterEvent(self, event)
end
break
end
end
elseif(curev == func) then
self[event] = nil
UnregisterEvent(self, event)
end
end
function frame_metatable.__index:IsEventRegistered(event)
return IsEventRegistered(self, event)
end
--[[
/$$$$$$$$ /$$
| $$_____/ | $$
| $$ /$$$$$$ /$$$$$$$/$$$$$$ /$$$$$$ /$$$$$$ /$$ /$$
| $$$$$|____ $$ /$$_____/_ $$_/ /$$__ $$ /$$__ $$| $$ | $$
| $$__/ /$$$$$$$| $$ | $$ | $$ \ $$| $$ \__/| $$ | $$
| $$ /$$__ $$| $$ | $$ /$$| $$ | $$| $$ | $$ | $$
| $$ | $$$$$$$| $$$$$$$ | $$$$/| $$$$$$/| $$ | $$$$$$$
|__/ \_______/ \_______/ \___/ \______/ |__/ \____ $$
/$$ | $$
| $$$$$$/
\______/
--]]
local tinsert = table.insert
local _QUEUE = {}
local _FACTORY = CreateFrame'Frame'
_FACTORY:SetScript('OnEvent', function(self, event, ...)
return self[event](self, event, ...)
end)
_FACTORY:RegisterEvent'PLAYER_LOGIN'
_FACTORY.active = true
function _FACTORY:PLAYER_LOGIN()
if(not self.active) then return end
for _, func in next, _QUEUE do
func(oUF)
end
-- Avoid creating dupes.
wipe(_QUEUE)
end
function oUF:Factory(func)
argcheck(func, 2, 'function')
-- Call the function directly if we're active and logged in.
if(IsLoggedIn() and _FACTORY.active) then
return func(self)
else
tinsert(_QUEUE, func)
end
end
function oUF:EnableFactory()
_FACTORY.active = true
end
function oUF:DisableFactory()
_FACTORY.active = nil
end
function oUF:RunFactoryQueue()
_FACTORY:PLAYER_LOGIN()
end
--[[
/$$$$$$$ /$$ /$$ /$$
| $$__ $$| $$|__/ | $$
| $$ \ $$| $$ /$$ /$$$$$$$$/$$$$$$$$ /$$$$$$ /$$$$$$ /$$$$$$$
| $$$$$$$ | $$| $$|____ /$$/____ /$$/ |____ $$ /$$__ $$/$$__ $$
| $$__ $$| $$| $$ /$$$$/ /$$$$/ /$$$$$$$| $$ \__/ $$ | $$
| $$ \ $$| $$| $$ /$$__/ /$$__/ /$$__ $$| $$ | $$ | $$
| $$$$$$$/| $$| $$ /$$$$$$$$/$$$$$$$$| $$$$$$$| $$ | $$$$$$$
|_______/ |__/|__/|________/________/ \_______/|__/ \_______/
--]]
local hiddenParent = CreateFrame("Frame")
hiddenParent:Hide()
local HandleFrame = function(baseName)
local frame
if(type(baseName) == 'string') then
frame = _G[baseName]
else
frame = baseName
end
if(frame) then
frame:UnregisterAllEvents()
frame:Hide()
-- Keep frame hidden without causing taint
frame:SetParent(hiddenParent)
local health = frame.healthbar
if(health) then
health:UnregisterAllEvents()
end
local power = frame.manabar
if(power) then
power:UnregisterAllEvents()
end
local spell = frame.spellbar
if(spell) then
spell:UnregisterAllEvents()
end
local altpowerbar = frame.powerBarAlt
if(altpowerbar) then
altpowerbar:UnregisterAllEvents()
end
end
end
function oUF:DisableBlizzard(unit)
if(not unit) or InCombatLockdown() then return end
if(unit == 'player') then
HandleFrame(PlayerFrame)
-- For the damn vehicle support:
PlayerFrame:RegisterUnitEvent('UNIT_ENTERING_VEHICLE', "player")
PlayerFrame:RegisterUnitEvent('UNIT_ENTERED_VEHICLE', "player")
PlayerFrame:RegisterUnitEvent('UNIT_EXITING_VEHICLE', "player")
PlayerFrame:RegisterUnitEvent('UNIT_EXITED_VEHICLE', "player")
-- User placed frames don't animate
PlayerFrame:SetUserPlaced(true)
PlayerFrame:SetDontSavePosition(true)
elseif(unit == 'pet') then
HandleFrame(PetFrame)
elseif(unit == 'target') then
HandleFrame(TargetFrame)
HandleFrame(ComboFrame)
elseif(unit == 'focus') then
HandleFrame(FocusFrame)
HandleFrame(TargetofFocusFrame)
elseif(unit == 'targettarget') then
HandleFrame(TargetFrameToT)
elseif(unit:match'(boss)%d?$' == 'boss') then
local id = unit:match'boss(%d)'
if(id) then
HandleFrame('Boss' .. id .. 'TargetFrame')
else
for i=1, 4 do
HandleFrame(('Boss%dTargetFrame'):format(i))
end
end
elseif(unit:match'(party)%d?$' == 'party') then
local id = unit:match'party(%d)'
if(id) then
HandleFrame('PartyMemberFrame' .. id)
else
for i=1, 4 do
HandleFrame(('PartyMemberFrame%d'):format(i))
end
end
elseif(unit:match'(arena)%d?$' == 'arena') then
local id = unit:match'arena(%d)'
if(id) then
HandleFrame('ArenaEnemyFrame' .. id)
else
for i=1, 4 do
HandleFrame(('ArenaEnemyFrame%d'):format(i))
end
end
-- Blizzard_ArenaUI should not be loaded
Arena_LoadUI = function() end
SetCVar('showArenaEnemyFrames', '0', 'SHOW_ARENA_ENEMY_FRAMES_TEXT')
end
end
--[[
/$$ /$$ /$$ /$$
| $$ | $$ |__/ | $$
| $$ | $$ /$$$$$$$ /$$ /$$$$$$ /$$$$$$$
| $$ | $$| $$__ $$| $$|_ $$_/ /$$_____/
| $$ | $$| $$ \ $$| $$ | $$ | $$$$$$
| $$ | $$| $$ | $$| $$ | $$ /$$\____ $$
| $$$$$$/| $$ | $$| $$ | $$$$//$$$$$$$/
\______/ |__/ |__/|__/ \___/ |_______/
--]]
local enableTargetUpdate = Private.enableTargetUpdate
-- Handles unit specific actions.
function oUF:HandleUnit(object, unit)
local unit = object.unit or unit
if(unit == 'target') then
object:RegisterEvent('PLAYER_TARGET_CHANGED', object.UpdateAllElements)
elseif(unit == 'mouseover') then
object:RegisterEvent('UPDATE_MOUSEOVER_UNIT', object.UpdateAllElements)
elseif(unit == 'focus') then
object:RegisterEvent('PLAYER_FOCUS_CHANGED', object.UpdateAllElements)
elseif(unit:match'(boss)%d?$' == 'boss') then
object:RegisterEvent('INSTANCE_ENCOUNTER_ENGAGE_UNIT', object.UpdateAllElements, true)
object:RegisterEvent('UNIT_TARGETABLE_CHANGED', object.UpdateAllElements)
elseif(unit:match'%w+target') then
enableTargetUpdate(object)
end
end
--[[
/$$$$$$ /$$
/$$__ $$ | $$
| $$ \__/ /$$$$$$ | $$ /$$$$$$ /$$$$$$ /$$$$$$$
| $$ /$$__ $$| $$ /$$__ $$ /$$__ $$/$$_____/
| $$ | $$ \ $$| $$| $$ \ $$| $$ \__/ $$$$$$
| $$ $$| $$ | $$| $$| $$ | $$| $$ \____ $$
| $$$$$$/| $$$$$$/| $$| $$$$$$/| $$ /$$$$$$$/
\______/ \______/ |__/ \______/ |__/ |_______/
--]]
local colors = {
smooth = {
1, 0, 0,
1, 1, 0,
0, 1, 0
},
disconnected = {.6, .6, .6},
tapped = {.6,.6,.6},
class = {},
reaction = {},
}
-- We do this because people edit the vars directly, and changing the default
-- globals makes SPICE FLOW!
local customClassColors = function()
if(CUSTOM_CLASS_COLORS) then
local updateColors = function()
for eclass, color in next, CUSTOM_CLASS_COLORS do
colors.class[eclass] = {color.r, color.g, color.b}
end
for _, obj in next, oUF.objects do
obj:UpdateAllElements("CUSTOM_CLASS_COLORS")
end
end
updateColors()
CUSTOM_CLASS_COLORS:RegisterCallback(updateColors)
return true
end
end
if not customClassColors() then
for eclass, color in next, RAID_CLASS_COLORS do
colors.class[eclass] = {color.r, color.g, color.b}
end
local f = CreateFrame("Frame")
f:RegisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", function()
if customClassColors() then
f:UnregisterEvent("ADDON_LOADED")
f:SetScript("OnEvent", nil)
end
end)
end
for eclass, color in next, FACTION_BAR_COLORS do
colors.reaction[eclass] = {color.r, color.g, color.b}
end
local function ColorsAndPercent(a, b, ...)
if a <= 0 or b == 0 then
return nil, ...
elseif a >= b then
return nil, select(select('#', ...) - 2, ...)
end
local num = select('#', ...) / 3
local segment, relperc = math.modf((a/b)*(num-1))
return relperc, select((segment*3)+1, ...)
end
-- http://www.wowwiki.com/ColorGradient
local RGBColorGradient = function(...)
local relperc, r1, g1, b1, r2, g2, b2 = ColorsAndPercent(...)
if relperc then
return r1 + (r2-r1)*relperc, g1 + (g2-g1)*relperc, b1 + (b2-b1)*relperc
else
return r1, g1, b1
end
end
local function GetY(r, g, b)
return 0.3 * r + 0.59 * g + 0.11 * b
end
local function RGBToHCY(r, g, b)
local min, max = min(r, g, b), max(r, g, b)
local chroma = max - min
local hue
if chroma > 0 then
if r == max then
hue = ((g - b) / chroma) % 6
elseif g == max then
hue = (b - r) / chroma + 2
elseif b == max then
hue = (r - g) / chroma + 4
end
hue = hue / 6
end
return hue, chroma, GetY(r, g, b)
end
local abs = math.abs
local function HCYtoRGB(hue, chroma, luma)
local r, g, b = 0, 0, 0
if hue then
local h2 = hue * 6
local x = chroma * (1 - abs(h2 % 2 - 1))
if h2 < 1 then
r, g, b = chroma, x, 0
elseif h2 < 2 then
r, g, b = x, chroma, 0
elseif h2 < 3 then
r, g, b = 0, chroma, x
elseif h2 < 4 then
r, g, b = 0, x, chroma
elseif h2 < 5 then
r, g, b = x, 0, chroma
else
r, g, b = chroma, 0, x
end
end
local m = luma - GetY(r, g, b)
return r + m, g + m, b + m
end
local HCYColorGradient = function(...)
local relperc, r1, g1, b1, r2, g2, b2 = ColorsAndPercent(...)
if not relperc then return r1, g1, b1 end
local h1, c1, y1 = RGBToHCY(r1, g1, b1)
local h2, c2, y2 = RGBToHCY(r2, g2, b2)
local c = c1 + (c2-c1) * relperc
local y = y1 + (y2-y1) * relperc
if h1 and h2 then
local dh = h2 - h1
if dh < -0.5 then
dh = dh + 1
elseif dh > 0.5 then
dh = dh - 1
end
return HCYtoRGB((h1 + dh * relperc) % 1, c, y)
else
return HCYtoRGB(h1 or h2, c, y)
end
end
local ColorGradient = function(...)
return (oUF.useHCYColorGradient and HCYColorGradient or RGBColorGradient)(...)
end
Private.colors = colors
oUF.colors = colors
oUF.ColorGradient = ColorGradient
oUF.RGBColorGradient = RGBColorGradient
oUF.HCYColorGradient = HCYColorGradient
oUF.useHCYColorGradient = false
frame_metatable.__index.colors = colors
frame_metatable.__index.ColorGradient = ColorGradient
--[[
/$$$$$$$$/$$ /$$ /$$
| $$_____/__/ | $$|__/
| $$ /$$ /$$$$$$$ /$$$$$$ | $$ /$$ /$$$$$$$$ /$$$$$$
| $$$$$ | $$| $$__ $$ |____ $$| $$| $$|____ /$$/ /$$__ $$
| $$__/ | $$| $$ \ $$ /$$$$$$$| $$| $$ /$$$$/ | $$$$$$$$
| $$ | $$| $$ | $$ /$$__ $$| $$| $$ /$$__/ | $$_____/
| $$ | $$| $$ | $$| $$$$$$$| $$| $$ /$$$$$$$$| $$$$$$$
|__/ |__/|__/ |__/ \_______/|__/|__/|________/ \_______/
--]]
-- It's named Private for a reason!
-- Private = nil
ns.oUF = oUF | mit |
UnfortunateFruit/darkstar | scripts/globals/abilities/warlocks_roll.lua | 11 | 2155 | -----------------------------------
-- Ability: Warlock's Roll
-- Enhances magic accuracy for party members within area of effect
-- Optimal Job: Red Mage
-- Lucky Number: 4
-- Unlucky Number: 8
-- Level: 46
--
-- Die Roll |No RDM |With RDM
-- -------- -------- -----------
-- 1 |+2 |+7
-- 2 |+3 |+8
-- 3 |+4 |+9
-- 4 |+12 |+17
-- 5 |+5 |+10
-- 6 |+6 |+11
-- 7 |+7 |+12
-- 8 |+1 |+6
-- 9 |+8 |+13
-- 10 |+9 |+14
-- 11 |+15 |+20
-- Bust |-5 |-5
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = getCorsairRollEffect(ability:getID());
if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbilityRoll
-----------------------------------
function onUseAbilityRoll(caster,target,ability,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {2, 3, 4, 12, 5, 6, 7, 1, 8, 9, 15, 5}
local effectpower = effectpowers[total]
if (total < 12 and caster:hasPartyJob(JOB_RDM) ) then
effectpower = effectpower + 5;
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_WARLOCKS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_MACC) == false) then
ability:setMsg(423);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Selbina/npcs/Humilitie.lua | 39 | 1459 | -----------------------------------
-- Area: Selbina
-- NPC: Humilitie
-- Reports the time remaining before boat arrival.
-- @pos 17.979 -2.39 -58.800 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua
local timer = 1152 - ((os.time() - 1009810800)%1152);
local direction = 0; -- Arrive, 1 for depart
local waiting = 216; -- Offset for Mhaura
if (timer <= waiting) then
direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart"
else
timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival
end
player:startEvent(231,timer,direction);
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/Selbina/npcs/Humilitie.lua | 39 | 1459 | -----------------------------------
-- Area: Selbina
-- NPC: Humilitie
-- Reports the time remaining before boat arrival.
-- @pos 17.979 -2.39 -58.800 248
-----------------------------------
package.loaded["scripts/zones/Selbina/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Based on scripts/zones/Mhaura/Dieh_Yamilsiah.lua
local timer = 1152 - ((os.time() - 1009810800)%1152);
local direction = 0; -- Arrive, 1 for depart
local waiting = 216; -- Offset for Mhaura
if (timer <= waiting) then
direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart"
else
timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival
end
player:startEvent(231,timer,direction);
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/items/bird_egg.lua | 35 | 1192 | -----------------------------------------
-- ID: 4570
-- Item: Bird Egg
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Health 6
-- Magic 6
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4570);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 6);
target:addMod(MOD_MP, 6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 6);
target:delMod(MOD_MP, 6);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/items/la_theine_cabbage.lua | 35 | 1201 | -----------------------------------------
-- ID: 4366
-- Item: la_theine_cabbage
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4366);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -3);
end;
| gpl-3.0 |
akdor1154/awesome | lib/wibox/layout/margin.lua | 1 | 5330 | ---------------------------------------------------------------------------
-- @author Uli Schlachter
-- @copyright 2010 Uli Schlachter
-- @release @AWESOME_VERSION@
-- @classmod wibox.layout.margin
---------------------------------------------------------------------------
local pairs = pairs
local type = type
local setmetatable = setmetatable
local base = require("wibox.widget.base")
local gcolor = require("gears.color")
local cairo = require("lgi").cairo
local margin = { mt = {} }
--- Draw a margin layout
function margin:draw(_, cr, width, height)
local x = self.left
local y = self.top
local w = self.right
local h = self.bottom
local color = self.color
if not self.widget or width <= x + w or height <= y + h then
return
end
if color then
cr:set_source(color)
cr:rectangle(0, 0, width, height)
cr:rectangle(x, y, width - x - w, height - y - h)
cr:set_fill_rule(cairo.FillRule.EVEN_ODD)
cr:fill()
end
end
--- Layout a margin layout
function margin:layout(_, width, height)
if self.widget then
local x = self.left
local y = self.top
local w = self.right
local h = self.bottom
return { base.place_widget_at(self.widget, x, y, width - x - w, height - y - h) }
end
end
--- Fit a margin layout into the given space
function margin:fit(context, width, height)
local extra_w = self.left + self.right
local extra_h = self.top + self.bottom
local w, h = 0, 0
if self.widget then
w, h = base.fit_widget(self, context, self.widget, width - extra_w, height - extra_h)
end
if self._draw_empty == false and (w == 0 or h == 0) then
return 0, 0
end
return w + extra_w, h + extra_h
end
--- Set the widget that this layout adds a margin on.
function margin:set_widget(widget)
if widget then
base.check_widget(widget)
end
self.widget = widget
self:emit_signal("widget::layout_changed")
end
--- Get the number of children element
-- @treturn table The children
function margin:get_children()
return {self.widget}
end
--- Replace the layout children
-- This layout only accept one children, all others will be ignored
-- @tparam table children A table composed of valid widgets
function margin:set_children(children)
self:set_widget(children[1])
end
--- Set all the margins to val.
function margin:set_margins(val)
self.left = val
self.right = val
self.top = val
self.bottom = val
self:emit_signal("widget::layout_changed")
end
--- Set the margins color to color
function margin:set_color(color)
self.color = color and gcolor(color)
self:emit_signal("widget::redraw_needed")
end
--- Draw the margin even if the content size is 0x0 (default: true)
-- @tparam boolean draw_empty Draw nothing is content is 0x0 or draw the margin anyway
function margin:set_draw_empty(draw_empty)
self._draw_empty = draw_empty
self:emit_signal("widget::layout_changed")
end
--- Reset this layout. The widget will be unreferenced, the margins set to 0
-- and the color erased
function margin:reset()
self:set_widget(nil)
self:set_margins(0)
self:set_color(nil)
end
--- Set the left margin that this layout adds to its widget.
-- @param layout The layout you are modifying.
-- @param margin The new margin to use.
-- @name set_left
-- @class function
--- Set the right margin that this layout adds to its widget.
-- @param layout The layout you are modifying.
-- @param margin The new margin to use.
-- @name set_right
-- @class function
--- Set the top margin that this layout adds to its widget.
-- @param layout The layout you are modifying.
-- @param margin The new margin to use.
-- @name set_top
-- @class function
--- Set the bottom margin that this layout adds to its widget.
-- @param layout The layout you are modifying.
-- @param margin The new margin to use.
-- @name set_bottom
-- @class function
-- Create setters for each direction
for _, v in pairs({ "left", "right", "top", "bottom" }) do
margin["set_" .. v] = function(layout, val)
layout[v] = val
layout:emit_signal("widget::layout_changed")
end
end
--- Returns a new margin layout.
-- @param[opt] widget A widget to use.
-- @param[opt] left A margin to use on the left side of the widget.
-- @param[opt] right A margin to use on the right side of the widget.
-- @param[opt] top A margin to use on the top side of the widget.
-- @param[opt] bottom A margin to use on the bottom side of the widget.
-- @param[opt] color A color for the margins.
-- @param[opt] draw_empty whether or not to draw the margin when the content is empty
local function new(widget, left, right, top, bottom, color, draw_empty)
local ret = base.make_widget()
for k, v in pairs(margin) do
if type(v) == "function" then
ret[k] = v
end
end
ret:set_left(left or 0)
ret:set_right(right or 0)
ret:set_top(top or 0)
ret:set_bottom(bottom or 0)
ret:set_draw_empty(draw_empty)
ret:set_color(color)
if widget then
ret:set_widget(widget)
end
return ret
end
function margin.mt:__call(...)
return new(...)
end
return setmetatable(margin, margin.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Abyssea-Grauberg/npcs/Dominion_Sergeant.lua | 65 | 1056 | -----------------------------------
-- Area: Abyssea - Grauberg
-- NPC: Dominion Sergeant
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Grauberg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/abyssea");
require("scripts/zones/Abyssea-Grauberg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(500)
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 |
johnmccabe/dockercraft | world/Plugins/APIDump/Hooks/OnCraftingNoRecipe.lua | 36 | 1325 | return
{
HOOK_CRAFTING_NO_RECIPE =
{
CalledWhen = " No built-in crafting recipe is found. Plugin may provide a recipe.",
DefaultFnName = "OnCraftingNoRecipe", -- also used as pagename
Desc = [[
This callback is called when a player places items in their {{cCraftingGrid|crafting grid}} and
Cuberite cannot find a built-in {{cCraftingRecipe|recipe}} for the combination. Plugins may provide
a recipe for the ingredients given.
]],
Params =
{
{ Name = "Player", Type = "{{cPlayer}}", Notes = "The player whose crafting is reported in this hook" },
{ Name = "Grid", Type = "{{cCraftingGrid}}", Notes = "Contents of the player's crafting grid" },
{ Name = "Recipe", Type = "{{cCraftingRecipe}}", Notes = "The recipe that will be used (can be filled by plugins)" },
},
Returns = [[
If the function returns false or no value, no recipe will be used. If the function returns true, no
other plugin will have their callback called for this event and Cuberite will use the crafting
recipe in Recipe.</p>
<p>
FIXME: To allow plugins give suggestions and overwrite other plugins' suggestions, we should change
the behavior with returning false, so that the recipe will still be used, but fill the recipe with
empty values by default.
]],
}, -- HOOK_CRAFTING_NO_RECIPE
}
| apache-2.0 |
FailcoderAddons/supervillain-ui | SVUI_UnitFrames/libs/oUF_1.6.9/elements/portraits.lua | 7 | 3228 | --[[ Element: Portraits
Handles updating of the unit's portrait.
Widget
Portrait - A PlayerModel or Texture used to represent the unit's portrait.
Notes
The quest delivery question mark will be used instead of the unit's model when
the client doesn't have the model information for the unit.
Examples
-- 3D Portrait
-- Position and size
local Portrait = CreateFrame('PlayerModel', nil, self)
Portrait:SetSize(32, 32)
Portrait:SetPoint('RIGHT', self, 'LEFT')
-- Register it with oUF
self.Portrait = Portrait
-- 2D Portrait
local Portrait = self:CreateTexture(nil, 'OVERLAY')
Portrait:SetSize(32, 32)
Portrait:SetPoint('RIGHT', self, 'LEFT')
-- Register it with oUF
self.Portrait = Portrait
Hooks
Override(self) - Used to completely override the internal update function.
Removing the table key entry will make the element fall-back
to its internal function again.
]]
local parent, ns = ...
local oUF = ns.oUF
local Update = function(self, event, unit)
if(not unit or not UnitIsUnit(self.unit, unit)) then return end
local portrait = self.Portrait
if(portrait.PreUpdate) then portrait:PreUpdate(unit) end
if(portrait:IsObjectType'Model') then
local guid = UnitGUID(unit)
if(not UnitExists(unit) or not UnitIsConnected(unit) or not UnitIsVisible(unit)) then
portrait:SetCamDistanceScale(0.25)
portrait:SetPortraitZoom(0)
portrait:SetPosition(0,0,0.5)
portrait:ClearModel()
portrait:SetModel('interface\\buttons\\talktomequestionmark.m2')
portrait.guid = nil
elseif(portrait.guid ~= guid or event == 'UNIT_MODEL_CHANGED') then
portrait:SetCamDistanceScale(1)
portrait:SetPortraitZoom(1)
portrait:SetPosition(0,0,0)
portrait:ClearModel()
portrait:SetUnit(unit)
portrait.guid = guid
end
else
SetPortraitTexture(portrait, unit)
end
if(portrait.PostUpdate) then
return portrait:PostUpdate(unit)
end
end
local Path = function(self, ...)
return (self.Portrait.Override or Update) (self, ...)
end
local ForceUpdate = function(element)
return Path(element.__owner, 'ForceUpdate', element.__owner.unit)
end
local Enable = function(self, unit)
local portrait = self.Portrait
if(portrait) then
portrait:Show()
portrait.__owner = self
portrait.ForceUpdate = ForceUpdate
self:RegisterEvent("UNIT_PORTRAIT_UPDATE", Path)
self:RegisterEvent("UNIT_MODEL_CHANGED", Path)
self:RegisterEvent('UNIT_CONNECTION', Path)
-- The quest log uses PARTY_MEMBER_{ENABLE,DISABLE} to handle updating of
-- party members overlapping quests. This will probably be enough to handle
-- model updating.
--
-- DISABLE isn't used as it fires when we most likely don't have the
-- information we want.
if(unit == 'party') then
self:RegisterEvent('PARTY_MEMBER_ENABLE', Path)
end
return true
end
end
local Disable = function(self)
local portrait = self.Portrait
if(portrait) then
portrait:Hide()
self:UnregisterEvent("UNIT_PORTRAIT_UPDATE", Path)
self:UnregisterEvent("UNIT_MODEL_CHANGED", Path)
self:UnregisterEvent('PARTY_MEMBER_ENABLE', Path)
self:UnregisterEvent('UNIT_CONNECTION', Path)
end
end
oUF:AddElement('Portrait', Path, Enable, Disable)
| mit |
nesstea/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/_20m.lua | 18 | 3593 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- Door: Runic Seal
-- @pos 125 -2 20 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/globals/besieged");
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS)) then
local assaultid = player:getCurrentAssault();
local recommendedLevel = getRecommendedAssaultLevel(assaultid);
local armband = 0;
if (player:hasKeyItem(ASSAULT_ARMBAND)) then
armband = 1;
end
player:startEvent(0x0195, assaultid, -4, 0, recommendedLevel, 2, armband);
else
player:messageSpecial(NOTHING_HAPPENS);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local assaultid = player:getCurrentAssault();
local cap = bit.band(option, 0x03);
if (cap == 0) then
cap = 99;
elseif (cap == 1) then
cap = 70;
elseif (cap == 2) then
cap = 60;
else
cap = 50;
end
player:setVar("AssaultCap", cap);
local party = player:getParty();
if (party ~= nil) then
for i,v in ipairs(party) do
if (not (v:hasKeyItem(NYZUL_ISLE_ASSAULT_ORDERS) and v:getCurrentAssault() == assaultid)) then
player:messageText(target,MEMBER_NO_REQS, false);
player:instanceEntry(target,1);
return;
elseif (v:getZone() == player:getZone() and v:checkDistance(player) > 50) then
player:messageText(target,MEMBER_TOO_FAR, false);
player:instanceEntry(target,1);
return;
end
end
end
player:createInstance(player:getCurrentAssault(), 77);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,target)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x74 or (csid == 0x195 and option == 4)) then
player:setPos(0,0,0,0,77);
end
end;
-----------------------------------
-- onInstanceLoaded
-----------------------------------
function onInstanceCreated(player,target,instance)
if (instance) then
instance:setLevelCap(player:getVar("AssaultCap"));
player:setVar("AssaultCap", 0);
player:setInstance(instance);
player:instanceEntry(target,4);
player:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS);
player:delKeyItem(ASSAULT_ARMBAND);
if (party ~= nil) then
for i,v in ipairs(party) do
if v:getID() ~= player:getID() and v:getZone() == player:getZone() then
v:setInstance(instance);
v:startEvent(0x74, 2);
v:delKeyItem(NYZUL_ISLE_ASSAULT_ORDERS);
end
end
end
else
player:messageText(target,CANNOT_ENTER, false);
player:instanceEntry(target,3);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/globals/abilities/stutter_step.lua | 28 | 8023 | -----------------------------------
-- Ability: Stutter Step
-- Applies Weakened Daze. Lowers the targets magic resistance. If successful, you will earn two Finishing Moves.
-- Obtained: Dancer Level 40
-- TP Required: 10%
-- Recast Time: 00:05
-- Duration: First Step lasts 1 minute, each following Step extends its current duration by 30 seconds.
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
if (player:getAnimation() ~= 1) then
return MSGBASIC_REQUIRES_COMBAT,0;
else
if (player:hasStatusEffect(EFFECT_TRANCE)) then
return 0,0;
elseif (player:getTP() < 10) then
return MSGBASIC_NOT_ENOUGH_TP,0;
else
return 0,0;
end
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
-- Only remove TP if the player doesn't have Trance.
if not player:hasStatusEffect(EFFECT_TRANCE) then
player:delTP(10);
end;
local hit = 3;
local effect = 1;
if math.random() <= getHitRate(player,target,true,player:getMod(MOD_STEP_ACCURACY)) then
hit = 7;
local mjob = player:getMainJob();
local daze = 1;
if (mjob == 19) then
if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
daze = 3;
effect = 3;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30);
daze = 2;
effect = 2;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
daze = 3;
effect = 4;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
daze = 2;
effect = 3;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
daze = 3;
effect = 5;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
daze = 2;
effect = 4;
end
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4);
if (player:hasStatusEffect(EFFECT_PRESTO)) then
daze = 3;
else
daze = 2;
end
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30);
effect = 5;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
daze = 1;
effect = 5;
else
if (player:hasStatusEffect(EFFECT_PRESTO)) then
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,60);
daze = 3;
effect = 2;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60);
daze = 2;
effect = 1;
end
end;
else
if (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_1)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_1):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_1);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_2,1,0,duration+30);
effect = 2;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_2)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_2):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_2);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_3,1,0,duration+30);
effect = 3;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_3)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_3):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_3);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_4,1,0,duration+30);
effect = 4;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_4)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_4):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_4);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
effect = 5;
elseif (target:hasStatusEffect(EFFECT_WEAKENED_DAZE_5)) then
local duration = target:getStatusEffect(EFFECT_WEAKENED_DAZE_5):getDuration();
target:delStatusEffectSilent(EFFECT_WEAKENED_DAZE_5);
target:addStatusEffect(EFFECT_WEAKENED_DAZE_5,1,0,duration+30);
effect = 5;
else
target:addStatusEffect(EFFECT_WEAKENED_DAZE_1,1,0,60);
effect = 1;
end;
end
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_1);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_2);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3);
if (daze > 2) then
daze = 2;
end;
player:addStatusEffect(EFFECT_FINISHING_MOVE_3+daze,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_5,1,0,7200);
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
else
player:addStatusEffect(EFFECT_FINISHING_MOVE_1 - 1 + daze,1,0,7200);
end;
else
ability:setMsg(158);
end
return effect, getStepAnimation(player:getWeaponSkillType(SLOT_MAIN)), hit;
end; | gpl-3.0 |
gabri94/packages-2 | lang/luaexpat/files/compat-5.1r5/compat-5.1.lua | 251 | 6391 | --
-- Compat-5.1
-- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat)
-- According to Lua 5.1
-- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $
--
_COMPAT51 = "Compat-5.1 R5"
local LUA_DIRSEP = '/'
local LUA_OFSEP = '_'
local OLD_LUA_OFSEP = ''
local POF = 'luaopen_'
local LUA_PATH_MARK = '?'
local LUA_IGMARK = ':'
local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type
local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub
--
-- avoid overwriting the package table if it's already there
--
package = package or {}
local _PACKAGE = package
package.path = LUA_PATH or os.getenv("LUA_PATH") or
("./?.lua;" ..
"/usr/local/share/lua/5.0/?.lua;" ..
"/usr/local/share/lua/5.0/?/?.lua;" ..
"/usr/local/share/lua/5.0/?/init.lua" )
package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or
"./?.so;" ..
"./l?.so;" ..
"/usr/local/lib/lua/5.0/?.so;" ..
"/usr/local/lib/lua/5.0/l?.so"
--
-- make sure require works with standard libraries
--
package.loaded = package.loaded or {}
package.loaded.debug = debug
package.loaded.string = string
package.loaded.math = math
package.loaded.io = io
package.loaded.os = os
package.loaded.table = table
package.loaded.base = _G
package.loaded.coroutine = coroutine
local _LOADED = package.loaded
--
-- avoid overwriting the package.preload table if it's already there
--
package.preload = package.preload or {}
local _PRELOAD = package.preload
--
-- looks for a file `name' in given path
--
local function findfile (name, pname)
name = gsub (name, "%.", LUA_DIRSEP)
local path = _PACKAGE[pname]
assert (type(path) == "string", format ("package.%s must be a string", pname))
for c in gfind (path, "[^;]+") do
c = gsub (c, "%"..LUA_PATH_MARK, name)
local f = io.open (c)
if f then
f:close ()
return c
end
end
return nil -- not found
end
--
-- check whether library is already loaded
--
local function loader_preload (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
assert (type(_PRELOAD) == "table", "`package.preload' must be a table")
return _PRELOAD[name]
end
--
-- Lua library loader
--
local function loader_Lua (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local filename = findfile (name, "path")
if not filename then
return false
end
local f, err = loadfile (filename)
if not f then
error (format ("error loading module `%s' (%s)", name, err))
end
return f
end
local function mkfuncname (name)
name = gsub (name, "^.*%"..LUA_IGMARK, "")
name = gsub (name, "%.", LUA_OFSEP)
return POF..name
end
local function old_mkfuncname (name)
--name = gsub (name, "^.*%"..LUA_IGMARK, "")
name = gsub (name, "%.", OLD_LUA_OFSEP)
return POF..name
end
--
-- C library loader
--
local function loader_C (name)
assert (type(name) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local filename = findfile (name, "cpath")
if not filename then
return false
end
local funcname = mkfuncname (name)
local f, err = loadlib (filename, funcname)
if not f then
funcname = old_mkfuncname (name)
f, err = loadlib (filename, funcname)
if not f then
error (format ("error loading module `%s' (%s)", name, err))
end
end
return f
end
local function loader_Croot (name)
local p = gsub (name, "^([^.]*).-$", "%1")
if p == "" then
return
end
local filename = findfile (p, "cpath")
if not filename then
return
end
local funcname = mkfuncname (name)
local f, err, where = loadlib (filename, funcname)
if f then
return f
elseif where ~= "init" then
error (format ("error loading module `%s' (%s)", name, err))
end
end
-- create `loaders' table
package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, }
local _LOADERS = package.loaders
--
-- iterate over available loaders
--
local function load (name, loaders)
-- iterate over available loaders
assert (type (loaders) == "table", "`package.loaders' must be a table")
for i, loader in ipairs (loaders) do
local f = loader (name)
if f then
return f
end
end
error (format ("module `%s' not found", name))
end
-- sentinel
local sentinel = function () end
--
-- new require
--
function _G.require (modname)
assert (type(modname) == "string", format (
"bad argument #1 to `require' (string expected, got %s)", type(name)))
local p = _LOADED[modname]
if p then -- is it there?
if p == sentinel then
error (format ("loop or previous error loading module '%s'", modname))
end
return p -- package is already loaded
end
local init = load (modname, _LOADERS)
_LOADED[modname] = sentinel
local actual_arg = _G.arg
_G.arg = { modname }
local res = init (modname)
if res then
_LOADED[modname] = res
end
_G.arg = actual_arg
if _LOADED[modname] == sentinel then
_LOADED[modname] = true
end
return _LOADED[modname]
end
-- findtable
local function findtable (t, f)
assert (type(f)=="string", "not a valid field name ("..tostring(f)..")")
local ff = f.."."
local ok, e, w = find (ff, '(.-)%.', 1)
while ok do
local nt = rawget (t, w)
if not nt then
nt = {}
t[w] = nt
elseif type(t) ~= "table" then
return sub (f, e+1)
end
t = nt
ok, e, w = find (ff, '(.-)%.', e+1)
end
return t
end
--
-- new package.seeall function
--
function _PACKAGE.seeall (module)
local t = type(module)
assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")")
local meta = getmetatable (module)
if not meta then
meta = {}
setmetatable (module, meta)
end
meta.__index = _G
end
--
-- new module function
--
function _G.module (modname, ...)
local ns = _LOADED[modname]
if type(ns) ~= "table" then
ns = findtable (_G, modname)
if not ns then
error (string.format ("name conflict for module '%s'", modname))
end
_LOADED[modname] = ns
end
if not ns._NAME then
ns._NAME = modname
ns._M = ns
ns._PACKAGE = gsub (modname, "[^.]*$", "")
end
setfenv (2, ns)
for i, f in ipairs (arg) do
f (ns)
end
end
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/globals/weaponskills/mercy_stroke.lua | 10 | 1999 | -----------------------------------
-- Mercy Stroke
-- Dagger weapon skill
-- Skill level: N/A
-- Batardeau/Mandau: Temporarily improves params.critical hit rate.
-- Aftermath gives +5% params.critical hit rate.
-- Must have Batardeau, Mandau, or Clement Skean equipped.
-- Aligned with the Shadow Gorget & Soil Gorget.
-- Aligned with the Shadow Belt & Soil Belt.
-- Element: None
-- Modifiers: STR:60%
-- 100%TP 200%TP 300%TP
-- 3.00 3.00 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3;
params.str_wsc = 0.6; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 6; params.ftp200 = 6; params.ftp300 = 6;
params.str_wsc = 0.8;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if((player:getEquipID(SLOT_MAIN) == 18270) and (player:getMainJob() == JOB_RDM or JOB_THF or JOB_BRD)) then
if(damage > 0) then
if(player:getTP() >= 100 and player:getTP() < 200) then
player:addStatusEffect(EFFECT_AFTERMATH, 5, 0, 20, 0, 2);
elseif(player:getTP() >= 200 and player:getTP() < 300) then
player:addStatusEffect(EFFECT_AFTERMATH, 5, 0, 40, 0, 2);
elseif(player:getTP() == 300) then
player:addStatusEffect(EFFECT_AFTERMATH, 5, 0, 60, 0, 2);
end
end
end
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Sacrificial_Chamber/npcs/_4j3.lua | 12 | 1337 | -----------------------------------
-- Area: Sacrificial Chamber
-- NPC: Mahogany Door
-- @pos 19 -1 -4 163
-------------------------------------
package.loaded["scripts/zones/Sacrificial_Chamber/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/missions");
require("scripts/zones/Sacrificial_Chamber/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZoneID(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option))then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Open_sea_route_to_Mhaura/npcs/Sheadon.lua | 13 | 1128 | -----------------------------------
-- Area: Open_sea_route_to_Mhaura
-- NPC: Sheadon
-- Notes: Tells ship ETA time
-- @pos 0.340 -12.232 -4.120 47
-----------------------------------
package.loaded["scripts/zones/Open_sea_route_to_Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Open_sea_route_to_Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(ON_WAY_TO_MHAURA,0,0); -- Earth Time, Vana Hours. Needs a get-time function for boat?
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/RuLude_Gardens/npcs/Pakh_Jatalfih.lua | 19 | 2721 | -----------------------------------
-- Area: Ru'Lud Gardens
-- NPC: Pakh Jatalfih
-- @pos 34 8 -35 243
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
package.loaded["scripts/globals/missions"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/RuLude_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
pNation = player:getNation();
if(pNation == WINDURST) then
currentMission = player:getCurrentMission(pNation);
MissionStatus = player:getVar("MissionStatus");
if(currentMission == A_NEW_JOURNEY and MissionStatus == 1) then
player:startEvent(0x002B);
elseif(currentMission == A_NEW_JOURNEY and MissionStatus == 2) then
player:startEvent(0x0044);
elseif(currentMission == A_NEW_JOURNEY and MissionStatus == 3) then
player:startEvent(0x008D);
elseif(player:getRank() == 4 and MissionStatus == 0) then
if(getMissionRankPoints(player,13) == 1) then
player:startEvent(0x0032);
else
player:startEvent(0x0036);
end
elseif(player:getRank() == 4 and player:getCurrentMission(WINDURST) == 255 and MissionStatus ~= 0 and getMissionRankPoints(player,13) == 1) then
player:startEvent(0x0086);
elseif(currentMission == MAGICITE and MissionStatus == 2) then
player:startEvent(0x0089);
elseif(currentMission == MAGICITE and MissionStatus == 6) then
player:startEvent(0x0025);
elseif(player:hasKeyItem(MESSAGE_TO_JEUNO_WINDURST)) then
player:startEvent(0x0039);
elseif(player:getRank() >= 5) then
player:startEvent(0x0039);
else
player:startEvent(0x006b);
end
elseif(pNation == SANDORIA) then
player:startEvent(0x0034);
elseif(pNation == BASTOK) then
player:startEvent(0x0033);
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 == 0x002B) then
player:setVar("MissionStatus",2);
elseif(csid == 0x008D) then
player:setVar("MissionStatus",4);
elseif(csid == 0x0025) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
nesstea/darkstar | scripts/globals/mobskills/Serpentine_Tail.lua | 37 | 1218 | ---------------------------------------------
-- Serpentine Tail
--
-- Description: Deals heavy damage to a target behind the user.
-- Type: Physical
-- 2-3 Shadows
-- Range: Back
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
if (mob:getFamily() == 316) then
local mobSkin = mob:getModelId();
if (mobSkin == 1796) then
return 0;
else
return 1;
end
elseif (mob:getFamily() == 313) then -- Tinnin
if (mob:AnimationSub() < 2 and target:isBehind(mob, 48) == true) then
return 0;
else
return 1;
end
end
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = 1;
local accmod = 1;
local dmgmod = 4.25;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,2,3,4);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_3_SHADOW);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
ndbeals/Luabox | lua/luabox/ui/folderview.lua | 2 | 12831 | local PANEL = {}
PANEL.ClassName = "Luabox_Folder_View_Row"
PANEL.Base = "DLabel"
local spacing = 4
function PANEL:SetBackgroundColor( col )
self.m_bgColor = col
end
function PANEL:Init()
self.Name = ""
self.Size = 0
self.Date = 0
self.DateLabel = vgui.Create( "DLabel" , self )
self.DateLabel:SetTextColor( luabox.Colors.Outline )
self.SizeLabel = vgui.Create( "DLabel" , self )
self.SizeLabel:SetTextColor( luabox.Colors.Outline )
self.NameLabel = vgui.Create( "DLabel" , self )
self.NameLabel:SetTextColor( luabox.Colors.Outline )
self.Icon = vgui.Create( "DImage" , self )
self.Icon:SetImage( "icon16/folder.png" )
self:SetText("")
self.m_bgColor = Color(255,255,255)
end
function PANEL:SetIsFile( bool )
if bool then
self.Icon:SetImage( "icon16/page.png" )
else
self.Icon:SetImage( "icon16/folder.png" )
end
end
function PANEL:Paint( w , h )
surface.SetDrawColor( self.m_bgColor )
surface.DrawRect( 0 , 0 , w , h )
if self:IsSelected() then
derma.SkinHook( "Paint" , "Selection" , self , w , h )
end
end
function PANEL:SetHeaderWidth( width )
self.HeaderWidth = width
end
function PANEL:SetInfo( filename , filesize , filedate )
self.Name = filename
self.Size = filesize
self.Date = filedate
self.NameLabel:SetText( filename )
if filesize == 0 then
self.SizeLabel:SetText( "" )
else
self.SizeLabel:SetText( string.NiceSize( filesize ) )
end
if filedate == 0 then
self.DateLabel:SetText( "" )
else
self.DateLabel:SetText( os.date( "%c" , filedate ) )
end
end
function PANEL:PerformLayout( w , h )
self.Icon:SetSize( 16 , 16 )
self.Icon:SetPos( spacing , (h - self.Icon:GetTall() ) / 2 )
self.NameLabel:SetWide( self:GetWide() - self.HeaderWidth * 2 - (spacing * 6.5) )
--self.NameLabel:SetPos( spacing * 1.5 , 0 )
self.NameLabel.y = (h - self.NameLabel:GetTall() ) / 2
self.NameLabel:MoveRightOf( self.Icon , spacing * 1.5 )
self.SizeLabel:SetWide( self.HeaderWidth - spacing * 1.5 )
self.SizeLabel.y = (h - self.SizeLabel:GetTall() ) / 2
self.SizeLabel:MoveRightOf( self.NameLabel , spacing * 1.5 )
self.DateLabel:SetWide( self.HeaderWidth - spacing * 1.5 )
self.DateLabel.y = (h - self.DateLabel:GetTall() ) / 2
self.DateLabel:MoveRightOf( self.SizeLabel , spacing * 1.5 )
end
function PANEL:SetFileSystem( fs )
self.FileSystem = fs
end
function PANEL:GetFileSystem()
return self.FileSystem
end
vgui.Register( PANEL.ClassName , PANEL , PANEL.Base )
local PANEL = {}
PANEL.ClassName = "Luabox_Folder_View"
PANEL.Base = "DPanel"
--PANEL.MinimumHeaderWidth = 50
function PANEL:Init()
self:DockPadding( 0 , 0 , 0 , 0 )
self.Headers = {}
self.Rows = {}
self.Files = {}
self.Directories = {}
self.HeaderWidth = 100
self:SetupHeader()
self:SetupList()
end
function PANEL:Paint( w , h )
draw.RoundedBox( 4 , 0 , 0 , w , h , self.m_bgColor )
end
function PANEL:SetupHeader()
self.HeaderArea = vgui.Create( "DPanel" , self )
self.HeaderArea:Dock( TOP )
self.FileHeader = vgui.Create( "DButton" , self.HeaderArea )
self.FileHeader:DockMargin( -1 , -1 , 0 , 0 )
self.FileHeader:Dock( FILL )
self.FileHeader:SetText( "Name" )
--[[
self.FileHeader.ResizeColumn = function( button , wide )
self:ResizeColumn( button , self.FileHeaderSizer , wide )
end
self.FileHeaderSizer = vgui.Create( "DListView_DraggerBar" , self.FileHeader )
self.FileHeaderSizer:SetWide( 4 )
self.FileHeaderSizer:Dock( RIGHT )
--]]
table.insert( self.Headers , { Header = self.FileHeader , Sizer = self.FileHeaderSizer } )
self.DateHeader = vgui.Create( "DButton" , self.HeaderArea )
self.DateHeader:DockMargin( -1 , -1 , -1 , 0 )
self.DateHeader:Dock( RIGHT )
self.DateHeader:SetText( "Date Modified" )
self.DateHeader:SetWide( self.HeaderWidth )
--[[
self.DateHeader.ResizeColumn = function( button , wide )
self:ResizeColumn( button , self.DateHeaderSizer , wide )
end
self.DateHeaderSizer = vgui.Create( "DListView_DraggerBar" , self.DateHeader )
self.DateHeaderSizer:SetWide( 4 )
self.DateHeaderSizer:Dock( RIGHT )
--]]
table.insert( self.Headers , { Header = self.DateHeader , Sizer = self.DateHeaderSizer } )
self.SizeHeader = vgui.Create( "DButton" , self.HeaderArea )
self.SizeHeader:DockMargin( -1 , -1 , 0 , 0 )
self.SizeHeader:Dock( RIGHT )
self.SizeHeader:SetText( "Size" )
self.SizeHeader:SetWide( self.HeaderWidth )
--[[
self.SizeHeader.ResizeColumn = function( button , wide )
self:ResizeColumn( button , self.SizeHeaderSizer , wide )
end
self.SizeHeaderSizer = vgui.Create( "DListView_DraggerBar" , self.SizeHeader )
self.SizeHeaderSizer:SetWide( 4 )
self.SizeHeaderSizer:Dock( RIGHT )
--]]
table.insert( self.Headers , { Header = self.SizeHeader , Sizer = self.SizeHeaderSizer } )
end
function PANEL:ResizeColumn( header , sizer , wide )
local startsizing = false
local remainingwidth = 0
local remainingheaders = 0
local minwidth = 0
for i , v in ipairs( self.Headers ) do
if v.Header == header then
startsizing = true
remainingheaders = ( #self.Headers - i)
minwidth = self.MinimumHeaderWidth * remainingheaders
if wide + minwidth >= self:GetWide() then
wide = self:GetWide() - minwidth
end
wide = math.Max( wide , self.MinimumHeaderWidth )
remainingwidth = self:GetWide() - wide
end
if startsizing then
v.Header:SetWide( remainingwidth / remainingheaders )
--v.Sizer:AlignRight()
end
end
header:SetWide( wide )
--sizer:AlignRight()
end
function PANEL:SetupList()
self.FileList = vgui.Create( "DListLayout" , self )
self.FileList:DockMargin( 0 , -1 , 0 , 0 )
self.FileList:Dock( FILL )
--self.FileList:SetTall(400)
--self.FileList:SetWide(300)
self.FileList:MakeDroppable( "luabox_file_drop" , true )
self.FileList:SetSelectionCanvas( true )
self.FileList:SetDropPos( "5" )
self.FileList.PerformLayout = function() end
self.FileList:Receiver( "luabox_file_drop" , self.DropAction )
self.FileList.OnMousePressed = function( list , mousecode )
if mousecode == MOUSE_RIGHT then
self:DoRightClick()
end
if ( list.m_bSelectionCanvas && !dragndrop.IsDragging() ) then
list:StartBoxSelection();
return
end
if ( list:IsDraggable() ) then
list:MouseCapture( true )
list:DragMousePress( mousecode );
end
end
self.FileList.PaintOver = function( pnl , w , h )
if not w or not h then
w = self:GetWide()
h = self:GetTall()
end
surface.SetDrawColor( Color ( 91 , 96 , 100 , 255 ) )
surface.DrawLine( -1 , 0 , w , 0 )
for i = 2 , #self.Headers do
local header = self.Headers[i].Header
surface.DrawLine( header.x , 0 , header.x , h )
end
end
self.FileList.OnModified = function( list )
self:ColorRows()
self:GetParent():GetParent():RefreshFileTree()
end
self.FileList.OldStartBoxSelection = self.FileList.StartBoxSelection
self.FileList.StartBoxSelection = function( list )
list.OldStartBoxSelection( list )
local drawselection = list.PaintOver
local drawlist = list.PaintOver_Old
list.PaintOver = function( list , w , h )
drawlist( list , w , h )
drawselection( list , w , h )
end
end
end
function PANEL:AddRow( filename , filesize , filedate )
local row = vgui.Create( "Luabox_Folder_View_Row" )
row:DockPadding( 0 , 0 , 0 , 0 )
row:SetHeaderWidth( self.HeaderWidth )
row:SetInfo( filename , filesize , filedate )
row:SetSelectable(true)
row.DroppedOn = function( row , drop )
local success = drop.FileSystem:Move( row.FileSystem )
if success then
drop:Remove()
table.RemoveByValue( self.Rows , drop )
table.RemoveByValue( self.Files , drop )
table.RemoveByValue( self.Directories , drop )
end
end
row.DoDoubleClick = function( row )
if not row.FileSystem:GetSingleFile() then
self:SetFileSystem( row.FileSystem )
--self:GetParent():GetParent():OnFolderOpened( row.FileSystem )
end
end
row.DoClick = function( row )
if self.SelectedRow == row then
row:SetSelected( false )
self.SelectedRow = nil
return
end
if IsValid( self.SelectedRow ) then
self.SelectedRow:SetSelected( false )
end
self.SelectedRow = row
row:SetSelected( true )
if row.OnClick then
row:OnClick()
end
end
table.insert( self.Rows , row )
self:ColorRows()
self.FileList:Add( row )
return row
end
function PANEL:ColorRows()
for i , row in ipairs( self.Rows ) do
if i % 2 == 1 then
row:SetBackgroundColor( luabox.Colors.White )
else
row:SetBackgroundColor( luabox.Colors.LightGray )
end
end
end
function PANEL:DropAction( Drops, bDoDrop, Command, x, y )
local closest = self:GetClosestChild( x, y )
if ( !IsValid( closest ) ) then
return self:DropAction_Simple( Drops, bDoDrop, Command, x, y )
end
local h = closest:GetTall()
local w = closest:GetWide()
local drop = 0
if ( self.bDropCenter ) then drop = 5 end
self:SetDropTarget( closest.x, closest.y, closest:GetWide() , closest:GetTall() )
for k , v in pairs(Drops) do
--v.Selected = true
end
if ( table.HasValue( Drops, closest ) ) then return end
if ( !bDoDrop && !self:GetUseLiveDrag() ) then return end
for k, v in pairs( Drops ) do
--v.Selected = false
-- Don't drop one of our parents onto us
-- because we'll be sucked into a vortex
if ( v:IsOurChild( self ) ) then continue end
v = v:OnDrop( self )
if ( drop == 5 ) then
closest:DroppedOn( v )
end
end
self:OnModified()
end
function PANEL:SetFileSystem( fs )
--if self.FileSystem == fs then return end
self.FileSystem = fs
self:Clear()
local back = self:AddRow( ".." , 0 , 0 )
back:SetFileSystem( self.FileSystem:GetRootFileSystem() )
back.DoDoubleClick = function( back )
self:SetFileSystem( back:GetFileSystem() )
end
table.insert( self.Directories , back )
back:SetSelectable( false )
for i , v in ipairs( fs:GetDirectories() ) do
local row = self:AddRow( v:GetName() , 0 , file.Time( v:GetPath() , "DATA" ) )
row:SetFileSystem( v )
table.insert( self.Directories , row )
end
for i , v in ipairs( fs:GetFiles() ) do
local row = self:AddRow( v:GetName() , file.Size( v:GetPath() , "DATA" ) , file.Time( v:GetPath() , "DATA" ) )
row:SetIsFile( true )
row:SetFileSystem( v )
table.insert( self.Files , row )
end
self:GetParent():GetParent():OnFolderViewChanged( fs )
end
function PANEL:GetFileSystem()
return self.FileSystem
end
function PANEL:Clear()
for i , v in ipairs( self.Rows ) do
v:Remove()
end
self.Rows = {}
self.Files = {}
self.Directories = {}
end
function PANEL:Refresh()
self:SetFileSystem( self.FileSystem )
end
function PANEL:PerformLayout()
--[[
self.FileHeaderSizer:StretchToParent( nil , 0 , nil , 0 )
self.FileHeaderSizer:AlignRight()
self.SizeHeaderSizer:StretchToParent( nil , 0 , nil , 0 )
self.SizeHeaderSizer:AlignRight()
self.DateHeaderSizer:StretchToParent( nil , 0 , nil , 0 )
self.DateHeaderSizer:AlignRight()
--]]
end
function PANEL:OnMousePressed( mousecode )
if ( self:GetDisabled() ) then return end
if ( mousecode == MOUSE_LEFT && !dragndrop.IsDragging() && self.m_bDoubleClicking ) then
if ( self.LastClickTime && SysTime() - self.LastClickTime < 0.2 ) then
self:DoDoubleClickInternal()
self:DoDoubleClick()
return
end
self.LastClickTime = SysTime()
end
-- If we're selectable and have shift held down then go up
-- the parent until we find a selection canvas and start box selection
if ( mousecode == MOUSE_LEFT ) then
if ( input.IsShiftDown() ) then
return self.FileList:StartBoxSelection()
end
end
--self:MouseCapture( true )
--self.Depressed = true
--self:OnDepressed()
--self:InvalidateLayout( true )
end
vgui.Register( PANEL.ClassName , PANEL , PANEL.Base )
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Chateau_dOraguille/npcs/Chaloutte.lua | 38 | 1053 | -----------------------------------
-- Area: Chateau d'Oraguille
-- NPC: Chaloutte
-- Type: Event Scene Replayer
-- @zone: 233
-- @pos 10.450 -1 -11.985
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x022d);
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/buttered_nebimonite.lua | 18 | 1386 | -----------------------------------------
-- ID: 4267
-- Item: Buttered Nebimonite
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 1
-- Vitality 2
-- defense % 25
-- defense Cap 75
-----------------------------------------
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,4267);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 1);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 75);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 1);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 75);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Antonian.lua | 13 | 2156 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Antonian
-- Regional Marchant NPC
-- Only sells when San d'Oria controlls Aragoneu.
-----------------------------------
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(ARAGONEU);
if(RegionOwner ~= SANDORIA) then
player:showText(npc,ANTONIAN_CLOSED_DIALOG);
else
player:showText(npc,ANTONIAN_OPEN_DIALOG);
stock = {0x0277,36, --Horo Flour
0x0275,43, --Millioncorn
0x113f,111, --Roasted Corn
0x0349,36, --Yagudo Feather
0x1199,90} --Sunflower Seeds
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 |
GabrielNicolasAvellaneda/boundary-plugin-ping-check | modules/framework.lua | 3 | 48474 | -- Copyright 2015 Boundary, Inc.
--
-- 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.-
---------------
-- A Boundary Plugin Framework for easy development of custom Boundary.com plugins.
--
-- [https://github.com/boundary/boundary-plugin-framework-lua](https://github.com/boundary/boundary-plugin-framework-lua)
-- @module Boundary Plugin Framework for LUA
-- @author Gabriel Nicolas Avellaneda <avellaneda.gabriel@gmail.com>
-- @license Apache 2.0
-- @copyright 2015 Boundary, Inc
local Emitter = require('core').Emitter
local Object = require('core').Object
local timer = require('timer')
local math = require('math')
local string = require('string')
local os = require('os')
local fs = require('fs')
local http = require('http')
local https = require('https')
local net = require('net')
local bit = require('bit')
local table = require('table')
local childprocess = require('childprocess')
local json = require('json')
local _url = require('url')
local framework = {}
local querystring = require('querystring')
local boundary = require('boundary')
local io = require('io')
local hrtime = require('uv').Process.hrtime
framework.version = '0.9.6'
framework.boundary = boundary
framework.params = boundary.param or json.parse(fs.readFileSync('param.json')) or {}
framework.plugin_params = boundary.plugin or json.parse(fs.readFileSync('plugin.json')) or {}
framework.metrics = boundary.metrics or json.parse(fs.readFileSync('metrics.json')) or {}
local plugin_params = framework.plugin_params
framework.string = {}
framework.functional = {}
framework.table = {}
framework.util = {}
framework.http = {}
-- Remove this when we migrate to luvit 2.0.x
function framework.util.parseUrl(url, parseQueryString)
assert(url, 'parse expect a non-nil value')
local href = url
local chunk, protocol = url:match("^(([a-z0-9+]+)://)")
url = url:sub((chunk and #chunk or 0) + 1)
local auth
chunk, auth = url:match('(([0-9a-zA-Z]+:?[0-9a-zA-Z]+)@)')
url = url:sub((chunk and #chunk or 0) + 1)
local host
local hostname
local port
if protocol then
host = url:match("^([%a%.%d-]+:?%d*)")
if host then
hostname = host:match("^([^:/]+)")
port = host:match(":(%d+)$")
end
url = url:sub((host and #host or 0) + 1)
end
host = hostname -- Just to be compatible with our code base. Discuss this.
local path
local pathname
local search
local query
local hash
hash = url:match("(#.*)$")
url = url:sub(1, (#url - (hash and #hash or 0)))
if url ~= '' then
path = url
local temp
temp = url:match("^[^?]*")
if temp ~= '' then
pathname = temp
end
temp = url:sub((pathname and #pathname or 0) + 1)
if temp ~= '' then
search = temp
end
if search then
temp = search:sub(2)
if temp ~= '' then
query = temp
end
end
end
if parseQueryString then
query = querystring.parse(query)
end
return {
href = href,
protocol = protocol,
host = host,
hostname = hostname,
port = port,
path = path or '/',
pathname = pathname or '/',
search = search,
query = query,
auth = auth,
hash = hash
}
end
_url.parse = framework.util.parseUrl
do
local encode_alphabet = {
'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/'
}
local decode_alphabet = {}
for i, v in ipairs(encode_alphabet) do
decode_alphabet[v] = i-1
end
local function translate(sixbit)
return encode_alphabet[sixbit + 1]
end
local function unTranslate(char)
return decode_alphabet[char]
end
local function toBytes(str)
return { str:byte(1, #str) }
end
local function mask6bits(byte)
return bit.band(0x3f, byte)
end
local function pad(bytes)
local to_pad = 3 - #bytes % 3
while to_pad > 0 and to_pad ~= 3 do
table.insert(bytes, 0x0)
to_pad = to_pad - 1
end
return bytes
end
local function encode(str, no_padding)
local bytes = toBytes(str)
local bytesTotal = #bytes
if bytesTotal == 0 then
return ''
end
bytes = pad(bytes)
local output = {}
local i = 1
while i < #bytes do
-- read three bytes into a 24 bit buffer to produce 4 coded bytes.
local buffer = bit.rol(bytes[i], 16)
buffer = bit.bor(buffer, bit.rol(bytes[i+1], 8))
buffer = bit.bor(buffer, bytes[i+2])
-- get six bits at a time and translate to base64
for j = 18, 0, -6 do
table.insert(output, translate(mask6bits(bit.ror(buffer, j))))
end
i = i + 3
end
-- If was padded then replace with = characters
local padding_char = no_padding and '' or '='
if bytesTotal % 3 == 1 then
output[#output-1] = padding_char
output[#output] = padding_char
elseif bytesTotal % 3 == 2 then
output[#output] = padding_char
end
return table.concat(output)
end
local function decode(str)
-- take four encoded octets and produce 3 decoded bytes.
local output = {}
local i = 1
while i < #str do
local buffer = 0
-- get the octet represented by the coded base64 char
-- shift left by 6 bits and or
-- mask the 3 bytes, and convert to ascii
for j = 18, 0, -6 do
local octet = unTranslate(str:sub(i, i))
buffer = bit.bor(bit.rol(octet, j), buffer)
i = i + 1
end
for j = 16, 0, -8 do
local byte = bit.band(0xff, bit.ror(buffer, j))
table.insert(output, byte)
end
end
return string.char(unpack(output))
end
framework.util.base64Encode = encode
framework.util.base64Decode = decode
end
local base64Encode = framework.util.base64Encode
do
local _pairs = pairs({ a = 0 }) -- get the generating function from pairs
local gpairs = function(t, key)
local value
key, value = _pairs(t, key)
return key, key, value
end
local function iterator (obj, param, state)
if (type(obj) == 'table') then
if #obj > 0 then
return ipairs(obj)
else
return gpairs, obj, nil
end
elseif type(obj) == 'function' then
return obj, param, state
end
error(("object %s of type %s can not be iterated."):format(obj, type(obj)))
end
local function call(func, state, ...)
if state == nil then
return nil
end
return state, func(...)
end
local function _each(func, gen, param, state)
repeat
state = call(func, gen(param, state))
until state == nil
end
local function each(func, gen, param, state)
_each(func, iterator(gen, param, state))
end
framework.functional.each = each
local function toMap(gen, param, state)
local t = {}
each(function (k, v)
v = v or k
t[k] = v
end, gen, param, state)
return t
end
framework.functional.toMap = toMap
-- naive version of map
local function map(func, xs)
local t = {}
table.foreach(xs, function (i, v)
--t[i] = func(v, i)
table.insert(t, func(v))
end)
return t
end
framework.functional.map = map
-- naive version of filter
local function filter(func, xs)
local t = {}
table.foreach(xs, function (i, v)
if func(v) then
table.insert(t, v)
--t[i] = v
end
end)
return t
end
framework.functional.filter = filter
-- naive version of reduce
local function reduce(func, acc, xs)
table.foreach(xs, function (i, v)
acc = func(acc, v)
end)
return acc
end
framework.functional.reduce = reduce
end
--- String functions
-- @section string
--- Trim blanks from the string.
-- @param self The string to trim
-- @return The string with trimmed blanks
function framework.string.trim(self)
return string.match(self, '^%s*(.-)%s*$')
end
local trim = framework.string.trim
--- Returns the char from a string at the specified position.
-- @param str the string from were a char will be extracted.
-- @param pos the position in the string. Should be a numeric value greater or equal than 1.
-- @return the char at the specified position. If the position does not exist in the string, nil is returned.
function framework.string.charAt(str, pos)
return string.sub(str, pos, pos)
end
local charAt = framework.string.charAt
--- Check if a string contains the specified pattern.
-- @param pattern the pattern to look for.
-- @param str the string to search from
-- @return true if the pattern exist inside the string.
function framework.string.contains(pattern, str)
local s,_ = string.find(str, pattern)
return s ~= nil
end
--- Replace placeholders with named keys inside a string.
-- @param str the string that has placeholders to be replaced. In example "Hello, {name}"
-- @param map a table with a list of key and values for replacement.
-- @return a string with all the ocurrences of placedholders replaced.
function framework.string.replace(str, map)
for k, v in pairs(map) do
str = str:gsub('{' .. k .. '}', v)
end
return str
end
local replace = framework.string.replace
--- Escape special characters used by pattern matching functionality.
-- @param str the string that will be escaped.
-- @return a new string with all the special characters escaped.
function framework.string.escape(str)
local s, _ = string.gsub(str, '%.', '%%.')
s, _ = string.gsub(s, '%-', '%%-')
return s
end
--- Decode an URL encoded string
-- @param str the URL encoded string
-- @return a new string decoded
function framework.string.urldecode(str)
local char, gsub, tonumber = string.char, string.gsub, tonumber
local function _(hex) return char(tonumber(hex, 16)) end
str = gsub(str, '%%(%x%x)', _)
return str
end
--- URL encode a string
-- @param str the string that will be encoded
-- @return a new string URL encoded
function framework.string.urlencode(str)
if str then
str = string.gsub(str, '\n', '\r\n')
str = string.gsub(str, '([^%w])', function(c)
return string.format('%%%02X', string.byte(c))
end)
end
return str
end
function framework.string.jsonsplit(self)
local outResults = {}
local theStart,theSplitEnd = string.find(self, "{")
local numOpens = theStart and 1 or 0
theSplitEnd = theSplitEnd and theSplitEnd + 1
while theSplitEnd < string.len(self) do
if self[theSplitEnd] == '{' then
numOpens = numOpens + 1
elseif self[theSplitEnd] == '}' then
numOpens = numOpens - 1
end
if numOpens == 0 then
table.insert( outResults, string.sub ( self, theStart, theSplitEnd ) )
theStart,theSplitEnd = string.find(self, "{", theSplitEnd)
numOpens = theStart and 0 or 1
theSplitEnd = theSplitEnd or string.len(self)
end
theSplitEnd = theSplitEnd + 1
end
return outResults
end
--- TODO: To be composable we need to change this interface to gsplit(separator, data)
function framework.string.gsplit(data, separator)
local pos = 1
local iter = function()
if not pos then -- stop the generator (maybe using stateless is a better option?)
return nil
end
local s, e = string.find(data, separator, pos)
if s then
local part = string.sub(data, pos, s-1)
pos = e + 1
return part
else
local part = string.sub(data, pos)
pos = nil
return part
end
end
return iter, data, 1
end
local gsplit = framework.string.gsplit
--- Split as an iterator
-- @param data that will be splitted.
-- @param separator a string or character for the split
-- @func func a function to call for each splitted part of the string
function framework.string.isplit(data, separator, func)
for part in gsplit(data, separator) do
func(part)
end
end
local isplit = framework.string.isplit
-- Split a string into parts
-- @param data the string to split
-- @param separator a string or character that breaks each part of the string.
-- @return a table with all the parts splitted from the string.
function framework.string.split(data, separator)
if not data then
return nil
end
local result = {}
isplit(data, separator, function (part) table.insert(result, part) end)
return result
end
local split = framework.string.split
--- Check if the string is empty. Before checking it will be trimmed to remove blank spaces.
function framework.string.isEmpty(str)
return (str == nil or framework.string.trim(str) == '')
end
local isEmpty = framework.string.isEmpty
--- If not empty returns the value. If is empty, an a default value was specified, it will return that value.
-- @param str the string that will be checked for empty
-- @param default a default value that will be returned if the string is empty
-- @return str or default is str is an empty string.
function framework.string.notEmpty(str, default)
return not framework.string.isEmpty(str) and str or default
end
local notEmpty = framework.string.notEmpty
--- Join two strings using a character
-- @param s1 any string
-- @param s2 any string
-- @param char a character
-- @return a new string with the join of s1 and s2 with character inbetween.
function framework.string.concat(s1, s2, char)
if isEmpty(s2) then
return s1
end
return s1 .. char .. s2
end
--- Utility functions.
-- Various functions that helps with common tasks.
-- @section util
--- Parses anchor links from an HTML string
-- @param html_str the html string from where links will be parsed.
-- @return a table with extracted links
function framework.util.parseLinks(html_str)
local links = {}
for link in string.gmatch(html_str, '<a%s+h?ref=["\']([^"^\']+)["\'][^>]*>[^<]*</%s*a>') do
table.insert(links, link)
end
return links
end
--- Creates an absolute link from a basePath and a relative link.
-- @param basePath the base path to generate an absolute link.
-- @param link a relative link
-- @return A string that represents the absolute link.
function framework.util.absoluteLink(basePath, link)
return basePath .. trim(link)
end
--- Check if the a link is a relative one.
-- @param link the link to check
-- @return true if the link is relative. false otherwise.
function framework.util.isRelativeLink(link)
return not string.match(link, '^https?')
end
--- Wraps a function to calculate the time passed between the wrap and the function execution.
function framework.util.timed(func, startTime)
startTime = startTime or os.time()
return function(...)
return os.time() - startTime, func(...)
end
end
--- Check if an HTTP Status code is of a success kind.
-- @param status the status code number
-- @return true if status code is a success one.
function framework.util.isHttpSuccess(status)
return status >= 200 and status < 300
end
--- Round a number by the to the specified decimal places.
-- @param val the value that will be rounded
-- @param decimal the number of decimal places
-- @return the val rounded at decimal places
function framework.util.round(val, decimal)
assert(val, 'round expect a non-nil value')
if (decimal) then
return math.floor( (val * 10^decimal) + 0.5) / (10^decimal)
else
return math.floor(val+0.5)
end
end
--- Return the current timestamp
-- @return the current timestamp
function framework.util.currentTimestamp()
return os.time()
end
--- Convert megabytes to bytes.
-- @param mb the number of megabytes
-- @return the number of bytes that represent mb
function framework.util.megaBytesToBytes(mb)
return mb * 1024 * 1024
end
--- Represent a number as a percentage
-- @param number the number to represent as a percentage
-- @return number/100
function framework.util.percentage(number)
return number/100
end
--- Pack a tuple that represent a metric into a table
function framework.util.pack(metric, value, timestamp, source)
if value then
return { metric = metric, value = value, timestamp = timestamp, source = source }
end
return nil
end
--- Pack a value for a metric into a table
function framework.util.packValue(value, timestamp, source)
return { value = value, timestamp = timestamp, source = source }
end
function framework.util.ipack(metrics, ...)
table.insert(metrics, framework.util.pack(...))
end
--- Create an auth for HTTP Basic Authentication
function framework.util.auth(username, password)
return notEmpty(username) and notEmpty(password) and (username .. ':' .. password) or nil
end
-- Returns an string for a Boundary Meter event.
-- @param type could be 'CRITICAL', 'ERROR', 'WARN', 'INFO'
function framework.util.eventString(type, message, tags)
tags = tags or ''
return string.format('_bevent:%s|t:%s|tags:%s', message, type, tags)
end
local eventString = framework.util.eventString
--- Functional functions
-- @section functional
--- Return the partial application of a function.
-- @param func a function that will be partially applied.
-- @param x the parameter to partially apply.
-- @return A new function with the application of the x parameter.
function framework.functional.partial(func, x)
return function (...)
return func(x, ...)
end
end
--- Represents the identity function
-- @param x any value
-- @return x
function framework.functional.identity(...)
return ...
end
local identity = framework.functional.identity
-- Propagate the event to another emitter.
function Emitter:propagate(eventName, target, transform)
if (target and target.emit) then
transform = transform or identity
self:on(eventName, function (...) target:emit(eventName, transform(...)) end)
return target
end
return self
end
--- Compose to functions g(f(x))
-- @param f any function
-- @param g any function
-- @return A new function that is the composition of f and g
function framework.functional.compose(f, g)
return function(...)
return g(f(...))
end
end
--- Table functions
-- @section table
--- Get the value at the specified key for a table
-- @param key the key for indexing the table
-- @param t a any table
-- @return the value at the specified key. If t is not a table nil will be returned.
function framework.table.get(key, t)
if type(t) ~= 'table' then
return nil
end
return t[key]
end
--- Find a value inside a table
-- @param a predicate function that test the items of the table
-- @return the first item in the table that satisfy the test condition
function framework.table.find(func, t)
for i, v in pairs(t) do
if func(v, i, t) then
return v, i
end
end
return nil
end
--- Get the number of elements of a table
-- @param t a table
-- @return the number of items from the table
function framework.table.count(t)
local count = 0
for _ in pairs(t) do
count = count + 1
end
return count
end
function framework.table.toSet(t)
if not t then return nil end
local result = {}
local n = 0
for _, v in pairs(t) do
v = trim(v)
if v ~= '' then
n = n + 1
result[v] = true
end
end
return n > 0 and result or nil
end
function framework.util.add(a, b)
return a + b
end
local add = framework.util.add
local reduce = framework.functional.reduce
function framework.util.sum(t)
return reduce(add, 0, t)
end
local sum = framework.util.sum
--- Get the mean value of the elements from a table
-- @param t a table
-- @return the mean value
function framework.util.mean(t)
local count = table.getn(t)
if count == 0 then
return 0
end
local s = sum(add, 0, t)
return s/count
end
function framework.util.ratio(x, y)
if y and tonumber(y) > 0 then
return x / y
end
return 0
end
function framework.util.parseJson(body)
return pcall(json.parse, body)
end
local parseJson = framework.util.parseJson
--- Get returns true if there is any element in the table.
-- @param t a table
-- @return true if there is any element in the table, false otherwise
function framework.table.hasAny(t)
return next(t) ~= nil
end
--- Get the index in the table for the specified value.
-- @param self any table
-- @param value the value to look for
-- @return a number that represent the index of value in the table. If the value does not exist, or t is not a table, nil will be returned.
function framework.table.indexOf(self, value)
if type(self) ~= 'table' then
return nil
end
for i,v in ipairs(self) do
if value == v then
return i
end
end
return nil
end
--- Get all the keys from the table.
-- @param t any table
-- @return a table with all the keys of t
function framework.table.keys(t)
local result = {}
for k,_ in pairs(t) do
table.insert(result, k)
end
return result
end
--- Get a deep copy of a table
-- @param t a table to be cloned
-- @return a new table that is the copy of t.
local clone
clone = function (t)
if type(t) ~= 'table' then return t end
local meta = getmetatable(t)
local target = {}
for k,v in pairs(t) do
if type(v) == 'table' then
target[k] = clone(v)
else
target[k] = v
end
end
setmetatable(target, meta)
return target
end
framework.table.clone = clone
--- Creates a table from a list of keys and values
-- @param keys a list of keys
-- @param values a list of kayes
-- @return a new table with the corresponding keys and values
function framework.table.create(keys, values)
local result = {}
for i, k in ipairs(keys) do
if notEmpty(trim(k)) then
result[k] = values[i]
end
end
return result
end
--- Merge to tables
-- @param t1 any table
-- @param t2 any table
-- @return return a new table with t1 and t2 merged.
function framework.table.merge(t1, t2)
local output = clone(t1)
for k, v in pairs(t2) do
if type(k) == 'number' then
table.insert(output, v)
else
output[k] = v
end
end
return output
end
local merge = framework.table.merge
--- Try to coerce a number or at least to a string.
-- @param x the value that will be converted.
-- @return return a number if x can be parsed, 0 if is an empty string or a string if is not convertible to a number.
function framework.util.parseValue(x)
return tonumber(x) or (isEmpty(x) and 0) or tostring(x) or 0
end
local parseValue = framework.util.parseValue
local map = framework.functional.map
-- TODO: Convert this to a generator
-- TODO: Use gsplit instead of split
function framework.string.parseCSV(data, separator, comment, header)
separator = separator or ','
local parsed = {}
local lines = split(data, '\n')
local headers
if header then
local header_line = string.match(lines[1], comment .. '%s*([' .. separator .. '%S]+)%s*')
headers = split(trim(header_line), separator)
end
for _, v in ipairs(lines) do
if notEmpty(v) then
if not comment or not (charAt(v, 1) == comment) then
local values = split(v, separator)
values = map(parseValue, values)
if headers then
table.insert(parsed, framework.table.create(headers, values))
else
table.insert(parsed, values)
end
end
end
end
return parsed
end
-- You can call framework.string() to export all functions to the string table to the global table for easy access.
local function exportable(t)
setmetatable(t, {
__call = function (u, warn)
for k,v in pairs(u) do
if (warn) then
if _G[k] ~= nil then
process.stderr:write('Warning: Overriding function ' .. k ..' on global space.')
end
end
_G[k] = v
end
end
})
end
-- Allow to export functions to global table
exportable(framework.string)
exportable(framework.util)
exportable(framework.functional)
exportable(framework.table)
exportable(framework.http)
--- Cache class.
-- Work as a cache of values
-- @type Cache
local Cache = Object:extend()
--- Cache constructor.
-- @name Cache:new
-- @param func a function that provides a default value for an inexisting key.
function Cache:initialize(func)
self.func = func
self.cache = {}
end
--- Get a cached value or create a default one.
-- @param key the key associated with the cached value.
-- @return return the value associated with the speciifed key or create a new default value using the constructor function.
function Cache:get(key)
assert(key, 'Cache:get key must be non-nil')
local result = self.cache[key]
if not result then
result = self.func()
self.cache[key] = result -- now cache the value
end
return result
end
framework.Cache = Cache
--- DataSource class.
-- @type DataSource
local DataSource = Emitter:extend()
--- DataSource is the base class for any DataSource. By default accepts a function/closure that will be called each fetch call.
framework.DataSource = DataSource
--- DataSource constructor.
-- @name DataSource:new
-- @param func a function that will be called on each fetch request.
function DataSource:initialize(func)
self.func = func
end
--- Chain the fetch result to the execution of the fetch on another DataSource.
-- @param data_source the DataSource that will be fetched passing the transformed result of the fetch operation.
-- @param transform (optional) transform function to be called on the result of the fetch operation in this instance.
-- @usage: first_ds:chain(second_ds, transformFunc):chain(third_ds, transformFunc)
function DataSource:chain(data_source, transform)
assert(data_source, 'chain: data_source not set.')
self.chained = { data_source, transform }
return data_source
end
function DataSource:onFetch()
self:emit('onFetch')
end
--- Fetch data from the datasource. This is an abstract method.
-- @param context Context information, this can be the caller or another object that you want to set.
-- @param callback A function that will be called when the fetch operation is done. If there are another DataSource chained, this call will be made when the ultimate DataSource in the chain is done.
-- @param params Additional parameters that will be send to the internal DataSource functioan.
function DataSource:fetch(context, callback, params)
self:onFetch(context, callback, params)
local result = self.func(params)
self:processResult(context, callback, result)
end
function DataSource:processResult(context, callback, ...)
if self.chained then
local ds, transform = unpack(self.chained)
if type(ds) == 'function' then
local f = ds
local data_sources = f(self, callback, ...)
if type(data_sources) == 'table' then
for i, v in ipairs(data_sources) do
v:fetch(self, callback, ...) -- TODO: This datasources where created by the function chained. Pass parameters on the constructor?
end
else
--TODO: Use the result of f() or just result? because f can be also a transform function and if you are asigning to a chain the result of this will be the continuated value.
callback(...)
end
else
transform = transform or identity
ds:fetch(self, callback, transform(...))
end
else
callback(...)
end
end
--- CachedDataSource class
-- @type CachedDataSource
local CachedDataSource = DataSource:extend()
--- CachedDataSource allows to cache DataSource fetch calls and refresh
framework.CachedDataSource = CachedDataSource
function CachedDataSource:initialize(ds, refresh_by)
self.ds = ds
self.refresh_by = refresh_by
self.expiration = nil
ds:propagate('error', self)
end
--- Fetch from the provided DataSource or return the cached value
function CachedDataSource:fetch(context, callback, params)
local now = os.time()
if not self.expiration or (now >= self.expiration and self.refresh_by) then
self.expiration = now + (self.refresh_by or 0)
local cache = function (result)
self.cached = result
self:processResult(context, callback, result)
end
self.ds:fetch(context, cache, params)
else
self:processResult(context, callback, self.cached)
end
end
--- NetDataSource class.
-- @type NetDataSource
local NetDataSource = DataSource:extend()
--- NetDataSource constructor
-- @param host the host to connect
-- @param port the port to connect
-- @param close_connection if true, the connection will be closed on each fetch operation.
-- @return a new instance of NetDataSource
function NetDataSource:initialize(host, port, close_connection)
self.host = host
self.port = port
self.close_connection = close_connection or false
end
function NetDataSource:onFetch(socket)
error('you must override the NetDataSource:onFetch')
end
--- Fetch data from the configured host and port
-- @param context A context object that can be used by the fetch operation.
-- @func callback A callback that gets called when there is some data on the socket.
function NetDataSource:fetch(context, callback)
self:connect(function ()
self:onFetch(self.socket)
if callback then
self.socket:once('data', function (data)
callback(data)
if self.close_connection then
self:disconnect()
end
end)
else
if self.close_connection then
self:disconnect()
end
end
end)
end
--- Disconnect the internal socket
function NetDataSource:disconnect()
self.socket:done()
self.socket = nil
end
--- Connect to the initialized host and port and call the callback function on success.
-- @func callback a callback to run on a successfull connection. If called for an already open connection, the callback will be executed immediatelly.
function NetDataSource:connect(callback)
if self.socket and not self.socket.destroyed then
callback()
return
end
assert(notEmpty(self.port), 'You must specify a port to connect to.')
assert(notEmpty(self.host), 'You must specify a host to connect to.')
self.socket = net.createConnection(self.port, self.host, callback)
self.socket:on('error', function (err) self:emit('error', 'Socket error: ' .. err.message) end)
end
framework.NetDataSource = NetDataSource
--- DataSourcePoller class
-- @type DataSourcePoller
local DataSourcePoller = Emitter:extend()
--- DataSourcePoller constructor.
-- DataSourcePoller Polls a DataSource at the specified interval and calls a callback when there is some data available.
-- @int pollInterval number of milliseconds to poll for data
-- @param dataSource A DataSource to be polled
-- @name DataSourcePoller:new
function DataSourcePoller:initialize(pollInterval, dataSource)
self.pollInterval = (pollInterval < 1000 and 1000) or pollInterval
self.dataSource = dataSource
dataSource:propagate('error', self)
end
function DataSourcePoller:_poll(callback)
local success, err = pcall(function ()
self.dataSource:fetch(self, callback)
end)
if not success then
self:emit('error', err)
end
timer.setTimeout(self.pollInterval, function () self:_poll(callback) end)
end
--- Start polling for data.
-- @func callback A callback function to call when the DataSource returns some data.
function DataSourcePoller:run(callback)
if self.running then
return
end
self.running = true
self:_poll(callback)
end
--- Plugin Class.
-- @type Plugin
local Plugin = Emitter:extend()
framework.Plugin = Plugin
--- Plugin constructor.
-- A base plugin implementation that accept a dataSource and polls periodically for new data and format the output so the boundary meter can collect the metrics.
-- @param params is a table of options that can be:
-- pollInterval (optional) the poll interval between data fetchs. This is required if you pass a plain DataSource and not a DataSourcePoller.
-- source (optional)
-- version (options) the version of the plugin.
-- @param dataSource A DataSource that will be polled for data.
-- If is a DataSource a DataSourcePoller will be created internally to pool for data
-- It can also be a DataSourcePoller or PollerCollection.
-- @name Plugin:new
function Plugin:initialize(params, dataSource)
assert(dataSource, 'Plugin:new dataSource is required.')
local pollInterval = (params.pollInterval < 1000 and 1000) or params.pollInterval
if not Plugin:_isPoller(dataSource) then
self.dataSource = DataSourcePoller:new(pollInterval, dataSource)
self.dataSource:propagate('error', self)
else
self.dataSource = dataSource
dataSource:propagate('error', self)
end
self.source = notEmpty(params.source, os.hostname())
if (plugin_params) then
self.version = notEmpty(plugin_params.version, notEmpty(params.version, '0.0'))
self.name = notEmpty(plugin_params.name, notEmpty(params.name, 'Boundary Plugin'))
self.tags = notEmpty(plugin_params.tags, notEmpty(params.tags, ''))
else
self.version = notEmpty(params.version, '0.0')
self.name = notEmpty(params.name, 'Boundary Plugin')
self.tags = notEmpty(params.tags, '')
end
self:on('error', function (err) self:error(err) end)
end
function Plugin:printError(title, host, source, msg)
self:printEvent('error', title, host, source, msg)
end
function Plugin:printInfo(title, host, source, msg)
self:printEvent('info', title, host, source, msg)
end
function Plugin:printWarn(title, host, source, msg)
self:printEvent('warn', title, host, source, msg)
end
function Plugin:printCritical(title, host, source, msg)
self:printEvent('critical', title, host, source, msg)
end
function Plugin.formatMessage(name, version, title, host, source, msg)
if title and title ~= "" then title = '-'..title else title = "" end
if msg and msg ~= "" then msg = '|m:'..msg else msg = "" end
if host and host ~= "" then host = '|h:'..host else host = "" end
if source and source ~= "" then source = '|s:'..source else source = "" end
return string.format('%s version %s%s%s%s%s', name, version, title, msg, host, source)
end
function Plugin.formatTags(tags)
tags = tags or {}
if type(tags) == 'string' then
tags = split(tags, ',')
end
return table.concat(merge({'lua', 'plugin'}, tags), ',')
end
function Plugin:printEvent(eventType, title, host, source, msg)
msg = Plugin.formatMessage(self.name, self.version, title, host, source, msg)
local tags = Plugin.formatTags(self.tags)
print(eventString(eventType, msg, tags))
end
--- Emit an event to the Boundary platform.
-- @type a string that represent the type of the event. It can be 'info', 'warning', 'critical', 'error'.
-- @param msg an string message to send
function Plugin:emitEvent(type, title, host, source, msg)
self:printEvent(type, title, host, source, msg)
end
function Plugin:_isPoller(poller)
return poller.run
end
--- Called when the Plugin detect and error in one of his components.
-- @param err the error emitted by one of the component that failed.
function Plugin:error(err)
err = self:onError(err)
local msg
if type(err) == 'table' and err.message then
msg = err.message
else
msg = tostring(err)
end
local source = err.source or self.source
self:printError(self.source .. ' Error', self.source, source, msg)
end
function Plugin:onError(err)
return err
end
--- Run the plugin and start polling from the configured DataSource
function Plugin:run()
self:emitEvent('info', self.source .. ' Status', self.source, self.source, 'Up')
self.dataSource:run(function (...) self:parseValues(...) end)
end
function Plugin:parseValues(...)
local success, result = pcall(self.onParseValues, self, unpack({...}))
if not success then
self:emitEvent('critical', result)
elseif result then
self:report(result)
end
end
function Plugin:onParseValues(...)
error('You must implement onParseValues')
end
function Plugin:report(metrics)
self:emit('report')
self:onReport(metrics)
end
--- Called by the framework when there are some metrics to send to Boundary platform
-- @param metrics a table that represent the metrics to send
function Plugin:onReport(metrics)
-- metrics can be { metric = value }
-- or {metric = {value, source}}
-- or {metric = {{value, source}, {value, source}, {value, source}}
-- or {metric, value, source}
-- or {{metric, value, source, timestamp}}
for metric, v in pairs(metrics) do
-- { { metric, value .. }, { metric, value .. } }
if type(metric) == 'number' then
print(self:format(v.metric, v.value, notEmpty(v.source, self.source), v.timestamp))
elseif type(v) ~= 'table' then
print(self:format(metric, v, self.source))
elseif type(v[1]) ~= 'table' and v.value then
-- looking for { metric = { value, source, timestamp }}
local source = v.source or self.source
local value = v.value
local timestamp = v.timestamp
print(self:format(metric, value, source, timestamp))
else
-- looking for { metric = {{ value, source, timestamp }}}
for _, j in pairs(v) do
local source = j.source or self.source
local value = j.value
local timestamp = j.timestamp
print(self:format(metric, value, source, timestamp))
end
end
end
end
function Plugin:format(metric, value, source, timestamp)
self:emit('format')
return self:onFormat(metric, value, source, timestamp)
end
--- Called by the framework before formating the metric output.
-- @string metric the metric name
-- @number value the value to format
-- @string source the source to report for the metric
-- @param timestamp the time the metric was retrieved
-- You can override this on your plugin instance.
function Plugin:onFormat(metric, value, source, timestamp)
source = string.gsub(source, '[!@#$%%^&*() {}<>/\\|]', '_')
if timestamp then
return string.format('%s %f %s %s', metric, value, source, timestamp)
else
return string.format('%s %f %s', metric, value, source)
end
end
--- Acumulator Class
-- @type Accumulator
local Accumulator = Emitter:extend()
--- Accumulator constructor.
-- Track values and return the delta for accumulated metrics.
-- @name Accumulator:new
function Accumulator:initialize()
self.map = {}
end
--- Accumulates a value an return the delta between the actual an latest value.
-- @string key the key for the item
-- @param value the item value
-- @return diff the delta between the latests and actual value.
function Accumulator:accumulate(key, value)
assert(value, "Accumulator:accumulate#value must not be null for key " .. key)
local oldValue = self.map[key]
if oldValue == nil then
oldValue = value
end
self.map[key] = value
local diff = value - oldValue
return diff
end
--- Return the last accumulated valor or 0 if there isnt any for the key
-- @param key the key for the item to retrieve
function Accumulator:get(key)
return self.map[key] or 0
end
--- Reset the specified value
-- @string key A key to untrack
function Accumulator:reset(key)
self.map[key] = nil
end
--- Clean up all the tracked key/values.
function Accumulator:resetAll()
self.map = {}
end
-- The object instance can be used as a function call that calls accumulate.
Accumulator.meta.__call = function (t, ...)
return t:accumulate(...)
end
framework.Accumulator = Accumulator
--- A Collection of DataSourcePoller
-- @type PollerCollection
local PollerCollection = Emitter:extend()
--- PollerCollection constructor
-- @param[opt] pollers a list of poller to initially add to this collection.
function PollerCollection:initialize(pollers)
self.pollers = pollers or {}
-- TODO: Configure propagation of errors.
end
--- Add a poller to the collection
-- @param poller a DataSourcePoller to add to the collection
function PollerCollection:add(poller)
table.insert(self.pollers, poller)
poller:propagate('error', self)
end
--- Run all the DataSourcePollers in the collection.
-- @func callback a callback function that will be passed to the DataSourcePollers.
function PollerCollection:run(callback)
if self.running then
return
end
self.running = true
for _,p in pairs(self.pollers) do
p:run(callback)
end
end
--- WebRequestDataSource Class
-- @type WebRequestDataSource
local WebRequestDataSource = DataSource:extend()
--- WebRequestDataSource
-- @name WebRequestDataSource:new
-- @param params a table with the configuraiton parameters.
-- TODO: Document params options
function WebRequestDataSource:initialize(params)
local options = params or {}
if type(params) == 'string' then
options = _url.parse(params)
end
self.wait_for_end = options.wait_for_end or false
self.options = options
self.info = options.meta
end
function WebRequestDataSource:onError(...)
return ...
end
--- Fetch data from the initialized url
function WebRequestDataSource:fetch(context, callback, params)
assert(callback, 'WebRequestDataSource:fetch: callback is required')
local start_time = hrtime()
local options = clone(self.options)
-- Replace variables
params = params or {}
if type(params) == 'table' then
options.path = replace(options.path, params)
options.pathname = replace(options.pathname, params)
end
local buffer = ''
local success = function (res)
if self.wait_for_end then
res:on('end', function ()
local exec_time = hrtime() - start_time
success, error = pcall(function ()
self:processResult(context, callback, buffer, {context = self, info = self.info, response_time = exec_time, status_code = res.statusCode}) end)
if not success then
self:emit('error', error)
end
res:destroy()
end)
else
res:once('data', function (data)
local exec_time = hrtime() - start_time
buffer = buffer .. data
if not self.wait_for_end then
self:processResult(context, callback, buffer, {context = self, info = self.info, response_time = exec_time, status_code = res.statusCode})
res:destroy()
end
end)
end
res:on('data', function (d)
buffer = buffer .. d
end)
res:propagate('data', self)
res:propagate('error', self)
end
options.headers = {}
options.headers['User-Agent'] = 'Boundary Meter <support@boundary.com>'
if options.auth then
options.headers['Authorization'] = 'Basic ' .. base64Encode(options.auth, false)
end
local data = options.data
local body
if data and table.getn(data) > 0 then
body = table.concat(data, '&')
options.headers['Content-Type'] = 'application/x-www-form-urlencoded'
options.headers['Content-Length'] = #body
end
local req
if options.protocol == 'https' then
req = https.request(options, success)
else
req = http.request(options, success)
end
if body and #body > 0 then
req:write(body)
end
req:propagate('error', self, function (err)
err.context = self
err.params = params
return err
end)
req:done()
end
--- RandomDataSource class returns a random number each time it get called.
-- @type RandomDataSource
-- @param context the object that called the fetch
-- @func callback A callback to call with the random generated number
-- @usage local ds = RandomDataSource:new(1, 100) -- Generate numbers from 1 to 100
local RandomDataSource = DataSource:extend()
--- RandomDataSource constructor
-- @int minValue the lower bounds for the random number generation.
-- @int maxValue the upper bound for the random number generation.
-- @usage local ds = RandomDataSource:new(1, 100)
function RandomDataSource:initialize(minValue, maxValue)
DataSource.initialize(self, function ()
return math.random(minValue, maxValue)
end)
end
--- CommandOutputDataSource. A DataSource for parsing the output of command line programs.
-- @type CommandOutputDataSource
local CommandOutputDataSource = DataSource:extend()
--- CommandOutputDataSource constructor
-- @param params a table with path and args of the command to execute
function CommandOutputDataSource:initialize(params)
-- TODO: Handle commands for each operating system.
assert(params, 'CommandOuptutDataSource:new expect a non-nil params parameter')
self.path = params.path
self.args = params.args
self.success_exitcode = params.success_exitcode or 0
self.info = params.info
self.callback_on_errors = params.callback_on_errors
self.use_popen = params.use_popen
end
--- Returns true if is a success exitcode.
-- @param exitcode the exit code to check for success
-- @return true if exitcode is success
function CommandOutputDataSource:isSuccess(exitcode)
return tonumber(exitcode) == self.success_exitcode
end
--- Returns the output of execution of the command
function CommandOutputDataSource:fetch(context, callback, parser, params)
local output = ''
if self.use_popen then
local proc, err = io.popen(self.path .. " " .. table.concat(self.args, ' '), 'r')
if not proc then
self:emit('error', err)
return
end
output = proc:read('*all')
local result = {proc:close()}
callback({context = self, info = self.info, output = output})
else
local proc = childprocess.spawn(self.path, self.args)
local code, ended
proc:propagate('error', self)
proc.stdout:on('data', function (data) output = output .. data end)
proc.stderr:on('data', function (data) output = output .. data end)
local function done()
if not code or not ended then
return
end
if not self:isSuccess(code) then
self:emit('error', {message = 'Command terminated with exitcode \'' .. code .. '\' and message \'' .. string.gsub(output, '\r?\n', ' ') .. '\''})
if not self.callback_on_errors then
return
end
end
if callback then
process.nextTick(function ()
callback({context = self, info = self.info, output = output})
end)
end
end
proc.stdout:on('end', function ()
ended = true
done()
end)
proc:on('exit', function (exitcode)
code = exitcode
done()
end)
end
end
--- MeterDataSource class.
-- @type MeterDataSource
local MeterDataSource = NetDataSource:extend()
--- MeterDatasource to get data from the meter. The meter has various metrics already for use inside plugins.
-- @name MeterDataSource:new
function MeterDataSource:initialize(host, port)
host = host or '127.0.0.1'
port = port or 9192
NetDataSource.initialize(self, host, port)
end
function MeterDataSource:fetch(context, callback)
local parse = function (value)
local success, parsed = parseJson(value)
if not success then
self:emit('error', string.gsub(parsed, '\n', ' '))
return
end
local result = {}
if parsed.result.status ~= 'Ok' then
self:emit('error', 'Error with status: ' .. parsed.result.status)
return
end
local query_metric = parsed.result.query_metric
-- TODO: Return a generator
if query_metric then
for i = 1, table.getn(query_metric), 3 do
table.insert(result, {metric = query_metric[i], value = query_metric[i+1], timestamp = query_metric[i+2]})
end
end
callback(result)
end
NetDataSource.fetch(self, context, parse)
end
--- Returns a json formatted string for query a metric
-- @param params the option for query a metric
function MeterDataSource:queryMetricCommand(params)
params = params or { match = ''}
return '{"jsonrpc":"2.0","method":"query_metric","id":1,"params":' .. json.stringify(params) .. '}\n'
end
local FileReaderDataSource = DataSource:extend()
function FileReaderDataSource:initialize(path)
self.path = path
end
function FileReaderDataSource:fetch(context, func, params)
if not fs.existsSync(self.path) then
self:emit('error', 'The "' .. self.path .. '" was not found.')
else
local success, result = pcall(fs.readFileSync, self.path)
if not success then
self:emit('error', failure)
else
func(result)
end
end
end
framework.FileReaderDataSource = FileReaderDataSource
framework.CommandOutputDataSource = CommandOutputDataSource
framework.RandomDataSource = RandomDataSource
framework.DataSourcePoller = DataSourcePoller
framework.WebRequestDataSource = WebRequestDataSource
framework.PollerCollection = PollerCollection
framework.MeterDataSource = MeterDataSource
return framework
| apache-2.0 |
nesstea/darkstar | scripts/zones/Gusgen_Mines/npcs/_5gb.lua | 13 | 1344 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5gb (Lever B)
-- @pos 19.999 -40.561 -54.198 196
-----------------------------------
package.loaded["scripts/zones/Gusgen_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Gusgen_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--local nID = npc:getID();
--printf("id: %u", nID);
local Lever = npc:getID();
npc:openDoor(2); -- Lever animation
if (GetNPCByID(Lever-6):getAnimation() == 9) then
GetNPCByID(Lever-7):setAnimation(9);--close door C
GetNPCByID(Lever-6):setAnimation(8);--open door B
GetNPCByID(Lever-5):setAnimation(9);--close door A
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/Cloister_of_Storms/bcnms/trial-size_trial_by_lightning.lua | 29 | 2592 | -----------------------------------
-- Area: Cloister of Storms
-- BCNM: Trial by Lightning
-----------------------------------
package.loaded["scripts/zones/Cloister_of_Storms/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/Cloister_of_Storms/TextIDs");
-----------------------------------
-- What should go here:
-- giving key items, playing ENDING cutscenes
--
-- What should NOT go here:
-- Handling of "battlefield" status, spawning of monsters,
-- putting loot into treasure pool,
-- enforcing ANY rules (SJ/number of people/etc), moving
-- chars around, playing entrance CSes (entrance CSes go in bcnm.lua)
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
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);
trialLightning = player:getQuestStatus(OTHER_AREAS,TRIAL_SIZE_TRIAL_BY_LIGHTNING)
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (trialLightning == QUEST_COMPLETED) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
if (player:hasSpell(303) == false) then
player:addSpell(303) -- Ramuh
player:messageSpecial(RAMUH_UNLOCKED,0,0,5);
end
if (player:hasItem(4181) == false) then
player:addItem(4181);
player:messageSpecial(ITEM_OBTAINED,4181); -- Scroll of instant warp
end
player:setVar("TrialSizeLightning_date", 0);
player:addFame(WINDURST,30);
player:completeQuest(OTHER_AREAS,TRIAL_SIZE_TRIAL_BY_LIGHTNING);
end
end;
| gpl-3.0 |
focusworld/aabb | plugins/service_entergroup.lua | 355 | 3585 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nDescription :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "You are in group '"..string.gsub(msg.to.print_name, "_", " ").."'\n"
local text = sambutan..about..rules.."\n"
local text = text.."Please welcome "..nama
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye '..bye_name..'!'
end
end
return {
description = "Service plugin that sends a custom message when an user enters a chat.",
usage = "Welcoming new member.",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
hamed9898/maxbot | plugins/service_entergroup.lua | 355 | 3585 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nDescription :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "You are in group '"..string.gsub(msg.to.print_name, "_", " ").."'\n"
local text = sambutan..about..rules.."\n"
local text = text.."Please welcome "..nama
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Bye '..bye_name..'!'
end
end
return {
description = "Service plugin that sends a custom message when an user enters a chat.",
usage = "Welcoming new member.",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
UnfortunateFruit/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5c8.lua | 17 | 2162 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Sealed Portal
-- Involved in Quest: Making the Grade
-- Working 50%
-- Notes: Door will open if player has Making the Grade quest active, or if the have the KI portal charm. Door should open when 3 mages stand on circles, but no API for this yet.
-- @pos -259 -1 -20 192
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
---- WHM BLM RDM CIRCLE LOCATIONS FOR WHEM API IS AVAILABLE TO QUERY POSITIONS IN ZONE EVERY 3 SECONDS --
-- if((whmzpos >= -26 and whmzpos <= -22) and (whmxpos <= -261 and whmxpos >= -265))
-- if((blmzpos >= -26 and blmzpos <= -22) and (blmxpos <= -254 and blmxpos >= -258))
-- if((rdmzpos >= -31 and rdmzpos <= -27) and (rdmxpos <= -257 and rdmxpos >= -261))
----------------------------------------------------------------------------------------------------------
if(player:getZPos() >= -15) then
player:messageSpecial(PORTAL_NOT_OPEN_THAT_SIDE);
else
if(player:hasKeyItem(PORTAL_CHARM)) then
npc:openDoor(30);
elseif(player:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then
-- quest not scripted ?
else
player:messageSpecial(PORTAL_SEALED_BY_3_MAGIC)
end
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
plajjan/snabbswitch | src/lib/pcap/pcap.lua | 6 | 2808 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local ffi = require("ffi")
-- PCAP file format: http://wiki.wireshark.org/Development/LibpcapFileFormat/
local pcap_file_t = ffi.typeof[[
struct {
/* file header */
uint32_t magic_number; /* magic number */
uint16_t version_major; /* major version number */
uint16_t version_minor; /* minor version number */
int32_t thiszone; /* GMT to local correction */
uint32_t sigfigs; /* accuracy of timestamps */
uint32_t snaplen; /* max length of captured packets, in octets */
uint32_t network; /* data link type */
}
]]
local pcap_record_t = ffi.typeof[[
struct {
/* record header */
uint32_t ts_sec; /* timestamp seconds */
uint32_t ts_usec; /* timestamp microseconds */
uint32_t incl_len; /* number of octets of packet saved in file */
uint32_t orig_len; /* actual length of packet */
}
]]
function write_file_header(file)
local pcap_file = ffi.new(pcap_file_t)
pcap_file.magic_number = 0xa1b2c3d4
pcap_file.version_major = 2
pcap_file.version_minor = 4
pcap_file.snaplen = 65535
pcap_file.network = 1
file:write(ffi.string(pcap_file, ffi.sizeof(pcap_file)))
file:flush()
end
function write_record (file, ffi_buffer, length)
write_record_header(file, length)
file:write(ffi.string(ffi_buffer, length))
file:flush()
end
function write_record_header (file, length)
local pcap_record = ffi.new(pcap_record_t)
pcap_record.incl_len = length
pcap_record.orig_len = length
file:write(ffi.string(pcap_record, ffi.sizeof(pcap_record)))
end
-- Return an iterator for pcap records in FILENAME.
function records (filename)
local file = io.open(filename, "r")
if file == nil then error("Unable to open file: " .. filename) end
local pcap_file = readc(file, pcap_file_t)
if pcap_file.magic_number == 0xD4C3B2A1 then
error("Endian mismatch in " .. filename)
elseif pcap_file.magic_number ~= 0xA1B2C3D4 then
error("Bad PCAP magic number in " .. filename)
end
local function pcap_records_it (t, i)
local record = readc(file, pcap_record_t)
if record == nil then return nil end
local datalen = math.min(record.orig_len, record.incl_len)
local packet = file:read(datalen)
return packet, record
end
return pcap_records_it, true, true
end
-- Read a C object of TYPE from FILE
function readc(file, type)
local string = file:read(ffi.sizeof(type))
if string == nil then return nil end
if #string ~= ffi.sizeof(type) then
error("short read of " .. type .. " from " .. tostring(file))
end
local obj = ffi.new(type)
ffi.copy(obj, string, ffi.sizeof(type))
return obj
end
| apache-2.0 |
nesstea/darkstar | scripts/globals/abilities/maguss_roll.lua | 2 | 2640 | -----------------------------------
-- Ability: Magus's Roll
-- Enhances magic defense for party members within area of effect
-- Optimal Job: Blue Mage
-- Lucky Number: 2
-- Unlucky Number: 6
-- Level: 17
--
-- Die Roll |No BLU |With BLU
----------- ------- -----------
-- 1 |+5 |+13
-- 2 |+20 |+28
-- 3 |+6 |+14
-- 4 |+8 |+16
-- 5 |+9 |+17
-- 6 |+3 |+11
-- 7 |+10 |+18
-- 8 |+13 |+21
-- 9 |+14 |+22
-- 10 |+15 |+23
-- 11 |+25 |+33
-- Bust |-5 |-5
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/ability");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
local effectID = EFFECT_MAGUSS_ROLL
ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE));
if (player:hasStatusEffect(effectID)) then
return MSGBASIC_ROLL_ALREADY_ACTIVE,0;
elseif atMaxCorsairBusts(player) then
return MSGBASIC_CANNOT_PERFORM,0;
else
return 0,0;
end
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(caster,target,ability,action)
if (caster:getID() == target:getID()) then
corsairSetup(caster, ability, action, EFFECT_MAGUSS_ROLL, JOB_BLU);
end
local total = caster:getLocalVar("corsairRollTotal")
return applyRoll(caster,target,ability,action,total)
end;
function applyRoll(caster,target,ability,action,total)
local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK)
local effectpowers = {5, 20, 6, 8, 9, 3, 10, 13, 14, 15, 25, 5}
local effectpower = effectpowers[total];
if (caster:getLocalVar("corsairRollBonus") == 1 and total < 12) then
effectpower = effectpower + 8
end
if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl());
elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then
effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl());
end
if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_MAGUSS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_MDEF) == false) then
ability:setMsg(422);
elseif total > 11 then
ability:setMsg(426);
end
return total;
end
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sorrowful_Sage.lua | 29 | 2456 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sorrowful Sage
-- Type: Assault Mission Giver
-- @pos 134.096 0.161 -30.401 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/besieged");
require("scripts/globals/missions");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local rank = getMercenaryRank(player);
local haveimperialIDtag;
local tokens = 3;--player:getAssaultPoint(ILRUSI_ASSAULT_POINT);
if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then
haveimperialIDtag = 1;
else
haveimperialIDtag = 0;
end
if (rank > 0) then
player:startEvent(278,rank,haveimperialIDtag,tokens,player:getCurrentAssault());
else
player:startEvent(284); -- no rank
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 278) then
local categorytype = bit.band(option, 0x0F);
if (categorytype == 3) then
-- low grade item
local item = bit.rshift(option, 16);
elseif (categorytype == 4) then
-- medium grade item
local item = bit.rshift(option, 16);
elseif (categorytype == 5) then
-- high grade item
local item = bit.rshift(option, 16);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 278) then
local selectiontype = bit.band(option, 0xF);
if (selectiontype == 1) then
-- taken assault mission
player:addAssault(bit.rshift(option,4));
player:delKeyItem(IMPERIAL_ARMY_ID_TAG);
player:addKeyItem(NYZUL_ISLE_ASSAULT_ORDERS);
player:messageSpecial(KEYITEM_OBTAINED,NYZUL_ISLE_ASSAULT_ORDERS);
end
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Port_San_dOria/npcs/Antreneau.lua | 13 | 2158 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Antreneau
-- Type: Standard NPC
-- @zone: 232
-- @pos -71 -5 -39
--
-- Involved in Quest: A Taste For Meat
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
player:startEvent(0x0214);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(SANDORIA, A_TASTE_FOR_MEAT) == QUEST_COMPLETED and player:getVar("aTasteForMeat") == 1) then
player:startEvent(0x0212);
elseif (player:getQuestStatus(SANDORIA, A_TASTE_FOR_MEAT) == QUEST_ACCEPTED) then
if (player:hasItem(4358) == true) then
player:startEvent(0x0213);
else
player:startEvent(0x020d);
end;
elseif (player:getQuestStatus(SANDORIA, A_TASTE_FOR_MEAT) == QUEST_AVAILABLE and player:getVar("aTasteForMeat") == 0) then
player:startEvent(0x020f);
else
player:startEvent(0x0215);
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 == 0x020f) then
player:setVar("aTasteForMeat", 1);
elseif (csid == 0x0212) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED_2, 4371);
else
player:addItem(4371,1);
player:messageSpecial(ITEM_OBTAINED,4371);
player:setVar("aTasteForMeat", 0);
end;
end;
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/East_Ronfaure/npcs/Cheval_River.lua | 34 | 1647 | -----------------------------------
-- Area: East Ronfaure
-- NPC: Cheval_River
-- @pos 223 -58 426 101
-- Involved in Quest: Waters of Cheval
-----------------------------------
package.loaded["scripts/zones/East_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/East_Ronfaure/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,WATER_OF_THE_CHEVAL) == QUEST_ACCEPTED and trade:hasItemQty(602, 1)) then
if (trade:getItemCount() == 1 and player:getFreeSlotsCount() > 0) then
player:tradeComplete();
player:addItem(603);
player:messageSpecial(CHEVAL_RIVER_WATER, 603);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 603);
end;
end;
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasItem(602) == true) then
player:messageSpecial(BLESSED_WATERSKIN);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
dpino/snabbswitch | lib/ljsyscall/test/linux-structures.lua | 18 | 6451 | -- test Linux structures against standard headers
-- Need to cross compile on correct 32/64 bits
--[[
luajit test/linux-structures.lua x64 > ./obj/s.c && cc -U__i386__ -DBITS_PER_LONG=64 -I./include/linux-kernel-headers/x86_64/include -o ./obj/s ./obj/s.c && ./obj/s
luajit32 test/linux-structures.lua x86 > ./obj/s.c && cc -m32 -D__i386__ -DBITS_PER_LONG=32 -I./include/linux-kernel-headers/i386/include -o ./obj/s ./obj/s.c && ./obj/s
luajit32 test/linux-structures.lua arm > ./obj/s.c && cc -m32 -D__ARM_EABI__ -DBITS_PER_LONG=32 -I./include/linux-kernel-headers/arm/include -o ./obj/s ./obj/s.c && ./obj/s
luajit32 test/linux-structures.lua ppc > ./obj/s.c && cc -m32 -DBITS_PER_LONG=32 -I./include/linux-kernel-headers/powerpc/include -o ./obj/s ./obj/s.c && ./obj/s
luajit32 test/linux-structures.lua mips > ./obj/s.c && cc -m32 -DBITS_PER_LONG=32 -D__MIPSEL__ -D_MIPS_SIM=_MIPS_SIM_ABI32 -DCONFIG_32BIT -DBITS_PER_LONG=32 -D__LITTLE_ENDIAN_BITFIELD -D__LITTLE_ENDIAN -DCONFIG_CPU_LITTLE_ENDIAN -I./include/linux-kernel-headers/mips/include -o ./obj/s ./obj/s.c && ./obj/s
]]
local abi = require "syscall.abi"
if arg[1] then -- fake arch
abi.arch = arg[1]
if abi.arch == "x64" then abi.abi32, abi.abi64 = false, true else abi.abi32, abi.abi64 = true, false end
if abi.arch == "mips" then abi.mipsabi = "o32" end
end
local function fixup_structs(abi, ctypes)
if abi.abi32 then
ctypes["struct stat64"], ctypes["struct stat"] = ctypes["struct stat"], nil
end
-- internal only
ctypes["struct capabilities"] = nil
ctypes["struct cap"] = nil
ctypes["struct {dev_t dev;}"] = nil
-- standard headers use __kernel types for these or just fixed sizes
ctypes.ino_t = nil
ctypes.blkcnt_t = nil
ctypes.dev_t = nil
ctypes.in_port_t = nil
ctypes.id_t = nil
ctypes.time_t = nil
ctypes.daddr_t = nil
ctypes.clockid_t = nil
ctypes.socklen_t = nil
ctypes.uid_t = nil
ctypes.gid_t = nil
ctypes.pid_t = nil
ctypes.nlink_t = nil
ctypes.clock_t = nil
ctypes.mode_t = nil
ctypes.nfds_t = nil
ctypes.blksize_t = nil
ctypes.off_t = nil -- we use loff_t
-- misc issues
ctypes["struct user_cap_data"] = nil -- defined as __user_cap_data_struct in new uapi headers, not in old ones at all
ctypes["fd_set"] = nil -- just a pointer for the kernel, you define size
ctypes["struct sched_param"] = nil -- not defined in our headers yet
ctypes["struct udphdr"] = nil -- not a kernel define
ctypes["struct ucred"] = nil -- not defined yet
ctypes["struct msghdr"] = nil -- not defined
ctypes.mcontext_t = nil -- not defined
ctypes.ucontext_t = nil -- not defined
ctypes.sighandler_t = nil -- not defined
ctypes["struct utsname"] = nil -- not defined
ctypes["struct linux_dirent64"] = nil -- not defined
ctypes["struct cpu_set_t"] = nil -- not defined
ctypes["struct fdb_entry"] = nil -- not defined
ctypes["struct user_cap_header"] = nil -- not defined
ctypes["struct sockaddr_storage"] = nil -- uses __kernel_
ctypes["struct k_sigaction"] = nil -- seems to be incorrect in headers
ctypes["struct mmsghdr"] = nil -- too new for our headers
ctypes["sigset_t"] = nil -- still some issues
return ctypes
end
-- not defined by kernel
print [[
#include <stdint.h>
#include <stdio.h>
#include <stddef.h>
typedef unsigned short int sa_family_t;
struct sockaddr {
sa_family_t sa_family;
char sa_data[14];
};
]]
print [[
#include <linux/types.h>
#include <linux/stddef.h>
#include <linux/unistd.h>
#include <linux/net.h>
#include <linux/uio.h>
#include <linux/socket.h>
#include <linux/poll.h>
#include <linux/eventpoll.h>
#include <linux/signal.h>
#include <linux/ip.h>
#include <linux/in.h>
#include <linux/un.h>
#include <linux/in6.h>
#include <linux/capability.h>
#include <linux/reboot.h>
#include <linux/falloc.h>
#include <linux/mman.h>
#include <linux/veth.h>
#include <linux/sockios.h>
#include <linux/sched.h>
#include <linux/posix_types.h>
#include <linux/if.h>
#include <linux/if_bridge.h>
#include <linux/if_tun.h>
#include <linux/if_arp.h>
#include <linux/if_link.h>
#include <linux/netlink.h>
#include <linux/rtnetlink.h>
#include <linux/ioctl.h>
#include <linux/input.h>
#include <linux/uinput.h>
#include <linux/audit.h>
#include <linux/filter.h>
#include <linux/netfilter.h>
#include <linux/netfilter/x_tables.h>
#include <linux/netfilter_ipv4/ip_tables.h>
#include <linux/vhost.h>
#include <linux/neighbour.h>
#include <linux/prctl.h>
#include <linux/fcntl.h>
#include <linux/timex.h>
#include <linux/aio_abi.h>
#include <linux/fs.h>
#include <linux/wait.h>
#include <linux/resource.h>
#include <linux/termios.h>
#include <linux/xattr.h>
#include <linux/stat.h>
#include <linux/fadvise.h>
#include <linux/inotify.h>
#include <linux/route.h>
#include <linux/ipv6_route.h>
#include <linux/neighbour.h>
#include <linux/errno.h>
#include <linux/signalfd.h>
#include <linux/mqueue.h>
#include <linux/virtio_pci.h>
#include <linux/pci.h>
#include <linux/vfio.h>
#include <linux/seccomp.h>
#include <asm/statfs.h>
#include <asm/stat.h>
#include <asm/termbits.h>
int ret;
void sassert_size(int a, int b, char *n) {
if (a != b) {
printf("size error with %s: %d (0x%x) != %d (0x%x)\n", n, a, a, b, b);
ret = 1;
}
}
void sassert_offset(int a, int b, char *n) {
if (a != b) {
printf("offset error: %s: %d (0x%x) != %d (0x%x)\n", n, a, a, b, b);
ret = 1;
}
}
int main(int argc, char **argv) {
]]
local ffi = require "ffi"
local reflect = require "include.ffi-reflect.reflect"
local S = require "syscall"
local ctypes = S.types.ctypes
ctypes = fixup_structs(abi, ctypes)
-- TODO fix
local ignore_offsets = {
st_atime_nsec = true, -- stat
st_ctime_nsec = true, -- stat
st_mtime_nsec = true, -- stat
ihl = true, -- bitfield
version = true, -- bitfield
}
-- iterate over S.ctypes
for k, v in pairs(ctypes) do
-- check size
print("sassert_size(sizeof(" .. k .. "), " .. ffi.sizeof(v) .. ', "' .. k .. '");')
-- check offset of struct fields
local refct = reflect.typeof(v)
if refct.what == "struct" then
for r in refct:members() do
local name = r.name
-- bit hacky - TODO fix these issues
if not name or ignore_offsets[name] or name:sub(1,2) == "__" then name = nil end
if name then
print("sassert_offset(offsetof(" .. k .. "," .. name .. "), " .. ffi.offsetof(v, name) .. ', " offset of ' .. name .. ' in ' .. k .. '");')
end
end
end
end
print [[
return ret;
}
]]
| apache-2.0 |
Cycloneteam/CycloneTg | plugins/invite.lua | 10 | 1194 | do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[Ii]nvite (.*)$"
},
run = run
}
end
| gpl-2.0 |
nesstea/darkstar | scripts/globals/weaponskills.lua | 5 | 35789 | -- Contains all common weaponskill calculations including but not limited to:
-- fSTR
-- Alpha
-- Ratio -> cRatio
-- min/max cRatio
-- applications of fTP
-- applications of critical hits ('Critical hit rate varies with TP.')
-- applications of accuracy mods ('Accuracy varies with TP.')
-- applications of damage mods ('Damage varies with TP.')
-- performance of the actual WS (rand numbers, etc)
require("scripts/globals/status");
require("scripts/globals/utils");
require("scripts/globals/magic");
require("scripts/globals/magicburst");
-- params contains: ftp100, ftp200, ftp300, str_wsc, dex_wsc, vit_wsc, int_wsc, mnd_wsc, canCrit, crit100, crit200, crit300, acc100, acc200, acc300, ignoresDef, ignore100, ignore200, ignore300, atkmulti
function doPhysicalWeaponskill(attacker, target, wsID, params, tp, primary)
local criticalHit = false;
local bonusTP = params.bonusTP or 0
local multiHitfTP = params.multiHitfTP or false
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
-- get fstr
local fstr = fSTR(attacker:getStat(MOD_STR),target:getStat(MOD_VIT),attacker:getWeaponDmgRank());
-- apply WSC
local weaponDamage = attacker:getWeaponDmg();
local weaponType = attacker:getWeaponSkillType(0);
if (weaponType == SKILL_H2H) then
local h2hSkill = ((attacker:getSkillLevel(1) * 0.11) + 3);
weaponDamage = attacker:getWeaponDmg()-3;
weaponDamage = weaponDamage + h2hSkill;
end
local base = weaponDamage + fstr +
(attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) * getAlpha(attacker:getMainLvl());
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
local ignoredDef = 0;
if (params.ignoresDef == not nil and params.ignoresDef == true) then
ignoredDef = calculatedIgnoredDef(tp, target:getStat(MOD_DEF), params.ignored100, params.ignored200, params.ignored300);
end
local taChar = nil
if (primary and attacker:hasStatusEffect(EFFECT_TRICK_ATTACK)) then
taChar = attacker:getTrickAttackChar(target)
end
-- get cratio min and max
local cratio, ccritratio = cMeleeRatio(attacker, target, params, ignoredDef);
local ccmin = 0;
local ccmax = 0;
local hasMightyStrikes = attacker:hasStatusEffect(EFFECT_MIGHTY_STRIKES);
local isSneakValid = attacker:hasStatusEffect(EFFECT_SNEAK_ATTACK);
if (isSneakValid and not (attacker:isBehind(target) or attacker:hasStatusEffect(EFFECT_HIDE))) then
isSneakValid = false;
end
attacker:delStatusEffectsByFlag(EFFECTFLAG_DETECTABLE);
attacker:delStatusEffect(EFFECT_SNEAK_ATTACK);
local isTrickValid = taChar ~= nil
local isAssassinValid = isTrickValid;
if (isAssassinValid and not attacker:hasTrait(68)) then
isAssassinValid = false;
end
local critrate = 0;
local nativecrit = 0;
if (params.canCrit) then -- work out critical hit ratios, by +1ing
critrate = fTP(tp,params.crit100,params.crit200,params.crit300);
-- add on native crit hit rate (guesstimated, it actually follows an exponential curve)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
critrate = critrate + (10 + flourisheffect:getSubPower()/2)/100;
end
nativecrit = (attacker:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; -- assumes +0.5% crit rate per 1 dDEX
nativecrit = nativecrit + (attacker:getMod(MOD_CRITHITRATE)/100) + attacker:getMerit(MERIT_CRIT_HIT_RATE)/100 - target:getMerit(MERIT_ENEMY_CRIT_RATE)/100;
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin acc boost attacker is behind target
nativecrit = nativecrit + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
if (nativecrit > 0.2) then -- caps!
nativecrit = 0.2;
elseif (nativecrit < 0.05) then
nativecrit = 0.05;
end
critrate = critrate + nativecrit;
end
local dmg = 0;
-- Applying pDIF
local pdif = generatePdif (cratio[1], cratio[2], true);
local firsthit = math.random();
local finaldmg = 0;
local hitrate = getHitRate(attacker,target,true,bonusacc);
if (params.acc100~=0) then
-- ACCURACY VARIES WITH TP, APPLIED TO ALL HITS.
-- print("Accuracy varies with TP.");
hr = accVariesWithTP(getHitRate(attacker,target,false,bonusacc),attacker:getACC(),tp,params.acc100,params.acc200,params.acc300);
hitrate = hr;
end
local tpHitsLanded = 0;
if ((firsthit <= hitrate or isSneakValid or isAssassinValid or math.random() < attacker:getMod(MOD_ZANSHIN)/100) and
not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then
dmg = base * ftp;
if (params.canCrit or isSneakValid or isAssassinValid) then
local critchance = math.random();
if (critchance <= critrate or hasMightyStrikes or isSneakValid or isAssassinValid) then -- crit hit!
local cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = dmg * cpdif;
if (isSneakValid and attacker:getMainJob()==6) then -- have to add on DEX bonus if on THF main
finaldmg = finaldmg + (attacker:getStat(MOD_DEX) * ftp * cpdif) * ((100+(attacker:getMod(MOD_AUGMENTS_SA)))/100);
end
if (isTrickValid and attacker:getMainJob()==6) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * cpdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
else
finaldmg = dmg * pdif;
if (isTrickValid and attacker:getMainJob()==6) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * pdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
end
else
finaldmg = dmg * pdif;
if (isTrickValid and attacker:getMainJob()==6) then
finaldmg = finaldmg + (attacker:getStat(MOD_AGI) * (1 + attacker:getMod(MOD_TRICK_ATK_AGI)/100) * ftp * pdif) * ((100+(attacker:getMod(MOD_AUGMENTS_TA)))/100);
end
end
tpHitsLanded = 1;
end
if not multiHitfTP then dmg = base end
if ((attacker:getOffhandDmg() ~= 0) and (attacker:getOffhandDmg() > 0 or weaponType==SKILL_H2H)) then
local chance = math.random();
if ((chance<=hitrate or math.random() < attacker:getMod(MOD_ZANSHIN)/100 or isSneakValid)
and not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then -- it hit
pdif = generatePdif (cratio[1], cratio[2], true);
if (params.canCrit) then
critchance = math.random();
if (critchance <= nativecrit or hasMightyStrikes) then -- crit hit!
criticalHit = true;
cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif;
end
tpHitsLanded = tpHitsLanded + 1;
end
end
local numHits = getMultiAttacks(attacker, params.numHits);
local extraHitsLanded = 0;
if (numHits > 1) then
local hitsdone = 1;
while (hitsdone < numHits) do
local chance = math.random();
local targetHP = target:getHP();
if ((chance<=hitrate or math.random() < attacker:getMod(MOD_ZANSHIN)/100) and
not target:hasStatusEffect(EFFECT_PERFECT_DODGE) and not target:hasStatusEffect(EFFECT_ALL_MISS) ) then -- it hit
pdif = generatePdif (cratio[1], cratio[2], true);
if (params.canCrit) then
critchance = math.random();
if (critchance <= nativecrit or hasMightyStrikes) then -- crit hit!
criticalHit = true;
cpdif = generatePdif (ccritratio[1], ccritratio[2], true);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif;
end
extraHitsLanded = extraHitsLanded + 1;
end
hitsdone = hitsdone + 1;
if (finaldmg > targetHP) then
break;
end
end
end
finaldmg = finaldmg + souleaterBonus(attacker, (tpHitsLanded+extraHitsLanded));
-- print("Landed " .. hitslanded .. "/" .. numHits .. " hits with hitrate " .. hitrate .. "!");
finaldmg = target:physicalDmgTaken(finaldmg);
if (weaponType == SKILL_H2H) then
finaldmg = finaldmg * target:getMod(MOD_HTHRES) / 1000;
elseif (weaponType == SKILL_DAG or weaponType == SKILL_POL) then
finaldmg = finaldmg * target:getMod(MOD_PIERCERES) / 1000;
elseif (weaponType == SKILL_CLB or weaponType == SKILL_STF) then
finaldmg = finaldmg * target:getMod(MOD_IMPACTRES) / 1000;
else
finaldmg = finaldmg * target:getMod(MOD_SLASHRES) / 1000;
end
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
finaldmg = finaldmg * (100 + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID))/100
end
attacker:delStatusEffectSilent(EFFECT_BUILDING_FLOURISH);
finaldmg = finaldmg * WEAPON_SKILL_POWER
if tpHitsLanded + extraHitsLanded > 0 then
finaldmg = takeWeaponskillDamage(target, attacker, params, finaldmg, SLOT_MAIN, tpHitsLanded, (extraHitsLanded * 10) + bonusTP, taChar)
end
return finaldmg, criticalHit, tpHitsLanded, extraHitsLanded;
end;
-- params: ftp100, ftp200, ftp300, wsc_str, wsc_dex, wsc_vit, wsc_agi, wsc_int, wsc_mnd, wsc_chr,
-- ele (ELE_FIRE), skill (SKILL_STF), includemab = true
function doMagicWeaponskill(attacker, target, wsID, params, tp, primary)
local bonusTP = params.bonusTP or 0
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
local fint = utils.clamp(8 + (attacker:getStat(MOD_INT) - target:getStat(MOD_INT)), -32, 32);
local dmg = attacker:getMainLvl() + 2 + (attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) + fint;
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
dmg = dmg * ftp;
dmg = addBonusesAbility(attacker, params.ele, target, dmg, params);
dmg = dmg * applyResistanceAbility(attacker,target,params.ele,params.skill, bonusacc);
dmg = target:magicDmgTaken(dmg);
dmg = adjustForTarget(target,dmg,params.ele);
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
dmg = dmg * (100 + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID))/100
end
dmg = dmg * WEAPON_SKILL_POWER
dmg = takeWeaponskillDamage(target, attacker, params, dmg, SLOT_MAIN, 1, bonusTP, nil)
return dmg, false, 1, 0;
end
function souleaterBonus(attacker, numhits)
if attacker:hasStatusEffect(EFFECT_SOULEATER) then
local damage = 0;
local percent = 0.1;
if attacker:getMainJob() ~= 8 then
percent = percent / 2;
end
if attacker:getEquipID(SLOT_HEAD) == 12516 or attacker:getEquipID(SLOT_HEAD) == 15232 or attacker:getEquipID(SLOT_BODY) == 14409 or attacker:getEquipID(SLOT_LEGS) == 15370 then
percent = percent + 0.02;
end
local hitscounted = 0;
while (hitscounted < numhits) do
local health = attacker:getHP();
if health > 10 then
damage = damage + health*percent;
end
hitscounted = hitscounted + 1;
end
attacker:delHP(numhits*0.10*attacker:getHP());
return damage;
else
return 0;
end
end;
function accVariesWithTP(hitrate,acc,tp,a1,a2,a3)
-- sadly acc varies with tp ALL apply an acc PENALTY, the acc at various %s are given as a1 a2 a3
accpct = fTP(tp,a1,a2,a3);
acclost = acc - (acc*accpct);
hrate = hitrate - (0.005*acclost);
-- cap it
if (hrate>0.95) then
hrate = 0.95;
end
if (hrate<0.2) then
hrate = 0.2;
end
return hrate;
end;
function getHitRate(attacker,target,capHitRate,bonus)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:addMod(MOD_ACC, 20 + flourisheffect:getSubPower())
end
local acc = attacker:getACC();
local eva = target:getEVA();
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:delMod(MOD_ACC, 20 + flourisheffect:getSubPower())
end
if (bonus == nil) then
bonus = 0;
end
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin acc boost if attacker is behind target
bonus = bonus + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
if (target:hasStatusEffect(EFFECT_YONIN) and attacker:isFacing(target, 23)) then -- Yonin evasion boost if attacker is facing target
bonus = bonus - target:getStatusEffect(EFFECT_YONIN):getPower();
end
acc = acc + bonus;
if (attacker:getMainLvl() > target:getMainLvl()) then -- acc bonus!
acc = acc + ((attacker:getMainLvl()-target:getMainLvl())*4);
elseif (attacker:getMainLvl() < target:getMainLvl()) then -- acc penalty :(
acc = acc - ((target:getMainLvl()-attacker:getMainLvl())*4);
end
local hitdiff = 0;
local hitrate = 75;
if (acc>eva) then
hitdiff = (acc-eva)/2;
end
if (eva>acc) then
hitdiff = ((-1)*(eva-acc))/2;
end
hitrate = hitrate+hitdiff;
hitrate = hitrate/100;
-- Applying hitrate caps
if (capHitRate) then -- this isn't capped for when acc varies with tp, as more penalties are due
if (hitrate>0.95) then
hitrate = 0.95;
end
if (hitrate<0.2) then
hitrate = 0.2;
end
end
return hitrate;
end;
function getRangedHitRate(attacker,target,capHitRate,bonus)
local acc = attacker:getRACC();
local eva = target:getEVA();
if (bonus == nil) then
bonus = 0;
end
if (target:hasStatusEffect(EFFECT_YONIN) and target:isFacing(attacker, 23)) then -- Yonin evasion boost if defender is facing attacker
bonus = bonus - target:getStatusEffect(EFFECT_YONIN):getPower();
end
acc = acc + bonus;
if (attacker:getMainLvl() > target:getMainLvl()) then -- acc bonus!
acc = acc + ((attacker:getMainLvl()-target:getMainLvl())*4);
elseif (attacker:getMainLvl() < target:getMainLvl()) then -- acc penalty :(
acc = acc - ((target:getMainLvl()-attacker:getMainLvl())*4);
end
local hitdiff = 0;
local hitrate = 75;
if (acc>eva) then
hitdiff = (acc-eva)/2;
end
if (eva>acc) then
hitdiff = ((-1)*(eva-acc))/2;
end
hitrate = hitrate+hitdiff;
hitrate = hitrate/100;
-- Applying hitrate caps
if (capHitRate) then -- this isn't capped for when acc varies with tp, as more penalties are due
if (hitrate>0.95) then
hitrate = 0.95;
end
if (hitrate<0.2) then
hitrate = 0.2;
end
end
return hitrate;
end;
function fTP(tp,ftp1,ftp2,ftp3)
if tp < 1000 then tp = 1000 end
if (tp>=1000 and tp<2000) then
return ftp1 + ( ((ftp2-ftp1)/1000) * (tp-1000));
elseif (tp>=2000 and tp<=3000) then
-- generate a straight line between ftp2 and ftp3 and find point @ tp
return ftp2 + ( ((ftp3-ftp2)/1000) * (tp-2000));
else
print("fTP error: TP value is not between 100-300!");
end
return 1; -- no ftp mod
end;
function calculatedIgnoredDef(tp, def, ignore1, ignore2, ignore3)
if (tp>=1000 and tp <2000) then
return (ignore1 + ( ((ignore2-ignore1)/1000) * (tp-1000)))*def;
elseif (tp>=2000 and tp<=3000) then
return (ignore2 + ( ((ignore3-ignore2)/1000) * (tp-2000)))*def;
end
return 1; -- no def ignore mod
end
-- Given the raw ratio value (atk/def) and levels, returns the cRatio (min then max)
function cMeleeRatio(attacker, defender, params, ignoredDef)
local flourisheffect = attacker:getStatusEffect(EFFECT_BUILDING_FLOURISH);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:addMod(MOD_ATTP, 25 + flourisheffect:getSubPower()/2)
end
local cratio = (attacker:getStat(MOD_ATT) * params.atkmulti) / (defender:getStat(MOD_DEF) - ignoredDef);
cratio = utils.clamp(cratio, 0, 2.25);
if flourisheffect ~= nil and flourisheffect:getPower() > 1 then
attacker:delMod(MOD_ATTP, 25 + flourisheffect:getSubPower()/2)
end
local levelcor = 0;
if (attacker:getMainLvl() < defender:getMainLvl()) then
levelcor = 0.05 * (defender:getMainLvl() - attacker:getMainLvl());
end
cratio = cratio - levelcor;
if (cratio < 0) then
cratio = 0;
end
local pdifmin = 0;
local pdifmax = 0;
-- max
if (cratio < 0.5) then
pdifmax = cratio + 0.5;
elseif (cratio < 0.7) then
pdifmax = 1;
elseif (cratio < 1.2) then
pdifmax = cratio + 0.3;
elseif (cratio < 1.5) then
pdifmax = (cratio * 0.25) + cratio;
elseif (cratio < 1.5) then
pdifmax = cratio + 0.375;
else
pdifmax = 3;
end
-- min
if (cratio < 0.38) then
pdifmin = 0;
elseif (cratio < 1.25) then
pdifmin = cratio * (1176/1024) - (448/1024);
elseif (cratio < 1.51) then
pdifmin = 1;
elseif (cratio < 2.44) then
pdifmin = cratio * (1176/1024) - (775/1024);
else
pdifmin = cratio - 0.375;
end
local pdif = {};
pdif[1] = pdifmin;
pdif[2] = pdifmax;
local pdifcrit = {};
cratio = cratio + 1;
cratio = utils.clamp(cratio, 0, 3);
-- printf("ratio: %f min: %f max %f\n", cratio, pdifmin, pdifmax);
if (cratio < 0.5) then
pdifmax = cratio + 0.5;
elseif (cratio < 0.7) then
pdifmax = 1;
elseif (cratio < 1.2) then
pdifmax = cratio + 0.3;
elseif (cratio < 1.5) then
pdifmax = (cratio * 0.25) + cratio;
elseif (cratio < 1.5) then
pdifmax = cratio + 0.375;
else
pdifmax = 3;
end
-- min
if (cratio < 0.38) then
pdifmin = 0;
elseif (cratio < 1.25) then
pdifmin = cratio * (1176/1024) - (448/1024);
elseif (cratio < 1.51) then
pdifmin = 1;
elseif (cratio < 2.44) then
pdifmin = cratio * (1176/1024) - (775/1024);
else
pdifmin = cratio - 0.375;
end
local critbonus = attacker:getMod(MOD_CRIT_DMG_INCREASE)
critbonus = utils.clamp(critbonus, 0, 100);
pdifcrit[1] = pdifmin * ((100 + critbonus)/100);
pdifcrit[2] = pdifmax * ((100 + critbonus)/100);
return pdif, pdifcrit;
end;
function cRangedRatio(attacker, defender, params, ignoredDef)
local cratio = attacker:getRATT() / (defender:getStat(MOD_DEF) - ignoredDef);
local levelcor = 0;
if (attacker:getMainLvl() < defender:getMainLvl()) then
levelcor = 0.025 * (defender:getMainLvl() - attacker:getMainLvl());
end
cratio = cratio - levelcor;
cratio = cratio * params.atkmulti;
if (cratio > 3 - levelcor) then
cratio = 3 - levelcor;
end
if (cratio < 0) then
cratio = 0;
end
-- max
local pdifmax = 0;
if (cratio < 0.9) then
pdifmax = cratio * (10/9);
elseif (cratio < 1.1) then
pdifmax = 1;
else
pdifmax = cratio;
end
-- min
local pdifmin = 0;
if (cratio < 0.9) then
pdifmin = cratio;
elseif (cratio < 1.1) then
pdifmin = 1;
else
pdifmin = (cratio * (20/19))-(3/19);
end
pdif = {};
pdif[1] = pdifmin;
pdif[2] = pdifmax;
-- printf("ratio: %f min: %f max %f\n", cratio, pdifmin, pdifmax);
pdifcrit = {};
pdifmin = pdifmin * 1.25;
pdifmax = pdifmax * 1.25;
pdifcrit[1] = pdifmin;
pdifcrit[2] = pdifmax;
return pdif, pdifcrit;
end
-- Given the attacker's str and the mob's vit, fSTR is calculated
function fSTR(atk_str,def_vit,base_dmg)
local dSTR = atk_str - def_vit;
if (dSTR >= 12) then
fSTR2 = ((dSTR+4)/2);
elseif (dSTR >= 6) then
fSTR2 = ((dSTR+6)/2);
elseif (dSTR >= 1) then
fSTR2 = ((dSTR+7)/2);
elseif (dSTR >= -2) then
fSTR2 = ((dSTR+8)/2);
elseif (dSTR >= -7) then
fSTR2 = ((dSTR+9)/2);
elseif (dSTR >= -15) then
fSTR2 = ((dSTR+10)/2);
elseif (dSTR >= -21) then
fSTR2 = ((dSTR+12)/2);
else
fSTR2 = ((dSTR+13)/2);
end
-- Apply fSTR caps.
if (fSTR2<((base_dmg/9)*(-1))) then
fSTR2 = (base_dmg/9)*(-1);
elseif (fSTR2>((base_dmg/9)+8)) then
fSTR2 = (base_dmg/9)+8;
end
return fSTR2;
end;
-- obtains alpha, used for working out WSC
function getAlpha(level)
alpha = 1.00;
if (level <= 5) then
alpha = 1.00;
elseif (level <= 11) then
alpha = 0.99;
elseif (level <= 17) then
alpha = 0.98;
elseif (level <= 23) then
alpha = 0.97;
elseif (level <= 29) then
alpha = 0.96;
elseif (level <= 35) then
alpha = 0.95;
elseif (level <= 41) then
alpha = 0.94;
elseif (level <= 47) then
alpha = 0.93;
elseif (level <= 53) then
alpha = 0.92;
elseif (level <= 59) then
alpha = 0.91;
elseif (level <= 61) then
alpha = 0.90;
elseif (level <= 63) then
alpha = 0.89;
elseif (level <= 65) then
alpha = 0.88;
elseif (level <= 67) then
alpha = 0.87;
elseif (level <= 69) then
alpha = 0.86;
elseif (level <= 71) then
alpha = 0.85;
elseif (level <= 73) then
alpha = 0.84;
elseif (level <= 75) then
alpha = 0.83;
elseif (level < 99) then
alpha = 0.85;
else
alpha = 1; -- Retail has no alpha anymore!
end
return alpha;
end;
-- params contains: ftp100, ftp200, ftp300, str_wsc, dex_wsc, vit_wsc, int_wsc, mnd_wsc, canCrit, crit100, crit200, crit300, acc100, acc200, acc300, ignoresDef, ignore100, ignore200, ignore300, atkmulti
function doRangedWeaponskill(attacker, target, wsID, params, tp, primary)
local bonusTP = params.bonusTP or 0
local multiHitfTP = params.multiHitfTP or false
local bonusfTP, bonusacc = handleWSGorgetBelt(attacker);
bonusacc = bonusacc + attacker:getMod(MOD_WSACC);
-- get fstr
local fstr = fSTR(attacker:getStat(MOD_STR),target:getStat(MOD_VIT),attacker:getRangedDmgForRank());
-- apply WSC
local base = attacker:getRangedDmg() + fstr +
(attacker:getStat(MOD_STR) * params.str_wsc + attacker:getStat(MOD_DEX) * params.dex_wsc +
attacker:getStat(MOD_VIT) * params.vit_wsc + attacker:getStat(MOD_AGI) * params.agi_wsc +
attacker:getStat(MOD_INT) * params.int_wsc + attacker:getStat(MOD_MND) * params.mnd_wsc +
attacker:getStat(MOD_CHR) * params.chr_wsc) * getAlpha(attacker:getMainLvl());
-- Applying fTP multiplier
local ftp = fTP(tp,params.ftp100,params.ftp200,params.ftp300) + bonusfTP;
local crit = false
local ignoredDef = 0;
if (params.ignoresDef == not nil and params.ignoresDef == true) then
ignoredDef = calculatedIgnoredDef(tp, target:getStat(MOD_DEF), params.ignored100, params.ignored200, params.ignored300);
end
-- get cratio min and max
local cratio, ccritratio = cRangedRatio( attacker, target, params, ignoredDef);
local ccmin = 0;
local ccmax = 0;
local hasMightyStrikes = attacker:hasStatusEffect(EFFECT_MIGHTY_STRIKES);
local critrate = 0;
if (params.canCrit) then -- work out critical hit ratios, by +1ing
critrate = fTP(tp,params.crit100,params.crit200,params.crit300);
-- add on native crit hit rate (guesstimated, it actually follows an exponential curve)
local nativecrit = (attacker:getStat(MOD_DEX) - target:getStat(MOD_AGI))*0.005; -- assumes +0.5% crit rate per 1 dDEX
nativecrit = nativecrit + (attacker:getMod(MOD_CRITHITRATE)/100) + attacker:getMerit(MERIT_CRIT_HIT_RATE)/100 - target:getMerit(MERIT_ENEMY_CRIT_RATE)/100;
if (attacker:hasStatusEffect(EFFECT_INNIN) and attacker:isBehind(target, 23)) then -- Innin crit boost if attacker is behind target
nativecrit = nativecrit + attacker:getStatusEffect(EFFECT_INNIN):getPower();
end
if (nativecrit > 0.2) then -- caps!
nativecrit = 0.2;
elseif (nativecrit < 0.05) then
nativecrit = 0.05;
end
critrate = critrate + nativecrit;
end
local dmg = base * ftp;
-- Applying pDIF
local pdif = generatePdif (cratio[1],cratio[2], false);
-- First hit has 95% acc always. Second hit + affected by hit rate.
local firsthit = math.random();
local finaldmg = 0;
local hitrate = getRangedHitRate(attacker,target,true,bonusacc);
if (params.acc100~=0) then
-- ACCURACY VARIES WITH TP, APPLIED TO ALL HITS.
-- print("Accuracy varies with TP.");
hr = accVariesWithTP(getRangedHitRate(attacker,target,false,bonusacc),attacker:getRACC(),tp,params.acc100,params.acc200,params.acc300);
hitrate = hr;
end
local tpHitsLanded = 0;
if (firsthit <= hitrate) then
if (params.canCrit) then
local critchance = math.random();
if (critchance <= critrate or hasMightyStrikes) then -- crit hit!
crit = true
local cpdif = generatePdif (ccritratio[1], ccritratio[2], false);
finaldmg = dmg * cpdif;
else
finaldmg = dmg * pdif;
end
else
finaldmg = dmg * pdif;
end
tpHitsLanded = 1;
end
local numHits = params.numHits;
if not multiHitfTP then dmg = base end
local extraHitsLanded = 0;
if (numHits>1) then
if (params.acc100==0) then
-- work out acc since we actually need it now
hitrate = getRangedHitRate(attacker,target,true,bonusacc);
end
hitsdone = 1;
while (hitsdone < numHits) do
chance = math.random();
if (chance<=hitrate) then -- it hit
pdif = generatePdif (cratio[1],cratio[2], false);
if (canCrit) then
critchance = math.random();
if (critchance <= critrate or hasMightyStrikes) then -- crit hit!
cpdif = generatePdif (ccritratio[1], ccritratio[2], false);
finaldmg = finaldmg + dmg * cpdif;
else
finaldmg = finaldmg + dmg * pdif;
end
else
finaldmg = finaldmg + dmg * pdif; -- NOTE: not using 'dmg' since fTP is 1.0 for subsequent hits!!
end
extraHitsLanded = extraHitsLanded + 1;
end
hitsdone = hitsdone + 1;
end
end
-- print("Landed " .. hitslanded .. "/" .. numHits .. " hits with hitrate " .. hitrate .. "!");
finaldmg = target:rangedDmgTaken(finaldmg);
finaldmg = finaldmg * target:getMod(MOD_PIERCERES) / 1000;
if (attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID) > 0) then
finaldmg = finaldmg * (100 + attacker:getMod(MOD_WEAPONSKILL_DAMAGE_BASE + wsID))/100
end
finaldmg = finaldmg * WEAPON_SKILL_POWER
if tpHitsLanded + extraHitsLanded > 0 then
finaldmg = takeWeaponskillDamage(target, attacker, params, finaldmg, SLOT_RANGED, tpHitsLanded, (extraHitsLanded * 10) + bonusTP, nil)
end
return finaldmg, crit, tpHitsLanded, extraHitsLanded;
end;
function getMultiAttacks(attacker, numHits)
local bonusHits = 0;
local multiChances = 1;
local doubleRate = (attacker:getMod(MOD_DOUBLE_ATTACK) + attacker:getMerit(MERIT_DOUBLE_ATTACK_RATE))/100;
local tripleRate = (attacker:getMod(MOD_TRIPLE_ATTACK) + attacker:getMerit(MERIT_TRIPLE_ATTACK_RATE))/100;
local quadRate = attacker:getMod(MOD_QUAD_ATTACK)/100;
-- QA/TA/DA can only proc on the first hit of each weapon or each fist
if (attacker:getOffhandDmg() > 0 or attacker:getWeaponSkillType(SLOT_MAIN) == SKILL_H2H) then
multiChances = 2;
end
for i = 1, multiChances, 1 do
local chance = math.random()
if (chance < quadRate) then
bonusHits = bonusHits + 3;
elseif (chance < tripleRate + quadRate) then
bonusHits = bonusHits + 2;
elseif(chance < doubleRate + tripleRate + quadRate) then
bonusHits = bonusHits + 1;
end
if (i == 1) then
attacker:delStatusEffect(EFFECT_ASSASSIN_S_CHARGE);
attacker:delStatusEffect(EFFECT_WARRIOR_S_CHARGE);
-- recalculate DA/TA/QA rate
doubleRate = (attacker:getMod(MOD_DOUBLE_ATTACK) + attacker:getMerit(MERIT_DOUBLE_ATTACK_RATE))/100;
tripleRate = (attacker:getMod(MOD_TRIPLE_ATTACK) + attacker:getMerit(MERIT_TRIPLE_ATTACK_RATE))/100;
quadRate = attacker:getMod(MOD_QUAD_ATTACK)/100;
end
end
if ((numHits + bonusHits ) > 8) then
return 8;
end
return numHits + bonusHits;
end;
function generatePdif (cratiomin, cratiomax, melee)
local pdif = math.random(cratiomin*1000, cratiomax*1000) / 1000;
if (melee) then
pdif = pdif * (math.random(100,105)/100);
end
return pdif;
end
function getStepAnimation(skill)
if skill <= 1 then
return 15;
elseif skill <= 3 then
return 14;
elseif skill == 4 then
return 19;
elseif skill == 5 then
return 16;
elseif skill <= 7 then
return 18;
elseif skill == 8 then
return 20;
elseif skill == 9 then
return 21;
elseif skill == 10 then
return 22;
elseif skill == 11 then
return 17;
elseif skill == 12 then
return 23;
else
return 0;
end
end
function getFlourishAnimation(skill)
if skill <= 1 then
return 25;
elseif skill <= 3 then
return 24;
elseif skill == 4 then
return 29;
elseif skill == 5 then
return 26;
elseif skill <= 7 then
return 28;
elseif skill == 8 then
return 30;
elseif skill == 9 then
return 31;
elseif skill == 10 then
return 32;
elseif skill == 11 then
return 27;
elseif skill == 12 then
return 33;
else
return 0;
end
end
function takeWeaponskillDamage(defender, attacker, params, finaldmg, slot, tpHitsLanded, bonusTP, taChar)
local targetTPMult = params.targetTPMult or 1
finaldmg = defender:takeWeaponskillDamage(attacker, finaldmg, slot, tpHitsLanded, bonusTP, targetTPMult)
local enmityEntity = taChar or attacker;
if (params.overrideCE and params.overrideVE) then
defender:addEnmity(enmityEntity, params.overrideCE, params.overrideVE)
else
local enmityMult = params.enmityMult or 1
defender:updateEnmityFromDamage(enmityEntity, finaldmg * enmityMult)
end
return finaldmg;
end
-- Params should have the following members:
-- params.power.lv1: Base value for AM power @ level 1
-- params.power.lv2: Base value for AM power @ level 2
-- params.power.lv3: Base value for AM power @ level 3
-- params.power.lv1_inc: How much to increment at each power level
-- params.power.lv2_inc: How much to increment at each power level
-- params.subpower.lv1: Subpower for level 1
-- params.subpower.lv2: Subpower for level 2
-- params.subpower.lv3: Subpower for level 3
-- params.duration.lv1: Duration for AM level 1
-- params.duration.lv2: Duration for AM level 2
-- params.duration.lv3: Duration for AM level 3
function applyAftermathEffect(player, tp, params)
if (params == nil) then
params = initAftermathParams()
end
local apply_power = 0
if (tp == 3000) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, params.power.lv3, 0,
params.duration.lv3, 0, params.subpower.lv3)
elseif (tp >= 2000) then
apply_power = params.power.lv2 + ((tp - 2000) / (100 / params.power.lv2_inc))
player:addStatusEffect(EFFECT_AFTERMATH_LV2, apply_power, 0,
params.duration.lv2, 0, params.subpower.lv2);
elseif (tp >= 1000) then
apply_power = params.power.lv1 + ((tp - 1000) / (100 / params.power.lv1_inc))
player:addStatusEffect(EFFECT_AFTERMATH_LV1, apply_power, 0,
params.duration.lv1, 0, params.subpower.lv1);
end
end;
function initAftermathParams()
local params = {}
params.power = {}
params.subpower = {}
params.duration = {}
params.power.lv1 = 10
params.power.lv2 = 20
params.power.lv3 = 45
params.power.lv1_inc = 1
params.power.lv2_inc = 4
params.subpower.lv1 = 1
params.subpower.lv2 = 1
params.subpower.lv3 = 1
params.duration.lv1 = 180
params.duration.lv2 = 180
params.duration.lv3 = 120
return params
end;
function handleWSGorgetBelt(attacker)
local ftpBonus = 0;
local accBonus = 0;
if (attacker:getObjType() == TYPE_PC) then
-- TODO: Get these out of itemid checks when possible.
local elementalGorget = { 15495, 15498, 15500, 15497, 15496, 15499, 15501, 15502 };
local elementalBelt = { 11755, 11758, 11760, 11757, 11756, 11759, 11761, 11762 };
local neck = attacker:getEquipID(SLOT_NECK);
local belt = attacker:getEquipID(SLOT_WAIST);
local SCProp1, SCProp2, SCProp3 = attacker:getWSSkillchainProp();
for i,v in ipairs(elementalGorget) do
if (neck == v) then
if (doesElementMatchWeaponskill(i, SCProp1) or doesElementMatchWeaponskill(i, SCProp2) or doesElementMatchWeaponskill(i, SCProp3)) then
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
break;
end
end
for i,v in ipairs(elementalBelt) do
if (belt == v) then
if (doesElementMatchWeaponskill(i, SCProp1) or doesElementMatchWeaponskill(i, SCProp2) or doesElementMatchWeaponskill(i, SCProp3)) then
accBonus = accBonus + 10;
ftpBonus = ftpBonus + 0.1;
end
break;
end
end
end
return ftpBonus, accBonus;
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Windurst_Woods/npcs/Shih_Tayuun.lua | 19 | 1163 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Shih Tayuun
-- Guild Merchant NPC: Bonecrafting Guild
-- @pos -3.064 -6.25 -131.374 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(514,8,23,3)) then
player:showText(npc,SHIH_TAYUUN_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 |
UnfortunateFruit/darkstar | scripts/zones/Halvung/npcs/qm1.lua | 8 | 1199 | -----------------------------------
-- Area: Halvung
-- NPC: ??? (Spawn Big Bomb)
-- @pos -233.830 13.613 286.714 62
-----------------------------------
package.loaded["scripts/zones/Halvung/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Halvung/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Smokey Flask
if(GetMobAction(17031401) == 0 and trade:hasItemQty(2384,1) and trade:getItemCount() == 1) then
player:tradeComplete();
SpawnMob(17031401,900):updateClaim(player); -- Big Bomb
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(BLUE_FLAMES);
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/Metalworks/npcs/Aishah.lua | 34 | 1044 | -----------------------------------
-- Area: Metalworks
-- NPC: Aishah
-- Type: Standard Info NPC
-- @pos -83.038 2.390 -26.209 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- 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 |
nesstea/darkstar | scripts/zones/Port_Bastok/npcs/Panana.lua | 13 | 1098 | -----------------------------------
-- Area: Port Bastok
-- NPC: Panana
-- Involved in Quest: Out of One's Shell
-----------------------------------
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
OutOfOneShell = player:getQuestStatus(BASTOK,OUT_OF_ONE_S_SHELL);
if (OutOfOneShell == QUEST_ACCEPTED and player:getVar("OutOfTheShellZone") == 0) then
player:startEvent(0x0053);
else
player:startEvent(0x002b);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
nesstea/darkstar | scripts/zones/Bastok_Markets/npcs/Yafafa.lua | 16 | 1557 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Yafafa
-- Only sells when Bastok controls Kolshushu
--
-- Updated Aug-09-2013 by Zerahn, based on bgwiki and gamerescape
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
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)
RegionOwner = GetRegionOwner(KOLSHUSHU);
if (RegionOwner ~= BASTOK) then
player:showText(npc,YAFAFA_CLOSED_DIALOG);
else
player:showText(npc,YAFAFA_OPEN_DIALOG);
stock = {
0x1197, 184, --Buburimu Grape
0x0460,1620, --Casablanca
0x1107, 220, --Dhalmel Meat
0x0266, 72, --Mhaura Garlic
0x115d, 40 --Yagudo Cherry
}
showShop(player,BASTOK,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Northern_San_dOria/npcs/Abioleget.lua | 19 | 2185 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Abioleget
-- Type: Quest Giver (Her Memories: The Faux Pas and The Vicasque's Sermon) / Merchant
-- @zone: 231
-- @pos 128.771 0.000 118.538
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(sermonQuest == QUEST_ACCEPTED) then
gil = trade:getGil();
count = trade:getItemCount();
if(gil == 70 and count == 1) then
player:tradeComplete();
player:startEvent(0x024F);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
sermonQuest = player:getQuestStatus(SANDORIA,THE_VICASQUE_S_SERMON);
if(sermonQuest == QUEST_AVAILABLE) then
player:startEvent(0x024d);
elseif(sermonQuest == QUEST_ACCEPTED) then
if(player:getVar("sermonQuestVar") == 1) then
player:tradeComplete();
player:startEvent(0x0258);
else
player:showText(npc,11103,618,70);
end
else
player:showText(npc,ABIOLEGET_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0258) then
player:addItem(13465);
player:messageSpecial(6567, 13465);
player:addFame(SANDORIA,SAN_FAME*30);
player:addTitle(THE_BENEVOLENT_ONE);
player:setVar("sermonQuestVar",0);
player:completeQuest(SANDORIA,THE_VICASQUE_S_SERMON );
elseif (csid == 0x024D) then
player:addQuest(SANDORIA,THE_VICASQUE_S_SERMON );
elseif (csid == 0x024F) then
player:addItem(618);
player:messageSpecial(6567, 618);
end
end;
| gpl-3.0 |
nesstea/darkstar | scripts/zones/Lufaise_Meadows/npcs/Cotete_WW.lua | 13 | 3325 | -----------------------------------
-- Area: Lufaise Meadows
-- NPC: Cotete, W.W.
-- Border Conquest Guards
-- @pos 414.659 0.905 -52.417 24
-----------------------------------
package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Lufaise_Meadows/TextIDs");
local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = TAVNAZIANARCH;
local csid = 0x7ff6;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
FailcoderAddons/supervillain-ui | SVUI_QuestTracker/components/achievements.lua | 2 | 13493 | --[[
##########################################################
S V U I By: Failcoder
##########################################################
LOCALIZED LUA FUNCTIONS
##########################################################
]]--
--[[ GLOBALS ]]--
local _G = _G;
local unpack = _G.unpack;
local select = _G.select;
local pairs = _G.pairs;
local ipairs = _G.ipairs;
local type = _G.type;
local error = _G.error;
local pcall = _G.pcall;
local tostring = _G.tostring;
local tonumber = _G.tonumber;
local tinsert = _G.tinsert;
local string = _G.string;
local math = _G.math;
local table = _G.table;
local band = _G.bit.band;
--[[ STRING METHODS ]]--
local format = string.format;
--[[ MATH METHODS ]]--
local abs, ceil, floor, round = math.abs, math.ceil, math.floor, math.round;
--[[ TABLE METHODS ]]--
local tremove, twipe = table.remove, table.wipe;
--BLIZZARD API
local CreateFrame = _G.CreateFrame;
local InCombatLockdown = _G.InCombatLockdown;
local GameTooltip = _G.GameTooltip;
local hooksecurefunc = _G.hooksecurefunc;
--[[
##########################################################
GET ADDON DATA
##########################################################
]]--
local SV = _G['SVUI']
local L = SV.L
local LSM = _G.LibStub("LibSharedMedia-3.0")
local MOD = SV.QuestTracker;
--[[
##########################################################
LOCALS
##########################################################
]]--
local ROW_WIDTH = 300;
local ROW_HEIGHT = 20;
local QUEST_ROW_HEIGHT = ROW_HEIGHT + 2;
local INNER_HEIGHT = ROW_HEIGHT - 4;
local LARGE_ROW_HEIGHT = ROW_HEIGHT * 2;
local LARGE_INNER_HEIGHT = LARGE_ROW_HEIGHT - 4;
local NO_ICON = SV.NoTexture;
local OBJ_ICON_ACTIVE = [[Interface\COMMON\Indicator-Yellow]];
local OBJ_ICON_COMPLETE = [[Interface\COMMON\Indicator-Green]];
local OBJ_ICON_INCOMPLETE = [[Interface\COMMON\Indicator-Gray]];
local LINE_ACHIEVEMENT_ICON = [[Interface\ICONS\Achievement_General]];
local MAX_OBJECTIVES_SHOWN = 8;
--[[
##########################################################
SCRIPT HANDLERS
##########################################################
]]--
local RowButton_OnEnter = function(self, ...)
if(MOD.DOCK_IS_FADED) then return end
GameTooltip:SetOwner(self, "ANCHOR_BOTTOMLEFT", 0, ROW_HEIGHT)
GameTooltip:ClearLines()
GameTooltip:AddDoubleLine("[Left-Click]", "View this in the achievements window.", 0, 1, 0, 1, 1, 1)
GameTooltip:AddLine(" ")
GameTooltip:AddDoubleLine("[Right-Click]", "Remove this achievement from the tracker.", 0, 1, 0, 1, 1, 1)
GameTooltip:Show()
end
local RowButton_OnLeave = function(self, ...)
GameTooltip:Hide()
end
local ViewButton_OnClick = function(self, button)
local achievementID = self:GetID();
if(achievementID and (achievementID ~= 0)) then
if(IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow()) then
local achievementLink = GetAchievementLink(achievementID);
if(achievementLink) then
ChatEdit_InsertLink(achievementLink);
end
else
CloseDropDownMenus();
if(not AchievementFrame ) then
AchievementFrame_LoadUI();
end
if(IsModifiedClick("QUESTWATCHTOGGLE") or (button and button == "RightButton")) then
AchievementObjectiveTracker_UntrackAchievement(self, achievementID);
elseif(not AchievementFrame:IsShown()) then
AchievementFrame_ToggleAchievementFrame();
AchievementFrame_SelectAchievement(achievementID);
else
if(AchievementFrameAchievements.selection ~= achievementID) then
AchievementFrame_SelectAchievement(achievementID);
else
AchievementFrame_ToggleAchievementFrame();
end
end
end
end
end
local BadgeButton_OnClick = function(self, button)
local achievementID = self.Link:GetID();
if(achievementID and (achievementID ~= 0)) then
if(IsModifiedClick("CHATLINK") and ChatEdit_GetActiveWindow()) then
local achievementLink = GetAchievementLink(achievementID);
if(achievementLink) then
ChatEdit_InsertLink(achievementLink);
end
else
CloseDropDownMenus();
if(not AchievementFrame ) then
AchievementFrame_LoadUI();
end
if(IsModifiedClick("QUESTWATCHTOGGLE") or (button and button == "RightButton")) then
AchievementObjectiveTracker_UntrackAchievement(self.Link, achievementID);
elseif(not AchievementFrame:IsShown()) then
AchievementFrame_ToggleAchievementFrame();
AchievementFrame_SelectAchievement(achievementID);
else
if(AchievementFrameAchievements.selection ~= achievementID) then
AchievementFrame_SelectAchievement(achievementID);
else
AchievementFrame_ToggleAchievementFrame();
end
end
end
end
end
--[[
##########################################################
TRACKER FUNCTIONS
##########################################################
]]--
local GetAchievementRow = function(self, index)
if(not self.Rows[index]) then
local previousFrame = self.Rows[#self.Rows]
local index = #self.Rows + 1;
local yOffset = -3;
local anchorFrame;
if(previousFrame and previousFrame.Objectives) then
anchorFrame = previousFrame.Objectives;
yOffset = -6;
else
anchorFrame = self.Header;
end
local row = CreateFrame("Frame", nil, self)
row:SetPoint("TOPLEFT", anchorFrame, "BOTTOMLEFT", 0, yOffset);
row:SetPoint("TOPRIGHT", anchorFrame, "BOTTOMRIGHT", 0, yOffset);
row:SetHeight(QUEST_ROW_HEIGHT);
row.Badge = CreateFrame("Frame", nil, row)
row.Badge:SetPoint("TOPLEFT", row, "TOPLEFT", 0, 0);
row.Badge:SetSize(QUEST_ROW_HEIGHT, QUEST_ROW_HEIGHT);
--row.Badge:SetStyle("Frame", "Lite");
row.Badge.Icon = row.Badge:CreateTexture(nil,"OVERLAY")
row.Badge.Icon:SetAllPoints(row.Badge);
row.Badge.Icon:SetTexture(LINE_ACHIEVEMENT_ICON)
row.Badge.Icon:SetTexCoord(unpack(_G.SVUI_ICON_COORDS))
row.Badge.Button = CreateFrame("Button", nil, row.Badge)
row.Badge.Button:SetAllPoints(row.Badge);
row.Badge.Button:SetStyle("LiteButton")
row.Badge.Button:SetID(0)
row.Badge.Button.Icon = row.Badge.Icon;
row.Badge.Button:RegisterForClicks("LeftButtonUp", "RightButtonUp")
row.Badge.Button:SetScript("OnClick", BadgeButton_OnClick)
row.Badge.Button:SetScript("OnEnter", RowButton_OnEnter)
row.Badge.Button:SetScript("OnLeave", RowButton_OnLeave)
row.Header = CreateFrame("Frame", nil, row)
row.Header:SetPoint("TOPLEFT", row, "TOPLEFT", (QUEST_ROW_HEIGHT + 6), 0);
row.Header:SetPoint("TOPRIGHT", row, "TOPRIGHT", -2, 0);
row.Header:SetHeight(QUEST_ROW_HEIGHT);
row.Header.Text = row.Header:CreateFontString(nil,"OVERLAY")
row.Header.Text:SetFontObject(SVUI_Font_Quest);
row.Header.Text:SetJustifyH('LEFT')
row.Header.Text:SetTextColor(1,1,0)
row.Header.Text:SetText('')
row.Header.Text:SetPoint("TOPLEFT", row.Header, "TOPLEFT", 4, 0);
row.Header.Text:SetPoint("BOTTOMRIGHT", row.Header, "BOTTOMRIGHT", 0, 0);
row.Button = CreateFrame("Button", nil, row.Header);
row.Button:SetPoint("TOPLEFT", row, "TOPLEFT", (QUEST_ROW_HEIGHT + 6), 0);
row.Button:SetPoint("TOPRIGHT", row, "TOPRIGHT", -2, 0);
row.Button:SetHeight(INNER_HEIGHT + 2);
row.Button:SetStyle("LiteButton")
row.Button:SetID(0)
row.Button:RegisterForClicks("LeftButtonUp", "RightButtonUp")
row.Button:SetScript("OnClick", ViewButton_OnClick)
row.Button:SetScript("OnEnter", RowButton_OnEnter)
row.Button:SetScript("OnLeave", RowButton_OnLeave)
row.Badge.Button.Link = row.Button
row.Objectives = MOD.NewObjectiveHeader(row);
row.Objectives:SetPoint("TOPLEFT", row, "BOTTOMLEFT", 0, 0);
row.Objectives:SetPoint("TOPRIGHT", row, "BOTTOMRIGHT", 0, 0);
row.Objectives:SetHeight(1);
row.RowID = 0;
self.Rows[index] = row;
return row;
end
return self.Rows[index];
end
local SetAchievementRow = function(self, index, title, details, icon, achievementID)
index = index + 1;
icon = icon or LINE_ACHIEVEMENT_ICON;
local fill_height = 0;
local shown_objectives = 0;
local objective_rows = 0;
local row = self:Get(index);
row.RowID = achievementID
row.Header.Text:SetText(title)
row.Badge.Icon:SetTexture(icon);
row.Badge:SetAlpha(1);
row.Button:Enable();
row.Button:SetID(achievementID);
row:SetHeight(ROW_HEIGHT);
row:FadeIn();
row.Header:FadeIn();
local objective_block = row.Objectives;
local subCount = GetAchievementNumCriteria(achievementID);
for i = 1, subCount do
local description, category, completed, quantity, totalQuantity, _, flags, assetID, quantityString, criteriaID, eligible, duration, elapsed = GetAchievementCriteriaInfo(achievementID, i);
if(completed or (shown_objectives > MAX_OBJECTIVES_SHOWN and not completed)) then
--DO NOTHING
elseif(shown_objectives == MAX_OBJECTIVES_SHOWN and subCount > (MAX_OBJECTIVES_SHOWN + 1)) then
shown_objectives = shown_objectives + 1;
else
if(description and band(flags, EVALUATION_TREE_FLAG_PROGRESS_BAR) == EVALUATION_TREE_FLAG_PROGRESS_BAR) then
if(string.find(quantityString:lower(), "interface\\moneyframe")) then
description = quantityString.."\n"..description;
else
description = string.gsub(quantityString, " / ", "/").." "..description;
end
else
if(category == CRITERIA_TYPE_ACHIEVEMENT and assetID) then
_, description = GetAchievementInfo(assetID);
end
end
if(description and description ~= '') then
shown_objectives = shown_objectives + 1;
fill_height = fill_height + (ROW_HEIGHT + 2);
objective_rows = objective_block:SetInfo(objective_rows, description, completed)
if(duration and elapsed and elapsed < duration) then
fill_height = fill_height + (ROW_HEIGHT + 2);
objective_rows = objective_block:SetTimer(objective_rows, duration, elapsed);
end
end
end
end
if(objective_rows > 0) then
objective_block:SetHeight(fill_height);
objective_block:FadeIn();
end
fill_height = fill_height + (ROW_HEIGHT + 2);
return index, fill_height;
end
local RefreshAchievements = function(self, event, ...)
local list = { GetTrackedAchievements() };
local fill_height = 0;
local rows = 0;
if(#list > 0) then
for i = 1, #list do
local achievementID = list[i];
local _, title, _, completed, _, _, _, details, _, icon, _, _, wasEarnedByMe = GetAchievementInfo(achievementID);
if(not wasEarnedByMe) then
local add_height = 0;
rows, add_height = self:Set(rows, title, details, icon, achievementID)
fill_height = fill_height + add_height
end
end
end
if(rows == 0 or (fill_height <= 1)) then
self:SetHeight(1);
self.Header.Text:SetText('');
self.Header:SetAlpha(0);
self:SetAlpha(0);
else
self:SetHeight(fill_height + 2);
self.Header.Text:SetText(TRACKER_HEADER_ACHIEVEMENTS);
self:FadeIn();
self.Header:FadeIn();
end
end
local ResetAchievementBlock = function(self)
for x = 1, #self.Rows do
local row = self.Rows[x]
if(row) then
row.RowID = 0;
row.Header.Text:SetText('');
row.Header:SetAlpha(0);
row.Button:Disable();
row.Button:SetID(0);
row.Badge.Icon:SetTexture(NO_ICON);
row.Badge:SetAlpha(0);
row:SetHeight(1);
row:SetAlpha(0);
row.Objectives:Reset();
end
end
end
--[[
##########################################################
CORE FUNCTIONS
##########################################################
]]--
function MOD:UpdateAchievements(event, ...)
self.Headers["Achievements"]:Reset()
self.Headers["Achievements"]:Refresh(event, ...)
self:UpdateDimensions();
end
local function UpdateAchievementLocals(...)
ROW_WIDTH, ROW_HEIGHT, INNER_HEIGHT, LARGE_ROW_HEIGHT, LARGE_INNER_HEIGHT = ...;
QUEST_ROW_HEIGHT = ROW_HEIGHT + 2;
end
function MOD:InitializeAchievements()
local scrollChild = self.Docklet.ScrollFrame.ScrollChild;
local achievements = CreateFrame("Frame", nil, scrollChild)
achievements:SetWidth(ROW_WIDTH);
achievements:SetHeight(ROW_HEIGHT);
achievements:SetPoint("TOPLEFT", self.Headers["Quests"], "BOTTOMLEFT", 0, -12);
achievements.Header = CreateFrame("Frame", nil, achievements)
achievements.Header:SetPoint("TOPLEFT", achievements, "TOPLEFT", 2, -2);
achievements.Header:SetPoint("TOPRIGHT", achievements, "TOPRIGHT", -2, -2);
achievements.Header:SetHeight(INNER_HEIGHT);
achievements.Header.Text = achievements.Header:CreateFontString(nil,"OVERLAY")
achievements.Header.Text:SetPoint("TOPLEFT", achievements.Header, "TOPLEFT", 2, 0);
achievements.Header.Text:SetPoint("BOTTOMLEFT", achievements.Header, "BOTTOMLEFT", 2, 0);
achievements.Header.Text:SetFontObject(SVUI_Font_Quest_Header);
achievements.Header.Text:SetJustifyH('LEFT')
achievements.Header.Text:SetTextColor(0.28,0.75,1)
achievements.Header.Text:SetText(TRACKER_HEADER_ACHIEVEMENTS)
achievements.Header.Divider = achievements.Header:CreateTexture(nil, 'BACKGROUND');
achievements.Header.Divider:SetPoint("TOPLEFT", achievements.Header.Text, "TOPRIGHT", -10, 0);
achievements.Header.Divider:SetPoint("BOTTOMRIGHT", achievements.Header, "BOTTOMRIGHT", 0, 0);
achievements.Header.Divider:SetTexture([[Interface\AddOns\SVUI_!Core\assets\textures\DROPDOWN-DIVIDER]]);
achievements.Rows = {};
achievements.Get = GetAchievementRow;
achievements.Set = SetAchievementRow;
achievements.Refresh = RefreshAchievements;
achievements.Reset = ResetAchievementBlock;
self.Headers["Achievements"] = achievements;
self:RegisterEvent("TRACKED_ACHIEVEMENT_UPDATE", self.UpdateAchievements);
self:RegisterEvent("TRACKED_ACHIEVEMENT_LIST_CHANGED", self.UpdateAchievements);
self.Headers["Achievements"]:Refresh()
SV.Events:On("QUEST_UPVALUES_UPDATED", UpdateAchievementLocals, true);
end
| mit |
UnfortunateFruit/darkstar | scripts/globals/items/serving_of_goblin_stir-fry.lua | 35 | 1286 | -----------------------------------------
-- ID: 5143
-- Item: serving_of_goblin_stir-fry
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Agility 5
-- Vitality 2
-- Charisma -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5143);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 5);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_CHR, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 5);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_CHR, -5);
end;
| gpl-3.0 |
danielmandlez/LuaClasses | Electric/TRU.lua | 1 | 3005 | ---------------------------------------------------------------------------------
-- Project: Useful Lua-Classes for X-Plane GIZMO
-- Developer: Daniel Mandlez
-- Date: 2014
-- FileBlock: Class Electric Transformer Rectifier Unit (TRU) AC/DC
---------------------------------------------------------------------------------
-- This is just a rough Idea how a TRU can work, and it's not finished!!
-- Take the Idea if you like, modify on your own choice!
-- Many Planes have AC Generators. You need to produce DC Power and this happen with TRUs
TRU = {}
TRU.new = function(ACvolt, DCvolt, freq, ACmaxamp, DCmaxamp, id) -- nominal AC Voltage, nominal DC Voltage, nominal Frequency, max AC Amperes, max DC Amperes, Source ID
local self = {}
self.SurceID = id -- Each Power Source should have another id, to know for the BUSes where they are actually connected
-- AC
self.ACnominalVolt = ACvolt
self.ACactVolt = 0
self.minVoltage = 70 -- is temporary set fix here
self.ACmaxAmp = ACmaxamp
self.ACactAmp = 0
self.nominalFreq = freq
self.actFreq = 0
-- DC
self.DCnominalVolt = DCvolt
self.DCactVolt = 0
self.DCmaxAmp = DCmaxamp
self.DCactAmp = 0
self.ON = false
-- Set actual Input from connected AC Bus
self.setAC = function (volt, freq)
self.ACactVolt = volt
self.ACactFreq = freq
end
-- Send actual used Amps to Electrical Source -- MUST BE AC-BUS!!
self.Consume = function()
if self.ACactVolt > 0.0 then -- Check against DIV by 0
-- Rough Transforming ratio without any reductions
self.ACactAmp = self.DCactAmp * self.DCactVolt / self.ACactVolt
end
return self.ACactAmp
end
-- Same as Consume, you can use to have same Methode names for example on the indication Display
self.getActAmps = function()
return self.ACactAmp
end
-- Set Amperes are used by all Consumers -- MUST BE DC-BUS
self.setUsedAmps = function(amp)
self.DCactAmp = amp
end
-- Get actual TRU Voltage
self.getDCVoltage = function()
local volt
if self.ON == true and self.ACactVolt > self.minVoltage then
-- Rough transforming ratio
volt = self.DCnominalVolt * self.ACactVolt / self.ACnominalVolt
else
volt = 0.0 -- If AC Voltage goes below
end
self.DCactVolt = volt
return volt
end
-- Get TRU Voltage when it's turned OFF
self.getOFFDCVoltage = function()
local volt
if self.ACactVolt > self.minVoltage then
-- Rough transforming ratio
volt = self.DCnominalVolt * self.ACactVolt / self.ACnominalVolt
else
volt = 0.0
end
return volt
end
-- Set TRU ON/OFF
self.setON = function(val)
if val == 1 or val == true then
self.ON = true
else
self.ON = false
end
end
-- Get TRU ON, true if ON
self.getON = function()
return self.ON
end
-- GET TRU OFF, returns true if OFF, used for the Button Indication
self.getOFF = function()
return not self.ON
end
-- Get Source ID for BUSes to now where to pull the AMPs
self.getID = function()
return self.SourceID
end
return self
end | unlicense |
nesstea/darkstar | scripts/globals/spells/knights_minne_ii.lua | 27 | 1501 | -----------------------------------------
-- Spell: Knight's Minne II
-- Grants Defense bonus to all allies.
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 12 + math.floor((sLvl + iLvl)/10);
if (power >= 41) then
power = 41;
end
local iBoost = caster:getMod(MOD_MINNE_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
if (iBoost > 0) then
power = power + 1 + (iBoost-1)*4;
end
power = power + caster:getMerit(MERIT_MINNE_EFFECT);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MINNE,power,0,duration,caster:getID(), 0, 2)) then
spell:setMsg(75);
end
return EFFECT_MINNE;
end; | gpl-3.0 |
dpino/snabbswitch | src/program/snabbnfv/fuzz/fuzz.lua | 9 | 5129 | -- Use of this source code is governed by the Apache 2.0 license; see COPYING.
module(...,package.seeall)
local lib = require("core.lib")
local usage = require("program.snabbnfv.fuzz.README_inc")
function run (args)
if #args ~= 2 then print(usage) main.exit(1) end
local spec_path, output_path = unpack(args)
local conf = fuzz_connective_ports(lib.load_conf(spec_path))
lib.store_conf(output_path, conf)
end
-- Produces a random config with ports A and B which can communicate with
-- each other over IPv6/TCP based on spec.
function fuzz_connective_ports (spec)
local vlan = random_vlan()
local addresses = { "fe80:0:0:0:5054:ff:fe00:0",
"fe80:0:0:0:5054:ff:fe00:1" }
local ports = { { port_id = "A",
mac_address = "52:54:00:00:00:00",
vlan = vlan },
{ port_id = "B",
mac_address = "52:54:00:00:00:01",
vlan = vlan } }
local function fuzz_filter (n_rules)
local filter = "(ip6 and tcp) or (icmp6)"
for i = 1, n_rules do
filter = filter.." or "..(random_filter_rule())
end
return filter
end
local function fuzz_tunnel ()
local cookies = { random_cookie(), random_cookie() }
return { type = "L2TPv3",
local_cookie = cookies[1],
remote_cookie = cookies[2],
next_hop = addresses[2],
local_ip = addresses[1],
remote_ip = addresses[2],
session = random_session() },
{ type = "L2TPv3",
local_cookie = cookies[2],
remote_cookie = cookies[1],
next_hop = addresses[1],
local_ip = addresses[2],
remote_ip = addresses[1],
session = random_session() }
end
if spec.ingress_filter then
ports[1].ingress_filter = fuzz_filter(spec.ingress_filter)
ports[2].ingress_filter = fuzz_filter(spec.ingress_filter)
end
if spec.egress_filter then
ports[1].egress_filter = fuzz_filter(spec.egress_filter)
ports[2].egress_filter = fuzz_filter(spec.egress_filter)
end
if spec.tunnel then
ports[1].tunnel, ports[2].tunnel = fuzz_tunnel()
end
if spec.rx_police then
ports[1].rx_police = random_gbps(spec.rx_police)
ports[2].rx_police = random_gbps(spec.rx_police)
end
if spec.tx_police then
ports[1].tx_police = random_gbps(spec.tx_police)
ports[2].tx_police = random_gbps(spec.tx_police)
end
return ports
end
function random_uint (nbits, min)
return math.random(min or 0, (2^nbits-1))
end
function random_vlan ()
-- Twelve bit integer, see apps.intel_mp.intel_mp
return random_uint(12)
end
function random_ip (version)
local version = version or "ip6"
local function b4 () return random_uint(8) end
local function b6 () return ("%X"):format(random_uint(16)) end
if version == "ip" then
return b4().."."..b4().."."..b4().."."..b4()
elseif version == "ip6" then
return b6()..":"..b6()..":"..b6()..":"..b6()..":"..b6()..":"..b6()..":"..b6()..":"..b6()
end
end
function random_cidr (version)
-- This is just lame, should be a "smart" random valid CIDR generator.
local random_cidr_ip4 = {
"109.0.0.0/8",
"109.145.0.0/16",
"109.145.29.0/24",
-- "109.145.29.1"
}
local random_cidr_ip6 = {
"CB51::0/16",
"CB51:B2E7::0/32",
"CB51:B2E7:9711::0/48",
"CB51:B2E7:9711:C0D3::0/64",
"CB51:B2E7:9711:C0D3:14BA::0/80",
"CB51:B2E7:9711:C0D3:14BA:A93E::0/96",
"CB51:B2E7:9711:C0D3:14BA:A93E:56DE:0/112",
-- "CB51:B2E7:9711:C0D3:14BA:A93E:56DE:1"
}
if version == "ip" then
return random_item(random_cidr_ip4)
elseif version == "ip6" then
return random_item(random_cidr_ip6)
end
end
function random_port (min)
local min = min or 1024
return random_uint(16, min)
end
function random_item (array)
return array[math.random(1, #array)]
end
function random_filter_rule ()
local options = { ethertype = { "ip", "ip6" },
protocol = { "udp", "tcp" } }
local ethertype = random_item(options.ethertype)
local source_port_min = random_port()
local dest_port_min = random_port()
-- See PcapFilter (apps.packet_filter.pcap_filter)
return ("(%s and %s and src net %s and dst net %s and src portrange %d-%d and dst portrange %d-%d)"):format(
ethertype,
random_item(options.protocol),
random_cidr(ethertype),
random_cidr(ethertype),
source_port_min,
random_port(source_port_min),
dest_port_min,
random_port(dest_port_min))
end
function random_cookie ()
local function b() return ("%X"):format(random_uint(8)) end
-- Eight byte hex string, see SimpleKeyedTunnel (apps.keyed_ipv6_tunnel.tunnel)
return b()..b()..b()..b()..b()..b()..b()..b()
end
function random_session ()
-- 32 bit uint, see SimpleKeyedTunnel (apps.keyed_ipv6_tunnel.tunnel)
return random_uint(32)
end
function random_gbps (max_gbps)
return math.random(1, max_gbps)
end
| apache-2.0 |
nesstea/darkstar | scripts/zones/QuBia_Arena/bcnms/heir_to_the_light.lua | 30 | 1916 | -----------------------------------
-- Name: Mission 9-2 SANDO
-----------------------------------
package.loaded["scripts/zones/Qubia_arena/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
require("scripts/zones/QuBia_Arena/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);
local currentMission = player:getCurrentMission(SANDORIA);
if (leavecode == 2) then
--printf("win");
if (currentMission == THE_HEIR_TO_THE_LIGHT) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,0);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,4,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);
local currentMission = player:getCurrentMission(SANDORIA);
local MissionStatus = player:getVar("MissionStatus");
if (csid == 0x7d01) then
if (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 3) then
player:setVar("MissionStatus",4);
end
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Jugner_Forest/npcs/Signpost.lua | 24 | 2848 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Signpost
-- Involved in Quest: Grimy Signposts
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local X = player:getXPos();
local Z = player:getZPos();
if ((X > -79.3 and X < -67.3) and (Z > 94.5 and Z < 106.5)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),0)) then
player:startEvent(0x0006,1);
else
player:startEvent(0x0001);
end
elseif ((X > -266.2 and X < -254.2) and (Z > -29.2 and Z < -17.2)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),1)) then
player:startEvent(0x0007,1);
else
player:startEvent(0x0002);
end
elseif ((X > -463.7 and X < -451.7) and (Z > -422.1 and Z < -410.1)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),2)) then
player:startEvent(0x0008,1);
else
player:startEvent(0x0003);
end
elseif ((X > 295.4 and X < 307.3) and (Z > 412.8 and Z < 424.8)) then
if (player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS) == QUEST_ACCEPTED and not player:getMaskBit(player:getVar("CleanSignPost"),3)) then
player:startEvent(0x0009,1);
else
player:startEvent(0x0004);
end
else
print("Unknown Signpost");
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 == 6 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",0,true);
elseif (csid == 7 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",1,true);
elseif (csid == 8 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",2,true);
elseif (csid == 9 and option == 1) then
player:setMaskBit(player:getVar("CleanSignPost"),"CleanSignPost",3,true);
end
end; | gpl-3.0 |
UnfortunateFruit/darkstar | scripts/zones/Crawlers_Nest/npcs/_5h1.lua | 12 | 2609 | -----------------------------------
-- Area: Crawlers' Nest
-- NPC: Strange Apparatus
-- @pos: 214 0 -339 197
-----------------------------------
package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil;
require("scripts/zones/Crawlers_Nest/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(0x0002, 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(0x0000, 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 == 0x0000) 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 == 0x0002) 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 |
Jacklli/redis-leveldb | deps/lua/dynasm/dasm_arm.lua | 15 | 34483 | ------------------------------------------------------------------------------
-- DynASM ARM module.
--
-- Copyright (C) 2005-2012 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "arm",
description = "DynASM ARM module",
version = "1.3.0",
vernum = 10300,
release = "2011-05-05",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable, rawget = assert, setmetatable, rawget
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch, gsub = _s.match, _s.gmatch, _s.gsub
local concat, sort, insert = table.concat, table.sort, table.insert
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local ror, tohex = bit.ror, bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMM12", "IMM16", "IMML8", "IMML12", "IMMV8",
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0x000fffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
if n <= 0x000fffff then
insert(actlist, pos+1, n)
n = map_action.ESC * 0x10000
end
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
-- Ext. register name -> int. name.
local map_archdef = { sp = "r13", lr = "r14", pc = "r15", }
-- Int. register name -> ext. name.
local map_reg_rev = { r13 = "sp", r14 = "lr", r15 = "pc", }
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
return map_reg_rev[s] or s
end
local map_shift = { lsl = 0, lsr = 1, asr = 2, ror = 3, }
local map_cond = {
eq = 0, ne = 1, cs = 2, cc = 3, mi = 4, pl = 5, vs = 6, vc = 7,
hi = 8, ls = 9, ge = 10, lt = 11, gt = 12, le = 13, al = 14,
hs = 2, lo = 3,
}
------------------------------------------------------------------------------
-- Template strings for ARM instructions.
local map_op = {
-- Basic data processing instructions.
and_3 = "e0000000DNPs",
eor_3 = "e0200000DNPs",
sub_3 = "e0400000DNPs",
rsb_3 = "e0600000DNPs",
add_3 = "e0800000DNPs",
adc_3 = "e0a00000DNPs",
sbc_3 = "e0c00000DNPs",
rsc_3 = "e0e00000DNPs",
tst_2 = "e1100000NP",
teq_2 = "e1300000NP",
cmp_2 = "e1500000NP",
cmn_2 = "e1700000NP",
orr_3 = "e1800000DNPs",
mov_2 = "e1a00000DPs",
bic_3 = "e1c00000DNPs",
mvn_2 = "e1e00000DPs",
and_4 = "e0000000DNMps",
eor_4 = "e0200000DNMps",
sub_4 = "e0400000DNMps",
rsb_4 = "e0600000DNMps",
add_4 = "e0800000DNMps",
adc_4 = "e0a00000DNMps",
sbc_4 = "e0c00000DNMps",
rsc_4 = "e0e00000DNMps",
tst_3 = "e1100000NMp",
teq_3 = "e1300000NMp",
cmp_3 = "e1500000NMp",
cmn_3 = "e1700000NMp",
orr_4 = "e1800000DNMps",
mov_3 = "e1a00000DMps",
bic_4 = "e1c00000DNMps",
mvn_3 = "e1e00000DMps",
lsl_3 = "e1a00000DMws",
lsr_3 = "e1a00020DMws",
asr_3 = "e1a00040DMws",
ror_3 = "e1a00060DMws",
rrx_2 = "e1a00060DMs",
-- Multiply and multiply-accumulate.
mul_3 = "e0000090NMSs",
mla_4 = "e0200090NMSDs",
umaal_4 = "e0400090DNMSs", -- v6
mls_4 = "e0600090DNMSs", -- v6T2
umull_4 = "e0800090DNMSs",
umlal_4 = "e0a00090DNMSs",
smull_4 = "e0c00090DNMSs",
smlal_4 = "e0e00090DNMSs",
-- Halfword multiply and multiply-accumulate.
smlabb_4 = "e1000080NMSD", -- v5TE
smlatb_4 = "e10000a0NMSD", -- v5TE
smlabt_4 = "e10000c0NMSD", -- v5TE
smlatt_4 = "e10000e0NMSD", -- v5TE
smlawb_4 = "e1200080NMSD", -- v5TE
smulwb_3 = "e12000a0NMS", -- v5TE
smlawt_4 = "e12000c0NMSD", -- v5TE
smulwt_3 = "e12000e0NMS", -- v5TE
smlalbb_4 = "e1400080NMSD", -- v5TE
smlaltb_4 = "e14000a0NMSD", -- v5TE
smlalbt_4 = "e14000c0NMSD", -- v5TE
smlaltt_4 = "e14000e0NMSD", -- v5TE
smulbb_3 = "e1600080NMS", -- v5TE
smultb_3 = "e16000a0NMS", -- v5TE
smulbt_3 = "e16000c0NMS", -- v5TE
smultt_3 = "e16000e0NMS", -- v5TE
-- Miscellaneous data processing instructions.
clz_2 = "e16f0f10DM", -- v5T
rev_2 = "e6bf0f30DM", -- v6
rev16_2 = "e6bf0fb0DM", -- v6
revsh_2 = "e6ff0fb0DM", -- v6
sel_3 = "e6800fb0DNM", -- v6
usad8_3 = "e780f010NMS", -- v6
usada8_4 = "e7800010NMSD", -- v6
rbit_2 = "e6ff0f30DM", -- v6T2
movw_2 = "e3000000DW", -- v6T2
movt_2 = "e3400000DW", -- v6T2
-- Note: the X encodes width-1, not width.
sbfx_4 = "e7a00050DMvX", -- v6T2
ubfx_4 = "e7e00050DMvX", -- v6T2
-- Note: the X encodes the msb field, not the width.
bfc_3 = "e7c0001fDvX", -- v6T2
bfi_4 = "e7c00010DMvX", -- v6T2
-- Packing and unpacking instructions.
pkhbt_3 = "e6800010DNM", pkhbt_4 = "e6800010DNMv", -- v6
pkhtb_3 = "e6800050DNM", pkhtb_4 = "e6800050DNMv", -- v6
sxtab_3 = "e6a00070DNM", sxtab_4 = "e6a00070DNMv", -- v6
sxtab16_3 = "e6800070DNM", sxtab16_4 = "e6800070DNMv", -- v6
sxtah_3 = "e6b00070DNM", sxtah_4 = "e6b00070DNMv", -- v6
sxtb_2 = "e6af0070DM", sxtb_3 = "e6af0070DMv", -- v6
sxtb16_2 = "e68f0070DM", sxtb16_3 = "e68f0070DMv", -- v6
sxth_2 = "e6bf0070DM", sxth_3 = "e6bf0070DMv", -- v6
uxtab_3 = "e6e00070DNM", uxtab_4 = "e6e00070DNMv", -- v6
uxtab16_3 = "e6c00070DNM", uxtab16_4 = "e6c00070DNMv", -- v6
uxtah_3 = "e6f00070DNM", uxtah_4 = "e6f00070DNMv", -- v6
uxtb_2 = "e6ef0070DM", uxtb_3 = "e6ef0070DMv", -- v6
uxtb16_2 = "e6cf0070DM", uxtb16_3 = "e6cf0070DMv", -- v6
uxth_2 = "e6ff0070DM", uxth_3 = "e6ff0070DMv", -- v6
-- Saturating instructions.
qadd_3 = "e1000050DMN", -- v5TE
qsub_3 = "e1200050DMN", -- v5TE
qdadd_3 = "e1400050DMN", -- v5TE
qdsub_3 = "e1600050DMN", -- v5TE
-- Note: the X for ssat* encodes sat_imm-1, not sat_imm.
ssat_3 = "e6a00010DXM", ssat_4 = "e6a00010DXMp", -- v6
usat_3 = "e6e00010DXM", usat_4 = "e6e00010DXMp", -- v6
ssat16_3 = "e6a00f30DXM", -- v6
usat16_3 = "e6e00f30DXM", -- v6
-- Parallel addition and subtraction.
sadd16_3 = "e6100f10DNM", -- v6
sasx_3 = "e6100f30DNM", -- v6
ssax_3 = "e6100f50DNM", -- v6
ssub16_3 = "e6100f70DNM", -- v6
sadd8_3 = "e6100f90DNM", -- v6
ssub8_3 = "e6100ff0DNM", -- v6
qadd16_3 = "e6200f10DNM", -- v6
qasx_3 = "e6200f30DNM", -- v6
qsax_3 = "e6200f50DNM", -- v6
qsub16_3 = "e6200f70DNM", -- v6
qadd8_3 = "e6200f90DNM", -- v6
qsub8_3 = "e6200ff0DNM", -- v6
shadd16_3 = "e6300f10DNM", -- v6
shasx_3 = "e6300f30DNM", -- v6
shsax_3 = "e6300f50DNM", -- v6
shsub16_3 = "e6300f70DNM", -- v6
shadd8_3 = "e6300f90DNM", -- v6
shsub8_3 = "e6300ff0DNM", -- v6
uadd16_3 = "e6500f10DNM", -- v6
uasx_3 = "e6500f30DNM", -- v6
usax_3 = "e6500f50DNM", -- v6
usub16_3 = "e6500f70DNM", -- v6
uadd8_3 = "e6500f90DNM", -- v6
usub8_3 = "e6500ff0DNM", -- v6
uqadd16_3 = "e6600f10DNM", -- v6
uqasx_3 = "e6600f30DNM", -- v6
uqsax_3 = "e6600f50DNM", -- v6
uqsub16_3 = "e6600f70DNM", -- v6
uqadd8_3 = "e6600f90DNM", -- v6
uqsub8_3 = "e6600ff0DNM", -- v6
uhadd16_3 = "e6700f10DNM", -- v6
uhasx_3 = "e6700f30DNM", -- v6
uhsax_3 = "e6700f50DNM", -- v6
uhsub16_3 = "e6700f70DNM", -- v6
uhadd8_3 = "e6700f90DNM", -- v6
uhsub8_3 = "e6700ff0DNM", -- v6
-- Load/store instructions.
str_2 = "e4000000DL", str_3 = "e4000000DL", str_4 = "e4000000DL",
strb_2 = "e4400000DL", strb_3 = "e4400000DL", strb_4 = "e4400000DL",
ldr_2 = "e4100000DL", ldr_3 = "e4100000DL", ldr_4 = "e4100000DL",
ldrb_2 = "e4500000DL", ldrb_3 = "e4500000DL", ldrb_4 = "e4500000DL",
strh_2 = "e00000b0DL", strh_3 = "e00000b0DL",
ldrh_2 = "e01000b0DL", ldrh_3 = "e01000b0DL",
ldrd_2 = "e00000d0DL", ldrd_3 = "e00000d0DL", -- v5TE
ldrsb_2 = "e01000d0DL", ldrsb_3 = "e01000d0DL",
strd_2 = "e00000f0DL", strd_3 = "e00000f0DL", -- v5TE
ldrsh_2 = "e01000f0DL", ldrsh_3 = "e01000f0DL",
ldm_2 = "e8900000oR", ldmia_2 = "e8900000oR", ldmfd_2 = "e8900000oR",
ldmda_2 = "e8100000oR", ldmfa_2 = "e8100000oR",
ldmdb_2 = "e9100000oR", ldmea_2 = "e9100000oR",
ldmib_2 = "e9900000oR", ldmed_2 = "e9900000oR",
stm_2 = "e8800000oR", stmia_2 = "e8800000oR", stmfd_2 = "e8800000oR",
stmda_2 = "e8000000oR", stmfa_2 = "e8000000oR",
stmdb_2 = "e9000000oR", stmea_2 = "e9000000oR",
stmib_2 = "e9800000oR", stmed_2 = "e9800000oR",
pop_1 = "e8bd0000R", push_1 = "e92d0000R",
-- Branch instructions.
b_1 = "ea000000B",
bl_1 = "eb000000B",
blx_1 = "e12fff30C",
bx_1 = "e12fff10M",
-- Miscellaneous instructions.
nop_0 = "e1a00000",
mrs_1 = "e10f0000D",
bkpt_1 = "e1200070K", -- v5T
svc_1 = "ef000000T", swi_1 = "ef000000T",
ud_0 = "e7f001f0",
-- VFP instructions.
["vadd.f32_3"] = "ee300a00dnm",
["vadd.f64_3"] = "ee300b00Gdnm",
["vsub.f32_3"] = "ee300a40dnm",
["vsub.f64_3"] = "ee300b40Gdnm",
["vmul.f32_3"] = "ee200a00dnm",
["vmul.f64_3"] = "ee200b00Gdnm",
["vnmul.f32_3"] = "ee200a40dnm",
["vnmul.f64_3"] = "ee200b40Gdnm",
["vmla.f32_3"] = "ee000a00dnm",
["vmla.f64_3"] = "ee000b00Gdnm",
["vmls.f32_3"] = "ee000a40dnm",
["vmls.f64_3"] = "ee000b40Gdnm",
["vnmla.f32_3"] = "ee100a40dnm",
["vnmla.f64_3"] = "ee100b40Gdnm",
["vnmls.f32_3"] = "ee100a00dnm",
["vnmls.f64_3"] = "ee100b00Gdnm",
["vdiv.f32_3"] = "ee800a00dnm",
["vdiv.f64_3"] = "ee800b00Gdnm",
["vabs.f32_2"] = "eeb00ac0dm",
["vabs.f64_2"] = "eeb00bc0Gdm",
["vneg.f32_2"] = "eeb10a40dm",
["vneg.f64_2"] = "eeb10b40Gdm",
["vsqrt.f32_2"] = "eeb10ac0dm",
["vsqrt.f64_2"] = "eeb10bc0Gdm",
["vcmp.f32_2"] = "eeb40a40dm",
["vcmp.f64_2"] = "eeb40b40Gdm",
["vcmpe.f32_2"] = "eeb40ac0dm",
["vcmpe.f64_2"] = "eeb40bc0Gdm",
["vcmpz.f32_1"] = "eeb50a40d",
["vcmpz.f64_1"] = "eeb50b40Gd",
["vcmpze.f32_1"] = "eeb50ac0d",
["vcmpze.f64_1"] = "eeb50bc0Gd",
vldr_2 = "ed100a00dl|ed100b00Gdl",
vstr_2 = "ed000a00dl|ed000b00Gdl",
vldm_2 = "ec900a00or",
vldmia_2 = "ec900a00or",
vldmdb_2 = "ed100a00or",
vpop_1 = "ecbd0a00r",
vstm_2 = "ec800a00or",
vstmia_2 = "ec800a00or",
vstmdb_2 = "ed000a00or",
vpush_1 = "ed2d0a00r",
["vmov.f32_2"] = "eeb00a40dm|eeb00a00dY", -- #imm is VFPv3 only
["vmov.f64_2"] = "eeb00b40Gdm|eeb00b00GdY", -- #imm is VFPv3 only
vmov_2 = "ee100a10Dn|ee000a10nD",
vmov_3 = "ec500a10DNm|ec400a10mDN|ec500b10GDNm|ec400b10GmDN",
vmrs_0 = "eef1fa10",
vmrs_1 = "eef10a10D",
vmsr_1 = "eee10a10D",
["vcvt.s32.f32_2"] = "eebd0ac0dm",
["vcvt.s32.f64_2"] = "eebd0bc0dGm",
["vcvt.u32.f32_2"] = "eebc0ac0dm",
["vcvt.u32.f64_2"] = "eebc0bc0dGm",
["vcvtr.s32.f32_2"] = "eebd0a40dm",
["vcvtr.s32.f64_2"] = "eebd0b40dGm",
["vcvtr.u32.f32_2"] = "eebc0a40dm",
["vcvtr.u32.f64_2"] = "eebc0b40dGm",
["vcvt.f32.s32_2"] = "eeb80ac0dm",
["vcvt.f64.s32_2"] = "eeb80bc0GdFm",
["vcvt.f32.u32_2"] = "eeb80a40dm",
["vcvt.f64.u32_2"] = "eeb80b40GdFm",
["vcvt.f32.f64_2"] = "eeb70bc0dGm",
["vcvt.f64.f32_2"] = "eeb70ac0GdFm",
-- VFPv4 only:
["vfma.f32_3"] = "eea00a00dnm",
["vfma.f64_3"] = "eea00b00Gdnm",
["vfms.f32_3"] = "eea00a40dnm",
["vfms.f64_3"] = "eea00b40Gdnm",
["vfnma.f32_3"] = "ee900a40dnm",
["vfnma.f64_3"] = "ee900b40Gdnm",
["vfnms.f32_3"] = "ee900a00dnm",
["vfnms.f64_3"] = "ee900b00Gdnm",
-- NYI: Advanced SIMD instructions.
-- NYI: I have no need for these instructions right now:
-- swp, swpb, strex, ldrex, strexd, ldrexd, strexb, ldrexb, strexh, ldrexh
-- msr, nopv6, yield, wfe, wfi, sev, dbg, bxj, smc, srs, rfe
-- cps, setend, pli, pld, pldw, clrex, dsb, dmb, isb
-- stc, ldc, mcr, mcr2, mrc, mrc2, mcrr, mcrr2, mrrc, mrrc2, cdp, cdp2
}
-- Add mnemonics for "s" variants.
do
local t = {}
for k,v in pairs(map_op) do
if sub(v, -1) == "s" then
local v2 = sub(v, 1, 2)..char(byte(v, 3)+1)..sub(v, 4, -2)
t[sub(k, 1, -3).."s"..sub(k, -2)] = v2
end
end
for k,v in pairs(t) do
map_op[k] = v
end
end
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(r1?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^r(1?[0-9])$")
if r then
r = tonumber(r)
if r <= 15 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_gpr_pm(expr)
local pm, expr2 = match(expr, "^([+-]?)(.*)$")
return parse_gpr(expr2), (pm == "-")
end
local function parse_vr(expr, tp)
local t, r = match(expr, "^([sd])([0-9]+)$")
if t == tp then
r = tonumber(r)
if r <= 31 then
if t == "s" then return shr(r, 1), band(r, 1) end
return band(r, 15), shr(r, 4)
end
end
werror("bad register name `"..expr.."'")
end
local function parse_reglist(reglist)
reglist = match(reglist, "^{%s*([^}]*)}$")
if not reglist then werror("register list expected") end
local rr = 0
for p in gmatch(reglist..",", "%s*([^,]*),") do
local rbit = shl(1, parse_gpr(gsub(p, "%s+$", "")))
if band(rr, rbit) ~= 0 then
werror("duplicate register `"..p.."'")
end
rr = rr + rbit
end
return rr
end
local function parse_vrlist(reglist)
local ta, ra, tb, rb = match(reglist,
"^{%s*([sd])([0-9]+)%s*%-%s*([sd])([0-9]+)%s*}$")
ra, rb = tonumber(ra), tonumber(rb)
if ta and ta == tb and ra and rb and ra <= 31 and rb <= 31 and ra <= rb then
local nr = rb+1 - ra
if ta == "s" then
return shl(shr(ra,1),12)+shl(band(ra,1),22) + nr
else
return shl(band(ra,15),12)+shl(shr(ra,4),22) + nr*2 + 0x100
end
end
werror("register list expected")
end
local function parse_imm(imm, bits, shift, scale, signed)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = tonumber(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_imm12(imm)
local n = tonumber(imm)
if n then
local m = band(n)
for i=0,-15,-1 do
if shr(m, 8) == 0 then return m + shl(band(i, 15), 8) end
m = ror(m, 2)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMM12", 0, imm)
return 0
end
end
local function parse_imm16(imm)
imm = match(imm, "^#(.*)$")
if not imm then werror("expected immediate operand") end
local n = tonumber(imm)
if n then
if shr(n, 16) == 0 then return band(n, 0x0fff) + shl(band(n, 0xf000), 4) end
werror("out of range immediate `"..imm.."'")
else
waction("IMM16", 32*16, imm)
return 0
end
end
local function parse_imm_load(imm, ext)
local n = tonumber(imm)
if n then
if ext then
if n >= -255 and n <= 255 then
local up = 0x00800000
if n < 0 then n = -n; up = 0 end
return shl(band(n, 0xf0), 4) + band(n, 0x0f) + up
end
else
if n >= -4095 and n <= 4095 then
if n >= 0 then return n+0x00800000 end
return -n
end
end
werror("out of range immediate `"..imm.."'")
else
waction(ext and "IMML8" or "IMML12", 32768 + shl(ext and 8 or 12, 5), imm)
return 0
end
end
local function parse_shift(shift, gprok)
if shift == "rrx" then
return 3 * 32
else
local s, s2 = match(shift, "^(%S+)%s*(.*)$")
s = map_shift[s]
if not s then werror("expected shift operand") end
if sub(s2, 1, 1) == "#" then
return parse_imm(s2, 5, 7, 0, false) + shl(s, 5)
else
if not gprok then werror("expected immediate shift operand") end
return shl(parse_gpr(s2), 8) + shl(s, 5) + 16
end
end
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
local function parse_load(params, nparams, n, op)
local oplo = band(op, 255)
local ext, ldrd = (oplo ~= 0), (oplo == 208)
local d
if (ldrd or oplo == 240) then
d = band(shr(op, 12), 15)
if band(d, 1) ~= 0 then werror("odd destination register") end
end
local pn = params[n]
local p1, wb = match(pn, "^%[%s*(.-)%s*%](!?)$")
local p2 = params[n+1]
if not p1 then
if not p2 then
if match(pn, "^[<>=%-]") or match(pn, "^extern%s+") then
local mode, n, s = parse_label(pn, false)
waction("REL_"..mode, n + (ext and 0x1800 or 0x0800), s, 1)
return op + 15 * 65536 + 0x01000000 + (ext and 0x00400000 or 0)
end
local reg, tailr = match(pn, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local d, tp = parse_gpr(reg)
if tp then
waction(ext and "IMML8" or "IMML12", 32768 + 32*(ext and 8 or 12),
format(tp.ctypefmt, tailr))
return op + shl(d, 16) + 0x01000000 + (ext and 0x00400000 or 0)
end
end
end
werror("expected address operand")
end
if wb == "!" then op = op + 0x00200000 end
if p2 then
if wb == "!" then werror("bad use of '!'") end
local p3 = params[n+2]
op = op + shl(parse_gpr(p1), 16)
local imm = match(p2, "^#(.*)$")
if imm then
local m = parse_imm_load(imm, ext)
if p3 then werror("too many parameters") end
op = op + m + (ext and 0x00400000 or 0)
else
local m, neg = parse_gpr_pm(p2)
if ldrd and (m == d or m-1 == d) then werror("register conflict") end
op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000)
if p3 then op = op + parse_shift(p3) end
end
else
local p1a, p2 = match(p1, "^([^,%s]*)%s*(.*)$")
op = op + shl(parse_gpr(p1a), 16) + 0x01000000
if p2 ~= "" then
local imm = match(p2, "^,%s*#(.*)$")
if imm then
local m = parse_imm_load(imm, ext)
op = op + m + (ext and 0x00400000 or 0)
else
local p2a, p3 = match(p2, "^,%s*([^,%s]*)%s*,?%s*(.*)$")
local m, neg = parse_gpr_pm(p2a)
if ldrd and (m == d or m-1 == d) then werror("register conflict") end
op = op + m + (neg and 0 or 0x00800000) + (ext and 0 or 0x02000000)
if p3 ~= "" then
if ext then werror("too many parameters") end
op = op + parse_shift(p3)
end
end
else
if wb == "!" then werror("bad use of '!'") end
op = op + (ext and 0x00c00000 or 0x00800000)
end
end
return op
end
local function parse_vload(q)
local reg, imm = match(q, "^%[%s*([^,%s]*)%s*(.*)%]$")
if reg then
local d = shl(parse_gpr(reg), 16)
if imm == "" then return d end
imm = match(imm, "^,%s*#(.*)$")
if imm then
local n = tonumber(imm)
if n then
if n >= -1020 and n <= 1020 and n%4 == 0 then
return d + (n >= 0 and n/4+0x00800000 or -n/4)
end
werror("out of range immediate `"..imm.."'")
else
waction("IMMV8", 32768 + 32*8, imm)
return d
end
end
else
if match(q, "^[<>=%-]") or match(q, "^extern%s+") then
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n + 0x2800, s, 1)
return 15 * 65536
end
local reg, tailr = match(q, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local d, tp = parse_gpr(reg)
if tp then
waction("IMMV8", 32768 + 32*8, format(tp.ctypefmt, tailr))
return shl(d, 16)
end
end
end
werror("expected address operand")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
local function parse_template(params, template, nparams, pos)
local op = tonumber(sub(template, 1, 8), 16)
local n = 1
local vr = "s"
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
local q = params[n]
if p == "D" then
op = op + shl(parse_gpr(q), 12); n = n + 1
elseif p == "N" then
op = op + shl(parse_gpr(q), 16); n = n + 1
elseif p == "S" then
op = op + shl(parse_gpr(q), 8); n = n + 1
elseif p == "M" then
op = op + parse_gpr(q); n = n + 1
elseif p == "d" then
local r,h = parse_vr(q, vr); op = op+shl(r,12)+shl(h,22); n = n + 1
elseif p == "n" then
local r,h = parse_vr(q, vr); op = op+shl(r,16)+shl(h,7); n = n + 1
elseif p == "m" then
local r,h = parse_vr(q, vr); op = op+r+shl(h,5); n = n + 1
elseif p == "P" then
local imm = match(q, "^#(.*)$")
if imm then
op = op + parse_imm12(imm) + 0x02000000
else
op = op + parse_gpr(q)
end
n = n + 1
elseif p == "p" then
op = op + parse_shift(q, true); n = n + 1
elseif p == "L" then
op = parse_load(params, nparams, n, op)
elseif p == "l" then
op = op + parse_vload(q)
elseif p == "B" then
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n, s, 1)
elseif p == "C" then -- blx gpr vs. blx label.
if match(q, "^([%w_]+):(r1?[0-9])$") or match(q, "^r(1?[0-9])$") then
op = op + parse_gpr(q)
else
if op < 0xe0000000 then werror("unconditional instruction") end
local mode, n, s = parse_label(q, false)
waction("REL_"..mode, n, s, 1)
op = 0xfa000000
end
elseif p == "F" then
vr = "s"
elseif p == "G" then
vr = "d"
elseif p == "o" then
local r, wb = match(q, "^([^!]*)(!?)$")
op = op + shl(parse_gpr(r), 16) + (wb == "!" and 0x00200000 or 0)
n = n + 1
elseif p == "R" then
op = op + parse_reglist(q); n = n + 1
elseif p == "r" then
op = op + parse_vrlist(q); n = n + 1
elseif p == "W" then
op = op + parse_imm16(q); n = n + 1
elseif p == "v" then
op = op + parse_imm(q, 5, 7, 0, false); n = n + 1
elseif p == "w" then
local imm = match(q, "^#(.*)$")
if imm then
op = op + parse_imm(q, 5, 7, 0, false); n = n + 1
else
op = op + shl(parse_gpr(q), 8) + 16
end
elseif p == "X" then
op = op + parse_imm(q, 5, 16, 0, false); n = n + 1
elseif p == "Y" then
local imm = tonumber(match(q, "^#(.*)$")); n = n + 1
if not imm or shr(imm, 8) ~= 0 then
werror("bad immediate operand")
end
op = op + shl(band(imm, 0xf0), 12) + band(imm, 0x0f)
elseif p == "K" then
local imm = tonumber(match(q, "^#(.*)$")); n = n + 1
if not imm or shr(imm, 16) ~= 0 then
werror("bad immediate operand")
end
op = op + shl(band(imm, 0xfff0), 4) + band(imm, 0x000f)
elseif p == "T" then
op = op + parse_imm(q, 24, 0, 0, false); n = n + 1
elseif p == "s" then
-- Ignored.
else
assert(false)
end
end
wputpos(pos, op)
end
map_op[".template__"] = function(params, template, nparams)
if not params then return sub(template, 9) end
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions.
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
local apos, spos = #actargs, secpos
local ok, err
for t in gmatch(template, "[^|]+") do
ok, err = pcall(parse_template, params, t, nparams, pos)
if ok then return end
secpos = spos
actargs[apos+1] = nil
actargs[apos+2] = nil
actargs[apos+3] = nil
end
error(err, 0)
end
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = function(t, k)
local v = map_coreop[k]
if v then return v end
local k1, cc, k2 = match(k, "^(.-)(..)([._].*)$")
local cv = map_cond[cc]
if cv then
local v = rawget(t, k1..k2)
if type(v) == "string" then
local scv = format("%x", cv)
return gsub(scv..sub(v, 2), "|e", "|"..scv)
end
end
end })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| bsd-3-clause |
NezzKryptic/Wire-Extras | lua/weapons/gmod_tool/stools/wire_touchplate.lua | 4 | 3489 | TOOL.Category = "Wire Extras/Detection"
TOOL.Name = "Touchplate"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
TOOL.ClientConVar["model"] = "models/props_phx/construct/metal_plate1.mdl"
TOOL.ClientConVar["only_players"] = "1"
if CLIENT then
language.Add("Tool.wire_touchplate.name", "Wired Touchplate")
language.Add("Tool.wire_touchplate.desc", "Spawns a touchplate for use with the wire system.")
language.Add("Tool.wire_touchplate.0", "Primary: Create touchplate. Secondary: Copy model.")
language.Add("undone_WireTouchplate", "Undone Wire Touchplate")
language.Add("Cleanup_wire_touchplates", "Wired Touchplates")
language.Add("Cleaned_wire_touchplates", "Cleaned up all Wire Touchplates")
language.Add("SBoxLimit_wire_touchplates", "You've reached the touchplates limit!")
else
CreateConVar("sbox_maxwire_touchplates", 30)
end
function TOOL:LeftClick(trace)
local ent = trace.Entity
if ent and ent:IsPlayer() then return false end
if SERVER and !util.IsValidPhysicsObject(ent, trace.PhysicsBone) then return false end
if CLIENT then return true end
local ply = self:GetOwner()
if not self:GetSWEP():CheckLimit("wire_touchplates") then return false end
local targetPhys = ent:GetPhysicsObjectNum(trace.PhysicsBone)
local model = self:GetClientInfo("model")
local only_players = self:GetClientNumber("only_players") ~= 0
if not util.IsValidModel(model) then return false end
if not util.IsValidProp(model) then return false end
local ang = trace.HitNormal:Angle()
ang.pitch = ang.pitch + 90
local tp_ent = MakeWireTouchplate(ply, trace.HitPos, ang, model, only_players)
local obb_min = tp_ent:OBBMins()
tp_ent:SetPos(trace.HitPos - trace.HitNormal * obb_min.z)
tp_ent:GetPhysicsObject():Wake()
undo.Create("WireTouchplate")
undo.AddEntity(tp_ent)
undo.SetPlayer(ply)
undo.Finish()
ply:AddCleanup("wire_touchplates", tp_ent)
return true
end
function TOOL:UpdateGhost(ent, player)
if not ent or not IsValid(ent) then return end
local trace = player:GetEyeTrace()
if not trace or not trace.Hit then return end
if trace.Entity and trace.Entity:IsPlayer() then
ent:SetNoDraw(true)
return
else
ent:SetNoDraw(false)
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)
end
function TOOL:Think()
local m = self:GetClientInfo("model")
if not IsValid(self.GhostEntity) or self.GhostEntity:GetModel() != m then
self:MakeGhostEntity(m, Vector(0,0,0), Angle(0,0,0))
end
self:UpdateGhost(self.GhostEntity, self:GetOwner())
end
function TOOL:RightClick(trace)
local tr_ent = trace.Entity
if not tr_ent or not tr_ent:IsValid() then return false end
local model = tr_ent:GetModel()
if game.SinglePlayer() and SERVER then
self:GetOwner():ConCommand( "wire_touchplate_model " .. model ) -- this will run serverside if SP
self:GetOwner():ChatPrint( "Touchplate model changed to '" .. model .. "'" )
elseif CLIENT then -- else we can just as well run it client side instead
RunConsoleCommand("wire_touchplate_model", model)
self:GetOwner():ChatPrint( "Touchplate model changed to '" .. model .. "'" )
end
return true
end
cleanup.Register("wire_touchplates")
function TOOL.BuildCPanel(panel)
panel:CheckBox("Only trigger for players", "wire_touchplate_only_players")
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.