repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
yinlei/tgame | game/player/init.lua | 1 | 1255 | -------------------------------------------------------------------------------
-- player
-------------------------------------------------------------------------------
local _PACKAGE = string.gsub(...,"%.","/") or ""
local pcall, assert, table_copy = pcall, assert, table.copy
local tlen = table.lenght
local actor = tengine.actor
local _M = require(_PACKAGE.."/player")
require(_PACKAGE.."/agent")
local players = {}
local function create(...)
local _player = _M:new(...)
if not _player then
return
end
players[_player:id()] = _player
return _player
end
local function destory(id)
players[id] = nil
end
local function find(id)
return players[id]
end
local function count()
return tlen(players)
end
local _call_meta = {}
_call_meta.__index = function(t, key)
local context = t
local f = key
return function(...)
local succ, ret =
actor.call(context[1], "call", f, context[2], ...)
return succ, ret
end
end
_call_meta.__newindex = function(t, key, value)
end
local function proxy(service)
local _service = table_copy(service)
return setmetatable(_service, _call_meta)
end
return {
create = create,
destory = destory,
find = find,
proxy = proxy,
} | mit |
mwoz123/koreader | plugins/calibre.koplugin/main.lua | 1 | 12753 | --[[
This plugin implements KOReader integration with *some* calibre features:
- metadata search
- wireless transfers
This module handles the UI part of the plugin.
--]]
local BD = require("ui/bidi")
local CalibreSearch = require("search")
local CalibreWireless = require("wireless")
local Dispatcher = require("dispatcher")
local InfoMessage = require("ui/widget/infomessage")
local LuaSettings = require("luasettings")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local _ = require("gettext")
local T = require("ffi/util").template
local Calibre = WidgetContainer:new{
name = "calibre",
is_doc_only = false,
}
function Calibre:onCalibreSearch()
CalibreSearch:ShowSearch()
return true
end
function Calibre:onCalibreBrowseTags()
CalibreSearch.search_value = ""
CalibreSearch:find("tags", 1)
return true
end
function Calibre:onCalibreBrowseSeries()
CalibreSearch.search_value = ""
CalibreSearch:find("series", 1)
return true
end
function Calibre:onNetworkDisconnected()
self:closeWirelessConnection()
end
function Calibre:onSuspend()
self:closeWirelessConnection()
end
function Calibre:onClose()
self:closeWirelessConnection()
end
function Calibre:closeWirelessConnection()
if CalibreWireless.calibre_socket then
CalibreWireless:disconnect()
end
end
function Calibre:onDispatcherRegisterActions()
Dispatcher:registerAction("calibre_search", { category="none", event="CalibreSearch", title=_("Calibre metadata search"), device=true,})
Dispatcher:registerAction("calibre_browse_tags", { category="none", event="CalibreBrowseTags", title=_("Browse all calibre tags"), device=true,})
Dispatcher:registerAction("calibre_browse_series", { category="none", event="CalibreBrowseSeries", title=_("Browse all calibre series"), device=true, separator=true,})
end
function Calibre:init()
CalibreWireless:init()
self:onDispatcherRegisterActions()
self.ui.menu:registerToMainMenu(self)
end
function Calibre:addToMainMenu(menu_items)
menu_items.calibre = {
-- its name is "calibre", but all our top menu items are uppercase.
text = _("Calibre"),
sub_item_table = {
{
text_func = function()
if CalibreWireless.calibre_socket then
return _("Disconnect")
else
return _("Connect")
end
end,
separator = true,
enabled_func = function()
return G_reader_settings:nilOrTrue("calibre_wireless")
end,
callback = function()
if not CalibreWireless.calibre_socket then
CalibreWireless:connect()
else
CalibreWireless:disconnect()
end
end,
},
{ text = _("Search settings"),
keep_menu_open = true,
sub_item_table = self:getSearchMenuTable(),
},
{
text = _("Wireless settings"),
keep_menu_open = true,
sub_item_table = self:getWirelessMenuTable(),
},
}
}
-- insert the metadata search
if G_reader_settings:isTrue("calibre_search_from_reader") or not self.ui.view then
menu_items.find_book_in_calibre_catalog = {
text = _("Calibre metadata search"),
callback = function()
CalibreSearch:ShowSearch()
end
}
end
end
-- search options available from UI
function Calibre:getSearchMenuTable()
return {
{
text = _("Manage libraries"),
separator = true,
keep_menu_open = true,
sub_item_table_func = function()
local result = {}
-- append previous scanned dirs to the list.
local cache = LuaSettings:open(CalibreSearch.cache_libs.path)
for path, _ in pairs(cache.data) do
table.insert(result, {
text = path,
keep_menu_open = true,
checked_func = function()
return cache:isTrue(path)
end,
callback = function()
cache:toggle(path)
cache:flush()
CalibreSearch:invalidateCache()
end,
})
end
-- if there's no result then no libraries are stored
if #result == 0 then
table.insert(result, {
text = _("No calibre libraries"),
enabled = false
})
end
table.insert(result, 1, {
text = _("Rescan disk for calibre libraries"),
separator = true,
callback = function()
CalibreSearch:prompt()
end,
})
return result
end,
},
{
text = _("Enable searches in the reader"),
checked_func = function()
return G_reader_settings:isTrue("calibre_search_from_reader")
end,
callback = function()
G_reader_settings:toggle("calibre_search_from_reader")
UIManager:show(InfoMessage:new{
text = _("This will take effect on next restart."),
})
end,
},
{
text = _("Store metadata in cache"),
checked_func = function()
return G_reader_settings:nilOrTrue("calibre_search_cache_metadata")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_search_cache_metadata")
end,
},
{
text = _("Case sensitive search"),
checked_func = function()
return not G_reader_settings:nilOrTrue("calibre_search_case_insensitive")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_search_case_insensitive")
end,
},
{
text = _("Search by title"),
checked_func = function()
return G_reader_settings:nilOrTrue("calibre_search_find_by_title")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_search_find_by_title")
end,
},
{
text = _("Search by authors"),
checked_func = function()
return G_reader_settings:nilOrTrue("calibre_search_find_by_authors")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_search_find_by_authors")
end,
},
{
text = _("Search by path"),
checked_func = function()
return G_reader_settings:nilOrTrue("calibre_search_find_by_path")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_search_find_by_path")
end,
},
}
end
-- wireless options available from UI
function Calibre:getWirelessMenuTable()
local function isEnabled()
local enabled = G_reader_settings:nilOrTrue("calibre_wireless")
return enabled and not CalibreWireless.calibre_socket
end
return {
{
text = _("Enable wireless client"),
separator = true,
enabled_func = function()
return not CalibreWireless.calibre_socket
end,
checked_func = function()
return G_reader_settings:nilOrTrue("calibre_wireless")
end,
callback = function()
G_reader_settings:flipNilOrTrue("calibre_wireless")
end,
},
{
text = _("Set password"),
enabled_func = isEnabled,
callback = function()
CalibreWireless:setPassword()
end,
},
{
text = _("Set inbox folder"),
enabled_func = isEnabled,
callback = function()
CalibreWireless:setInboxDir()
end,
},
{
text_func = function()
local address = _("automatic")
if G_reader_settings:has("calibre_wireless_url") then
address = G_reader_settings:readSetting("calibre_wireless_url")
address = string.format("%s:%s", address["address"], address["port"])
end
return T(_("Server address (%1)"), BD.ltr(address))
end,
enabled_func = isEnabled,
sub_item_table = {
{
text = _("Automatic"),
checked_func = function()
return G_reader_settings:hasNot("calibre_wireless_url")
end,
callback = function()
G_reader_settings:delSetting("calibre_wireless_url")
end,
},
{
text = _("Manual"),
checked_func = function()
return G_reader_settings:has("calibre_wireless_url")
end,
callback = function(touchmenu_instance)
local MultiInputDialog = require("ui/widget/multiinputdialog")
local url_dialog
local calibre_url = G_reader_settings:readSetting("calibre_wireless_url")
local calibre_url_address, calibre_url_port
if calibre_url then
calibre_url_address = calibre_url["address"]
calibre_url_port = calibre_url["port"]
end
url_dialog = MultiInputDialog:new{
title = _("Set custom calibre address"),
fields = {
{
text = calibre_url_address,
input_type = "string",
hint = _("IP Address"),
},
{
text = calibre_url_port,
input_type = "number",
hint = _("Port"),
},
},
buttons = {
{
{
text = _("Cancel"),
callback = function()
UIManager:close(url_dialog)
end,
},
{
text = _("OK"),
callback = function()
local fields = url_dialog:getFields()
if fields[1] ~= "" then
local port = tonumber(fields[2])
if not port or port < 1 or port > 65355 then
--default port
port = 9090
end
G_reader_settings:saveSetting("calibre_wireless_url", {address = fields[1], port = port })
end
UIManager:close(url_dialog)
if touchmenu_instance then touchmenu_instance:updateItems() end
end,
},
},
},
}
UIManager:show(url_dialog)
url_dialog:onShowKeyboard()
end,
},
},
},
}
end
return Calibre
| agpl-3.0 |
fluxxu/luape | luape/scripts/libs/asm.lua | 1 | 1090 | local asm_line_meta = {
__index = {
number = function (self, i)
local pattern = "%x+h"
local n = i or 1
local p_begin = 1, p_end
for i = 0, n, 1 do
p_begin, p_end = self.code_:find(pattern, p)
if p_begin ~= nil then
if i == n - 1 then
local hex = self.code_:sub(p_begin, p_end - 1)
return tonumber(hex, 16)
end
end
end
return nil
end,
offset = function (self, i)
return self:number(i) - self.base_
end
},
__tostring = function (self)
return self.code_
end
}
local function newASM(addr, base, n)
n = n or 20
local asm = luape.diasm(addr, n)
if #asm then
asm.base = base
setmetatable(asm, {
__index = {
dump = function (self)
for k, v in ipairs(self) do
print(k, v)
end
end,
line = function (self, n)
local obj = {
code_ = self[n],
base_ = base
}
setmetatable(obj, asm_line_meta)
return obj
end,
diasm = function (addr, n)
return newASM(addr, n)
end
}
})
return asm
else
return nil
end
end
return {
new = newASM
} | mit |
bnetcc/darkstar | scripts/zones/Western_Adoulin/npcs/Defliaa.lua | 5 | 1653 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Defliaa
-- Type: Quest NPC and Shop NPC
-- Involved with Quest: 'All the Way to the Bank'
-- !pos 43 2 -113 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Western_Adoulin/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/npc_util");
require("scripts/globals/shop");
function onTrade(player,npc,trade)
-- ALL THE WAY TO THE BANK
if (player:hasKeyItem(TARUTARU_SAUCE_INVOICE)) then
local ATWTTB_Paid_Defliaa = player:getMaskBit(player:getVar("ATWTTB_Payments"), 0);
if (not ATWTTB_Paid_Defliaa and npcUtil.tradeHas( trade, {{"gil",19440}} )) then
player:startEvent(5069);
end
end
end;
function onTrigger(player,npc)
player:showText(npc, DEFLIAA_SHOP_TEXT);
local stock =
{
5166, 3400, -- Coeurl Sub
4421, 1560, -- Melon Pie
5889, 19440, -- Stuffed Pitaru
5885, 18900, -- Saltena
4396, 280, -- Sausage Roll
4356, 200, -- White Bread
5686, 800, -- Cheese Sandwich
}
showShop(player, STATIC, stock);
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- ALL THE WAY TO THE BANK
if (csid == 5069) then
player:confirmTrade();
player:setMaskBit("ATWTTB_Payments", 0, true);
if (player:isMaskFull(player:getVar("ATWTTB_Payments"), 5)) then
npcUtil.giveKeyItem(player, TARUTARU_SAUCE_RECEIPT);
end
end
end;
| gpl-3.0 |
bnetcc/darkstar | scripts/globals/items/pear_crepe.lua | 3 | 1221 | -----------------------------------------
-- ID: 5777
-- Item: Pear Crepe
-- Food Effect: 30 Min, All Races
-----------------------------------------
-- Intelligence +2
-- MP Healing +2
-- Magic Accuracy +20% (cap 45)
-- Magic Defense +1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
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;
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5777);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 2);
target:addMod(MOD_FOOD_MACCP, 20);
target:addMod(MOD_FOOD_MACC_CAP, 45);
target:addMod(MOD_MDEF, 1);
target:addMod(MOD_MPHEAL, 2);
end;
function onEffectLose(target, effect)
target:delMod(MOD_INT, 2);
target:delMod(MOD_FOOD_MACCP, 20);
target:delMod(MOD_FOOD_MACC_CAP, 45);
target:delMod(MOD_MDEF, 1);
target:delMod(MOD_MPHEAL, 2);
end;
| gpl-3.0 |
Ravenlord/ddp-testing | tests/calculated_values/row-derived/02_vc_virtual-insert.lua | 1 | 2251 | --[[!
- This is free and unencumbered software released into the public domain.
-
- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form
- or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
-
- In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright
- interest in the software to the public domain. We make this dedication for the benefit of the public at large and to
- the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in
- perpetuity of all present and future rights to this software under copyright law.
-
- 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 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.
-
- For more information, please refer to <http://unlicense.org/>
--]]
--[[
- Benchmark file for design problem "Calculated Values", truly virtual column solution.
- Insert new product.
-
- @author Markus Deutschl <deutschl.markus@gmail.com>
- @copyright 2014 Markus Deutschl
- @license http://unlicense.org/ Unlicense
--]]
-- --------------------------------------------------------------------------------------------------------------------- Includes
pathtest = string.match(test, "(.*/)") or ""
-- Total reusal of preparations.
dofile(pathtest .. "02_vc_virtual-select.lua")
-- --------------------------------------------------------------------------------------------------------------------- Benchmark functions
--- Execute the benchmark queries.
-- Is called during the run command of sysbench.
function benchmark()
local query = [[
INSERT INTO `products` (`name`, `description`, `base_price`, `vat_rate`)
VALUES ('New Product', 'New Description', 10.0, 0.2)
]]
db_query('BEGIN')
db_query(query)
db_query('ROLLBACK')
end
| unlicense |
Etiene/Algorithm-Implementations | Pi_Algorithms/Lua/Yonaba/pi_test.lua | 26 | 1962 | -- Tests for golden_ratio.lua
local PI = require 'pi'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
local function fuzzyEqual(a, b, eps)
local eps = eps or 1e-4
return (math.abs(a - b) < eps)
end
run('Testing Statistical (Monte-Carlo pi)', function()
assert(fuzzyEqual(PI.statistical(100000, os.time()), math.pi,1e-2))
assert(fuzzyEqual(PI.statistical(100000, os.time()), math.pi,1e-2))
end)
run('Testing Madhava-Leibniz series', function()
assert(fuzzyEqual(PI.madhava_leibniz( 100), math.pi,1e-8))
assert(fuzzyEqual(PI.madhava_leibniz( 500), math.pi,1e-8))
assert(fuzzyEqual(PI.madhava_leibniz(1000), math.pi,1e-8))
end)
run('Testing Ramanujan series', function()
assert(fuzzyEqual(PI.ramanujan(20), math.pi,1e-8))
assert(fuzzyEqual(PI.ramanujan(30), math.pi,1e-8))
assert(fuzzyEqual(PI.ramanujan(40), math.pi,1e-8))
end)
run('Testing Chudnovsky series', function()
assert(fuzzyEqual(PI.chudnovsky(10), math.pi,1e-8))
assert(fuzzyEqual(PI.chudnovsky(20), math.pi,1e-8))
assert(fuzzyEqual(PI.chudnovsky(25), math.pi,1e-8))
end)
run('Testing Viete series', function()
assert(fuzzyEqual(PI.viete( 100), math.pi,1e-8))
assert(fuzzyEqual(PI.viete( 200), math.pi,1e-8))
assert(fuzzyEqual(PI.viete(10000), math.pi,1e-8))
end)
run('Testing Circle area sum method', function()
assert(fuzzyEqual(PI.circle_area( 100), math.pi,1e-2))
assert(fuzzyEqual(PI.circle_area( 1000), math.pi,1e-4))
assert(fuzzyEqual(PI.circle_area(10000), math.pi,1e-5))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
bnetcc/darkstar | scripts/globals/items/emerald_quiche.lua | 3 | 1128 | -----------------------------------------
-- ID: 5171
-- Item: emerald_quiche
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Magic 15
-- Agility 1
-- Ranged ACC % 7
-- Ranged ACC Cap 20
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
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;
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5171);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 15);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 20);
end;
function onEffectLose(target, effect)
target:delMod(MOD_MP, 15);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 20);
end;
| gpl-3.0 |
bnetcc/darkstar | scripts/zones/Ghelsba_Outpost/npcs/Hut_Door.lua | 5 | 2017 | -----------------------------------
-- Area: Ghelsba_Outpost
-- NPC: Hut Door
-- !pos -165.357 -11.672 77.771 140
-------------------------------------
package.loaded["scripts/zones/Ghelsba_Outpost/TextIDs"] = nil;
package.loaded["scripts/globals/bcnm"] = nil;
-------------------------------------
require("scripts/globals/bcnm");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/missions");
require("scripts/zones/Ghelsba_Outpost/TextIDs");
---- 0:
---- 1:
---- 2:
---- 3:
---- 4:
---- 5:
---- 6:
-----------------------------------
-- 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 (player:hasKeyItem(ORCISH_HUT_KEY)) then
if (player:hasCompletedMission(SANDORIA,SAVE_THE_CHILDREN)) then
player:startEvent(3);
else
player:startEvent(55);
end
else
if (EventTriggerBCNM(player,npc)) then
return;
end
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 (csid == 3 or csid == 55) then
player:delKeyItem(ORCISH_HUT_KEY);
player:setVar("MissionStatus",4);
else
if (EventFinishBCNM(player,csid,option)) then
return;
end
end
end; | gpl-3.0 |
bnetcc/darkstar | scripts/zones/Apollyon/mobs/Evil_Armory.lua | 5 | 1091 | -----------------------------------
-- Area: Apollyon SE
-- NPC: Evil_Armory
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
function onMobSpawn(mob)
end;
function onMobEngaged(mob,target)
GetMobByID(16933033):updateEnmity(target);
GetMobByID(16933034):updateEnmity(target);
GetMobByID(16933035):updateEnmity(target);
GetMobByID(16933036):updateEnmity(target);
GetMobByID(16933037):updateEnmity(target);
GetMobByID(16933038):updateEnmity(target);
GetMobByID(16933039):updateEnmity(target);
GetMobByID(16933040):updateEnmity(target);
end;
function onMobDeath(mob, player, isKiller)
end;
function onMobDespawn(mob)
local mobID = mob:getID();
-- print(mobID);
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
GetNPCByID(16932864+263):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+263):setStatus(STATUS_NORMAL);
end; | gpl-3.0 |
bnetcc/darkstar | scripts/globals/items/clear_drop.lua | 1 | 2074 | -----------------------------------------
-- ID: 4259
-- Item: Clear Drop
-- Intelligence 5
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/msg");
function onItemCheck(target)
--[[
if (target:hasStatusEffect(EFFECT_MEDICINE)) then
return msgBasic.ITEM_NO_USE_MEDICATED;
end
]]
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
return 246;
end
return 0;
end;
function onItemUse(target)
--[[
target:addStatusEffect(EFFECT_INT_BOOST,5,0,600);
target:addStatusEffect(EFFECT_MEDICINE,0,0,3600);
]]
target:addStatusEffect(EFFECT_FOOD,0,0,2700,4259);
end;
----------------------------------------
-- onEffectGain
----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_INT, 6);
target:addMod(MOD_MP, 40);
target:addMod(MOD_MATT, 12);
target:addMod(MOD_MDEF, 5);
target:addMod(MOD_MACC, 8);
target:addMod(MOD_MEVA, 10);
target:addMod(MOD_FASTCAST, 4);
target:addMod(MOD_BLACK_MAGIC_CAST, -4);
target:addMod(MOD_BLACK_MAGIC_RECAST, -4);
target:addMod(MOD_MAG_BURST_BONUS, 5);
target:addMod(MOD_MAGIC_CRITHITRATE, 5);
target:addMod(MOD_MPHEAL, 5);
target:addMod(MOD_ETUDE_EFFECT, 2);
target:addMod(MOD_BALLAD_EFFECT, 2);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_INT, 6);
target:delMod(MOD_MP, 40);
target:delMod(MOD_MATT, 11);
target:delMod(MOD_MDEF, 5);
target:delMod(MOD_MACC, 8);
target:delMod(MOD_MEVA, 10);
target:delMod(MOD_FASTCAST, 4);
target:delMod(MOD_BLACK_MAGIC_CAST, -4);
target:delMod(MOD_BLACK_MAGIC_RECAST, -4);
target:delMod(MOD_MAG_BURST_BONUS, 5);
target:delMod(MOD_MAGIC_CRITHITRATE, 5);
target:delMod(MOD_MPHEAL, 5);
target:delMod(MOD_ETUDE_EFFECT, 2);
target:delMod(MOD_BALLAD_EFFECT, 2);
end;
| gpl-3.0 |
knyghtmare/War_of_Legends | lua/equipment-system/item-list.lua | 1 | 3053 | item_types = {
Helmet = {
Cloth = {
level = 1,
armor = {
impact = 10,
},
image = "icons/cloak_leather_brown.png",
ground_icon = "items/fur_hat.png",
category = "light",
type = "armor",
value = 6,
},
Leather = {
level = 1,
armor = {
impact = 5,
pierce = 10,
blade = 10,
},
image = "icons/helmet_leather-cap.png",
ground_icon = "items/coif.png",
category = "medium",
type = "armor",
value = 8,
},
Bronze = {
level = 1,
armor = {
pierce = 15,
blade = 15,
},
image = "icons/helmet_conical.png",
ground_icon = "items/helmet_rusty.png",
category = "heavy",
type = "armor",
value = 10,
},
},
Armor = {
Cloth = {
level = 1,
armor = {
impact = 5,
pierce = 10,
blade = 10,
},
image = "icons/dress_silk_green.png",
ground_icon = "items/brigandine_vest.png",
category = "light",
type = "armor",
value = 15,
},
Leather = {
level = 1,
armor = {
impact = 10,
pierce = 10,
blade = 10,
},
image = "icons/armor_leather.png",
ground_icon = "items/leather_vest.png",
category = "medium",
type = "armor",
value = 18,
},
Bronze = {
level = 1,
armor = {
pierce = 20,
blade = 20,
},
image = "icons/cuirass_muscled.png",
ground_icon = "items/breastplate.png",
category = "heavy",
type = "armor",
value = 20,
},
Studded = {
level = 5,
armor = {
impact = 15,
pierce = 15,
blade = 15,
},
image = "icons/cuirass_leather_studded.png",
ground_icon = "items/armor-leather.png",
category = "medium",
type = "armor",
value = 32,
},
},
Ring = {
Gold = {
image = "icons/ring_gold.png",
ground_icon = "items/ring-gold.png",
level = 2,
ranged_damage = "10%",
category = "ring",
type = "ranged_buff",
value = 22,
},
Uncommon = {
image = "icons/skull_ring.png",
ground_icon = "items/ring-brown.png",
level = 2,
melee_damage = "10%",
category = "ring",
type = "melee_buff",
value = 22,
},
},
Amulet = {
Ankh = {
image = "icons/ankh_necklace.png",
ground_icon = "items/ankh-necklace.png",
level = 2,
ranged_damage = "10%",
category = "amulet",
type = "ranged_buff",
value = 22,
},
Jade = {
image = "icons/jewelry_butterfly_pin.png",
ground_icon = "items/rock.png",
level = 2,
melee_damage = "10%",
category = "amulet",
type = "melee_buff",
value = 22,
},
},
}
modifiers = {
armor = {
Refined = {
name = "Refined",
hitpoints = 6,
},
Augmented = {
name = "Augmented",
hitpoints = 12,
},
},
}
item_cache = {} | gpl-2.0 |
Atebite/NutScript | gamemode/core/derma/cl_attribute.lua | 3 | 3007 | local PANEL = {}
local gradient = nut.util.getMaterial("vgui/gradient-u")
local gradient2 = nut.util.getMaterial("vgui/gradient-d")
function PANEL:Init()
self:SetTall(20)
self.add = self:Add("DImageButton")
self.add:SetSize(16, 16)
self.add:Dock(RIGHT)
self.add:DockMargin(2, 2, 2, 2)
self.add:SetImage("icon16/add.png")
self.add.OnMousePressed = function()
self.pressing = 1
self:doChange()
self.add:SetAlpha(150)
end
self.add.OnMouseReleased = function()
if (self.pressing) then
self.pressing = nil
self.add:SetAlpha(255)
end
end
self.add.OnCursorExited = self.add.OnMouseReleased
self.sub = self:Add("DImageButton")
self.sub:SetSize(16, 16)
self.sub:Dock(LEFT)
self.sub:DockMargin(2, 2, 2, 2)
self.sub:SetImage("icon16/delete.png")
self.sub.OnMousePressed = function()
self.pressing = -1
self:doChange()
self.sub:SetAlpha(150)
end
self.sub.OnMouseReleased = function()
if (self.pressing) then
self.pressing = nil
self.sub:SetAlpha(255)
end
end
self.sub.OnCursorExited = self.sub.OnMouseReleased
self.value = 0
self.deltaValue = self.value
self.max = 10
self.bar = self:Add("DPanel")
self.bar:Dock(FILL)
self.bar.Paint = function(this, w, h)
surface.SetDrawColor(35, 35, 35, 250)
surface.DrawRect(0, 0, w, h)
w, h = w - 4, h - 4
local value = self.deltaValue / self.max
if (value > 0) then
local color = nut.config.get("color")
local add = 0
if (self.deltaValue != self.value) then
add = 35
end
surface.SetDrawColor(color.r + add, color.g + add, color.b + add, 230)
surface.DrawRect(2, 2, w * value, h)
surface.SetDrawColor(255, 255, 255, 35)
surface.SetMaterial(gradient)
surface.DrawTexturedRect(2, 2, w * value, h)
end
surface.SetDrawColor(255, 255, 255, 5)
surface.SetMaterial(gradient2)
surface.DrawTexturedRect(2, 2, w, h)
end
self.label = self.bar:Add("DLabel")
self.label:Dock(FILL)
self.label:SetExpensiveShadow(1, Color(0, 0, 60))
self.label:SetContentAlignment(5)
end
function PANEL:Think()
if (self.pressing) then
if ((self.nextPress or 0) < CurTime()) then
self:doChange()
end
end
self.deltaValue = math.Approach(self.deltaValue, self.value, FrameTime() * 7.5)
end
function PANEL:doChange()
if ((self.value == 0 and self.pressing == -1) or (self.value == self.max and self.pressing == 1)) then
return
end
self.nextPress = CurTime() + 0.2
if (self:onChanged(self.pressing) != false) then
self.value = math.Clamp(self.value + self.pressing, 0, self.max)
end
end
function PANEL:onChanged(difference)
end
function PANEL:getValue()
return self.value
end
function PANEL:setValue(value)
self.value = value
end
function PANEL:setMax(max)
self.max = max
end
function PANEL:setText(text)
self.label:SetText(text)
end
function PANEL:setReadOnly()
self.sub:Remove()
self.add:Remove()
end
vgui.Register("nutAttribBar", PANEL, "DPanel") | mit |
awesomeWM/awesome | lib/awful/widget/only_on_screen.lua | 1 | 3980 | ---------------------------------------------------------------------------
--
-- A container that makes a widget display only on a specified screen.
--
-- @author Uli Schlachter
-- @copyright 2017 Uli Schlachter
-- @containermod awful.widget.only_on_screen
-- @supermodule wibox.widget.base
---------------------------------------------------------------------------
local type = type
local pairs = pairs
local setmetatable = setmetatable
local base = require("wibox.widget.base")
local gtable = require("gears.table")
local capi = {
screen = screen,
awesome = awesome
}
local only_on_screen = { mt = {} }
local instances = setmetatable({}, { __mode = "k" })
local function should_display_on(self, s)
if not self._private.widget then
return false
end
local own_s = self._private.screen
if type(own_s) == "number" and (own_s < 1 or own_s > capi.screen.count()) then
-- Invalid screen number
return false
end
return capi.screen[self._private.screen] == s
end
-- Layout this layout
function only_on_screen:layout(context, ...)
if not should_display_on(self, context.screen) then return end
return { base.place_widget_at(self._private.widget, 0, 0, ...) }
end
-- Fit this layout into the given area
function only_on_screen:fit(context, ...)
if not should_display_on(self, context.screen) then
return 0, 0
end
return base.fit_widget(self, context, self._private.widget, ...)
end
--- The widget to be displayed
-- @property widget
-- @tparam[opt=nil] widget|nil widget
only_on_screen.set_widget = base.set_widget_common
function only_on_screen:get_widget()
return self._private.widget
end
function only_on_screen:get_children()
return {self._private.widget}
end
function only_on_screen:set_children(children)
self:set_widget(children[1])
end
--- The screen to display on.
-- Can be a screen object, a screen index, a screen
-- name ("VGA1") or the string "primary" for the primary screen.
-- @property screen
-- @tparam[opt="primary"] screen screen
function only_on_screen:set_screen(s)
self._private.screen = s
self:emit_signal("widget::layout_changed")
end
function only_on_screen:get_screen()
return self._private.screen
end
--- Returns a new `awful.widget.only_on_screen` container.
-- This widget makes some other widget visible on just some screens. Use
-- `:set_widget()` to set the widget and `:set_screen()` to set the screen.
-- @tparam[opt=nil] widget widget The widget to display.
-- @tparam[opt="primary"] screen s The screen to display on.
-- @treturn table A new only_on_screen container
-- @constructorfct awful.widget.only_on_screen
local function new(widget, s)
local ret = base.make_widget(nil, nil, {enable_properties = true})
gtable.crush(ret, only_on_screen, true)
ret:set_widget(widget)
ret:set_screen(s or "primary")
instances[ret] = true
return ret
end
function only_on_screen.mt:__call(...)
return new(...)
end
-- Handle lots of cases where a screen changes and thus this widget jumps around
capi.screen.connect_signal("primary_changed", function()
for widget in pairs(instances) do
if widget._private.widget and widget._private.screen == "primary" then
widget:emit_signal("widget::layout_changed")
end
end
end)
capi.screen.connect_signal("list", function()
for widget in pairs(instances) do
if widget._private.widget and type(widget._private.screen) == "number" then
widget:emit_signal("widget::layout_changed")
end
end
end)
capi.screen.connect_signal("property::outputs", function()
for widget in pairs(instances) do
if widget._private.widget and type(widget._private.screen) == "string" then
widget:emit_signal("widget::layout_changed")
end
end
end)
return setmetatable(only_on_screen, only_on_screen.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
mwoz123/koreader | spec/unit/filemanagerconverter_spec.lua | 8 | 2252 | describe("FileConverter module", function()
local FileConverter
setup(function()
require("commonrequire")
FileConverter = require("apps/filemanager/filemanagerconverter")
end)
it("should show conversion support for Markdown", function()
assert.is_true(FileConverter:isSupported("/markdown_file.md"))
end)
it("should not show conversion support for PDF", function()
assert.is_false(FileConverter:isSupported("/pdf_file.pdf"))
end)
it("should convert Markdown to HTML", function()
local markdown = [[
# KOReader Quickstart Guide
Welcome to KOreader. You can activate the menu by swiping down from the top of the screen. Clicking outside the menu or swiping up on the menu will discard it. Turning pages can be done either by swiping left and right or by single taps on the left or right side of the screen.
**Main menu**
 You can always view this quickstart guide again through *Help* → *Quickstart guide* in the top right menu.
**Settings**
 You can change the language and other settings through the gear icon.
------------
Generated by KOReader v2015.11-982-g704d4238.
]]
local title = "KOReader Quickstart Guide"
local html_expected = [[<!DOCTYPE html>
<html>
<head>
<title>KOReader Quickstart Guide</title>
</head>
<body>
<h1>KOReader Quickstart Guide</h1>
<p>Welcome to KOreader. You can activate the menu by swiping down from the top of the screen. Clicking outside the menu or swiping up on the menu will discard it. Turning pages can be done either by swiping left and right or by single taps on the left or right side of the screen.</p>
<p><strong>Main menu</strong></p>
<p><img alt="Menu" src="../resources/menu.svg"> You can always view this quickstart guide again through <em>Help</em> → <em>Quickstart guide</em> in the top right menu.</p>
<p><strong>Settings</strong></p>
<p><img alt="Settings" src="../resources/settings.svg"> You can change the language and other settings through the gear icon.</p>
<hr>
<p>Generated by KOReader v2015.11-982-g704d4238.</p>
</body>
</html>]]
assert.are.same(html_expected, FileConverter:mdToHtml(markdown, title))
end)
end)
| agpl-3.0 |
Ravenlord/ddp-testing | tests/calculated_values/dependent/01_trivial-select.lua | 1 | 2637 | --[[!
- This is free and unencumbered software released into the public domain.
-
- Anyone is free to copy, modify, publish, use, compile, sell, or distribute this software, either in source code form
- or as a compiled binary, for any purpose, commercial or non-commercial, and by any means.
-
- In jurisdictions that recognize copyright laws, the author or authors of this software dedicate any and all copyright
- interest in the software to the public domain. We make this dedication for the benefit of the public at large and to
- the detriment of our heirs and successors. We intend this dedication to be an overt act of relinquishment in
- perpetuity of all present and future rights to this software under copyright law.
-
- 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 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.
-
- For more information, please refer to <http://unlicense.org/>
--]]
--[[
- Benchmark file for design problem "Calculated Values (dependent)", trivial solution.
- Select top 20 most ordered products.
-
- @author Markus Deutschl <deutschl.markus@gmail.com>
- @copyright 2014 Markus Deutschl
- @license http://unlicense.org/ Unlicense
--]]
-- --------------------------------------------------------------------------------------------------------------------- Includes
pathtest = string.match(test, "(.*/)") or ""
dofile(pathtest .. "../../common.inc")
dofile(pathtest .. "prepare.inc")
-- --------------------------------------------------------------------------------------------------------------------- Preparation functions
--- Prepare data for the benchmark.
-- Is called during the prepare command of sysbench in common.lua.
function prepare_data()
-- Reuse data preparation.
prepare_dependent()
end
-- --------------------------------------------------------------------------------------------------------------------- Benchmark functions
--- Execute the benchmark queries.
-- Is called during the run command of sysbench.
function benchmark()
local query = [[
SELECT
p.`id`,
p.`name`,
SUM(l.`amount`) AS `amount_ordered`
FROM `products` AS p
INNER JOIN `line_items` AS `l` ON p.`id` = l.`product_id`
GROUP BY p.`id`, p.`name`
ORDER BY `amount_ordered` DESC
LIMIT 20
]]
rs = db_query(query)
end
| unlicense |
yswifi/APlan | build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/applications/luci-firewall/luasrc/model/cbi/firewall/zone-details.lua | 47 | 6266 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2010-2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
local ds = require "luci.dispatcher"
local ut = require "luci.util"
local m, p, i, v
local s, name, net, family, msrc, mdest, log, lim
local s2, out, inp
m = Map("firewall", translate("Firewall - Zone Settings"))
m.redirect = luci.dispatcher.build_url("admin/network/firewall/zones")
fw.init(m.uci)
nw.init(m.uci)
local zone = fw:get_zone(arg[1])
if not zone then
luci.http.redirect(dsp.build_url("admin/network/firewall/zones"))
return
else
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", zone:name() or "?")
}
end
s = m:section(NamedSection, zone.sid, "zone",
translatef("Zone %q", zone:name()),
translatef("This section defines common properties of %q. \
The <em>input</em> and <em>output</em> options set the default \
policies for traffic entering and leaving this zone while the \
<em>forward</em> option describes the policy for forwarded traffic \
between different networks within the zone. \
<em>Covered networks</em> specifies which available networks are \
member of this zone.", zone:name()))
s.anonymous = true
s.addremove = false
m.on_commit = function(map)
local zone = fw:get_zone(arg[1])
if zone then
s.section = zone.sid
s2.section = zone.sid
end
end
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
name = s:taboption("general", Value, "name", translate("Name"))
name.optional = false
name.forcewrite = true
name.datatype = "uciname"
function name.write(self, section, value)
if zone:name() ~= value then
fw:rename_zone(zone:name(), value)
out.exclude = value
inp.exclude = value
end
m.redirect = ds.build_url("admin/network/firewall/zones", value)
m.title = "%s - %s" %{
translate("Firewall - Zone Settings"),
translatef("Zone %q", value or "?")
}
end
p = {
s:taboption("general", ListValue, "input", translate("Input")),
s:taboption("general", ListValue, "output", translate("Output")),
s:taboption("general", ListValue, "forward", translate("Forward"))
}
for i, v in ipairs(p) do
v:value("REJECT", translate("reject"))
v:value("DROP", translate("drop"))
v:value("ACCEPT", translate("accept"))
end
s:taboption("general", Flag, "masq", translate("Masquerading"))
s:taboption("general", Flag, "mtu_fix", translate("MSS clamping"))
net = s:taboption("general", Value, "network", translate("Covered networks"))
net.template = "cbi/network_netlist"
net.widget = "checkbox"
net.cast = "string"
function net.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function net.cfgvalue(self, section)
return Value.cfgvalue(self, section) or name:cfgvalue(section)
end
function net.write(self, section, value)
zone:clear_networks()
local n
for n in ut.imatch(value) do
zone:add_network(n)
end
end
family = s:taboption("advanced", ListValue, "family",
translate("Restrict to address family"))
family.rmempty = true
family:value("", translate("IPv4 and IPv6"))
family:value("ipv4", translate("IPv4 only"))
family:value("ipv6", translate("IPv6 only"))
msrc = s:taboption("advanced", DynamicList, "masq_src",
translate("Restrict Masquerading to given source subnets"))
msrc.optional = true
msrc.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
msrc.placeholder = "0.0.0.0/0"
msrc:depends("family", "")
msrc:depends("family", "ipv4")
mdest = s:taboption("advanced", DynamicList, "masq_dest",
translate("Restrict Masquerading to given destination subnets"))
mdest.optional = true
mdest.datatype = "list(neg(or(uciname,hostname,ip4addr)))"
mdest.placeholder = "0.0.0.0/0"
mdest:depends("family", "")
mdest:depends("family", "ipv4")
s:taboption("advanced", Flag, "conntrack",
translate("Force connection tracking"))
log = s:taboption("advanced", Flag, "log",
translate("Enable logging on this zone"))
log.rmempty = true
log.enabled = "1"
lim = s:taboption("advanced", Value, "log_limit",
translate("Limit log messages"))
lim.placeholder = "10/minute"
lim:depends("log", "1")
s2 = m:section(NamedSection, zone.sid, "fwd_out",
translate("Inter-Zone Forwarding"),
translatef("The options below control the forwarding policies between \
this zone (%s) and other zones. <em>Destination zones</em> cover \
forwarded traffic <strong>originating from %q</strong>. \
<em>Source zones</em> match forwarded traffic from other zones \
<strong>targeted at %q</strong>. The forwarding rule is \
<em>unidirectional</em>, e.g. a forward from lan to wan does \
<em>not</em> imply a permission to forward from wan to lan as well.",
zone:name(), zone:name(), zone:name()
))
out = s2:option(Value, "out",
translate("Allow forward to <em>destination zones</em>:"))
out.nocreate = true
out.widget = "checkbox"
out.exclude = zone:name()
out.template = "cbi/firewall_zonelist"
inp = s2:option(Value, "in",
translate("Allow forward from <em>source zones</em>:"))
inp.nocreate = true
inp.widget = "checkbox"
inp.exclude = zone:name()
inp.template = "cbi/firewall_zonelist"
function out.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("src")) do
v[#v+1] = f:dest()
end
return table.concat(v, " ")
end
function inp.cfgvalue(self, section)
local v = { }
local f
for _, f in ipairs(zone:get_forwardings_by("dest")) do
v[#v+1] = f:src()
end
return v
end
function out.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function inp.formvalue(self, section)
return Value.formvalue(self, section) or "-"
end
function out.write(self, section, value)
zone:del_forwardings_by("src")
local f
for f in ut.imatch(value) do
zone:add_forwarding_to(f)
end
end
function inp.write(self, section, value)
zone:del_forwardings_by("dest")
local f
for f in ut.imatch(value) do
zone:add_forwarding_from(f)
end
end
return m
| gpl-2.0 |
UniverseMelowdi/TheMelowdi | plugins/help.lua | 2 | 1654 | do
-- Returns true if is not empty
local function has_usage_data(dict)
if (dict.usage == nil or dict.usage == '') then
return false
end
return true
end
-- Get commands for that plugin
local function plugin_help(name)
local plugin = plugins[name]
if not plugin then return nil end
local text = ""
if (type(plugin.usage) == "table") then
for ku,usage in pairs(plugin.usage) do
text = text..usage..'\n'
end
text = text..'\n'
elseif has_usage_data(plugin) then -- Is not empty
text = text..plugin.usage..'\n\n'
end
return text
end
-- !help command
local function telegram_help()
local text = "Plugin list: \n\n"
-- Plugins names
for name in pairs(plugins) do
text = text..name..'\n'
end
text = text..'\n'..'Write "!help [plugin name]" for more info.'
text = text..'\n'..'Or "!help all" to show all info.'
return text
end
-- !help all command
local function help_all()
local ret = ""
for name in pairs(plugins) do
ret = ret .. plugin_help(name)
end
return ret
end
local function run(msg, matches)
if matches[1] == "!help" then
return telegram_help()
elseif matches[1] == "!help all" then
return help_all()
else
local text = plugin_help(matches[1])
if not text then
text = telegram_help()
end
return text
end
end
return {
description = "Help plugin. Get info from other plugins. ",
usage = {
"#help: Show list of plugins.",
"#help all: Show all commands for every plugin.",
"#help [plugin name]: Commands for that plugin."
},
patterns = {
"^#help$",
"^#help all",
"^#help (.+)"
},
run = run
}
end
| gpl-2.0 |
bnetcc/darkstar | scripts/zones/Port_Bastok/npcs/Rosswald.lua | 5 | 1360 | -----------------------------------
-- Area: Port Bastok
-- NPC: Rosswald
-- Only sells when Bastok controlls Zulkheim Region
-- Confirmed shop stock, August 2013
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_Bastok/TextIDs");
require("scripts/globals/conquest");
require("scripts/globals/shop");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local RegionOwner = GetRegionOwner(ZULKHEIM);
if (RegionOwner ~= NATION_BASTOK) then
player:showText(npc,ROSSWALD_CLOSED_DIALOG);
else
player:showText(npc,ROSSWALD_OPEN_DIALOG);
local stock =
{
4372, 44, -- Giant Sheep Meat
622, 44, -- Dried Marjoram
610, 55, -- San d'Orian Flour
611, 36, -- Rye Flour
1840, 1840, -- Semolina
4366, 22, -- La Theine Cabbage
4378, 55 -- Selbina Milk
}
showShop(player,BASTOK,stock);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bnetcc/darkstar | scripts/zones/Newton_Movalpolos/npcs/Furnace_Hatch.lua | 1 | 2805 | -----------------------------------
-- Area: Newton Movalpolos
-- NPC: Furnace_Hatch
-----------------------------------
package.loaded["scripts/zones/Newton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Newton_Movalpolos/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(947,1)) then
player:tradeComplete();
-- player:messageSpecial(???); -- Needs retail info
local npcid = npc:getID();
local Door_Offset = 16826582; -- _0c0 in NPC_List
if (npcid == Door_Offset+29 or npcid == Door_Offset+28 or npcid == Door_Offset+27) then
if (GetNPCByID(Door_Offset+10):getAnimation() == 8) then
GetNPCByID(Door_Offset+10):setAnimation(9);
GetNPCByID(Door_Offset+11):setAnimation(8);
GetNPCByID(Door_Offset+8):setAnimation(9);
GetNPCByID(Door_Offset+9):setAnimation(8);
else
GetNPCByID(Door_Offset+10):setAnimation(8);
GetNPCByID(Door_Offset+11):setAnimation(9);
GetNPCByID(Door_Offset+8):setAnimation(8);
GetNPCByID(Door_Offset+9):setAnimation(9);
end
elseif (npcid == Door_Offset+25) then
if (GetNPCByID(Door_Offset+3):getAnimation() == 8) then
GetNPCByID(Door_Offset+3):setAnimation(9);
GetNPCByID(Door_Offset+2):setAnimation(8);
GetNPCByID(Door_Offset+1):setAnimation(9);
GetNPCByID(Door_Offset):setAnimation(8);
else
GetNPCByID(Door_Offset+3):setAnimation(8);
GetNPCByID(Door_Offset+2):setAnimation(9);
GetNPCByID(Door_Offset+1):setAnimation(8);
GetNPCByID(Door_Offset):setAnimation(9);
end
elseif (npcid == Door_Offset+26) then
if (GetNPCByID(Door_Offset+4):getAnimation() == 8) then
GetNPCByID(Door_Offset+4):setAnimation(9);
GetNPCByID(Door_Offset+5):setAnimation(8);
GetNPCByID(Door_Offset+6):setAnimation(9);
GetNPCByID(Door_Offset+7):setAnimation(8);
else
GetNPCByID(Door_Offset+4):setAnimation(8);
GetNPCByID(Door_Offset+5):setAnimation(9);
GetNPCByID(Door_Offset+6):setAnimation(8);
GetNPCByID(Door_Offset+7):setAnimation(9);
end
end
end
end;
function onTrigger(player,npc)
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
TeleDALAD/test | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
bnetcc/darkstar | scripts/zones/Rolanberry_Fields/npcs/Legion_Moogle.lua | 1 | 6749 | -----------------------------------
-- Area: Rolanberry Fields (110)
-- NPC: Legion Moogle
-- Type: Legion +1 Helper
-----------------------------------
package.loaded["scripts/zones/Rolanberry_Fields/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Rolanberry_Fields/TextIDs");
local LegionPointPrice = 2000; -- It's up here so it can be seen by both functions
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local PRIZE;
if (player:getCurrency("legion_point") >= LegionPointPrice) then
--------------------------
-- Legion Gear +1 upgrades
--------------------------
-- Gorney +1 - ilvl 119
if (trade:hasItemQty(3925, 10) and trade:hasItemQty(27761,1) and trade:getItemCount() == 11) then -- head
PRIZE = 27711;
elseif (trade:hasItemQty(3925, 20) and trade:hasItemQty(27907,1) and trade:getItemCount() == 21) then -- body
PRIZE = 27863;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28046,1) and trade:getItemCount() == 11) then -- hands
PRIZE = 28010;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28188,1) and trade:getItemCount() == 11) then -- legs
PRIZE = 28152;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28327,1) and trade:getItemCount() == 11) then -- feet
PRIZE = 28289;
-- Shneddick +1 ilvl 119
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(27762,1) and trade:getItemCount() == 11) then -- head
PRIZE = 27712;
elseif (trade:hasItemQty(3925, 20) and trade:hasItemQty(27908,1) and trade:getItemCount() == 21) then -- body
PRIZE = 27864;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28047,1) and trade:getItemCount() == 11) then -- hands
PRIZE = 28011;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28189,1) and trade:getItemCount() == 11) then -- legs
PRIZE = 28153;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28328,1) and trade:getItemCount() == 11) then -- feet
PRIZE = 28290;
-- Weatherspoon +1 ilvl 119
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(27763,1) and trade:getItemCount() == 11) then -- head
PRIZE = 27713;
elseif (trade:hasItemQty(3925, 20) and trade:hasItemQty(27909,1) and trade:getItemCount() == 21) then -- body
PRIZE = 27865;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28048,1) and trade:getItemCount() == 11) then -- hands
PRIZE = 28012;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28190,1) and trade:getItemCount() == 11) then -- legs
PRIZE = 28154;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(28329,1) and trade:getItemCount() == 11) then -- feet
PRIZE = 28291;
-- Karieyh ilvl 109
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(27785,1) and trade:getItemCount() == 6) then -- head
PRIZE = 27752;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(27925,1) and trade:getItemCount() == 11) then -- body
PRIZE = 27895;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28065,1) and trade:getItemCount() == 6) then -- hands
PRIZE = 28042;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28205,1) and trade:getItemCount() == 6) then -- legs
PRIZE = 28182;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28345,1) and trade:getItemCount() == 6) then -- feet
PRIZE = 28320;
-- Thurandaunts ilvl 109
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(27784,1) and trade:getItemCount() == 6) then -- head
PRIZE = 27753;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(27924,1) and trade:getItemCount() == 11) then -- body
PRIZE = 27896;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28064,1) and trade:getItemCount() == 6) then -- hands
PRIZE = 28043;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28204,1) and trade:getItemCount() == 6) then -- legs
PRIZE = 28183;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28344,1) and trade:getItemCount() == 6) then -- feet
PRIZE = 28321;
-- Orvail ilvl 109
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(27782,1) and trade:getItemCount() == 6) then -- head
PRIZE = 27754;
elseif (trade:hasItemQty(3925, 10) and trade:hasItemQty(27922,1) and trade:getItemCount() == 11) then -- body
PRIZE = 27897;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28061,1) and trade:getItemCount() == 6) then -- hands
PRIZE = 28044;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28203,1) and trade:getItemCount() == 6) then -- legs
PRIZE = 28184;
elseif (trade:hasItemQty(3925, 5) and trade:hasItemQty(28342,1) and trade:getItemCount() == 6) then -- feet
PRIZE = 28322;
end
if (PRIZE ~= nil) then
if (player:getFreeSlotsCount() >= 1) then
player:delCurrency("legion_point", LegionPointPrice);
player:messageSpecial(ITEM_OBTAINED, PRIZE);
player:tradeComplete();
player:addItem(PRIZE, 1);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, PRIZE);
end
end
else
player:PrintToPlayer("You do not have enough Legion points for the upgrade!", chatType.SAY, npc:getName());
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local MSG1 = string.format("Hello %s! I'm here to help you upgrade your Legion Armor. ", player:getName());
local MSG2 = string.format("This service will cost %s Legion points and some Tanzanite Jewels, Kupo! ", LegionPointPrice);
player:PrintToPlayer(MSG1, chatType.SAY, npc:getName());
player:PrintToPlayer(MSG2, chatType.SAY, npc:getName());
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("onUpdate CSID: %u", csid);
-- printf("onUpdate RESULT: %u", option);
end;
| gpl-3.0 |
best98ir/SASAN | plugins/fun.lua | 1 | 17395 |
--Begin Fun.lua By @BeyondTeam
--Special Thx To @To0fan
--------------------------------
local function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
--------------------------------
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
--------------------------------
local function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
--------------------------------
local function get_staticmap(area)
local api = base_api .. "/staticmap?"
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale == "locality" then
zoom=8
elseif scale == "country" then
zoom=4
else
zoom = 13
end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~= nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
--------------------------------
local function get_weather(location)
print("Finding weather in ", location)
local BASE_URL = "http://api.openweathermap.org/data/2.5/weather"
local url = BASE_URL
url = url..'?q='..location..'&APPID=eedbc05ba060c787ab0614cad1f2e12b'
url = url..'&units=metric'
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local weather = json:decode(b)
local city = weather.name
local country = weather.sys.country
local temp = 'دمای شهر '..city..' هم اکنون '..weather.main.temp..' درجه سانتی گراد می باشد\n____________________'
local conditions = 'شرایط فعلی آب و هوا : '
if weather.weather[1].main == 'Clear' then
conditions = conditions .. 'آفتابی☀'
elseif weather.weather[1].main == 'Clouds' then
conditions = conditions .. 'ابری ☁☁'
elseif weather.weather[1].main == 'Rain' then
conditions = conditions .. 'بارانی ☔'
elseif weather.weather[1].main == 'Thunderstorm' then
conditions = conditions .. 'طوفانی ☔☔☔☔'
elseif weather.weather[1].main == 'Mist' then
conditions = conditions .. 'مه 💨'
end
return temp .. '\n' .. conditions
end
--------------------------------
local function calc(exp)
url = 'http://api.mathjs.org/v1/'
url = url..'?expr='..URL.escape(exp)
b,c = http.request(url)
text = nil
if c == 200 then
text = 'Result = '..b..'\n____________________'..msg_caption
elseif c == 400 then
text = b
else
text = 'Unexpected error\n'
..'Is api.mathjs.org up?'
end
return text
end
--------------------------------
function exi_file(path, suffix)
local files = {}
local pth = tostring(path)
local psv = tostring(suffix)
for k, v in pairs(scandir(pth)) do
if (v:match('.'..psv..'$')) then
table.insert(files, v)
end
end
return files
end
--------------------------------
function file_exi(name, path, suffix)
local fname = tostring(name)
local pth = tostring(path)
local psv = tostring(suffix)
for k,v in pairs(exi_file(pth, psv)) do
if fname == v then
return true
end
end
return false
end
--------------------------------
function run(msg, matches)
local Chash = "cmd_lang:"..msg.to.id
local Clang = redis:get(Chash)
if (matches[1]:lower() == 'calc' and not Clang) or (matches[1]:lower() == 'ماشین حساب' and Clang) and matches[2] then
if msg.to.type == "pv" then
return
end
return calc(matches[2])
end
--------------------------------
if (matches[1]:lower() == 'praytime' and not Clang) or (matches[1]:lower() == 'ساعات شرعی' and Clang) then
if matches[2] then
city = matches[2]
elseif not matches[2] then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = 'شهر: '..city
text = text..'\nاذان صبح: '..data.Fajr
text = text..'\nطلوع آفتاب: '..data.Sunrise
text = text..'\nاذان ظهر: '..data.Dhuhr
text = text..'\nغروب آفتاب: '..data.Sunset
text = text..'\nاذان مغرب: '..data.Maghrib
text = text..'\nعشاء : '..data.Isha
text = text..msg_caption
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if (matches[1]:lower() == 'tophoto' and not Clang) or (matches[1]:lower() == 'تبدیل به عکس' and Clang) and msg.reply_id then
function tophoto(arg, data)
function tophoto_cb(arg,data)
if data.content_.sticker_ then
local file = data.content_.sticker_.sticker_.path_
local secp = tostring(tcpath)..'/data/sticker/'
local ffile = string.gsub(file, '-', '')
local fsecp = string.gsub(secp, '-', '')
local name = string.gsub(ffile, fsecp, '')
local sname = string.gsub(name, 'webp', 'jpg')
local pfile = 'data/photos/'..sname
local pasvand = 'webp'
local apath = tostring(tcpath)..'/data/sticker'
if file_exi(tostring(name), tostring(apath), tostring(pasvand)) then
os.rename(file, pfile)
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This sticker does not exist. Send sticker again._'..msg_caption, 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a sticker._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tophoto_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tophoto, nil)
end
--------------------------------
if (matches[1]:lower() == 'tosticker' and not Clang) or (matches[1]:lower() == 'تبدیل به استیکر' and Clang) and msg.reply_id then
function tosticker(arg, data)
function tosticker_cb(arg,data)
if data.content_.ID == 'MessagePhoto' then
file = data.content_.photo_.id_
local pathf = tcpath..'/data/photo/'..file..'_(1).jpg'
local pfile = 'data/photos/'..file..'.webp'
if file_exi(file..'_(1).jpg', tcpath..'/data/photo', 'jpg') then
os.rename(pathf, pfile)
tdcli.sendDocument(msg.chat_id_, 0, 0, 1, nil, pfile, msg_caption, dl_cb, nil)
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This photo does not exist. Send photo again._', 1, 'md')
end
else
tdcli.sendMessage(msg.to.id, msg.id_, 1, '_This is not a photo._', 1, 'md')
end
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = data.id_ }, tosticker_cb, nil)
end
tdcli_function ({ ID = 'GetMessage', chat_id_ = msg.chat_id_, message_id_ = msg.reply_id }, tosticker, nil)
end
--------------------------------
if (matches[1]:lower() == 'weather' and not Clang) or (matches[1]:lower() == 'اب و هوا' and Clang) then
city = matches[2]
local wtext = get_weather(city)
if not wtext then
wtext = 'مکان وارد شده صحیح نیست'
end
return wtext
end
--------------------------------
if (matches[1]:lower() == 'time' and not Clang) or (matches[1]:lower() == 'ساعت' and Clang) then
local url , res = http.request('http://api.beyond-dev.ir/time/')
if res ~= 200 then
return "No connection"
end
local colors = {'blue','green','yellow','magenta','Orange','DarkOrange','red'}
local fonts = {'mathbf','mathit','mathfrak','mathrm'}
local jdat = json:decode(url)
local url = 'http://latex.codecogs.com/png.download?'..'\\dpi{600}%20\\huge%20\\'..fonts[math.random(#fonts)]..'{{\\color{'..colors[math.random(#colors)]..'}'..jdat.ENtime..'}}'
local file = download_to_file(url,'time.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if (matches[1]:lower() == 'voice' and not Clang) or (matches[1]:lower() == 'تبدیل به صدا' and Clang) then
local text = matches[2]
textc = text:gsub(' ','.')
if msg.to.type == 'pv' then
return nil
else
local url = "http://tts.baidu.com/text2audio?lan=en&ie=UTF-8&text="..textc
local file = download_to_file(url,'BD-Reborn.mp3')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
end
--------------------------------
if (matches[1]:lower() == 'tr' and not Clang) or (matches[1]:lower() == 'ترجمه' and Clang) then
url = https.request('https://translate.yandex.net/api/v1.5/tr.json/translate?key=trnsl.1.1.20160119T111342Z.fd6bf13b3590838f.6ce9d8cca4672f0ed24f649c1b502789c9f4687a&format=plain&lang='..URL.escape(matches[2])..'&text='..URL.escape(matches[3]))
data = json:decode(url)
return 'زبان : '..data.lang..'\nترجمه : '..data.text[1]..'\n____________________'..msg_caption
end
--------------------------------
if (matches[1]:lower() == 'short' and not Clang) or (matches[1]:lower() == 'لینک کوتاه' and Clang) then
if matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = matches[2]
elseif not matches[2]:match("[Hh][Tt][Tt][Pp][Ss]://") then
shortlink = "https://"..matches[2]
end
local yon = http.request('http://api.yon.ir/?url='..URL.escape(shortlink))
local jdat = json:decode(yon)
local bitly = https.request('https://api-ssl.bitly.com/v3/shorten?access_token=f2d0b4eabb524aaaf22fbc51ca620ae0fa16753d&longUrl='..URL.escape(shortlink))
local data = json:decode(bitly)
local u2s = http.request('http://u2s.ir/?api=1&return_text=1&url='..URL.escape(shortlink))
local llink = http.request('http://llink.ir/yourls-api.php?signature=a13360d6d8&action=shorturl&url='..URL.escape(shortlink)..'&format=simple')
local text = ' 🌐لینک اصلی :\n'..check_markdown(data.data.long_url)..'\n\nلینکهای کوتاه شده با 6 سایت کوتاه ساز لینک : \n》کوتاه شده با bitly :\n___________________________\n'..(check_markdown(data.data.url) or '---')..'\n___________________________\n》کوتاه شده با u2s :\n'..(check_markdown(u2s) or '---')..'\n___________________________\n》کوتاه شده با llink : \n'..(check_markdown(llink) or '---')..'\n___________________________\n》لینک کوتاه شده با yon : \nyon.ir/'..(check_markdown(jdat.output) or '---')..'\n____________________'..msg_caption
return tdcli.sendMessage(msg.chat_id_, 0, 1, text, 1, 'html')
end
--------------------------------
if (matches[1]:lower() == 'sticker' and not Clang) or (matches[1]:lower() == 'استیکر' and Clang) then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.webp')
tdcli.sendDocument(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if (matches[1]:lower() == 'عکس' and not Clang) or (matches[1]:lower() == 'عکس' and Clang) then
local eq = URL.escape(matches[2])
local w = "500"
local h = "500"
local txtsize = "100"
local txtclr = "ff2e4357"
if matches[3] then
txtclr = matches[3]
end
if matches[4] then
txtsize = matches[4]
end
if matches[5] and matches[6] then
w = matches[5]
h = matches[6]
end
local url = "https://assets.imgix.net/examples/clouds.jpg?blur=150&w="..w.."&h="..h.."&fit=crop&txt="..eq.."&txtsize="..txtsize.."&txtclr="..txtclr.."&txtalign=middle,center&txtfont=Futura%20Condensed%20Medium&mono=ff6598cc"
local receiver = msg.to.id
local file = download_to_file(url,'text.jpg')
tdcli.sendPhoto(msg.to.id, 0, 0, 1, nil, file, msg_caption, dl_cb, nil)
end
--------------------------------
if matches[1] == "helpfun" and not Clang then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not lang then
helpfun_en = [[
_ 🎮 Fun Help Commands:_
*🔰 /time*
_🔸 Get time in a sticker_
*🔰 /short* `[link]`
_🔸 Make short url_
*🔰 /voice* `[text]`
_🔸 Convert text to voice_
*🔰 /tr* `[lang] [word]`
_🔸 Translates FA to EN and EN to FA_
*🔰 /sticker* `[word]`
_🔸 Convert text to sticker_
*🔰 /photo* `[word]`
_🔸 Convert text to photo_
*🔰 /calc* `[number]`
_🔸 Calculator_
*🔰 /praytime* `[city]`
_🔸 Get Patent (Pray Time)_
*🔰 /tosticker* `[reply]`
_🔸 Convert photo to sticker_
*🔰 /tophoto* `[reply]`
_🔸 Convert text to photo_
*🔰 /weather* `[city]`
_🔸 Get weather_
_✅ You can use_ *[!/#]* _at the beginning of commands._
*Good luck ;)*]]
else
helpfun_en = [[
_🎮 راهنمای فان_
*!time*
_دریافت ساعت به صورت استیکر_
*🔰 /short* `[link]`
_🔸 کوتاه کننده لینک_
*🔰 /voice* `[text]`
_🔸 تبدیل متن به صدا_
*🔰 /tr* `[lang]` `[word]`
_🔸 ترجمه متن فارسی به انگلیسی وبرعکس_
*🔰 /sticker* `[word]`
_🔸 تبدیل متن به استیکر_
*🔰 /photo* `[word]`
_🔸 تبدیل متن به عکس_
*🔰 /calc* `[number]`
_🔸 ماشین حساب_
*🔰 /praytime* `[city]`
_🔸 اعلام ساعات شرعی_
*🔰 /tosticker* `[reply]`
_🔸 تبدیل عکس به استیکر_
*🔰 /tophoto* `[reply]`
_🔸 تبدیل استیکربه عکس_
*🔰 /weather* `[city]`
_🔸 دریافت اب وهوا_
*✅ شما میتوانید از [!/#] در اول دستورات برای اجرای آنها بهره بگیرید*
موفق باشید ;)]]
end
return helpfun_en..msg_caption
end
if matches[1] == "راهنمای سرگرمی" and Clang then
local hash = "gp_lang:"..msg.to.id
local lang = redis:get(hash)
if not lang then
helpfun_fa = [[
_🎮 Fun Help Commands:_
*🔰 ساعت*
_🔸 Get time in a sticker_
*🔰 لینک کوتاه* `[لینک]`
_🔸 Make short url_
*🔰 تبدیل به صدا* `[متن]`
_🔸 Convert text to voice_
*🔰 ترجمه* `[زبان] [کلمه]`
_🔸 Translates FA to EN and EN to FA_
*🔰 استیکر* `[متن]`
_🔸 Convert text to sticker_
*🔰 عکس* `[متن]`
_🔸 Convert text to photo_
*🔰 ماشین حساب* `[معادله]`
_🔸 Calculator_
*🔰 ساعات شرعی* `[شهر]`
_🔸 Get Patent (Pray Time)_
*🔰 تبدیل به استیکر* `[ریپلی]`
_🔸 Convert photo to sticker_
*🔰 تبدیل به عکس* `[ریپلی]`
_🔸 Convert text to photo_
*🔰 اب و هوا* `[شهر]`
_🔸 Get weather_
*Good luck ;)*]]
else
helpfun_fa = [[
_🎮 راهنمای فان_
*🔰 ساعت*
_🔸 دریافت ساعت به صورت استیکر_
*🔰 لینک کوتاه* `[لینک]`
_🔸 کوتاه کننده لینک_
*🔰 تبدیل به صدا* `[متن]`
_🔸 تبدیل متن به صدا_
*🔰 ترجمه* `[زبان]` `[متن]`
_🔸 ترجمه متن فارسی به انگلیسی وبرعکس_
*🔰 استیکر* `[متن]`
_🔸 تبدیل متن به استیکر_
*🔰 استیکر* `[متن]`
_🔸 تبدیل متن به عکس_
*🔰 ماشین حساب* `[معادله]`
_🔸 ماشین حساب_
*🔰 ساعات شرعی* `[شهر]`
_🔸 اعلام ساعات شرعی_
*🔰 تبدیل به استیکر* `[ریپلی]`
_🔸 تبدیل عکس به استیکر_
*🔰 تبدیل به عکس* `[ریپلی]`
_🔸 تبدیل استیکربه عکس_
*🔰 اب و هوا* `[شهر]`
_🔸 دریافت اب وهوا_
موفق باشید ;)]]
end
return helpfun_fa..msg_caption
end
end
--------------------------------
return {
patterns = {
"^[!/#](helpfun)$",
"^[!/#](weather) (.*)$",
"^[!/](calc) (.*)$",
"^[#!/](time)$",
"^[#!/](tophoto)$",
"^[#!/](tosticker)$",
"^[!/#](voice) +(.*)$",
"^[/!#]([Pp]raytime) (.*)$",
"^[/!#](praytime)$",
"^[!/]([Tt]r) ([^%s]+) (.*)$",
"^[!/]([Ss]hort) (.*)$",
"^[!/](photo) (.+)$",
"^[!/](sticker) (.+)$",
"^(راهنمای سرگرمی)$",
"^(اب و هوا) (.*)$",
"^(ماشین حساب) (.*)$",
"^(ساعت)$",
"^(تبدیل به عکس)$",
"^(تبدیل به استیکر)$",
"^(تبدیل به صدا) +(.*)$",
"^(ساعات شرعی) (.*)$",
"^(ساعات شرعی)$",
"^(ترجمه) ([^%s]+) (.*)$",
"^(لینک کوتاه) (.*)$",
"^(عکس) (.+)$",
"^(استیکر) (.+)$"
},
run = run,
}
--#by @BeyondTeam :)
| gpl-3.0 |
awesomeWM/awesome | lib/wibox/layout/grid.lua | 1 | 34818 | ---------------------------------------------------------------------------
--- Place multiple widgets in multiple rows and columns.
--
-- Widgets spanning several columns or rows cannot be included using the
-- declarative system.
-- Instead, create the grid layout and call the `add_widget_at` method.
--
--@DOC_wibox_layout_grid_imperative_EXAMPLE@
--
-- Using the declarative system, widgets are automatically added next to each
-- other spanning only one cell.
--
--@DOC_wibox_layout_defaults_grid_EXAMPLE@
-- @author getzze
-- @copyright 2017 getzze
-- @layoutmod wibox.layout.grid
-- @supermodule wibox.widget.base
---------------------------------------------------------------------------
local setmetatable = setmetatable
local unpack = unpack or table.unpack -- luacheck: globals unpack (compatibility with Lua 5.1)
local table = table
local pairs = pairs
local ipairs = ipairs
local math = math
local gtable = require("gears.table")
local base = require("wibox.widget.base")
local grid = { mt = {} }
local properties = {
"orientation", "superpose",
"forced_num_rows", "forced_num_cols",
"min_cols_size", "min_rows_size",
}
local dir_properties = { "spacing", "homogeneous", "expand" }
--- Set the preferred orientation of the grid layout.
--
-- When calling `get_next_empty`, empty cells are browsed differently.
--
--@DOC_wibox_layout_grid_orientation_EXAMPLE@
-- @tparam[opt="vertical"] string orientation Preferred orientation.
-- @propertyvalue "horizontal" The grid can be extended horizontally. The current
-- column is filled first; if no empty cell is found up to `forced_num_rows`,
-- the next column is filled, creating it if it does not exist.
-- @propertyvalue "vertical" The grid can be extended vertically. The current row is
-- filled first; if no empty cell is found up to `forced_num_cols`, the next
-- row is filled, creating it if it does not exist.
-- @property orientation
--- Allow to superpose widgets in the same cell.
-- If false, check before adding a new widget if it will superpose with another
-- widget and prevent from adding it.
--
--@DOC_wibox_layout_grid_superpose_EXAMPLE@
-- @tparam[opt=false] boolean superpose
-- @property superpose
--- Force the number of rows of the layout.
-- @property forced_num_rows
-- @tparam[opt=nil] number|nil forced_num_rows
-- @propertytype nil Automatically determine the number of rows.
-- @propertyunit rows
-- @negativeallowed false
-- @see forced_num_cols
--- Force the number of columns of the layout.
-- @property forced_num_cols
-- @tparam[opt=nil] number|nil forced_num_cols
-- @propertytype nil Automatically determine the number of columns.'
-- @propertyunit columns
-- @negativeallowed false
-- @see forced_num_rows
--- Set the minimum size for the columns.
--
--@DOC_wibox_layout_grid_min_size_EXAMPLE@
-- @tparam[opt=0] number min_cols_size Minimum size of the columns.
-- @property min_cols_size
-- @propertyunit pixel
-- @negativeallowed false
-- @see min_rows_size
--- Set the minimum size for the rows.
-- @tparam[opt=0] number min_rows_size Minimum size of the rows.
-- @property min_rows_size
-- @propertyunit pixel
-- @negativeallowed false
-- @see min_cols_size
--- The spacing between columns.
--
-- @tparam[opt=0] number horizontal_spacing
-- @property horizontal_spacing
-- @propertyunit pixel
-- @negativeallowed false
-- @see spacing
-- @see vertical_spacing
--- The spacing between rows.
--
-- @tparam[opt=0] number vertical_spacing
-- @property vertical_spacing
-- @propertyunit pixel
-- @negativeallowed false
-- @see spacing
-- @see horizontal_spacing
--- The spacing between rows and columns.
--
-- Get the value `horizontal_spacing` or `vertical_spacing` defined by the
-- preferred `orientation`.
--
--@DOC_wibox_layout_grid_spacing_EXAMPLE@
-- @tparam[opt=0] number spacing
-- @property spacing
-- @negativeallowed false
-- @see vertical_spacing
-- @see horizontal_spacing
--- Controls if the columns are expanded to use all the available width.
--
-- @tparam[opt=false] boolean horizontal_expand Expand the grid into the available space
-- @property horizontal_expand
-- @see expand
-- @see vertical_expand
--- Controls if the rows are expanded to use all the available height.
--
-- @tparam[opt=false] boolean vertical_expand Expand the grid into the available space
-- @property vertical_expand
-- @see expand
-- @see horizontal_expand
--- Controls if the columns/rows are expanded to use all the available space.
--
-- Get the value `horizontal_expand` or `vertical_expand` defined by the
-- preferred `orientation`.
--
--@DOC_wibox_layout_grid_expand_EXAMPLE@
-- @tparam[opt=false] boolean expand Expand the grid into the available space
-- @property expand
-- @see horizontal_expand
-- @see vertical_expand
--- Controls if the columns all have the same width or if the width of each
-- column depends on the content.
--
-- see `homogeneous`
--
-- @tparam[opt=true] boolean horizontal_homogeneous All the columns have the same width.
-- @property horizontal_homogeneous
-- @see vertical_homogeneous
-- @see homogeneous
--- Controls if the rows all have the same height or if the height of each row
-- depends on the content.
--
-- see `homogeneous`
--
-- @tparam[opt=true] boolean vertical_homogeneous All the rows have the same height.
-- @property vertical_homogeneous
-- @see homogeneous
-- @see horizontal_homogeneous
--- Controls if the columns/rows all have the same size or if the size depends
-- on the content.
-- Set both `horizontal_homogeneous` and `vertical_homogeneous` to the same value.
-- Get the value `horizontal_homogeneous` or `vertical_homogeneous` defined
-- by the preferred `orientation`.
--
--@DOC_wibox_layout_grid_expand_EXAMPLE@
-- @tparam[opt=true] boolean homogeneous All the columns/rows have the same size.
-- @property homogeneous
-- @see vertical_homogeneous
-- @see horizontal_homogeneous
--- Child widget position. Return of `get_widget_position`.
-- @field row Top row index
-- @field col Left column index
-- @field row_span Number of rows to span
-- @field col_span Number of columns to span
-- @table position
-- Return the maximum value of a table.
local function max_value(t)
local m = 0
for _,v in ipairs(t) do
if m < v then m = v end
end
return m
end
-- Return the sum of the values in the table.
local function sum_values(t)
local m = 0
for _,v in ipairs(t) do
m = m + v
end
return m
end
-- Find a widget in a widget_table, by matching the coordinates.
-- Using the `row`:`col` coordinates, and the spans `row_span` and `col_span`
-- @tparam table widgets_table Table of the widgets present in the grid
-- @tparam number row Row number for the top left corner of the widget
-- @tparam number col Column number for the top left corner of the widget
-- @tparam number row_span The number of rows the widget spans (default to 1)
-- @tparam number col_span The number of columns the widget spans (default to 1)
-- @treturn table Table of index of widget_table
local function find_widgets_at(widgets_table, row, col, row_span, col_span)
if not row or row < 1 or not col or col < 1 then return nil end
row_span = (row_span and row_span > 0) and row_span or 1
col_span = (col_span and col_span > 0) and col_span or 1
local ret = {}
for index, data in ipairs(widgets_table) do
-- If one rectangular widget is on left side of other
local test_horizontal = not (row > data.row + data.row_span - 1
or data.row > row + row_span - 1)
-- If one rectangular widget is above other
local test_vertical = not (col > data.col + data.col_span - 1
or data.col > col + col_span - 1)
if test_horizontal and test_vertical then
table.insert(ret, index)
end
end
-- reverse sort for safe removal of indices
table.sort(ret, function(a,b) return a>b end)
return #ret > 0 and ret or nil
end
-- Find a widget in a widget_table, by matching the object.
-- @tparam table widgets_table Table of the widgets present in the grid
-- @param widget The widget to find
-- @treturn number|nil The index of the widget in widget_table, `nil` if not found
local function find_widget(widgets_table, widget)
for index, data in ipairs(widgets_table) do
if data.widget == widget then
return index
end
end
return nil
end
--- Get the number of rows and columns occupied by the widgets in the grid.
-- @method get_dimension
-- @treturn number,number The number of rows and columns
function grid:get_dimension()
return self._private.num_rows, self._private.num_cols
end
-- Update the number of rows and columns occupied by the widgets in the grid.
local function update_dimension(self)
local num_rows, num_cols = 0, 0
if self._private.forced_num_rows then
num_rows = self._private.forced_num_rows
end
if self._private.forced_num_cols then
num_cols = self._private.forced_num_cols
end
for _, data in ipairs(self._private.widgets) do
num_rows = math.max(num_rows, data.row + data.row_span - 1)
num_cols = math.max(num_cols, data.col + data.col_span - 1)
end
self._private.num_rows = num_rows
self._private.num_cols = num_cols
end
--- Find the next available cell to insert a widget.
-- The grid is browsed according to the `orientation`.
-- @method get_next_empty
-- @tparam[opt=1] number hint_row The row coordinate of the last occupied cell.
-- @tparam[opt=1] number hint_column The column coordinate of the last occupied cell.
-- @return number,number The row,column coordinate of the next empty cell
function grid:get_next_empty(hint_row, hint_column)
local row = (hint_row and hint_row > 0) and hint_row or 1
local column = (hint_column and hint_column > 0) and hint_column or 1
local next_field
if self._private.orientation == "vertical" then
next_field = function(x, y)
if y < self._private.num_cols then
return x, y+1
end
return x+1,1
end
elseif self._private.orientation == "horizontal" then
next_field = function(x, y)
if x < self._private.num_rows then
return x+1, y
end
return 1,y+1
end
end
while true do
if find_widgets_at(self._private.widgets, row, column, 1, 1) == nil then
return row, column
end
row, column = next_field(row, column)
end
end
--- Add some widgets to the given grid layout.
--
-- The widgets are assumed to span one cell.
--
-- @method add
-- @tparam wibox.widget ... Widgets that should be added (must at least be one)
-- @interface layout
-- @noreturn
function grid:add(...)
local args = { n=select('#', ...), ... }
assert(args.n > 0, "need at least one widget to add")
local row, column
for i=1, args.n do
-- Get the next empty coordinate to insert the widget
row, column = self:get_next_empty(row, column)
self:add_widget_at(args[i], row, column, 1, 1)
end
end
--- Add a widget to the grid layout at specific coordinate.
--
--@DOC_wibox_layout_grid_add_EXAMPLE@
--
-- @method add_widget_at
-- @tparam wibox.widget child Widget that should be added
-- @tparam number row Row number for the top left corner of the widget
-- @tparam number col Column number for the top left corner of the widget
-- @tparam[opt=1] number row_span The number of rows the widget spans.
-- @tparam[opt=1] number col_span The number of columns the widget spans.
-- @treturn boolean index If the operation is successful
function grid:add_widget_at(child, row, col, row_span, col_span)
if not row or row < 1 or not col or col < 1 then return false end
row_span = (row_span and row_span > 0) and row_span or 1
col_span = (col_span and col_span > 0) and col_span or 1
-- check if the object is a widget
child = base.make_widget_from_value(child)
base.check_widget(child)
-- test if the new widget superpose with existing ones
local superpose = find_widgets_at(
self._private.widgets, row, col, row_span, col_span
)
if not self._private.superpose and superpose then
return false
end
-- Add grid information attached to the widget
local child_data = {
widget = child,
row = row,
col = col,
row_span = row_span,
col_span = col_span
}
table.insert(self._private.widgets, child_data)
-- Update the row and column numbers
self._private.num_rows = math.max(self._private.num_rows, row + row_span - 1)
self._private.num_cols = math.max(self._private.num_cols, col + col_span - 1)
self:emit_signal("widget::layout_changed")
self:emit_signal("widget::redraw_needed")
return true
end
--- Remove one or more widgets from the layout.
-- @method remove
-- @param ... Widgets that should be removed (must at least be one)
-- @treturn boolean If the operation is successful
function grid:remove(...)
local args = { ... }
local ret = false
for _, rem_widget in ipairs(args) do
local index = find_widget(self._private.widgets, rem_widget)
if index ~= nil then
table.remove(self._private.widgets, index)
ret = true
end
end
if ret then
-- Recalculate num_rows and num_cols
update_dimension(self)
self:emit_signal("widget::layout_changed")
self:emit_signal("widget::redraw_needed")
end
return ret
end
--- Remove widgets at the coordinates.
--
--@DOC_wibox_layout_grid_remove_EXAMPLE@
--
-- @method remove_widgets_at
-- @tparam number row The row coordinate of the widget to remove
-- @tparam number col The column coordinate of the widget to remove
-- @tparam[opt=1] number row_span The number of rows the area to remove spans.
-- @tparam[opt=1] number col_span The number of columns the area to remove spans.
-- @treturn boolean If the operation is successful (widgets found)
function grid:remove_widgets_at(row, col, row_span, col_span)
local widget_indices = find_widgets_at(
self._private.widgets, row, col, row_span, col_span
)
if widget_indices == nil then return false end
for _,index in ipairs(widget_indices) do
table.remove(self._private.widgets, index)
end
-- Recalculate num_rows and num_cols
update_dimension(self)
self:emit_signal("widget::layout_changed")
self:emit_signal("widget::redraw_needed")
return true
end
--- Return the coordinates of the widget.
-- @method get_widget_position
-- @tparam widget widget The widget
-- @treturn table The `position` table of the coordinates in the grid, with
-- fields `row`, `col`, `row_span` and `col_span`.
function grid:get_widget_position(widget)
local index = find_widget(self._private.widgets, widget)
if index == nil then return nil end
local data = self._private.widgets[index]
local ret = {}
ret["row"] = data.row
ret["col"] = data.col
ret["row_span"] = data.row_span
ret["col_span"] = data.col_span
return ret
end
--- Return the widgets at the coordinates.
-- @method get_widgets_at
-- @tparam number row The row coordinate of the widget
-- @tparam number col The column coordinate of the widget
-- @tparam[opt=1] number row_span The number of rows to span.
-- @tparam[opt=1] number col_span The number of columns to span.
-- @treturn table The widget(s) found at the specific coordinates, nil if no widgets found
function grid:get_widgets_at(row, col, row_span, col_span)
local widget_indices = find_widgets_at(
self._private.widgets, row, col, row_span, col_span
)
if widget_indices == nil then return nil end
local ret = {}
for _,index in ipairs(widget_indices) do
local data = self._private.widgets[index]
table.insert(ret, data.widget)
end
return #ret > 0 and ret or nil
end
--- Replace old widget by new widget, spanning the same columns and rows.
-- @method replace_widget
-- @tparam widget old The widget to remove
-- @tparam widget new The widget to add
-- @treturn boolean If the operation is successful (widget found)
function grid:replace_widget(old, new)
-- check if the new object is a widget
local status = pcall(function () base.check_widget(new) end)
if not status then return false end
-- find the old widget
local index = find_widget(self._private.widgets, old)
if index == nil then return false end
-- get old widget position
local data = self._private.widgets[index]
local row, col, row_span, col_span = data.row, data.col, data.row_span, data.col_span
table.remove(self._private.widgets, index)
return self:add_widget_at(new, row, col, row_span, col_span)
end
-- Update position of the widgets when inserting, adding or removing a row or a column.
-- @tparam table table_widgets Table of widgets
-- @tparam string orientation Orientation of the line: "horizontal" -> column, "vertical" -> row
-- @tparam number index Index of the line
-- @tparam string mode insert, extend or remove
-- @tparam boolean after Add the line after the index instead of inserting it before.
-- @tparam boolean extend Extend the line at index instead of inserting an empty line.
local function update_widgets_position(table_widgets, orientation, index, mode)
local t = orientation == "horizontal" and "col" or "row"
local to_remove = {}
-- inc : Index increment or decrement
-- first : Offset index for top-left cell of the widgets to shift
-- last : Offset index for bottom-right cell of the widgets to resize
local inc, first, last
if mode == "remove" then
inc, first, last = -1, 1, 1
elseif mode == "insert" then
inc, first, last = 1, 0, 0
elseif mode == "extend" then
inc, first, last = 1, 1, 0
else
return
end
for i, data in ipairs(table_widgets) do
-- single widget in the line
if mode == "remove" and data[t] == index and data[t .. "_span"] == 1 then
table.insert(to_remove, i)
-- widgets to shift
elseif data[t] >= index + first then
data[t] = data[t] + inc
-- widgets to resize
elseif data[t] + data[t .. "_span"] - 1 >= index + last then
data[t .. "_span"] = data[t .. "_span"] + inc
end
end
if mode == "remove" then
-- reverse sort to remove
table.sort(to_remove, function(a,b) return a>b end)
-- Remove widgets
for _,i in ipairs(to_remove) do
table.remove(table_widgets, i)
end
end
end
--- Insert column at index.
--
--@DOC_wibox_layout_grid_insert_column_EXAMPLE@
--
-- @method insert_column
-- @tparam number|nil index Insert the new column at index. If `nil`, the column is added at the end.
-- @treturn number The index of the inserted column
function grid:insert_column(index)
if index == nil or index > self._private.num_cols + 1 or index < 1 then
index = self._private.num_cols + 1
end
-- Update widget positions
update_widgets_position(self._private.widgets, "horizontal", index, "insert")
-- Recalculate number of rows and columns
self._private.num_cols = self._private.num_cols + 1
return index
end
--- Extend column at index.
--@DOC_wibox_layout_grid_extend_column_EXAMPLE@
--
-- @method extend_column
-- @tparam number|nil index Extend the column at index. If `nil`, the last column is extended.
-- @treturn number The index of the extended column
function grid:extend_column(index)
if index == nil or index > self._private.num_cols or index < 1 then
index = self._private.num_cols
end
-- Update widget positions
update_widgets_position(self._private.widgets, "horizontal", index, "extend")
-- Recalculate number of rows and columns
self._private.num_cols = self._private.num_cols + 1
return index
end
--- Remove column at index.
--
--@DOC_wibox_layout_grid_remove_column_EXAMPLE@
--
-- @method remove_column
-- @tparam number|nil index Remove column at index. If `nil`, the last column is removed.
-- @treturn number The index of the removed column
function grid:remove_column(index)
if index == nil or index > self._private.num_cols or index < 1 then
index = self._private.num_cols
end
-- Update widget positions
update_widgets_position(self._private.widgets, "horizontal", index, "remove")
-- Recalculate number of rows and columns
update_dimension(self)
return index
end
--- Insert row at index.
--
-- see `insert_column`
--
-- @method insert_row
-- @tparam number|nil index Insert the new row at index. If `nil`, the row is added at the end.
-- @treturn number The index of the inserted row
function grid:insert_row(index)
if index == nil or index > self._private.num_rows + 1 or index < 1 then
index = self._private.num_rows + 1
end
-- Update widget positions
update_widgets_position(self._private.widgets, "vertical", index, "insert")
-- Recalculate number of rows and columns
self._private.num_rows = self._private.num_rows + 1
return index
end
--- Extend row at index.
--
-- see `extend_column`
--
-- @method extend_row
-- @tparam number|nil index Extend the row at index. If `nil`, the last row is extended.
-- @treturn number The index of the extended row
function grid:extend_row(index)
if index == nil or index > self._private.num_rows or index < 1 then
index = self._private.num_rows
end
-- Update widget positions
update_widgets_position(self._private.widgets, "vertical", index, "extend")
-- Recalculate number of rows and columns
self._private.num_rows = self._private.num_rows + 1
return index
end
--- Remove row at index.
--
-- see `remove_column`
--
-- @method remove_row
-- @tparam number|nil index Remove row at index. If `nil`, the last row is removed.
-- @treturn number The index of the removed row
function grid:remove_row(index)
if index == nil or index > self._private.num_rows or index < 1 then
index = self._private.num_rows
end
-- Update widget positions
update_widgets_position(self._private.widgets, "vertical", index, "remove")
-- Recalculate number of rows and columns
update_dimension(self)
return index
end
-- Return list of children
function grid:get_children()
local ret = {}
for _, data in ipairs(self._private.widgets) do
table.insert(ret, data.widget)
end
return ret
end
-- Add list of children to the layout.
function grid:set_children(children)
self:reset()
if #children > 0 then
self:add(unpack(children))
end
end
-- Set the preferred orientation of the grid layout.
function grid:set_orientation(val)
if self._private.orientation ~= val and (val == "horizontal" or val == "vertical") then
self._private.orientation = val
end
end
-- Set the minimum size for the columns.
function grid:set_min_cols_size(val)
if self._private.min_cols_size ~= val and val >= 0 then
self._private.min_cols_size = val
end
end
-- Set the minimum size for the rows.
function grid:set_min_rows_size(val)
if self._private.min_rows_size ~= val and val >= 0 then
self._private.min_rows_size = val
end
end
-- Force the number of columns of the layout.
function grid:set_forced_num_cols(val)
if self._private.forced_num_cols ~= val then
self._private.forced_num_cols = val
update_dimension(self)
self:emit_signal("widget::layout_changed")
end
end
-- Force the number of rows of the layout.
function grid:set_forced_num_rows(val)
if self._private.forced_num_rows ~= val then
self._private.forced_num_rows = val
update_dimension(self)
self:emit_signal("widget::layout_changed")
end
end
-- Set the grid properties
for _, prop in ipairs(properties) do
if not grid["set_" .. prop] then
grid["set_"..prop] = function(self, value)
if self._private[prop] ~= value then
self._private[prop] = value
self:emit_signal("widget::layout_changed")
end
end
end
if not grid["get_" .. prop] then
grid["get_"..prop] = function(self)
return self._private[prop]
end
end
end
-- Set the directional grid properties
-- create a couple of properties by prepending `horizontal_` and `vertical_`
-- create a common property for the two directions:
-- setting the common property sets both directional properties
-- getting the common property returns the directional property
-- defined by the `orientation` property
for _, prop in ipairs(dir_properties) do
for _,dir in ipairs{"horizontal", "vertical"} do
local dir_prop = dir .. "_" .. prop
grid["set_"..dir_prop] = function(self, value)
if self._private[dir_prop] ~= value then
self._private[dir_prop] = value
self:emit_signal("widget::layout_changed")
end
end
grid["get_"..dir_prop] = function(self)
return self._private[dir_prop]
end
end
-- Non-directional options
grid["set_"..prop] = function(self, value)
if self._private["horizontal_"..prop] ~= value or self._private["vertical_"..prop] ~= value then
self._private["horizontal_"..prop] = value
self._private["vertical_"..prop] = value
self:emit_signal("widget::layout_changed")
end
end
grid["get_"..prop] = function(self)
return self._private[self._private.orientation .. "_" .. prop]
end
end
-- Return two tables of the fitted sizes of the rows and columns
-- @treturn table,table Tables of row heights and column widths
local function get_grid_sizes(self, context, orig_width, orig_height)
local rows_size = {}
local cols_size = {}
-- Set the row and column sizes to the minimum value
for i = 1,self._private.num_rows do
rows_size[i] = self._private.min_rows_size
end
for j = 1,self._private.num_cols do
cols_size[j] = self._private.min_cols_size
end
-- Calculate cell sizes
for _, data in ipairs(self._private.widgets) do
local w, h = base.fit_widget(self, context, data.widget, orig_width, orig_height)
h = math.max( self._private.min_rows_size, h / data.row_span )
w = math.max( self._private.min_cols_size, w / data.col_span )
-- update the row and column maximum size
for i = data.row, data.row + data.row_span - 1 do
if h > rows_size[i] then rows_size[i] = h end
end
for j = data.col, data.col + data.col_span - 1 do
if w > cols_size[j] then cols_size[j] = w end
end
end
return rows_size, cols_size
end
-- Fit the grid layout into the given space.
-- @param context The context in which we are fit.
-- @param orig_width The available width.
-- @param orig_height The available height.
function grid:fit(context, orig_width, orig_height)
local width, height = orig_width, orig_height
-- Calculate the space needed
local function fit_direction(dir, sizes)
local m = 0
if self._private[dir .. "_homogeneous"] then
-- all the columns/rows have the same size
m = #sizes * max_value(sizes) + (#sizes - 1) * self._private[dir .. "_spacing"]
else
-- sum the columns/rows size
for _,s in ipairs(sizes) do
m = m + s + self._private[dir .. "_spacing"]
end
m = m - self._private[dir .. "_spacing"]
end
return m
end
-- fit matrix cells
local rows_size, cols_size = get_grid_sizes(self, context, width, height)
-- compute the width
local used_width_max = fit_direction("horizontal", cols_size)
local used_height_max = fit_direction("vertical", rows_size)
return used_width_max, used_height_max
end
-- Layout a grid layout.
-- @param context The context in which we are drawn.
-- @param width The available width.
-- @param height The available height.
function grid:layout(context, width, height)
local result = {}
local hspacing, vspacing = self._private.horizontal_spacing, self._private.vertical_spacing
-- Fit matrix cells
local rows_size, cols_size = get_grid_sizes(self, context, width, height)
local total_expected_width, total_expected_height = sum_values(cols_size), sum_values(rows_size)
-- Figure out the maximum size we can give out to sub-widgets
local single_width, single_height = max_value(cols_size), max_value(rows_size)
if self._private.horizontal_expand then
single_width = (width - (self._private.num_cols-1)*hspacing) / self._private.num_cols
end
if self._private.vertical_expand then
single_height = (height - (self._private.num_rows-1)*vspacing) / self._private.num_rows
end
-- Calculate the position and size to place the widgets
local cumul_width, cumul_height = {}, {}
local cw, ch = 0, 0
for j = 1, #cols_size do
cumul_width[j] = cw
if self._private.horizontal_homogeneous then
cols_size[j] = math.max(self._private.min_cols_size, single_width)
elseif self._private.horizontal_expand then
local hpercent = self._private.num_cols * single_width * cols_size[j] / total_expected_width
cols_size[j] = math.max(self._private.min_cols_size, hpercent)
end
cw = cw + cols_size[j] + hspacing
end
cumul_width[#cols_size + 1] = cw
for i = 1, #rows_size do
cumul_height[i] = ch
if self._private.vertical_homogeneous then
rows_size[i] = math.max(self._private.min_rows_size, single_height)
elseif self._private.vertical_expand then
local vpercent = self._private.num_rows * single_height * rows_size[i] / total_expected_height
rows_size[i] = math.max(self._private.min_rows_size, vpercent)
end
ch = ch + rows_size[i] + vspacing
end
cumul_height[#rows_size + 1] = ch
-- Place widgets
local fill_space = true -- should be fill_space property?
for _, v in pairs(self._private.widgets) do
local x, y, w, h
-- Round numbers to avoid decimals error, force to place tight widgets
-- and avoid redraw glitches
x = math.floor(cumul_width[v.col])
y = math.floor(cumul_height[v.row])
w = math.floor(cumul_width[v.col + v.col_span] - hspacing - x)
h = math.floor(cumul_height[v.row + v.row_span] - vspacing - y)
-- Recalculate the width so the last widget fits
if (fill_space or self._private.horizontal_expand) and x + w > width then
w = math.floor(math.max(self._private.min_cols_size, width - x))
end
-- Recalculate the height so the last widget fits
if (fill_space or self._private.vertical_expand) and y + h > height then
h = math.floor(math.max(self._private.min_rows_size, height - y))
end
-- Place the widget if it fits in the area
if x + w <= width and y + h <= height then
table.insert(result, base.place_widget_at(v.widget, x, y, w, h))
end
end
return result
end
--- Reset the grid layout.
-- Remove all widgets and reset row and column counts
--
-- @method reset
-- @emits reset
-- @noreturn
function grid:reset()
self._private.widgets = {}
-- reset the number of columns and rows to the forced value or to 0
self._private.num_rows = self._private.forced_num_rows ~= nil
and self._private.forced_num_rows or 0
self._private.num_cols = self._private.forced_num_cols ~= nil
and self._private.forced_num_cols or 0
-- emit signals
self:emit_signal("widget::layout_changed")
self:emit_signal("widget::reset")
end
--- When the layout is reset.
-- This signal is emitted when the layout has been reset,
-- all the widgets removed and the row and column counts reset.
-- @signal widget::reset
--- Return a new grid layout.
--
-- A grid layout sets widgets in a grids of custom number of rows and columns.
-- @tparam[opt="y"] string orientation The preferred grid extension direction.
-- @constructorfct wibox.layout.grid
local function new(orientation)
-- Preference for vertical direction: fill rows first, extend grid with new row
local dir = (orientation == "horizontal"or orientation == "vertical")
and orientation or "vertical"
local ret = base.make_widget(nil, nil, {enable_properties = true})
gtable.crush(ret, grid, true)
ret._private.orientation = dir
ret._private.widgets = {}
ret._private.num_rows = 0
ret._private.num_cols = 0
ret._private.rows_size = {}
ret._private.cols_size = {}
ret._private.superpose = false
ret._private.forced_num_rows = nil
ret._private.forced_num_cols = nil
ret._private.min_rows_size = 0
ret._private.min_cols_size = 0
ret._private.horizontal_homogeneous = true
ret._private.vertical_homogeneous = true
ret._private.horizontal_expand = false
ret._private.vertical_expand = false
ret._private.horizontal_spacing = 0
ret._private.vertical_spacing = 0
return ret
end
--- Return a new horizontal grid layout.
--
-- Each new widget is positioned below the last widget on the same column
-- up to `forced_num_rows`. Then the next column is filled, creating it if it doesn't exist.
-- @tparam number|nil forced_num_rows Forced number of rows (`nil` for automatic).
-- @tparam widget ... Widgets that should be added to the layout.
-- @constructorfct wibox.layout.grid.horizontal
function grid.horizontal(forced_num_rows, widget, ...)
local ret = new("horizontal")
ret:set_forced_num_rows(forced_num_rows)
if widget then
ret:add(widget, ...)
end
return ret
end
--- Return a new vertical grid layout.
--
-- Each new widget is positioned left of the last widget on the same row
-- up to `forced_num_cols`. Then the next row is filled, creating it if it doesn't exist.
-- @tparam number|nil forced_num_cols Forced number of columns (`nil` for automatic).
-- @tparam widget ... Widgets that should be added to the layout.
-- @constructorfct wibox.layout.grid.vertical
function grid.vertical(forced_num_cols, widget, ...)
local ret = new("vertical")
ret:set_forced_num_cols(forced_num_cols)
if widget then
ret:add(widget, ...)
end
return ret
end
function grid.mt:__call(...)
return new(...)
end
--@DOC_fixed_COMMON@
return setmetatable(grid, grid.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
bnetcc/darkstar | scripts/zones/Southern_San_dOria/npcs/Simmie.lua | 5 | 1084 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Simmie
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Southern_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
local count = trade:getItemCount();
local MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
player:startEvent(673);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
bnetcc/darkstar | scripts/globals/magic.lua | 1 | 52800 |
require("scripts/globals/magicburst");
require("scripts/globals/settings");
require("scripts/globals/weather");
require("scripts/globals/status");
require("scripts/globals/utils");
require("scripts/globals/msg");
DIVINE_MAGIC_SKILL = 32;
HEALING_MAGIC_SKILL = 33;
ENHANCING_MAGIC_SKILL = 34;
ENFEEBLING_MAGIC_SKILL = 35;
ELEMENTAL_MAGIC_SKILL = 36;
DARK_MAGIC_SKILL = 37;
NINJUTSU_SKILL = 39;
SUMMONING_SKILL = 38;
SINGING_SKILL = 40;
STRING_SKILL = 41;
WIND_SKILL = 42;
BLUE_SKILL = 43;
FIRESDAY = 0;
EARTHSDAY = 1;
WATERSDAY = 2;
WINDSDAY = 3;
ICEDAY = 4;
LIGHTNINGDAY = 5;
LIGHTSDAY = 6;
DARKSDAY = 7;
ELE_NONE = 0;
ELE_FIRE = 1;
ELE_EARTH = 2;
ELE_WATER = 3;
ELE_WIND = 4;
ELE_ICE = 5;
ELE_LIGHTNING = 6;
-- added both because monsterstpmoves calls it thunder
ELE_THUNDER = 6;
ELE_LIGHT = 7;
ELE_DARK = 8;
dayStrong = {FIRESDAY, EARTHSDAY, WATERSDAY, WINDSDAY, ICEDAY, LIGHTNINGDAY, LIGHTSDAY, DARKSDAY};
dayWeak = {WATERSDAY, WINDSDAY, LIGHTNINGDAY, ICEDAY, FIRESDAY, EARTHSDAY, DARKSDAY, LIGHTSDAY};
singleWeatherStrong = {WEATHER_HOT_SPELL, WEATHER_DUST_STORM, WEATHER_RAIN, WEATHER_WIND, WEATHER_SNOW, WEATHER_THUNDER, WEATHER_AURORAS, WEATHER_GLOOM};
doubleWeatherStrong = {WEATHER_HEAT_WAVE, WEATHER_SAND_STORM, WEATHER_SQUALL, WEATHER_GALES, WEATHER_BLIZZARDS, WEATHER_THUNDERSTORMS, WEATHER_STELLAR_GLARE, WEATHER_DARKNESS};
singleWeatherWeak = {WEATHER_RAIN, WEATHER_WIND, WEATHER_THUNDER, WEATHER_SNOW, WEATHER_HOT_SPELL, WEATHER_DUST_STORM, WEATHER_GLOOM, WEATHER_AURORAS};
doubleWeatherWeak = {WEATHER_SQUALL, WEATHER_GALES, WEATHER_THUNDERSTORMS, WEATHER_BLIZZARDS, WEATHER_HEAT_WAVE, WEATHER_SAND_STORM, WEATHER_DARKNESS, WEATHER_STELLAR_GLARE};
elementalObi = {MOD_FORCE_FIRE_DWBONUS, MOD_FORCE_EARTH_DWBONUS, MOD_FORCE_WATER_DWBONUS, MOD_FORCE_WIND_DWBONUS, MOD_FORCE_ICE_DWBONUS, MOD_FORCE_LIGHTNING_DWBONUS, MOD_FORCE_LIGHT_DWBONUS, MOD_FORCE_DARK_DWBONUS};
elementalObiWeak = {MOD_FORCE_WATER_DWBONUS, MOD_FORCE_WIND_DWBONUS, MOD_FORCE_LIGHTNING_DWBONUS, MOD_FORCE_ICE_DWBONUS, MOD_FORCE_FIRE_DWBONUS, MOD_FORCE_EARTH_DWBONUS, MOD_FORCE_DARK_DWBONUS, MOD_FORCE_LIGHT_DWBONUS};
spellAcc = {MOD_FIREACC, MOD_EARTHACC, MOD_WATERACC, MOD_WINDACC, MOD_ICEACC, MOD_THUNDERACC, MOD_LIGHTACC, MOD_DARKACC};
strongAffinityDmg = {MOD_FIRE_AFFINITY_DMG, MOD_EARTH_AFFINITY_DMG, MOD_WATER_AFFINITY_DMG, MOD_WIND_AFFINITY_DMG, MOD_ICE_AFFINITY_DMG, MOD_THUNDER_AFFINITY_DMG, MOD_LIGHT_AFFINITY_DMG, MOD_DARK_AFFINITY_DMG};
strongAffinityAcc = {MOD_FIRE_AFFINITY_ACC, MOD_EARTH_AFFINITY_ACC, MOD_WATER_AFFINITY_ACC, MOD_WIND_AFFINITY_ACC, MOD_ICE_AFFINITY_ACC, MOD_THUNDER_AFFINITY_ACC, MOD_LIGHT_AFFINITY_ACC, MOD_DARK_AFFINITY_ACC};
resistMod = {MOD_FIRERES, MOD_EARTHRES, MOD_WATERRES, MOD_WINDRES, MOD_ICERES, MOD_THUNDERRES, MOD_LIGHTRES, MOD_DARKRES};
defenseMod = {MOD_FIREDEF, MOD_EARTHDEF, MOD_WATERDEF, MOD_WINDDEF, MOD_ICEDEF, MOD_THUNDERDEF, MOD_LIGHTDEF, MOD_DARKDEF};
absorbMod = {MOD_FIRE_ABSORB, MOD_EARTH_ABSORB, MOD_WATER_ABSORB, MOD_WIND_ABSORB, MOD_ICE_ABSORB, MOD_LTNG_ABSORB, MOD_LIGHT_ABSORB, MOD_DARK_ABSORB};
nullMod = {MOD_FIRE_NULL, MOD_EARTH_NULL, MOD_WATER_NULL, MOD_WIND_NULL, MOD_ICE_NULL, MOD_LTNG_NULL, MOD_LIGHT_NULL, MOD_DARK_NULL};
blmMerit = {MERIT_FIRE_MAGIC_POTENCY, MERIT_EARTH_MAGIC_POTENCY, MERIT_WATER_MAGIC_POTENCY, MERIT_WIND_MAGIC_POTENCY, MERIT_ICE_MAGIC_POTENCY, MERIT_LIGHTNING_MAGIC_POTENCY};
rdmMerit = {MERIT_FIRE_MAGIC_ACCURACY, MERIT_EARTH_MAGIC_ACCURACY, MERIT_WATER_MAGIC_ACCURACY, MERIT_WIND_MAGIC_ACCURACY, MERIT_ICE_MAGIC_ACCURACY, MERIT_LIGHTNING_MAGIC_ACCURACY};
blmAMIIMerit = {MERIT_FLARE_II, MERIT_QUAKE_II, MERIT_FLOOD_II, MERIT_TORNADO_II, MERIT_FREEZE_II, MERIT_BURST_II};
barSpells = {EFFECT_BARFIRE, EFFECT_BARSTONE, EFFECT_BARWATER, EFFECT_BARAERO, EFFECT_BARBLIZZARD, EFFECT_BARTHUNDER};
-- USED FOR DAMAGING MAGICAL SPELLS (Stages 1 and 2 in Calculating Magic Damage on wiki)
--Calculates magic damage using the standard magic damage calc.
--Does NOT handle resistance.
-- Inputs:
-- dmg - The base damage of the spell
-- multiplier - The INT multiplier of the spell
-- skilltype - The skill ID of the spell.
-- atttype - The attribute type (usually MOD_INT , except for things like Banish which is MOD_MND)
-- hasMultipleTargetReduction - true ifdamage is reduced on AoE. False otherwise (e.g. Charged Whisker vs -ga3 spells)
--
-- Output:
-- The total damage, before resistance and before equipment (so no HQ staff bonus worked out here).
SOFT_CAP = 60; --guesstimated
HARD_CAP = 120; --guesstimated
function calculateMagicDamage(caster, target, spell, params)
local dINT = caster:getStat(params.attribute) - target:getStat(params.attribute);
local dmg = params.dmg;
if (dINT <= 0) then --if dINT penalises, it's always M=1
dmg = dmg + dINT;
if (dmg <= 0) then --dINT penalty cannot result in negative damage (target absorption)
return 0;
end
elseif (dINT > 0 and dINT <= SOFT_CAP) then --The standard calc, most spells hit this
dmg = dmg + (dINT * params.multiplier);
elseif (dINT > 0 and dINT > SOFT_CAP and dINT < HARD_CAP) then --After SOFT_CAP, INT is only half effective
dmg = dmg + SOFT_CAP * params.multiplier + ((dINT - SOFT_CAP) * params.multiplier) / 2;
elseif (dINT > 0 and dINT > SOFT_CAP and dINT >= HARD_CAP) then --After HARD_CAP, INT has no effect.
dmg = dmg + HARD_CAP * params.multiplier;
end
if (params.skillType == DIVINE_MAGIC_SKILL and target:isUndead()) then
-- 150% bonus damage
dmg = dmg * 1.5;
end
-- printf("dmg: %d dINT: %d\n", dmg, dINT);
return dmg;
end;
function doBoostGain(caster,target,spell,effect)
local duration = 300;
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
--calculate potency
local magicskill = target:getSkillLevel(ENHANCING_MAGIC_SKILL);
local potency = math.floor((magicskill - 300) / 10) + 5;
if (potency > 25) then
potency = 25;
elseif (potency < 5) then
potency = 5;
end
--printf("BOOST-GAIN: POTENCY = %d", potency);
--Only one Boost Effect can be active at once, so if the player has any we have to cancel & overwrite
local effectOverwrite = {80, 81, 82, 83, 84, 85, 86};
for i, effect in ipairs(effectOverwrite) do
--printf("BOOST-GAIN: CHECKING FOR EFFECT %d...",effect);
if (caster:hasStatusEffect(effect)) then
--printf("BOOST-GAIN: HAS EFFECT %d, DELETING...",effect);
caster:delStatusEffect(effect);
end
end
if (target:addStatusEffect(effect,potency,0,duration)) then
spell:setMsg(msgBasic.MAGIC_GAIN_EFFECT);
else
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
end
end;
function doEnspell(caster,target,spell,effect)
if (effect==EFFECT_BLOOD_WEAPON) then
target:addStatusEffect(EFFECT_BLOOD_WEAPON,1,0,30);
return;
end
local duration = 180;
if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then
duration = duration * 3;
end
--calculate potency
local magicskill = target:getSkillLevel(ENHANCING_MAGIC_SKILL);
local potency = 3 + math.floor((6*magicskill)/100);
if (magicskill>200) then
potency = 5 + math.floor((5*magicskill)/100);
end
if (target:addStatusEffect(effect,potency,0,duration)) then
spell:setMsg(msgBasic.MAGIC_GAIN_EFFECT);
else
spell:setMsg(msgBasic.MAGIC_NO_EFFECT);
end
end;
---------------------------------
-- getCurePower returns the caster's cure power
-- getCureFinal returns the final cure amount
-- Source: http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html
---------------------------------
function getCurePower(caster,isBlueMagic)
local MND = caster:getStat(MOD_MND);
local VIT = caster:getStat(MOD_VIT);
local skill = caster:getSkillLevel(HEALING_MAGIC_SKILL);
local power = math.floor(MND/2) + math.floor(VIT/4) + skill;
return power;
end;
function getCurePowerOld(caster)
local MND = caster:getStat(MOD_MND);
local VIT = caster:getStat(MOD_VIT);
local skill = caster:getSkillLevel(HEALING_MAGIC_SKILL); -- it's healing magic skill for the BLU cures as well
local power = ((3 * MND) + VIT + (3 * math.floor(skill/5)));
return power;
end;
function getBaseCure(power,divisor,constant,basepower)
return ((power - basepower) / divisor) + constant;
end;
function getBaseCureOld(power,divisor,constant)
return (power / 2) / divisor + constant;
end;
function getCureFinal(caster,spell,basecure,minCure,isBlueMagic)
if (basecure < minCure) then
basecure = minCure;
end
local potency = 1 + (caster:getMod(MOD_CURE_POTENCY) / 100);
if (potency > 1.5) then
potency = 1.5;
end
local dSeal = 1;
if (caster:hasStatusEffect(EFFECT_DIVINE_SEAL)) then
dSeal = 2;
end
local rapture = 1;
if (isBlueMagic == false) then --rapture doesn't affect BLU cures as they're not white magic
if (caster:hasStatusEffect(EFFECT_RAPTURE)) then
rapture = 1.5 + caster:getMod(MOD_RAPTURE_AMOUNT)/100;
caster:delStatusEffectSilent(EFFECT_RAPTURE);
end
end
local dayWeatherBonus = 1;
local ele = spell:getElement();
local castersWeather = caster:getWeather();
if (castersWeather == singleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (castersWeather == singleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
elseif (castersWeather == doubleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.25;
end
elseif (castersWeather == doubleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.25;
end
end
local dayElement = VanadielDayElement();
if (dayElement == dayStrong[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (dayElement == dayWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
end
if (dayWeatherBonus > 1.4) then
dayWeatherBonus = 1.4;
end
local final = math.floor(math.floor(math.floor(math.floor(basecure) * potency) * dayWeatherBonus) * rapture) * dSeal;
return final;
end;
function getCureAsNukeFinal(caster,spell,power,divisor,constant,basepower)
return getCureFinal(caster,spell,power,divisor,constant,basepower);
end;
-----------------------------------
-- Returns the staff bonus for the caster and spell.
-----------------------------------
-- affinities that strengthen/weaken the index element
function AffinityBonusDmg(caster,ele)
local affinity = caster:getMod(strongAffinityDmg[ele]);
local bonus = 1.00 + affinity * 0.05; -- 5% per level of affinity
-- print(bonus);
return bonus;
end;
function AffinityBonusAcc(caster,ele)
local affinity = caster:getMod(strongAffinityAcc[ele]);
local bonus = 0 + affinity * 10; -- 10 acc per level of affinity
-- print(bonus);
return bonus;
end;
-- USED FOR DAMAGING MAGICAL SPELLS. Stage 3 of Calculating Magic Damage on wiki
-- Reduces damage ifit resists.
--
-- Output:
-- The factor to multiply down damage (1/2 1/4 1/8 1/16) - In this format so this func can be used for enfeebs on duration.
function applyResistance(caster, target, spell, params)
return applyResistanceEffect(caster, target, spell, params);
end;
-- USED FOR Status Effect Enfeebs (blind, slow, para, etc.)
-- Output:
-- The factor to multiply down duration (1/2 1/4 1/8 1/16)
--[[
local params = {};
params.attribute = $2;
params.skillType = $3;
params.bonus = $4;
params.effect = $5;
]]
function applyResistanceEffect(caster, target, spell, params)
local diff = params.diff or (caster:getStat(params.attribute) - target:getStat(params.attribute));
local skill = params.skillType;
local bonus = params.bonus;
local effect = params.effect;
if (math.random(1,1000) <= customResCheck(target, effect)) then return 0; end
-- If Stymie is active, as long as the mob is not immune then the effect is not resisted
if (effect ~= nil) then -- Dispel's script doesn't have an "effect" to send here, nor should it.
if (skill == ENFEEBLING_MAGIC_SKILL and caster:hasStatusEffect(EFFECT_STYMIE) and target:canGainStatusEffect(effect)) then
caster:delStatusEffect(EFFECT_STYMIE);
return 1;
end
end
if (skill == SINGING_SKILL and caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
if (math.random(0,99) < caster:getMerit(MERIT_TROUBADOUR)-25) then
return 1.0;
end
end
local element = spell:getElement();
local percentBonus = 0;
local magicaccbonus = getSpellBonusAcc(caster, target, spell);
if (diff > 10) then
magicaccbonus = magicaccbonus + 10 + (diff - 10)/2;
else
magicaccbonus = magicaccbonus + diff;
end
if (bonus ~= nil) then
magicaccbonus = magicaccbonus + bonus;
end
if (effect ~= nil) then
percentBonus = percentBonus - getEffectResistance(target, effect);
end
local p = getMagicHitRate(caster, target, skill, element, percentBonus, magicaccbonus);
return getMagicResist(p);
end;
-- Applies resistance for things that may not be spells - ie. Quick Draw
function applyResistanceAbility(player,target,element,skill,bonus)
local p = getMagicHitRate(player, target, skill, element, 0, bonus);
return getMagicResist(p);
end;
-- Applies resistance for additional effects
function applyResistanceAddEffect(player,target,element,bonus)
local p = getMagicHitRate(player, target, 0, element, 0, bonus);
return getMagicResist(p);
end;
function getMagicHitRate(caster, target, skillType, element, percentBonus, bonusAcc)
-- resist everything if magic shield is active
--[[
if (target:hasStatusEffect(EFFECT_MAGIC_SHIELD, 0)) then
return 0;
end
]]
if (target:hasStatusEffect(EFFECT_MAGIC_SHIELD)) then
if (target:getStatusEffect(EFFECT_MAGIC_SHIELD):getPower() ~= 100) then
return 0;
end
end
local magiceva = 0;
if (bonusAcc == nil) then
bonusAcc = 0;
end
local magicacc = caster:getMod(MOD_MACC) + caster:getILvlMacc();
-- Get the base acc (just skill + skill mod (79 + skillID = ModID) + magic acc mod)
if (skillType ~= 0) then
magicacc = magicacc + caster:getSkillLevel(skillType);
else
-- for mob skills / additional effects which don't have a skill
magicacc = magicacc + utils.getSkillLvl(1, caster:getMainLvl());
end
local resMod = 0; -- Some spells may possibly be non elemental, but have status effects.
if (element ~= ELE_NONE) then
resMod = target:getMod(resistMod[element]);
-- Add acc for elemental affinity accuracy and element specific accuracy
local affinityBonus = AffinityBonusAcc(caster, element);
local elementBonus = caster:getMod(spellAcc[element]);
-- print(elementBonus);
bonusAcc = bonusAcc + affinityBonus + elementBonus;
end
-- Base magic evasion (base magic evasion plus resistances(players), plus elemental defense(mobs)
local magiceva = target:getMod(MOD_MEVA) + resMod;
magicacc = magicacc + bonusAcc;
-- Add macc% from food
local maccFood = magicacc * (caster:getMod(MOD_FOOD_MACCP)/100);
magicacc = magicacc + utils.clamp(maccFood, 0, caster:getMod(MOD_FOOD_MACC_CAP));
return calculateMagicHitRate(magicacc, magiceva, percentBonus, caster:getMainLvl(), target:getMainLvl());
end
function calculateMagicHitRate(magicacc, magiceva, percentBonus, casterLvl, targetLvl)
local p = 0;
--add a scaling bonus or penalty based on difference of targets level from caster
local levelDiff = utils.clamp(casterLvl - targetLvl, -5, 5);
p = 70 - 0.5 * (magiceva - magicacc) + levelDiff * 3 + percentBonus;
return utils.clamp(p, 5, 95);
end
-- Returns resistance value from given magic hit rate (p)
function getMagicResist(magicHitRate)
local p = magicHitRate / 100;
local resist = 1;
-- Resistance thresholds based on p. A higher p leads to lower resist rates, and a lower p leads to higher resist rates.
local half = (1 - p);
local quart = ((1 - p)^2);
local eighth = ((1 - p)^3);
local sixteenth = ((1 - p)^4);
-- print("HALF: "..half);
-- print("QUART: "..quart);
-- print("EIGHTH: "..eighth);
-- print("SIXTEENTH: "..sixteenth);
local resvar = math.random();
-- Determine final resist based on which thresholds have been crossed.
if (resvar <= sixteenth) then
resist = 0.0625;
--printf("Spell resisted to 1/16!!! Threshold = %u",sixteenth);
elseif (resvar <= eighth) then
resist = 0.125;
--printf("Spell resisted to 1/8! Threshold = %u",eighth);
elseif (resvar <= quart) then
resist = 0.25;
--printf("Spell resisted to 1/4. Threshold = %u",quart);
elseif (resvar <= half) then
resist = 0.5;
--printf("Spell resisted to 1/2. Threshold = %u",half);
else
resist = 1.0;
--printf("1.0");
end
return resist;
end
-- Returns the amount of resistance the
-- target has to the given effect (stun, sleep, etc..)
function getEffectResistance(target, effect)
local effectres = 0;
if (effect == EFFECT_SLEEP_I or effect == EFFECT_SLEEP_II) then
effectres = MOD_SLEEPRES;
elseif (effect == EFFECT_LULLABY) then
effectres = MOD_LULLABYRES;
elseif (effect == EFFECT_POISON) then
effectres = MOD_POISONRES;
elseif (effect == EFFECT_PARALYSIS) then
effectres = MOD_PARALYZERES;
elseif (effect == EFFECT_BLINDNESS) then
effectres = MOD_BLINDRES
elseif (effect == EFFECT_SILENCE) then
effectres = MOD_SILENCERES;
elseif (effect == EFFECT_PLAGUE or effect == EFFECT_DISEASE) then
effectres = MOD_VIRUSRES;
elseif (effect == EFFECT_PETRIFICATION) then
effectres = MOD_PETRIFYRES;
elseif (effect == EFFECT_BIND) then
effectres = MOD_BINDRES;
elseif (effect == EFFECT_CURSE_I or effect == EFFECT_CURSE_II or effect == EFFECT_BANE) then
effectres = MOD_CURSERES;
elseif (effect == EFFECT_WEIGHT) then
effectres = MOD_GRAVITYRES;
elseif (effect == EFFECT_SLOW or effect == EFFECT_ELEGY) then
effectres = MOD_SLOWRES;
elseif (effect == EFFECT_STUN) then
effectres = MOD_STUNRES;
elseif (effect == EFFECT_CHARM) then
effectres = MOD_CHARMRES;
elseif (effect == EFFECT_AMNESIA) then
effectres = MOD_AMNESIARES;
elseif (effect == EFFECT_TERROR) then
effectres = MOD_TERRORRES;
-- Don't put MOD_DOOMRES here.
end
if (effectres ~= 0) then
return target:getMod(effectres);
end
return 0;
end;
-- Returns the bonus magic accuracy for any spell
function getSpellBonusAcc(caster, target, spell)
local magicAccBonus = 0;
local spellId = spell:getID();
local element = spell:getElement();
local castersWeather = caster:getWeather();
local skill = spell:getSkillType();
local spellGroup = spell:getSpellGroup();
if caster:hasStatusEffect(EFFECT_ALTRUISM) and spellGroup == SPELLGROUP_WHITE then
magicAccBonus = magicAccBonus + caster:getStatusEffect(EFFECT_ALTRUISM):getPower();
end
if caster:hasStatusEffect(EFFECT_FOCALIZATION) and spellGroup == SPELLGROUP_BLACK then
magicAccBonus = magicAccBonus + caster:getStatusEffect(EFFECT_FOCALIZATION):getPower();
end
local skillchainTier, skillchainCount = FormMagicBurst(element, target);
--add acc for BLM AMII spells
if (spellId == 205 or spellId == 207 or spellId == 209 or spellId == 211 or spellId == 213 or spellId == 215) then
-- no bonus if the caster has zero merit investment - don't want to give them a negative bonus
if (caster:getMerit(blmAMIIMerit[element]) ~= 0) then
-- bonus value granted by merit is 1; subtract 1 since unlock doesn't give an accuracy bonus
magicAccBonus = magicAccBonus + (caster:getMerit(blmAMIIMerit[element]) - 1) * 5;
end
end
--add acc for skillchains
if (skillchainTier > 0) then
magicAccBonus = magicAccBonus + 25;
end
--Add acc for klimaform
if (caster:hasStatusEffect(EFFECT_KLIMAFORM) and (castersWeather == singleWeatherStrong[element] or castersWeather == doubleWeatherStrong[element])) then
magicAccBonus = magicAccBonus + 15;
end
--Add acc for dark seal
if (skill == DARK_MAGIC_SKILL and caster:hasStatusEffect(EFFECT_DARK_SEAL)) then
magicAccBonus = magicAccBonus + 256;
end
--add acc for RDM group 1 merits
if (element > 0 and element <= 6) then
magicAccBonus = magicAccBonus + caster:getMerit(rdmMerit[element]);
end
-- BLU mag acc merits - nuke acc is handled in bluemagic.lua
if (skill == BLUE_SKILL) then
magicAccBonus = magicAccBonus + caster:getMerit(MERIT_MAGICAL_ACCURACY);
end
return magicAccBonus;
end;
function handleAfflatusMisery(caster, spell, dmg)
if (caster:hasStatusEffect(EFFECT_AFFLATUS_MISERY)) then
local misery = caster:getMod(MOD_AFFLATUS_MISERY);
local miseryMax = caster:getMaxHP() / 4;
-- BGwiki puts the boost capping at 200% bonus at 1/4th max HP.
if (misery > miseryMax) then
misery = miseryMax;
end;
-- Damage is 2x at boost cap.
local boost = 1 + (misery / miseryMax);
dmg = math.floor(dmg * boost);
-- printf("AFFLATUS MISERY: Damage boosted by %f to %d", boost, dmg);
--Afflatus Mod is Used Up...
caster:setMod(MOD_AFFLATUS_MISERY, 0)
end
return dmg;
end;
function finalMagicAdjustments(caster,target,spell,dmg)
--Handles target's HP adjustment and returns UNSIGNED dmg (absorb message is set in this function)
-- handle multiple targets
if (caster:isSpellAoE(spell:getID())) then
local total = spell:getTotalTargets();
if (total > 9) then
-- ga spells on 10+ targets = 0.4
dmg = dmg * 0.4;
elseif (total > 1) then
-- -ga spells on 2 to 9 targets = 0.9 - 0.05T where T = number of targets
dmg = dmg * (0.9 - 0.05 * total);
end
-- kill shadows
-- target:delStatusEffect(EFFECT_COPY_IMAGE);
-- target:delStatusEffect(EFFECT_BLINK);
else
-- this logic will eventually be moved here
-- dmg = utils.takeShadows(target, dmg, 1);
-- if (dmg == 0) then
-- spell:setMsg(msgBasic.SHADOW_ABSORB);
-- return 1;
-- end
end
local skill = spell:getSkillType();
if (skill == ELEMENTAL_MAGIC_SKILL) then
dmg = dmg * ELEMENTAL_POWER;
elseif (skill == DARK_MAGIC_SKILL) then
dmg = dmg * DARK_POWER;
elseif (skill == NINJUTSU_SKILL) then
dmg = dmg * NINJUTSU_POWER;
elseif (skill == DIVINE_MAGIC_SKILL) then
dmg = dmg * DIVINE_POWER;
end
dmg = target:magicDmgTaken(dmg);
if (dmg > 0) then
dmg = dmg - target:getMod(MOD_PHALANX);
dmg = utils.clamp(dmg, 0, 99999);
end
--handling stoneskin
dmg = utils.stoneskin(target, dmg);
dmg = utils.clamp(dmg, -99999, 99999);
if (dmg < 0) then
dmg = target:addHP(-dmg);
spell:setMsg(msgBasic.MAGIC_RECOVERS_HP);
else
target:delHP(dmg);
target:handleAfflatusMiseryDamage(dmg);
target:updateEnmityFromDamage(caster,dmg*customEnmityAdjust(caster,spell));
-- Only add TP if the target is a mob
if (target:getObjType() ~= TYPE_PC) then
target:addTP(100);
end
end
-- debugSpellDamageEnmity(caster,target,dmg,customEnmityAdjust(caster,spell),spell);
return dmg;
end;
function finalMagicNonSpellAdjustments(caster,target,ele,dmg)
--Handles target's HP adjustment and returns SIGNED dmg (negative values on absorb)
dmg = target:magicDmgTaken(dmg);
if (dmg > 0) then
dmg = dmg - target:getMod(MOD_PHALANX);
dmg = utils.clamp(dmg, 0, 99999);
end
--handling stoneskin
dmg = utils.stoneskin(target, dmg);
dmg = utils.clamp(dmg, -99999, 99999);
if (dmg < 0) then
dmg = -(target:addHP(-dmg));
else
target:delHP(dmg);
end
--Not updating enmity from damage, as this is primarily used for additional effects (which don't generate emnity)
-- in the case that updating enmity is needed, do it manually after calling this
--target:updateEnmityFromDamage(caster,dmg);
return dmg;
end;
function adjustForTarget(target,dmg,ele)
if (dmg > 0 and math.random(0,99) < target:getMod(absorbMod[ele])) then
return -dmg;
end
if (math.random(0,99) < target:getMod(nullMod[ele])) then
return 0;
end
--Moved non element specific absorb and null mod checks to core
--TODO: update all lua calls to magicDmgTaken with appropriate element and remove this function
return dmg;
end;
function calculateMagicBurst(caster, spell, target)
local burst = 1.0;
if (spell:getSpellGroup() == 3 and not caster:hasStatusEffect(EFFECT_BURST_AFFINITY)) then
return burst;
end
local skillchainTier, skillchainCount = FormMagicBurst(spell:getElement(), target);
if (skillchainTier > 0) then
if (skillchainCount == 1) then
burst = 1.3;
elseif (skillchainCount == 2) then
burst = 1.35;
elseif (skillchainCount == 3) then
burst = 1.40;
elseif (skillchainCount == 4) then
burst = 1.45;
elseif (skillchainCount == 5) then
burst = 1.50;
else
-- Something strange is going on if this occurs.
burst = 1.0;
end
--add burst bonus for BLM AMII spells
if (spell:getID() == 205 or spell:getID() == 207 or spell:getID() == 209 or spell:getID() == 211 or spell:getID() == 213 or spell:getID() == 215) then
if (caster:getMerit(blmAMIIMerit[spell:getElement()]) ~= 0) then -- no bonus if the caster has zero merit investment - don't want to give them a negative bonus
burst = burst + (caster:getMerit(blmAMIIMerit[spell:getElement()]) - 1) * 0.03; -- bonus value granted by merit is 1; subtract 1 since unlock doesn't give a magic burst bonus
-- print((caster:getMerit(blmAMIIMerit[spell:getElement()]) - 1) * 0.03)
end
end
end
-- Add in Magic Burst Bonus Modifier
if (burst > 1) then
burst = burst + (caster:getMod(MOD_MAG_BURST_BONUS) / 100);
end
return burst;
end;
function addBonuses(caster, spell, target, dmg, bonusmab)
local ele = spell:getElement();
local affinityBonus = AffinityBonusDmg(caster, ele);
dmg = math.floor(dmg * affinityBonus);
if (bonusmab == nil) then
bonusmab = 0;
end
local magicDefense = getElementalDamageReduction(target, ele);
dmg = math.floor(dmg * magicDefense);
local dayWeatherBonus = 1.00;
local weather = caster:getWeather();
if (weather == singleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (caster:getWeather() == singleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
elseif (weather == doubleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus + 0.25;
end
elseif (weather == doubleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus - 0.25;
end
end
local dayElement = VanadielDayElement();
if (dayElement == dayStrong[ele]) then
dayWeatherBonus = dayWeatherBonus + caster:getMod(MOD_DAY_NUKE_BONUS)/100; -- sorc. tonban(+1)/zodiac ring
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (dayElement == dayWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1 or isHelixSpell(spell)) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
end
if dayWeatherBonus > 1.4 then
dayWeatherBonus = 1.4;
end
dmg = math.floor(dmg * dayWeatherBonus);
local burst = calculateMagicBurst(caster, spell, target);
if (burst > 1.0) then
spell:setMsg(spell:getMagicBurstMessage()); -- "Magic Burst!"
end
dmg = math.floor(dmg * burst);
local mabbonus = 0;
if (spell:getID() >= 245 and spell:getID() <= 248) then -- Drain/Aspir (II)
mabbonus = 1 + caster:getMod(MOD_ENH_DRAIN_ASPIR)/100;
-- print(mabbonus);
else
local mab = caster:getMod(MOD_MATT) + bonusmab;
local mab_crit = caster:getMod(MOD_MAGIC_CRITHITRATE);
if ( math.random(1,100) < mab_crit ) then
mab = mab + ( 10 + caster:getMod(MOD_MAGIC_CRIT_DMG_INCREASE ) );
end
local mdefBarBonus = 0;
if (ele > 0 and ele <= 6) then
mab = mab + caster:getMerit(blmMerit[ele]);
if (target:hasStatusEffect(barSpells[ele])) then -- bar- spell magic defense bonus
mdefBarBonus = target:getStatusEffect(barSpells[ele]):getSubPower();
end
end
mabbonus = (100 + mab) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus);
end
if (mabbonus < 0) then
mabbonus = 0;
end
dmg = math.floor(dmg * mabbonus);
if (caster:hasStatusEffect(EFFECT_EBULLIENCE)) then
dmg = dmg * (1.2 + caster:getMod(MOD_EBULLIENCE_AMOUNT)/100);
caster:delStatusEffectSilent(EFFECT_EBULLIENCE);
end
dmg = math.floor(dmg);
-- print(affinityBonus);
-- print(speciesReduction);
-- print(dayWeatherBonus);
-- print(burst);
-- print(mab);
-- print(magicDmgMod);
return dmg;
end;
function addBonusesAbility(caster, ele, target, dmg, params)
local affinityBonus = AffinityBonusDmg(caster, ele);
dmg = math.floor(dmg * affinityBonus);
local magicDefense = getElementalDamageReduction(target, ele);
dmg = math.floor(dmg * magicDefense);
local dayWeatherBonus = 1.00;
local weather = caster:getWeather();
if (weather == singleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (caster:getWeather() == singleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
elseif (weather == doubleWeatherStrong[ele]) then
if (caster:getMod(MOD_IRIDESCENCE) >= 1) then
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
end
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.25;
end
elseif (weather == doubleWeatherWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.25;
end
end
local dayElement = VanadielDayElement();
if (dayElement == dayStrong[ele]) then
dayWeatherBonus = dayWeatherBonus + caster:getMod(MOD_DAY_NUKE_BONUS)/100; -- sorc. tonban(+1)/zodiac ring
if (math.random() < 0.33 or caster:getMod(elementalObi[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus + 0.10;
end
elseif (dayElement == dayWeak[ele]) then
if (math.random() < 0.33 or caster:getMod(elementalObiWeak[ele]) >= 1) then
dayWeatherBonus = dayWeatherBonus - 0.10;
end
end
if dayWeatherBonus > 1.4 then
dayWeatherBonus = 1.4;
end
dmg = math.floor(dmg * dayWeatherBonus);
local mab = 1;
local mdefBarBonus = 0;
if (ele > 0 and ele <= 6 and target:hasStatusEffect(barSpells[ele])) then -- bar- spell magic defense bonus
mdefBarBonus = target:getStatusEffect(barSpells[ele]):getSubPower();
end
if (params ~= nil and params.bonusmab ~= nil and params.includemab == true) then
mab = (100 + caster:getMod(MOD_MATT) + params.bonusmab) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus);
elseif (params == nil or (params ~= nil and params.includemab == true)) then
mab = (100 + caster:getMod(MOD_MATT)) / (100 + target:getMod(MOD_MDEF) + mdefBarBonus);
end
if (mab < 0) then
mab = 0;
end
dmg = math.floor(dmg * mab);
-- print(affinityBonus);
-- print(speciesReduction);
-- print(dayWeatherBonus);
-- print(burst);
-- print(mab);
-- print(magicDmgMod);
return dmg;
end;
-- get elemental damage reduction
function getElementalDamageReduction(target, element)
local defense = 1;
if (element > 0) then
defense = 1 - (target:getMod(defenseMod[element]) / 256);
return utils.clamp(defense, 0.0, 2.0);
end
return defense;
end
---------------------------------------------
-- Elemental Debuff Potency functions
---------------------------------------------
function getElementalDebuffDOT(INT)
local DOT = 0;
if (INT<= 39) then
DOT = 1;
elseif (INT <= 69) then
DOT = 2;
elseif (INT <= 99) then
DOT = 3;
elseif (INT <= 149) then
DOT = 4;
else
DOT = 5;
end
return DOT;
end;
function getElementalDebuffStatDownFromDOT(dot)
local stat_down = 0;
if (dot == 1) then
stat_down = 5;
elseif (dot == 2) then
stat_down = 7;
elseif (dot == 3) then
stat_down = 9;
elseif (dot == 4) then
stat_down = 11;
else
stat_down = 13;
end
return stat_down;
end;
function getHelixDuration(caster)
--Dark Arts will further increase Helix duration, but testing is ongoing.
local casterLevel = caster:getMainLvl();
local duration = 30; --fallthrough
if (casterLevel <= 39) then
duration = 30;
elseif (casterLevel <= 59) then
duration = 60;
elseif (casterLevel <= 99) then
duration = 90;
end
return duration;
end;
function isHelixSpell(spell)
--Dark Arts will further increase Helix duration, but testing is ongoing.
local id = spell:getID();
if id >= 278 and id <= 285 then
return true;
end
return false;
end;
function handleThrenody(caster, target, spell, basePower, baseDuration, modifier)
-- Process resitances
local staff = AffinityBonusAcc(caster, spell:getElement());
-- print("staff=" .. staff);
local dCHR = (caster:getStat(MOD_CHR) - target:getStat(MOD_CHR));
-- print("dCHR=" .. dCHR);
local params = {};
params.attribute = MOD_CHR;
params.skillType = SINGING_SKILL;
params.bonus = staff;
local resm = applyResistance(caster, target, spell, params);
-- print("rsem=" .. resm);
if (resm < 0.5) then
-- print("resm resist");
spell:setMsg(msgBasic.MAGIC_RESIST);
return EFFECT_THRENODY;
end
-- Remove previous Threnody
target:delStatusEffect(EFFECT_THRENODY);
local iBoost = caster:getMod(MOD_THRENODY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
local power = basePower + iBoost*5;
local duration = baseDuration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
-- Set spell message and apply status effect
target:addStatusEffect(EFFECT_THRENODY, power, 0, duration, 0, modifier, 0);
return EFFECT_THRENODY;
end;
function handleNinjutsuDebuff(caster, target, spell, basePower, baseDuration, modifier)
-- Add new
target:addStatusEffectEx(EFFECT_NINJUTSU_ELE_DEBUFF, 0, basePower, 0, baseDuration, 0, modifier, 0);
return EFFECT_NINJUTSU_ELE_DEBUFF;
end;
-- Returns true if you can overwrite the effect
-- Example: canOverwrite(target, EFFECT_SLOW, 25)
function canOverwrite(target, effect, power, mod)
mod = mod or 1;
local statusEffect = target:getStatusEffect(effect);
-- effect not found so overwrite
if (statusEffect == nil) then
return true;
end
-- overwrite if its weaker
if (statusEffect:getPower()*mod > power) then
return false;
end
return true;
end
function doElementalNuke(caster, spell, target, spellParams)
local DMG = 0;
local V = 0;
local M = 0;
local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT);
local hasMultipleTargetReduction = spellParams.hasMultipleTargetReduction; --still unused!!!
local resistBonus = spellParams.resistBonus;
local mDMG = caster:getMod(MOD_MAGIC_DAMAGE);
--[[
Calculate base damage:
D = mDMG + V + (dINT × M)
D is then floored
For dINT reduce by amount factored into the V value (example: at 134 INT, when using V100 in the calculation, use dINT = 134-100 = 34)
]]
if (dINT <= 49) then
V = spellParams.V0;
M = spellParams.M0;
DMG = math.floor(DMG + mDMG + V + (dINT * M));
if (DMG <= 0) then
return 0;
end
elseif (dINT >= 50 and dINT <= 99) then
V = spellParams.V50;
M = spellParams.M50;
DMG = math.floor(DMG + mDMG + V + ((dINT - 50) * M));
elseif (dINT >= 100 and dINT <= 199) then
V = spellParams.V100;
M = spellParams.M100;
DMG = math.floor(DMG + mDMG + V + ((dINT - 100) * M));
elseif (dINT > 199) then
V = spellParams.V200;
M = spellParams.M200;
DMG = math.floor(DMG + mDMG + V + ((dINT - 200) * M));
end
--get resist multiplier (1x if no resist)
local params = {};
params.attribute = MOD_INT;
params.skillType = ELEMENTAL_MAGIC_SKILL;
params.resistBonus = resistBonus;
local resist = applyResistance(caster, target, spell, params);
--get the resisted damage
DMG = DMG * resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
DMG = addBonuses(caster, spell, target, DMG);
--add in target adjustment
local ele = spell:getElement();
DMG = adjustForTarget(target, DMG, ele);
--add in final adjustments
DMG = finalMagicAdjustments(caster, target, spell, DMG);
return DMG;
end
function doDivineNuke(caster, target, spell, params)
params.skillType = DIVINE_MAGIC_SKILL;
params.attribute = MOD_MND;
return doNuke(caster, target, spell, params);
end
function doNinjutsuNuke(caster, target, spell, params)
local mabBonus = params.mabBonus;
mabBonus = mabBonus or 0;
mabBonus = mabBonus + caster:getMod(MOD_NIN_NUKE_BONUS); -- "enhances ninjutsu damage" bonus
if (caster:hasStatusEffect(EFFECT_INNIN) and caster:isBehind(target, 23)) then -- Innin mag atk bonus from behind, guesstimating angle at 23 degrees
mabBonus = mabBonus + caster:getStatusEffect(EFFECT_INNIN):getPower();
end
params.skillType = NINJUTSU_SKILL;
params.attribute = MOD_INT;
params.mabBonus = mabBonus;
return doNuke(caster, target, spell, params);
end
function doNuke(caster, target, spell, params)
--calculate raw damage
local dmg = calculateMagicDamage(caster, target, spell, params);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster, target, spell, params);
--get the resisted damage
dmg = dmg*resist;
if (skill == NINJUTSU_SKILL) then
if (caster:getMainJob() == JOBS.NIN) then -- NIN main gets a bonus to their ninjutsu nukes
local ninSkillBonus = 100;
if (spell:getID() % 3 == 2) then -- ichi nuke spell ids are 320, 323, 326, 329, 332, and 335
ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 50)/2); -- getSkillLevel includes bonuses from merits and modifiers (ie. gear)
elseif (spell:getID() % 3 == 0) then -- ni nuke spell ids are 1 more than their corresponding ichi spell
ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 125)/2);
else -- san nuke spell, also has ids 1 more than their corresponding ni spell
ninSkillBonus = 100 + math.floor((caster:getSkillLevel(SKILL_NIN) - 275)/2);
end
ninSkillBonus = utils.clamp(ninSkillBonus, 100, 200); -- bonus caps at +100%, and does not go negative
dmg = dmg * ninSkillBonus/100;
end
-- boost with Futae
if (caster:hasStatusEffect(EFFECT_FUTAE)) then
dmg = math.floor(dmg * 1.50);
caster:delStatusEffect(EFFECT_FUTAE);
end
end
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg,mabBonus);
--add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
--add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg);
return dmg;
end
function doDivineBanishNuke(caster, target, spell, params)
params.skillType = DIVINE_MAGIC_SKILL;
params.attribute = MOD_MND;
--calculate raw damage
local dmg = calculateMagicDamage(caster, target, spell, params);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster, target, spell, params);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
--handling afflatus misery
dmg = handleAfflatusMisery(caster, spell, dmg);
--add in final adjustments
dmg = finalMagicAdjustments(caster,target,spell,dmg);
return dmg;
end
function calculateDurationForLvl(duration, spellLvl, targetLvl)
if (targetLvl < spellLvl) then
return duration * targetLvl / spellLvl;
end
return duration;
end
function calculateBarspellPower(caster,enhanceSkill)
local meritBonus = caster:getMerit(MERIT_BAR_SPELL_EFFECT);
local equipBonus = caster:getMod(MOD_BARSPELL_AMOUNT);
--printf("Barspell: Merit Bonus +%d", meritBonus);
if (enhanceSkill == nil or enhanceSkill < 0) then
enhanceSkill = 0;
end
local power = 40 + 0.2 * enhanceSkill + meritBonus + equipBonus;
return power;
end
-- Output magic hit rate for all levels
function outputMagicHitRateInfo()
for casterLvl = 1, 75 do
printf("");
printf("-------- CasterLvl: %d", casterLvl);
for lvlMod = -5, 20 do
local targetLvl = casterLvl + lvlMod;
if (targetLvl >= 0) then
-- assume BLM spell, A+
local magicAcc = utils.getSkillLvl(6, casterLvl);
-- assume default monster magic eva, D
local magicEvaRank = 3;
local rate = 0;
local magicEva = utils.getMobSkillLvl(magicEvaRank, targetLvl);
local dINT = (lvlMod + 1) * -1;
if (dINT > 10) then
magicAcc = magicAcc + 10 + (dINT - 10)/2;
else
magicAcc = magicAcc + dINT;
end
local magicHitRate = calculateMagicHitRate(magicAcc, magicEva, 0, casterLvl, targetLvl);
printf("Lvl: %d vs %d, %d%%, MA: %d, ME: %d", casterLvl, targetLvl, magicHitRate, magicAcc, magicEva);
end
end
end
end;
-- outputMagicHitRateInfo();
-- Had to create this because DSP treats status resist traits like additional magic evasion..
function customResCheck(target, effect)
local effectRes = 0;
if (effect == EFFECT_SLEEP_I or effect == EFFECT_SLEEP_II) then
effectRes = target:getMod(MOD_SLEEPRES);
elseif(effect == EFFECT_LULLABY) then
effectRes = target:getMod(MOD_LULLABYRES);
elseif (effect == EFFECT_POISON) then
if (target:hasStatusEffect(EFFECT_NEGATE_POISON)) then
return 1000;
end
effectRes = target:getMod(MOD_POISONRES);
elseif (effect == EFFECT_PARALYZE) then
effectRes = target:getMod(MOD_PARALYZERES);
elseif (effect == EFFECT_BLINDNESS) then
effectRes = target:getMod(MOD_BLINDRES)
elseif (effect == EFFECT_SILENCE) then
effectRes = target:getMod(MOD_SILENCERES);
elseif (effect == EFFECT_PLAGUE or effect == EFFECT_DISEASE) then
if (target:hasStatusEffect(EFFECT_NEGATE_VIRUS)) then
return 1000;
end
effectRes = target:getMod(MOD_VIRUSRES);
elseif (effect == EFFECT_PETRIFICATION) then
if (target:hasStatusEffect(EFFECT_NEGATE_PETRIFY)) then
return 1000;
end
effectRes = target:getMod(MOD_PETRIFYRES);
elseif (effect == EFFECT_BIND) then
effectRes = target:getMod(MOD_BINDRES);
elseif (effect == EFFECT_CURSE_I or effect == EFFECT_CURSE_II or effect == EFFECT_BANE) then
if (target:hasStatusEffect(EFFECT_NEGATE_CURSE)) then
return 1000;
end
effectRes = target:getMod(MOD_CURSERES);
elseif (effect == EFFECT_WEIGHT) then
effectRes = target:getMod(MOD_GRAVITYRES);
elseif (effect == EFFECT_SLOW or effect == EFFECT_ELEGY) then
effectRes = target:getMod(MOD_SLOWRES);
elseif (effect == EFFECT_STUN) then
effectRes = target:getMod(MOD_STUNRES);
elseif (effect == EFFECT_CHARM) then
if (target:hasStatusEffect(EFFECT_NEGATE_CHARM)) then
return 1000;
end
effectRes = target:getMod(MOD_CHARMRES);
elseif (effect == EFFECT_AMNESIA) then
if (target:hasStatusEffect(EFFECT_NEGATE_AMNESIA)) then
return 1000;
end
effectRes = target:getMod(MOD_AMNESIARES);
elseif (effect == EFFECT_TERROR) then
if (target:hasStatusEffect(EFFECT_NEGATE_TERROR)) then
return 1000;
end
effectRes = target:getMod(MOD_TERRORRES);
elseif (effect == EFFECT_DOOM) then
if (target:hasStatusEffect(EFFECT_NEGATE_DOOM)) then
return 1000;
end
effectRes = target:getMod(MOD_DOOMRES);
end
-- Temp! DSP seems to be using x/100 where data suggests x/1000ths or possibly x/1024ths
effectRes = effectRes*10;
-- just going to fudge it for now because actually raising the modifier total
-- would effect DSP's garbage magic evasion calculations.
if (effectRes > 400) then
-- I pulled this threshold number outa my ass, because there
-- is zero data for very high values of status resist trait.
effectRes = (400+((effectRes -400)*0.5));
-- modifier amount above 400 worth half as much, because I say so..
end
if (effectRes > 950) then
effectRes = 950; -- 95% cap!
-- I don't think it would even be possible to reach this on retail..
-- In theory LegionDS might stack augments later though.
end
return effectRes;
end;
-- This is used to modify enmity for damage type spells ONLY!
function customEnmityAdjust(caster,spell,params)
local multiplier = 1;
-- Don't even check all this if not a player..
if (caster:getObjType() == TYPE_PC) then
-- Spell specific adjustments..
if (spell:getID() == 21) then -- Holy
multiplier = multiplier*1.2;
elseif (spell:getID() == 22) then -- Holy 2
multiplier = multiplier*1.2;
end
-- Main Job specific adjustments..
local mJob = caster:getMainJob();
if (mJob == JOBS.PLD) then
multiplier = multiplier*1.11;
end
-- Sub Job specific adjustments..
local sJob = caster:getSubJob();
if (sJob == JOBS.DRK) then
multiplier = multiplier*1.11;
end
-- Skill specific adjustments..
local skill = spell:getSkillType();
if (skill == ELEMENTAL_MAGIC_SKILL) then
multiplier = multiplier*0.9;
elseif (skill == NINJUTSU_SKILL) then
multiplier = multiplier*1.11;
--[[ Rethinking blue magic enmity.. People are tanking intentionally with blue spells.
elseif (skill == BLUE_SKILL and params ~= nil) then
if (params.dmgtype == nil) then -- This will be nil unless physical type
multiplier = multiplier*1.25;
elseif (params.dmgtype == DMGTYPE_BLUNT or params.dmgtype == DMGTYPE_PIERCE
or params.dmgtype == DMGTYPE_SLASH or params.dmgtype == DMGTYPE_H2H) then
multiplier = multiplier*1.11;
end
]]
end
end
-- Remember multiple conditions can be tripped and stacked,
-- but if it doesn't do damage it doesn't get adjusted!
-- Other spells are handled in the database table instead.
-- print(multiplier)
return multiplier;
end;
-- Big huge pile of debug code, replicating a lot of core shit to be less spammy than a core print..
function debugSpellDamageEnmity(caster,target,dmg,multiplier,spell)
local levelMod;
if (target == nil) then
levelMod = utils.clamp(caster:getMainLvl(), 0, 99); -- same as "default fallback" in core
else
levelMod = utils.clamp(target:getMainLvl(), 0, 99); -- core says "correct mod value"
end
levelMod = ((31*levelMod)/50)+6; -- And this is the math core does to it..
local CE = (80 / levelMod * dmg);
local VE = (240 / levelMod * dmg);
print("[EnmityFromDamage-Spell]\n Caster: "..caster:getName().."\t Target: "..target:getName().."\n CE: "..CE.."\t VE: "..VE.."\n Spell ID: "..spell:getID().."\t\t Dmg: "..dmg.."\n levelMod: "..levelMod.."\t\t multiplier: "..multiplier);
end;
| gpl-3.0 |
erosennin/koreader | plugins/zsync.koplugin/main.lua | 1 | 9988 | local FileManagerHistory = require("apps/filemanager/filemanagerhistory")
local FileManagerMenu = require("apps/filemanager/filemanagermenu")
local InputContainer = require("ui/widget/container/inputcontainer")
local FrameContainer = require("ui/widget/container/framecontainer")
local FileManager = require("apps/filemanager/filemanager")
local VerticalGroup = require("ui/widget/verticalgroup")
local VerticalSpan = require("ui/widget/verticalspan")
local ButtonDialog = require("ui/widget/buttondialog")
local InfoMessage = require("ui/widget/infomessage")
local TextWidget = require("ui/widget/textwidget")
local DocSettings = require("docsettings")
local UIManager = require("ui/uimanager")
local Screen = require("ui/screen")
local Event = require("ui/event")
local Font = require("ui/font")
local ltn12 = require("ltn12")
local DEBUG = require("dbg")
local _ = require("gettext")
local util = require("ffi/util")
-- lfs
local ffi = require("ffi")
ffi.cdef[[
int remove(const char *);
int rmdir(const char *);
]]
local dummy = require("ffi/zeromq_h")
local ZSync = InputContainer:new{
name = "zsync",
}
function ZSync:init()
self.ui.menu:registerToMainMenu(self)
self.outbox = self.path.."/outbox"
self.server_config = self.path.."/server.cfg"
self.client_config = self.path.."/client.cfg"
end
function ZSync:addToMainMenu(tab_item_table)
table.insert(tab_item_table.plugins, {
text = _("ZSync"),
sub_item_table = {
{
text_func = function()
return not self.filemq_server
and _("Publish this document")
or _("Stop publisher")
end,
enabled_func = function()
return self.filemq_client == nil
end,
callback = function()
if not self.filemq_server then
self:publish()
else
self:unpublish()
end
end
},
{
text_func = function()
return not self.filemq_client
and _("Subscribe documents")
or _("Stop subscriber")
end,
enabled_func = function()
return self.filemq_server == nil
end,
callback = function()
if not self.filemq_client then
self:subscribe()
else
self:unsubscribe()
end
end
}
}
})
end
function ZSync:initServerZyreMQ()
local ZyreMessageQueue = require("ui/message/zyremessagequeue")
if self.zyre_messagequeue == nil then
self.server_zyre = ZyreMessageQueue:new{
header = {["FILEMQ-SERVER"] = tostring(self.fmq_port)},
}
self.server_zyre:start()
self.zyre_messagequeue = UIManager:insertZMQ(self.server_zyre)
end
end
function ZSync:initClientZyreMQ()
local ZyreMessageQueue = require("ui/message/zyremessagequeue")
if self.zyre_messagequeue == nil then
self.client_zyre = ZyreMessageQueue:new{}
self.client_zyre:start()
self.zyre_messagequeue = UIManager:insertZMQ(self.client_zyre)
end
end
function ZSync:initServerFileMQ(outboxes)
local FileMessageQueue = require("ui/message/filemessagequeue")
local filemq = ffi.load("libs/libfmq.so.1")
if self.file_messagequeue == nil then
self.filemq_server = filemq.fmq_server_new()
self.file_messagequeue = UIManager:insertZMQ(FileMessageQueue:new{
server = self.filemq_server
})
self.fmq_port = filemq.fmq_server_bind(self.filemq_server, "tcp://*:*")
filemq.fmq_server_configure(self.filemq_server, self.server_config)
filemq.fmq_server_set_anonymous(self.filemq_server, true)
end
UIManager:scheduleIn(1, function()
for _, outbox in ipairs(outboxes) do
DEBUG("publish", outbox.path, outbox.alias)
filemq.fmq_server_publish(self.filemq_server, outbox.path, outbox.alias)
end
end)
end
function ZSync:initClientFileMQ(inbox)
local FileMessageQueue = require("ui/message/filemessagequeue")
local filemq = ffi.load("libs/libfmq.so.1")
if self.file_messagequeue == nil then
self.filemq_client = filemq.fmq_client_new()
self.file_messagequeue = UIManager:insertZMQ(FileMessageQueue:new{
client = self.filemq_client
})
filemq.fmq_client_configure(self.filemq_client, self.client_config)
end
UIManager:scheduleIn(1, function()
filemq.fmq_client_set_inbox(self.filemq_client, inbox)
end)
end
local function clearDirectory(dir, rmdir)
for f in lfs.dir(dir) do
local path = dir.."/"..f
local mode = lfs.attributes(path, "mode")
if mode == "file" then
ffi.C.remove(path)
elseif mode == "directory" and f ~= "." and f ~= ".." then
clearDirectory(path, true)
end
end
if rmdir then
ffi.C.rmdir(dir)
end
end
local function mklink(path, filename)
local basename = filename:match(".*/(.*)") or filename
local linkname = path .. "/" .. basename .. ".ln"
local linkfile = io.open(linkname, "w")
if linkfile then
linkfile:write(filename .. "\n")
linkfile:close()
end
end
-- add directory directly into outboxes
function ZSync:outboxesAddDirectory(outboxes, dir)
if lfs.attributes(dir, "mode") == "directory" then
local basename = dir:match(".*/(.*)") or dir
table.insert(outboxes, {
path = dir,
alias = "/"..basename,
})
end
end
-- link file in root outbox
function ZSync:outboxAddFileLink(filename)
local mode = lfs.attributes(filename, "mode")
if mode == "file" then
mklink(self.outbox, filename)
end
end
-- copy directory content into root outbox(no recursively)
function ZSync:outboxCopyDirectory(dir)
local basename = dir:match(".*/(.*)") or dir
local newdir = self.outbox.."/"..basename
lfs.mkdir(newdir)
if pcall(lfs.dir, dir) then
for f in lfs.dir(dir) do
local filename = dir.."/"..f
if lfs.attributes(filename, "mode") == "file" then
local newfile = newdir.."/"..f
ltn12.pump.all(
ltn12.source.file(assert(io.open(filename, "rb"))),
ltn12.sink.file(assert(io.open(newfile, "wb")))
)
end
end
end
end
function ZSync:publish()
DEBUG("publish document", self.view.document.file)
lfs.mkdir(self.outbox)
clearDirectory(self.outbox)
local file = self.view.document.file
local sidecar = file:match("(.*)%.")..".sdr"
self:outboxAddFileLink(file)
self:outboxCopyDirectory(sidecar)
local outboxes = {}
table.insert(outboxes, {
path = self.outbox,
alias = "/",
})
-- init filemq first to get filemq port
self:initServerFileMQ(outboxes)
self:initServerZyreMQ()
end
function ZSync:unpublish()
DEBUG("ZSync unpublish")
clearDirectory(self.outbox)
self:stopZyreMQ()
self:stopFileMQ()
end
function ZSync:onChooseInbox(inbox)
DEBUG("choose inbox", inbox)
self.inbox = inbox
-- init zyre first for filemq endpoint
self:initClientZyreMQ()
self:initClientFileMQ(inbox)
return true
end
function ZSync:subscribe()
DEBUG("subscribe documents")
self.received = {}
local zsync = self
require("ui/downloadmgr"):new{
title = _("Choose inbox"),
onConfirm = function(inbox)
G_reader_settings:saveSetting("inbox_dir", inbox)
zsync:onChooseInbox(inbox)
end,
}:chooseDir()
end
function ZSync:unsubscribe()
DEBUG("ZSync unsubscribe")
self.received = {}
self:stopFileMQ()
self:stopZyreMQ()
end
function ZSync:onZyreEnter(id, name, header, endpoint)
local filemq = ffi.load("libs/libfmq.so.1")
if header and endpoint and header["FILEMQ-SERVER"] then
self.server_zyre_endpoint = endpoint
local port = header["FILEMQ-SERVER"]
local host = endpoint:match("(.*:)") or "*:"
local fmq_server_endpoint = host..port
DEBUG("connect filemq server at", fmq_server_endpoint)
-- wait for filemq server setup befor connecting
UIManager:scheduleIn(2, function()
filemq.fmq_client_set_resync(self.filemq_client, true)
filemq.fmq_client_subscribe(self.filemq_client, "/")
filemq.fmq_client_connect(self.filemq_client, fmq_server_endpoint)
end)
end
return true
end
function ZSync:onFileDeliver(filename, fullname)
-- sometimes several FileDelever msgs are sent from filemq
if self.received[filename] then return end
UIManager:show(InfoMessage:new{
text = _("Received file:") .. "\n" .. filename,
timeout = 1,
})
self.received[filename] = true
end
--[[
-- We assume that ZSync is running in either server mode or client mode
-- but never both. The zyre_messagequeue may be a server_zyre or client_zyre.
-- And the file_messagequeue may be a filemq_server or filemq_client.
--]]
function ZSync:stopZyreMQ()
if self.zyre_messagequeue then
self.zyre_messagequeue:stop()
UIManager:removeZMQ(self.zyre_messagequeue)
self.zyre_messagequeue = nil
self.server_zyre = nil
self.client_zyre = nil
end
end
function ZSync:stopFileMQ()
if self.file_messagequeue then
self.file_messagequeue:stop()
UIManager:removeZMQ(self.file_messagequeue)
self.file_messagequeue = nil
self.filemq_server = nil
self.filemq_client = nil
end
end
function ZSync:onCloseReader()
self:stopZyreMQ()
self:stopFileMQ()
end
return ZSync
| agpl-3.0 |
awesomeWM/awesome | tests/examples/wibox/awidget/tasklist/style_bg_focus.lua | 1 | 1681 | --DOC_HIDE_START
--DOC_GEN_IMAGE
local parent = ...
local beautiful = require("beautiful")
local wibox = require("wibox")
local awful = { widget = { tasklist = require("awful.widget.tasklist") } }
local gears = { color = require("gears.color") }
local t_real = require("awful.tag").add("Test", {screen=screen[1]})
local s = screen[1]
parent.spacing = 5
beautiful.tasklist_fg_focus = "#000000"
for i=1, 5 do
client.gen_fake{
class = "client",
name = "Client #"..i,
icon = beautiful.awesome_icon,
tags = {t_real}
}
end
client.get()[1].name = "Client 1# (floating)"
client.get()[2].name = "Client 2# (sticky)"
client.get()[3].name = "Client 3# (focus)"
client.get()[4].name = "Client 4# (urgent)"
client.get()[5].name = "Client 5# (minimized)"
client.get()[1].floating = true
client.get()[2].sticky = true
client.get()[4].urgent = true
client.get()[5].minimized = true
client.focus = client.get()[3]
--DOC_HIDE_END
local grad = gears.color {
type = "linear",
from = { 0, 0 },
to = { 0, 22 },
stops = {
{ 0, "#ff0000" },
{ 1, "#0000ff" },
}
}
--DOC_NEWLINE
for _, col in ipairs { "#ff0000", "#00ff00", "#0000ff", grad } do
beautiful.tasklist_bg_focus = col
--DOC_HIDE_START
local tasklist = awful.widget.tasklist {
screen = s,
filter = awful.widget.tasklist.filter.currenttags,
layout = wibox.layout.fixed.horizontal
}
tasklist._do_tasklist_update_now()
parent:add(_memento(tasklist, nil, 22)) --luacheck: globals _memento
--DOC_HIDE_END
end
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
mwoz123/koreader | plugins/terminal.koplugin/main.lua | 1 | 17116 | local ButtonDialog = require("ui/widget/buttondialog")
local CenterContainer = require("ui/widget/container/centercontainer")
local DataStorage = require("datastorage")
local Dispatcher = require("dispatcher")
local Font = require("ui/font")
local InfoMessage = require("ui/widget/infomessage")
local InputDialog = require("ui/widget/inputdialog")
local LuaSettings = require("luasettings")
local Menu = require("ui/widget/menu")
local TextViewer = require("ui/widget/textviewer")
local Trapper = require("ui/trapper")
local UIManager = require("ui/uimanager")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local logger = require("logger")
local util = require("ffi/util")
local _ = require("gettext")
local N_ = _.ngettext
local Screen = require("device").screen
local T = util.template
local Terminal = WidgetContainer:new{
name = "terminal",
command = "",
dump_file = util.realpath(DataStorage:getDataDir()) .. "/terminal_output.txt",
items_per_page = 16,
settings = LuaSettings:open(DataStorage:getSettingsDir() .. "/terminal_shortcuts.lua"),
shortcuts_dialog = nil,
shortcuts_menu = nil,
-- shortcuts_file = DataStorage:getSettingsDir() .. "/terminal_shortcuts.lua",
shortcuts = {},
source = "terminal",
}
function Terminal:onDispatcherRegisterActions()
Dispatcher:registerAction("show_terminal", { category = "none", event = "TerminalStart", title = _("Show terminal"), device = true, })
end
function Terminal:init()
self:onDispatcherRegisterActions()
self.ui.menu:registerToMainMenu(self)
self.items_per_page = G_reader_settings:readSetting("items_per_page") or 16
self.shortcuts = self.settings:readSetting("shortcuts", {})
end
function Terminal:saveShortcuts()
self.settings:flush()
UIManager:show(InfoMessage:new{
text = _("Shortcuts saved"),
timeout = 2
})
end
function Terminal:manageShortcuts()
self.shortcuts_dialog = CenterContainer:new {
dimen = Screen:getSize(),
}
self.shortcuts_menu = Menu:new{
show_parent = self.ui,
width = Screen:getWidth(),
height = Screen:getHeight(),
covers_fullscreen = true, -- hint for UIManager:_repaint()
is_borderless = true,
is_popout = false,
perpage = self.items_per_page,
onMenuHold = self.onMenuHoldShortcuts,
_manager = self,
}
table.insert(self.shortcuts_dialog, self.shortcuts_menu)
self.shortcuts_menu.close_callback = function()
UIManager:close(self.shortcuts_dialog)
end
-- sort the shortcuts:
if #self.shortcuts > 0 then
table.sort(self.shortcuts, function(v1, v2)
return v1.text < v2.text
end)
end
self:updateItemTable()
end
function Terminal:updateItemTable()
local item_table = {}
if #self.shortcuts > 0 then
local actions_count = 3 -- separator + actions
for nr, f in ipairs(self.shortcuts) do
local item = {
nr = nr,
text = f.text,
commands = f.commands,
editable = true,
deletable = true,
callback = function()
-- so we know which middle button to display in the results:
self.source = "shortcut"
-- execute immediately, skip terminal dialog:
self.command = self:ensureWhitelineAfterCommands(f.commands)
Trapper:wrap(function()
self:execute()
end)
end
}
table.insert(item_table, item)
-- add page actions at end of each page with shortcuts:
local factor = self.items_per_page - actions_count
if nr % factor == 0 or nr == #self.shortcuts then
-- insert "separator":
table.insert(item_table, {
text = " ",
deletable = false,
editable = false,
callback = function()
self:manageShortcuts()
end,
})
-- actions:
self:insertPageActions(item_table)
end
end
-- no shortcuts defined yet:
else
self:insertPageActions(item_table)
end
local title = N_("Terminal shortcut", "Terminal shortcuts", #self.shortcuts)
self.shortcuts_menu:switchItemTable(tostring(#self.shortcuts) .. " " .. title, item_table)
UIManager:show(self.shortcuts_dialog)
end
function Terminal:insertPageActions(item_table)
table.insert(item_table, {
text = " " .. _("to terminal…"),
deletable = false,
editable = false,
callback = function()
self:terminal()
end,
})
table.insert(item_table, {
text = " " .. _("close…"),
deletable = false,
editable = false,
callback = function()
return false
end,
})
end
function Terminal:onMenuHoldShortcuts(item)
if item.deletable or item.editable then
local shortcut_shortcuts_dialog
shortcut_shortcuts_dialog = ButtonDialog:new{
buttons = {{
{
text = _("Edit name"),
enabled = item.editable,
callback = function()
UIManager:close(shortcut_shortcuts_dialog)
if self._manager.shortcuts_dialog ~= nil then
UIManager:close(self._manager.shortcuts_dialog)
self._manager.shortcuts_dialog = nil
end
self._manager:editName(item)
end
},
{
text = _("Edit commands"),
enabled = item.editable,
callback = function()
UIManager:close(shortcut_shortcuts_dialog)
if self._manager.shortcuts_dialog ~= nil then
UIManager:close(self._manager.shortcuts_dialog)
self._manager.shortcuts_dialog = nil
end
self._manager:editCommands(item)
end
},
},
{
{
text = _("Copy"),
enabled = item.editable,
callback = function()
UIManager:close(shortcut_shortcuts_dialog)
if self._manager.shortcuts_dialog ~= nil then
UIManager:close(self._manager.shortcuts_dialog)
self._manager.shortcuts_dialog = nil
end
self._manager:copyCommands(item)
end
},
{
text = _("Delete"),
enabled = item.deletable,
callback = function()
UIManager:close(shortcut_shortcuts_dialog)
if self._manager.shortcuts_dialog ~= nil then
UIManager:close(self._manager.shortcuts_dialog)
self._manager.shortcuts_dialog = nil
end
self._manager:deleteShortcut(item)
end
}
}}
}
UIManager:show(shortcut_shortcuts_dialog)
return true
end
end
function Terminal:copyCommands(item)
local new_item = {
text = item.text .. " (copy)",
commands = item.commands
}
table.insert(self.shortcuts, new_item)
UIManager:show(InfoMessage:new{
text = _("Shortcut copied"),
timeout = 2
})
self:saveShortcuts()
self:manageShortcuts()
end
function Terminal:editCommands(item)
local edit_dialog
edit_dialog = InputDialog:new{
title = T(_('Edit commands for "%1"'), item.text),
input = item.commands,
width = Screen:getWidth() * 0.9,
para_direction_rtl = false, -- force LTR
input_type = "string",
allow_newline = true,
cursor_at_end = true,
fullscreen = true,
buttons = {{{
text = _("Cancel"),
callback = function()
UIManager:close(edit_dialog)
edit_dialog = nil
self:manageShortcuts()
end,
}, {
text = _("Save"),
callback = function()
local input = edit_dialog:getInputText()
UIManager:close(edit_dialog)
edit_dialog = nil
if input:match("[A-Za-z]") then
self.shortcuts[item.nr]["commands"] = input
self:saveShortcuts()
self:manageShortcuts()
end
end,
}}},
}
UIManager:show(edit_dialog)
edit_dialog:onShowKeyboard()
end
function Terminal:editName(item)
local edit_dialog
edit_dialog = InputDialog:new{
title = _("Edit name"),
input = item.text,
width = Screen:getWidth() * 0.9,
para_direction_rtl = false, -- force LTR
input_type = "string",
allow_newline = false,
cursor_at_end = true,
fullscreen = true,
buttons = {{{
text = _("Cancel"),
callback = function()
UIManager:close(edit_dialog)
edit_dialog = nil
self:manageShortcuts()
end,
}, {
text = _("Save"),
callback = function()
local input = edit_dialog:getInputText()
UIManager:close(edit_dialog)
edit_dialog = nil
if input:match("[A-Za-z]") then
self.shortcuts[item.nr]["text"] = input
self:saveShortcuts()
self:manageShortcuts()
end
end,
}}},
}
UIManager:show(edit_dialog)
edit_dialog:onShowKeyboard()
end
function Terminal:deleteShortcut(item)
for i = #self.shortcuts, 1, -1 do
local element = self.shortcuts[i]
if element.text == item.text and element.commands == item.commands then
table.remove(self.shortcuts, i)
end
end
self:saveShortcuts()
self:manageShortcuts()
end
function Terminal:onTerminalStart()
-- if shortcut commands are defined, go directly to the the shortcuts manager (so we can execute scripts more quickly):
if #self.shortcuts == 0 then
self:terminal()
else
self:manageShortcuts()
end
end
function Terminal:terminal()
self.input = InputDialog:new{
title = _("Enter a command and press \"Execute\""),
input = self.command:gsub("\n+$", ""),
para_direction_rtl = false, -- force LTR
input_type = "string",
allow_newline = true,
cursor_at_end = true,
fullscreen = true,
buttons = {{{
text = _("Cancel"),
callback = function()
UIManager:close(self.input)
end,
}, {
text = _("Shortcuts"),
callback = function()
UIManager:close(self.input)
self:manageShortcuts()
end,
}, {
text = _("Save"),
callback = function()
local input = self.input:getInputText()
if input:match("[A-Za-z]") then
local function callback(name)
local new_shortcut = {
text = name,
commands = input,
}
table.insert(self.shortcuts, new_shortcut)
self:saveShortcuts()
end
local prompt
prompt = InputDialog:new{
title = _("Name"),
input = "",
input_type = "text",
fullscreen = true,
condensed = true,
allow_newline = false,
cursor_at_end = true,
buttons = {{{
text = _("Cancel"),
callback = function()
UIManager:close(prompt)
end,
},
{
text = _("Save"),
is_enter_default = true,
callback = function()
local newval = prompt:getInputText()
UIManager:close(prompt)
callback(newval)
end,
}}}
}
UIManager:show(prompt)
prompt:onShowKeyboard()
end
end,
}, {
text = _("Execute"),
callback = function()
UIManager:close(self.input)
-- so we know which middle button to display in the results:
self.source = "terminal"
self.command = self:ensureWhitelineAfterCommands(self.input:getInputText())
Trapper:wrap(function()
self:execute()
end)
end,
}}},
}
UIManager:show(self.input)
self.input:onShowKeyboard()
end
-- for prettier formatting of output by separating commands and result thereof with a whiteline:
function Terminal:ensureWhitelineAfterCommands(commands)
if string.sub(commands, -1) ~= "\n" then
commands = commands .. "\n"
end
return commands
end
function Terminal:execute()
local wait_msg = InfoMessage:new{
text = _("Executing…"),
}
UIManager:show(wait_msg)
local entries = { self.command }
local command = self.command .. " 2>&1 ; echo" -- ensure we get stderr and output something
local completed, result_str = Trapper:dismissablePopen(command, wait_msg)
if completed then
table.insert(entries, result_str)
self:dump(entries)
table.insert(entries, _("Output was also written to"))
table.insert(entries, self.dump_file)
else
table.insert(entries, _("Execution canceled."))
end
UIManager:close(wait_msg)
local viewer
local buttons_table
local back_button = {
text = _("Back"),
callback = function()
UIManager:close(viewer)
if self.source == "terminal" then
self:terminal()
else
self:manageShortcuts()
end
end,
}
local close_button = {
text = _("Close"),
callback = function()
UIManager:close(viewer)
end,
}
if self.source == "terminal" then
buttons_table = {
{
back_button,
{
text = _("Shortcuts"),
-- switch to shortcuts:
callback = function()
UIManager:close(viewer)
self:manageShortcuts()
end,
},
close_button,
},
}
else
buttons_table = {
{
back_button,
{
text = _("Terminal"),
-- switch to terminal:
callback = function()
UIManager:close(viewer)
self:terminal()
end,
},
close_button,
},
}
end
viewer = TextViewer:new{
title = _("Command output"),
text = table.concat(entries, "\n"),
justified = false,
text_face = Font:getFace("smallinfont"),
buttons_table = buttons_table,
}
UIManager:show(viewer)
end
function Terminal:dump(entries)
local content = table.concat(entries, "\n")
local file = io.open(self.dump_file, "w")
if file then
file:write(content)
file:close()
else
logger.warn("Failed to dump terminal output " .. content .. " to " .. self.dump_file)
end
end
function Terminal:addToMainMenu(menu_items)
menu_items.terminal = {
text = _("Terminal emulator"),
keep_menu_open = true,
callback = function()
self:onTerminalStart()
end,
}
end
return Terminal
| agpl-3.0 |
bnetcc/darkstar | scripts/globals/effects/sigil.lua | 1 | 3517 | -----------------------------------
--
-- EFFECT_SIGIL
--
-----------------------------------
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower(); -- Tracks which bonus effects are in use.
local subPower = effect:getSubPower(); -- subPower sets % required to trigger regen/refresh.
if (power == 1 or power == 3 or power == 5 or power == 7 or power == 9 or power == 11 or power == 13 or power == 15) then
-- target:addLatent(LATENT_SIGIL_REGEN, subPower+10, MOD_REGEN, 1);
-- Not yet implemented
target:addMod(MOD_REGEN,1); -- Todo: should be latent
end
if (power == 2 or power == 3 or power == 6 or power == 7 or power == 10 or power == 11 or power >= 14) then
-- target:addLatent(LATENT_SIGIL_REFRESH, subPower, MOD_REFRESH, 1);
-- Not yet implemented
target:addMod(MOD_REFRESH,1); -- Todo: should be latent
end
if (power >= 4 and power <= 7) then
-- target:addMod(MOD_FOOD_DURATION), ???);
-- food duration not implemented.
elseif (power >= 8 and power <= 11) then
-- target:addMod(MOD_EXPLOSS_REDUCTION), ???);
-- exp loss reduction not implemented.
elseif (power >= 12) then
-- Possibly handle exp loss reduction in core instead..Maybe the food bonus also?
-- target:addMod(MOD_FOOD_DURATION), ???);
-- food duration not implemented.
-- target:addLatent(LATENT_SIGIL_EXPLOSS, ?, MOD_EXPLOSS_REDUCTION, ?);
-- exp loss reduction not implemented.
end
-- Begin Custom stuff
if (target:isPC()) then
target:addMod(MOD_RERAISE_III,1);
end
-- End Custom Stuff
end;
-----------------------------------
-- onEffectTick Action
-----------------------------------
function onEffectTick(target,effect)
end;
-----------------------------------
-- onEffectLose Action
-----------------------------------
function onEffectLose(target,effect)
local power = effect:getPower(); -- Tracks which bonus effects are in use.
local subPower = effect:getSubPower(); -- subPower sets % required to trigger regen/refresh.
if (power == 1 or power == 3 or power == 5 or power == 7 or power == 9 or power == 11 or power == 13 or power == 15) then
-- target:delLatent(LATENT_SIGIL_REGEN, subPower+10, MOD_REGEN, 1);
-- Not yet implemented
target:delMod(MOD_REGEN,1); -- Todo: should be latent
end
if (power == 2 or power == 3 or power == 6 or power == 7 or power == 10 or power == 11 or power >= 14) then
-- target:delLatent(LATENT_SIGIL_REFRESH, subPower, MOD_REFRESH, 1);
-- Not yet implemented
target:delMod(MOD_REFRESH,1); -- Todo: should be latent
end
if (effect:getPower() >= 4 and effect:getPower() <= 7) then
-- target:delMod(MOD_FOOD_DURATION), ???);
-- food duration not implemented.
elseif (effect:getPower() >= 8 and effect:getPower() <= 11) then
-- target:delMod(MOD_EXPLOSS_REDUCTION), ???);
-- exp loss reduction not implemented.
elseif (effect:getPower() >= 12) then
-- target:delMod(MOD_FOOD_DURATION), ???);
-- food duration not implemented.
-- target:delMod(MOD_EXPLOSS_REDUCTION), ???);
-- exp loss reduction not implemented.
end
-- Begin Custom stuff
if (target:isPC()) then
target:delMod(MOD_RERAISE_III,1);
end
-- End Custom Stuff
end; | gpl-3.0 |
graphdat/plugin-pingcheck | init.lua | 1 | 2627 | local framework = require('framework')
local CommandOutputDataSource = framework.CommandOutputDataSource
local PollerCollection = framework.PollerCollection
local DataSourcePoller = framework.DataSourcePoller
local Plugin = framework.Plugin
local os = require('os')
local table = require('table')
local string = require('string')
local isEmpty = framework.string.isEmpty
local clone = framework.table.clone
local params = framework.params
local commands = {
linux = { path = '/bin/ping', args = {'-n', '-w 2', '-c 1'} },
win32 = { path = 'C:/windows/system32/ping.exe', args = {'-n', '1', '-w', '3000'} },
darwin = { path = '/sbin/ping', args = {'-n', '-t 2', '-c 1'} }
}
local ping_command = commands[string.lower(os.type())]
if ping_command == nil then
print("_bevent:"..(Plugin.name or params.name)..":"..(Plugin.version or params.version)..":Your platform is not supported. We currently support Linux, Windows and OSX|t:error|tags:lua,plugin"..(Plugin.tags and framework.string.concat(Plugin.tags, ',') or params.tags))
process:exit(-1)
end
local function createPollers (params, cmd)
local pollers = PollerCollection:new()
for _, item in ipairs(params.items) do
cmd = clone(cmd)
table.insert(cmd.args, item.host)
cmd.info = item.source
local data_source = CommandOutputDataSource:new(cmd)
local poll_interval = tonumber(item.pollInterval or params.pollInterval) * 1000
local poller = DataSourcePoller:new(poll_interval, data_source)
pollers:add(poller)
end
return pollers
end
local function parseOutput(context, output)
assert(output ~= nil, 'parseOutput expect some data')
if isEmpty(output) then
context:emit('error', 'Unable to obtain any output.')
return
end
if (string.find(output, "unknown host") or string.find(output, "could not find host.")) then
context:emit('error', 'The host ' .. context.args[#context.args] .. ' was not found.')
return
end
local index
local prevIndex = 0
while true do
index = string.find(output, '\n', prevIndex+1)
if not index then break end
local line = string.sub(output, prevIndex, index-1)
local _, _, time = string.find(line, "time=([0-9]*%.?[0-9]+)")
if time then
return tonumber(time)
end
prevIndex = index
end
return -1
end
local pollers = createPollers(params, ping_command)
local plugin = Plugin:new(params, pollers)
function plugin:onParseValues(data)
local result = {}
local value = parseOutput(self, data['output'])
result['PING_RESPONSETIME'] = { value = value, source = data['info'] }
return result
end
plugin:run()
| apache-2.0 |
tahashakiba/booooooo | plugins/inrealm.lua | 71 | 25005 | -- data saved to moderation.json
-- check moderation plugin
do
local function create_group(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function create_realm(msg)
-- superuser and admins only (because sudo are always has privilege)
if is_sudo(msg) or is_realm(msg) and is_admin(msg) then
local group_creator = msg.from.print_name
create_group_chat (group_creator, group_name, ok_cb, false)
return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.'
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function get_group_type(msg)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if not data[tostring(msg.to.id)]['group_type'] then
return 'No group type available.'
end
local group_type = data[tostring(msg.to.id)]['group_type']
return group_type
else
return 'Chat type not found.'
end
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function set_description(msg, data, target, about)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function set_rules(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
-- lock/unlock group name. bot automatically change group name when locked
local function lock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
--lock/unlock group member. bot automatically kick new added user when locked
local function lock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
--lock/unlock group photo. bot automatically keep group photo when locked
local function lock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'Group photo is already locked'
else
data[tostring(target)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'Please send me the group photo now'
end
local function unlock_group_photo(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function lock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_flood(msg, data, target)
if not is_admin(msg) then
return "For admins only!"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
-- show group settings
local function show_group_settings(msg, data, target)
local data = load_data(_config.moderation.data, data)
if not is_admin(msg) then
return "For admins only!"
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member
return text
end
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
send_large_msg(receiver, text)
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
end
local function returnidsfile(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..''
for k,v in pairs(result.members) do
if v.print_name then
local username = ""
text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n"
end
end
local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false)
end
local function admin_promote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(admins)][tostring(admin_id)] then
return admin_name..' is already an admin.'
end
data[tostring(admins)][tostring(admin_id)] = admin_id
save_data(_config.moderation.data, data)
return admin_id..' has been promoted as admin.'
end
local function admin_demote(msg, admin_id)
if not is_sudo(msg) then
return "Access denied!"
end
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
if not data[tostring(admins)][tostring(admin_id)] then
return admin_id..' is not an admin.'
end
data[tostring(admins)][tostring(admin_id)] = nil
save_data(_config.moderation.data, data)
return admin_id..' has been demoted from admin.'
end
local function admin_list(msg)
local data = load_data(_config.moderation.data)
local admins = 'admins'
if not data[tostring(admins)] then
data[tostring(admins)] = {}
save_data(_config.moderation.data, data)
end
local message = 'List for Realm admins:\n'
for k,v in pairs(data[tostring(admins)]) do
message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n'
end
return message
end
local function groups_list(msg)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] then
return 'No groups at the moment'
end
local message = 'List of groups:\n'
for k,v in pairs(data[tostring(groups)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['set_owner'] then
group_owner = tostring(data[tostring(v)]['set_owner'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/groups.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function realms_list(msg)
local data = load_data(_config.moderation.data)
local realms = 'realms'
if not data[tostring(realms)] then
return 'No Realms at the moment'
end
local message = 'List of Realms:\n'
for k,v in pairs(data[tostring(realms)]) do
local settings = data[tostring(v)]['settings']
for m,n in pairs(settings) do
if m == 'set_name' then
name = n
end
end
local group_owner = "No owner"
if data[tostring(v)]['admins_in'] then
group_owner = tostring(data[tostring(v)]['admins_in'])
end
local group_link = "No link"
if data[tostring(v)]['settings']['set_link'] then
group_link = data[tostring(v)]['settings']['set_link']
end
message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n"
end
local file = io.open("./groups/lists/realms.txt", "w")
file:write(message)
file:flush()
file:close()
return message
end
local function admin_user_promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already as admin.')
end
data['admins'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.')
end
local function admin_user_demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
if not data['admins'] then
data['admins'] = {}
save_data(_config.moderation.data, data)
end
if not data['admins'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not an admin.')
end
data['admins'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.')
end
local function username_id(cb_extra, success, result)
local mod_cmd = cb_extra.mod_cmd
local receiver = cb_extra.receiver
local member = cb_extra.member
local text = 'No user @'..member..' in this group.'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == member then
member_username = member
member_id = v.id
if mod_cmd == 'addadmin' then
return admin_user_promote(receiver, member_username, member_id)
elseif mod_cmd == 'removeadmin' then
return admin_user_demote(receiver, member_username, member_id)
end
end
end
send_large_msg(receiver, text)
end
local function set_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'yes' then
return 'Log group is already set'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes'
save_data(_config.moderation.data, data)
return 'Log group has been set'
end
end
local function unset_log_group(msg)
if not is_admin(msg) then
return
end
local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group']
if log_group == 'no' then
return 'Log group is already disabled'
else
data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no'
save_data(_config.moderation.data, data)
return 'log group has been disabled'
end
end
local function help()
local help_text = tostring(_config.help_text_realm)
return help_text
end
function run(msg, matches)
--vardump(msg)
local name_log = user_print_name(msg.from)
if matches[1] == 'log' and is_owner(msg) then
savelog(msg.to.id, "log file created by owner")
send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false)
end
if matches[1] == 'who' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ")
local receiver = get_receiver(msg)
chat_info(receiver, returnidsfile, {receiver=receiver})
end
if matches[1] == 'wholist' and is_momod(msg) then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file")
local receiver = get_receiver(msg)
chat_info(receiver, returnids, {receiver=receiver})
end
if matches[1] == 'creategroup' and matches[2] then
group_name = matches[2]
group_type = 'group'
return create_group(msg)
end
if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then
return --Do nothing
end
if matches[1] == 'createrealm' and matches[2] then
group_name = matches[2]
group_type = 'realm'
return create_realm(msg)
end
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if matches[2] then if data[tostring(matches[2])] then
local settings = data[tostring(matches[2])]['settings']
if matches[1] == 'setabout' and matches[2] then
local target = matches[2]
local about = matches[3]
return set_description(msg, data, target, about)
end
if matches[1] == 'setrules' then
rules = matches[3]
local target = matches[2]
return set_rules(msg, data, target)
end
if matches[1] == 'lock' then --group lock *
local target = matches[2]
if matches[3] == 'name' then
return lock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return lock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return lock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return lock_group_flood(msg, data, target)
end
end
if matches[1] == 'unlock' then --group unlock *
local target = matches[2]
if matches[3] == 'name' then
return unlock_group_name(msg, data, target)
end
if matches[3] == 'member' then
return unlock_group_member(msg, data, target)
end
if matches[3] == 'photo' then
return unlock_group_photo(msg, data, target)
end
if matches[3] == 'flood' then
return unlock_group_flood(msg, data, target)
end
end
if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then
local target = matches[2]
return show_group_settings(msg, data, target)
end
if matches[1] == 'setname' and is_realm(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'setgpname' and is_admin(msg) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
end
end
if matches[1] == 'help' and is_realm(msg) then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'set' then
if matches[2] == 'loggroup' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group")
return set_log_group(msg)
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return modrem(msg),
print("Closing Group: "..receiver),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'Error: Group '..matches[3]..' not found'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if is_realm(msg) then
local receiver = 'chat#id'..matches[3]
return realmrem(msg),
print("Closing realm: "..receiver),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'Error: Realm '..matches[3]..' not found'
end
end
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if not is_admin(msg) then
chat_del_user(chat, user, ok_cb, true)
end
end
if matches[1] == 'addadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been promoted as admin")
return admin_promote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "addadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'removeadmin' then
if string.match(matches[2], '^%d+$') then
local admin_id = matches[2]
print("user "..admin_id.." has been demoted")
return admin_demote(msg, admin_id)
else
local member = string.gsub(matches[2], "@", "")
local mod_cmd = "removeadmin"
chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member})
end
end
if matches[1] == 'type'then
local group_type = get_group_type(msg)
return group_type
end
if matches[1] == 'list' and matches[2] == 'admins' then
return admin_list(msg)
end
if matches[1] == 'list' and matches[2] == 'groups' then
if msg.to.type == 'chat' then
groups_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
elseif msg.to.type == 'user' then
groups_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false)
return "Group list created" --group_list(msg)
end
end
if matches[1] == 'list' and matches[2] == 'realms' then
if msg.to.type == 'chat' then
realms_list(msg)
send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
elseif msg.to.type == 'user' then
realms_list(msg)
send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false)
return "Realms list created" --realms_list(msg)
end
end
if matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
end
return {
patterns = {
"^(creategroup) (.*)$",
"^(createrealm) (.*)$",
"^(setabout) (%d+) (.*)$",
"^(setrules) (%d+) (.*)$",
"^(setname) (.*)$",
"^(setgpname) (%d+) (.*)$",
"^(setname) (%d+) (.*)$",
"^(lock) (%d+) (.*)$",
"^(unlock) (%d+) (.*)$",
"^(setting) (%d+)$",
"^(wholist)$",
"^(who)$",
"^(type)$",
"^(kill) (chat) (%d+)$",
"^(kill) (realm) (%d+)$",
"^(addadmin) (.*)$", -- sudoers only
"^(removeadmin) (.*)$", -- sudoers only
"^(list) (.*)$",
"^(log)$",
"^(help)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
bnetcc/darkstar | scripts/globals/items/bottle_of_barbarians_drink.lua | 1 | 1102 | -----------------------------------------
-- ID: 5385
-- Item: Bottle of Barbarian's Drink
-- Item Effect: +50% Attk
-- Durration: 60 Secs
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_MEDICINE)) then
result = 111;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
if (target:addStatusEffect(EFFECT_MEDICINE,0,0,60,5835)) then
target:messageBasic(205);
else
target:messageBasic(423); -- no effect
end
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_ATTP, 50);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_ATTP, 50);
end;
| gpl-3.0 |
TurkeyMan/premake-core | modules/vstudio/tests/vc2010/test_ensure_nuget_imports.lua | 11 | 1951 | --
-- tests/actions/vstudio/vc2010/test_ensure_nuget_imports.lua
-- Check the EnsureNuGetPackageBuildImports block of a VS 2010 project.
-- Copyright (c) 2016 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vs2010_ensure_nuget_imports")
local vc2010 = p.vstudio.vc2010
local project = p.project
--
-- Setup
--
local wks
function suite.setup()
p.action.set("vs2010")
wks = test.createWorkspace()
end
local function prepare()
local prj = p.workspace.getproject(wks, 1)
vc2010.ensureNuGetPackageBuildImports(prj)
end
--
-- Should not output anything if no packages have been set.
--
function suite.noOutputIfNoPackages()
prepare()
test.isemptycapture()
end
--
-- Writes the pre-build check that makes sure that all packages are installed.
--
function suite.structureIsCorrect()
nuget { "boost:1.59.0-b1", "sdl2.v140:2.0.3", "sdl2.v140.redist:2.0.3" }
prepare()
test.capture [[
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('packages\boost.1.59.0-b1\build\native\boost.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\boost.1.59.0-b1\build\native\boost.targets'))" />
<Error Condition="!Exists('packages\sdl2.v140.2.0.3\build\native\sdl2.v140.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\sdl2.v140.2.0.3\build\native\sdl2.v140.targets'))" />
<Error Condition="!Exists('packages\sdl2.v140.redist.2.0.3\build\native\sdl2.v140.redist.targets')" Text="$([System.String]::Format('$(ErrorText)', 'packages\sdl2.v140.redist.2.0.3\build\native\sdl2.v140.redist.targets'))" />
</Target>
]]
end
| bsd-3-clause |
bnetcc/darkstar | scripts/globals/spells/bluemagic/thermal_pulse.lua | 1 | 1666 | -----------------------------------------
-- Spell: Thermal Pulse
-----------------------------------------
require("scripts/globals/bluemagic");
require("scripts/globals/status");
require("scripts/globals/magic");
require("scripts/globals/msg");
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local params = {};
params.attribute = MOD_INT;
params.skillType = BLUE_SKILL;
params.effect = EFFECT_BLINDNESS;
params.multiplier = 4.0;
params.tMultiplier = 2.0;
params.duppercap = 90;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.4;
params.agi_wsc = 0.0;
params.int_wsc = 0.0;
params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
local damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local resist = applyResistance(caster, target, spell, params);
if (caster:hasStatusEffect(EFFECT_AZURE_LORE)) then
multi = multi + 0.50;
end
if (damage > 0 and resist < 0.4) then
-- Def nawt retail at all, there is no info for how strong the blind is
local nawtRetail = (caster:getStat(MOD_MND) - target:getStat(MOD_INT));
local nawtRetail = math.floor(nawtRetail * 3/8) + 45;
if (nawtRetail < 15) then
nawtRetail = 15;
elseif (nawtRetail > 90) then
nawtRetail = 90;
end
target:addStatusEffect(params.effect,nawtRetail,0,getBlueEffectDuration(caster,resist,params.effect));
end
return damage;
end;
| gpl-3.0 |
yswifi/APlan | build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/libs/sys/luasrc/sys.lua | 43 | 25825 | --[[
LuCI - System library
Description:
Utilities for interaction with the Linux system
FileId:
$Id$
License:
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
]]--
local io = require "io"
local os = require "os"
local table = require "table"
local nixio = require "nixio"
local fs = require "nixio.fs"
local uci = require "luci.model.uci"
local luci = {}
luci.util = require "luci.util"
luci.ip = require "luci.ip"
local tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select =
tonumber, ipairs, pairs, pcall, type, next, setmetatable, require, select
--- LuCI Linux and POSIX system utilities.
module "luci.sys"
--- Execute a given shell command and return the error code
-- @class function
-- @name call
-- @param ... Command to call
-- @return Error code of the command
function call(...)
return os.execute(...) / 256
end
--- Execute a given shell command and capture its standard output
-- @class function
-- @name exec
-- @param command Command to call
-- @return String containg the return the output of the command
exec = luci.util.exec
--- Retrieve information about currently mounted file systems.
-- @return Table containing mount information
function mounts()
local data = {}
local k = {"fs", "blocks", "used", "available", "percent", "mountpoint"}
local ps = luci.util.execi("df")
if not ps then
return
else
ps()
end
for line in ps do
local row = {}
local j = 1
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
if row[k[1]] then
-- this is a rather ugly workaround to cope with wrapped lines in
-- the df output:
--
-- /dev/scsi/host0/bus0/target0/lun0/part3
-- 114382024 93566472 15005244 86% /mnt/usb
--
if not row[k[2]] then
j = 2
line = ps()
for value in line:gmatch("[^%s]+") do
row[k[j]] = value
j = j + 1
end
end
table.insert(data, row)
end
end
return data
end
--- Retrieve environment variables. If no variable is given then a table
-- containing the whole environment is returned otherwise this function returns
-- the corresponding string value for the given name or nil if no such variable
-- exists.
-- @class function
-- @name getenv
-- @param var Name of the environment variable to retrieve (optional)
-- @return String containg the value of the specified variable
-- @return Table containing all variables if no variable name is given
getenv = nixio.getenv
--- Get or set the current hostname.
-- @param String containing a new hostname to set (optional)
-- @return String containing the system hostname
function hostname(newname)
if type(newname) == "string" and #newname > 0 then
fs.writefile( "/proc/sys/kernel/hostname", newname )
return newname
else
return nixio.uname().nodename
end
end
--- Returns the contents of a documented referred by an URL.
-- @param url The URL to retrieve
-- @param stream Return a stream instead of a buffer
-- @param target Directly write to target file name
-- @return String containing the contents of given the URL
function httpget(url, stream, target)
if not target then
local source = stream and io.popen or luci.util.exec
return source("wget -qO- '"..url:gsub("'", "").."'")
else
return os.execute("wget -qO '%s' '%s'" %
{target:gsub("'", ""), url:gsub("'", "")})
end
end
--- Returns the system load average values.
-- @return String containing the average load value 1 minute ago
-- @return String containing the average load value 5 minutes ago
-- @return String containing the average load value 15 minutes ago
function loadavg()
local info = nixio.sysinfo()
return info.loads[1], info.loads[2], info.loads[3]
end
--- Initiate a system reboot.
-- @return Return value of os.execute()
function reboot()
return os.execute("reboot >/dev/null 2>&1")
end
--- Returns the system type, cpu name and installed physical memory.
-- @return String containing the system or platform identifier
-- @return String containing hardware model information
-- @return String containing the total memory amount in kB
-- @return String containing the memory used for caching in kB
-- @return String containing the memory used for buffering in kB
-- @return String containing the free memory amount in kB
-- @return String containing the cpu bogomips (number)
function sysinfo()
local cpuinfo = fs.readfile("/proc/cpuinfo")
local meminfo = fs.readfile("/proc/meminfo")
local memtotal = tonumber(meminfo:match("MemTotal:%s*(%d+)"))
local memcached = tonumber(meminfo:match("\nCached:%s*(%d+)"))
local memfree = tonumber(meminfo:match("MemFree:%s*(%d+)"))
local membuffers = tonumber(meminfo:match("Buffers:%s*(%d+)"))
local bogomips = tonumber(cpuinfo:match("[Bb]ogo[Mm][Ii][Pp][Ss].-: ([^\n]+)")) or 0
local swaptotal = tonumber(meminfo:match("SwapTotal:%s*(%d+)"))
local swapcached = tonumber(meminfo:match("SwapCached:%s*(%d+)"))
local swapfree = tonumber(meminfo:match("SwapFree:%s*(%d+)"))
local system =
cpuinfo:match("system type\t+: ([^\n]+)") or
cpuinfo:match("Processor\t+: ([^\n]+)") or
cpuinfo:match("model name\t+: ([^\n]+)")
local model =
luci.util.pcdata(fs.readfile("/tmp/sysinfo/model")) or
cpuinfo:match("machine\t+: ([^\n]+)") or
cpuinfo:match("Hardware\t+: ([^\n]+)") or
luci.util.pcdata(fs.readfile("/proc/diag/model")) or
nixio.uname().machine or
system
return system, model, memtotal, memcached, membuffers, memfree, bogomips, swaptotal, swapcached, swapfree
end
--- Retrieves the output of the "logread" command.
-- @return String containing the current log buffer
function syslog()
return luci.util.exec("logread")
end
--- Retrieves the output of the "dmesg" command.
-- @return String containing the current log buffer
function dmesg()
return luci.util.exec("dmesg")
end
--- Generates a random id with specified length.
-- @param bytes Number of bytes for the unique id
-- @return String containing hex encoded id
function uniqueid(bytes)
local rand = fs.readfile("/dev/urandom", bytes)
return rand and nixio.bin.hexlify(rand)
end
--- Returns the current system uptime stats.
-- @return String containing total uptime in seconds
function uptime()
return nixio.sysinfo().uptime
end
--- LuCI system utilities / network related functions.
-- @class module
-- @name luci.sys.net
net = {}
--- Returns the current arp-table entries as two-dimensional table.
-- @return Table of table containing the current arp entries.
-- The following fields are defined for arp entry objects:
-- { "IP address", "HW address", "HW type", "Flags", "Mask", "Device" }
function net.arptable(callback)
local arp = (not callback) and {} or nil
local e, r, v
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
local r = { }, v
for v in e:gmatch("%S+") do
r[#r+1] = v
end
if r[1] ~= "IP" then
local x = {
["IP address"] = r[1],
["HW type"] = r[2],
["Flags"] = r[3],
["HW address"] = r[4],
["Mask"] = r[5],
["Device"] = r[6]
}
if callback then
callback(x)
else
arp = arp or { }
arp[#arp+1] = x
end
end
end
end
return arp
end
local function _nethints(what, callback)
local _, k, e, mac, ip, name
local cur = uci.cursor()
local ifn = { }
local hosts = { }
local function _add(i, ...)
local k = select(i, ...)
if k then
if not hosts[k] then hosts[k] = { } end
hosts[k][1] = select(1, ...) or hosts[k][1]
hosts[k][2] = select(2, ...) or hosts[k][2]
hosts[k][3] = select(3, ...) or hosts[k][3]
hosts[k][4] = select(4, ...) or hosts[k][4]
end
end
if fs.access("/proc/net/arp") then
for e in io.lines("/proc/net/arp") do
ip, mac = e:match("^([%d%.]+)%s+%S+%s+%S+%s+([a-fA-F0-9:]+)%s+")
if ip and mac then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/etc/ethers") then
for e in io.lines("/etc/ethers") do
mac, ip = e:match("^([a-f0-9]%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, nil)
end
end
end
if fs.access("/var/dhcp.leases") then
for e in io.lines("/var/dhcp.leases") do
mac, ip, name = e:match("^%d+ (%S+) (%S+) (%S+)")
if mac and ip then
_add(what, mac:upper(), ip, nil, name ~= "*" and name)
end
end
end
cur:foreach("dhcp", "host",
function(s)
for mac in luci.util.imatch(s.mac) do
_add(what, mac:upper(), s.ip, nil, s.name)
end
end)
for _, e in ipairs(nixio.getifaddrs()) do
if e.name ~= "lo" then
ifn[e.name] = ifn[e.name] or { }
if e.family == "packet" and e.addr and #e.addr == 17 then
ifn[e.name][1] = e.addr:upper()
elseif e.family == "inet" then
ifn[e.name][2] = e.addr
elseif e.family == "inet6" then
ifn[e.name][3] = e.addr
end
end
end
for _, e in pairs(ifn) do
if e[what] and (e[2] or e[3]) then
_add(what, e[1], e[2], e[3], e[4])
end
end
for _, e in luci.util.kspairs(hosts) do
callback(e[1], e[2], e[3], e[4])
end
end
--- Returns a two-dimensional table of mac address hints.
-- @return Table of table containing known hosts from various sources.
-- Each entry contains the values in the following order:
-- [ "mac", "name" ]
function net.mac_hints(callback)
if callback then
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
callback(mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4)
end
end)
else
local rv = { }
_nethints(1, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4 or v6, nil, 100) or v4
if name and name ~= mac then
rv[#rv+1] = { mac, name or nixio.getnameinfo(v4 or v6, nil, 100) or v4 }
end
end)
return rv
end
end
--- Returns a two-dimensional table of IPv4 address hints.
-- @return Table of table containing known hosts from various sources.
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv4_hints(callback)
if callback then
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
callback(v4, name)
end
end)
else
local rv = { }
_nethints(2, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v4, nil, 100) or mac
if name and name ~= v4 then
rv[#rv+1] = { v4, name }
end
end)
return rv
end
end
--- Returns a two-dimensional table of IPv6 address hints.
-- @return Table of table containing known hosts from various sources.
-- Each entry contains the values in the following order:
-- [ "ip", "name" ]
function net.ipv6_hints(callback)
if callback then
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
callback(v6, name)
end
end)
else
local rv = { }
_nethints(3, function(mac, v4, v6, name)
name = name or nixio.getnameinfo(v6, nil, 100) or mac
if name and name ~= v6 then
rv[#rv+1] = { v6, name }
end
end)
return rv
end
end
--- Returns conntrack information
-- @return Table with the currently tracked IP connections
function net.conntrack(callback)
local connt = {}
if fs.access("/proc/net/nf_conntrack", "r") then
for line in io.lines("/proc/net/nf_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[6] ~= "TIME_WAIT" then
entry.layer3 = flags[1]
entry.layer4 = flags[3]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
elseif fs.access("/proc/net/ip_conntrack", "r") then
for line in io.lines("/proc/net/ip_conntrack") do
line = line:match "^(.-( [^ =]+=).-)%2"
local entry, flags = _parse_mixed_record(line, " +")
if flags[4] ~= "TIME_WAIT" then
entry.layer3 = "ipv4"
entry.layer4 = flags[1]
for i=1, #entry do
entry[i] = nil
end
if callback then
callback(entry)
else
connt[#connt+1] = entry
end
end
end
else
return nil
end
return connt
end
--- Determine the current IPv4 default route. If multiple default routes exist,
-- return the one with the lowest metric.
-- @return Table with the properties of the current default route.
-- The following fields are defined:
-- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
-- "flags", "device" }
function net.defaultroute()
local route
net.routes(function(rt)
if rt.dest:prefix() == 0 and (not route or route.metric > rt.metric) then
route = rt
end
end)
return route
end
--- Determine the current IPv6 default route. If multiple default routes exist,
-- return the one with the lowest metric.
-- @return Table with the properties of the current default route.
-- The following fields are defined:
-- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
-- "flags", "device" }
function net.defaultroute6()
local route
net.routes6(function(rt)
if rt.dest:prefix() == 0 and rt.device ~= "lo" and
(not route or route.metric > rt.metric)
then
route = rt
end
end)
if not route then
local global_unicast = luci.ip.IPv6("2000::/3")
net.routes6(function(rt)
if rt.dest:equal(global_unicast) and
(not route or route.metric > rt.metric)
then
route = rt
end
end)
end
return route
end
--- Determine the names of available network interfaces.
-- @return Table containing all current interface names
function net.devices()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
devs[#devs+1] = v.name
end
end
return devs
end
--- Return information about available network interfaces.
-- @return Table containing all current interface names and their information
function net.deviceinfo()
local devs = {}
for k, v in ipairs(nixio.getifaddrs()) do
if v.family == "packet" then
local d = v.data
d[1] = d.rx_bytes
d[2] = d.rx_packets
d[3] = d.rx_errors
d[4] = d.rx_dropped
d[5] = 0
d[6] = 0
d[7] = 0
d[8] = d.multicast
d[9] = d.tx_bytes
d[10] = d.tx_packets
d[11] = d.tx_errors
d[12] = d.tx_dropped
d[13] = 0
d[14] = d.collisions
d[15] = 0
d[16] = 0
devs[v.name] = d
end
end
return devs
end
-- Determine the MAC address belonging to the given IP address.
-- @param ip IPv4 address
-- @return String containing the MAC address or nil if it cannot be found
function net.ip4mac(ip)
local mac = nil
net.arptable(function(e)
if e["IP address"] == ip then
mac = e["HW address"]
end
end)
return mac
end
--- Returns the current kernel routing table entries.
-- @return Table of tables with properties of the corresponding routes.
-- The following fields are defined for route entry tables:
-- { "dest", "gateway", "metric", "refcount", "usecount", "irtt",
-- "flags", "device" }
function net.routes(callback)
local routes = { }
for line in io.lines("/proc/net/route") do
local dev, dst_ip, gateway, flags, refcnt, usecnt, metric,
dst_mask, mtu, win, irtt = line:match(
"([^%s]+)\t([A-F0-9]+)\t([A-F0-9]+)\t([A-F0-9]+)\t" ..
"(%d+)\t(%d+)\t(%d+)\t([A-F0-9]+)\t(%d+)\t(%d+)\t(%d+)"
)
if dev then
gateway = luci.ip.Hex( gateway, 32, luci.ip.FAMILY_INET4 )
dst_mask = luci.ip.Hex( dst_mask, 32, luci.ip.FAMILY_INET4 )
dst_ip = luci.ip.Hex(
dst_ip, dst_mask:prefix(dst_mask), luci.ip.FAMILY_INET4
)
local rt = {
dest = dst_ip,
gateway = gateway,
metric = tonumber(metric),
refcount = tonumber(refcnt),
usecount = tonumber(usecnt),
mtu = tonumber(mtu),
window = tonumber(window),
irtt = tonumber(irtt),
flags = tonumber(flags, 16),
device = dev
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
--- Returns the current ipv6 kernel routing table entries.
-- @return Table of tables with properties of the corresponding routes.
-- The following fields are defined for route entry tables:
-- { "source", "dest", "nexthop", "metric", "refcount", "usecount",
-- "flags", "device" }
function net.routes6(callback)
if fs.access("/proc/net/ipv6_route", "r") then
local routes = { }
for line in io.lines("/proc/net/ipv6_route") do
local dst_ip, dst_prefix, src_ip, src_prefix, nexthop,
metric, refcnt, usecnt, flags, dev = line:match(
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) ([a-f0-9]+) " ..
"([a-f0-9]+) +([^%s]+)"
)
if dst_ip and dst_prefix and
src_ip and src_prefix and
nexthop and metric and
refcnt and usecnt and
flags and dev
then
src_ip = luci.ip.Hex(
src_ip, tonumber(src_prefix, 16), luci.ip.FAMILY_INET6, false
)
dst_ip = luci.ip.Hex(
dst_ip, tonumber(dst_prefix, 16), luci.ip.FAMILY_INET6, false
)
nexthop = luci.ip.Hex( nexthop, 128, luci.ip.FAMILY_INET6, false )
local rt = {
source = src_ip,
dest = dst_ip,
nexthop = nexthop,
metric = tonumber(metric, 16),
refcount = tonumber(refcnt, 16),
usecount = tonumber(usecnt, 16),
flags = tonumber(flags, 16),
device = dev,
-- lua number is too small for storing the metric
-- add a metric_raw field with the original content
metric_raw = metric
}
if callback then
callback(rt)
else
routes[#routes+1] = rt
end
end
end
return routes
end
end
--- Tests whether the given host responds to ping probes.
-- @param host String containing a hostname or IPv4 address
-- @return Number containing 0 on success and >= 1 on error
function net.pingtest(host)
return os.execute("ping -c1 '"..host:gsub("'", '').."' >/dev/null 2>&1")
end
--- LuCI system utilities / process related functions.
-- @class module
-- @name luci.sys.process
process = {}
--- Get the current process id.
-- @class function
-- @name process.info
-- @return Number containing the current pid
function process.info(key)
local s = {uid = nixio.getuid(), gid = nixio.getgid()}
return not key and s or s[key]
end
--- Retrieve information about currently running processes.
-- @return Table containing process information
function process.list()
local data = {}
local k
local ps = luci.util.execi("/bin/busybox top -bn1")
if not ps then
return
end
for line in ps do
local pid, ppid, user, stat, vsz, mem, cpu, cmd = line:match(
"^ *(%d+) +(%d+) +(%S.-%S) +([RSDZTW][W ][<N ]) +(%d+) +(%d+%%) +(%d+%%) +(.+)"
)
local idx = tonumber(pid)
if idx then
data[idx] = {
['PID'] = pid,
['PPID'] = ppid,
['USER'] = user,
['STAT'] = stat,
['VSZ'] = vsz,
['%MEM'] = mem,
['%CPU'] = cpu,
['COMMAND'] = cmd
}
end
end
return data
end
--- Set the gid of a process identified by given pid.
-- @param gid Number containing the Unix group id
-- @return Boolean indicating successful operation
-- @return String containing the error message if failed
-- @return Number containing the error code if failed
function process.setgroup(gid)
return nixio.setgid(gid)
end
--- Set the uid of a process identified by given pid.
-- @param uid Number containing the Unix user id
-- @return Boolean indicating successful operation
-- @return String containing the error message if failed
-- @return Number containing the error code if failed
function process.setuser(uid)
return nixio.setuid(uid)
end
--- Send a signal to a process identified by given pid.
-- @class function
-- @name process.signal
-- @param pid Number containing the process id
-- @param sig Signal to send (default: 15 [SIGTERM])
-- @return Boolean indicating successful operation
-- @return Number containing the error code if failed
process.signal = nixio.kill
--- LuCI system utilities / user related functions.
-- @class module
-- @name luci.sys.user
user = {}
--- Retrieve user informations for given uid.
-- @class function
-- @name getuser
-- @param uid Number containing the Unix user id
-- @return Table containing the following fields:
-- { "uid", "gid", "name", "passwd", "dir", "shell", "gecos" }
user.getuser = nixio.getpw
--- Retrieve the current user password hash.
-- @param username String containing the username to retrieve the password for
-- @return String containing the hash or nil if no password is set.
-- @return Password database entry
function user.getpasswd(username)
local pwe = nixio.getsp and nixio.getsp(username) or nixio.getpw(username)
local pwh = pwe and (pwe.pwdp or pwe.passwd)
if not pwh or #pwh < 1 or pwh == "!" or pwh == "x" then
return nil, pwe
else
return pwh, pwe
end
end
--- Test whether given string matches the password of a given system user.
-- @param username String containing the Unix user name
-- @param pass String containing the password to compare
-- @return Boolean indicating wheather the passwords are equal
function user.checkpasswd(username, pass)
local pwh, pwe = user.getpasswd(username)
if pwe then
return (pwh == nil or nixio.crypt(pass, pwh) == pwh)
end
return false
end
--- Change the password of given user.
-- @param username String containing the Unix user name
-- @param password String containing the password to compare
-- @return Number containing 0 on success and >= 1 on error
function user.setpasswd(username, password)
if password then
password = password:gsub("'", [['"'"']])
end
if username then
username = username:gsub("'", [['"'"']])
end
return os.execute(
"(echo '" .. password .. "'; sleep 1; echo '" .. password .. "') | " ..
"passwd '" .. username .. "' >/dev/null 2>&1"
)
end
--- LuCI system utilities / wifi related functions.
-- @class module
-- @name luci.sys.wifi
wifi = {}
--- Get wireless information for given interface.
-- @param ifname String containing the interface name
-- @return A wrapped iwinfo object instance
function wifi.getiwinfo(ifname)
local stat, iwinfo = pcall(require, "iwinfo")
if ifname then
local c = 0
local u = uci.cursor_state()
local d, n = ifname:match("^(%w+)%.network(%d+)")
if d and n then
ifname = d
n = tonumber(n)
u:foreach("wireless", "wifi-iface",
function(s)
if s.device == d then
c = c + 1
if c == n then
ifname = s.ifname or s.device
return false
end
end
end)
elseif u:get("wireless", ifname) == "wifi-device" then
u:foreach("wireless", "wifi-iface",
function(s)
if s.device == ifname and s.ifname then
ifname = s.ifname
return false
end
end)
end
local t = stat and iwinfo.type(ifname)
local x = t and iwinfo[t] or { }
return setmetatable({}, {
__index = function(t, k)
if k == "ifname" then
return ifname
elseif x[k] then
return x[k](ifname)
end
end
})
end
end
--- LuCI system utilities / init related functions.
-- @class module
-- @name luci.sys.init
init = {}
init.dir = "/etc/init.d/"
--- Get the names of all installed init scripts
-- @return Table containing the names of all inistalled init scripts
function init.names()
local names = { }
for name in fs.glob(init.dir.."*") do
names[#names+1] = fs.basename(name)
end
return names
end
--- Get the index of he given init script
-- @param name Name of the init script
-- @return Numeric index value
function init.index(name)
if fs.access(init.dir..name) then
return call("env -i sh -c 'source %s%s enabled; exit ${START:-255}' >/dev/null"
%{ init.dir, name })
end
end
local function init_action(action, name)
if fs.access(init.dir..name) then
return call("env -i %s%s %s >/dev/null" %{ init.dir, name, action })
end
end
--- Test whether the given init script is enabled
-- @param name Name of the init script
-- @return Boolean indicating whether init is enabled
function init.enabled(name)
return (init_action("enabled", name) == 0)
end
--- Enable the given init script
-- @param name Name of the init script
-- @return Boolean indicating success
function init.enable(name)
return (init_action("enable", name) == 1)
end
--- Disable the given init script
-- @param name Name of the init script
-- @return Boolean indicating success
function init.disable(name)
return (init_action("disable", name) == 0)
end
--- Start the given init script
-- @param name Name of the init script
-- @return Boolean indicating success
function init.start(name)
return (init_action("start", name) == 0)
end
--- Stop the given init script
-- @param name Name of the init script
-- @return Boolean indicating success
function init.stop(name)
return (init_action("stop", name) == 0)
end
-- Internal functions
function _parse_mixed_record(cnt, delimiter)
delimiter = delimiter or " "
local data = {}
local flags = {}
for i, l in pairs(luci.util.split(luci.util.trim(cnt), "\n")) do
for j, f in pairs(luci.util.split(luci.util.trim(l), delimiter, nil, true)) do
local k, x, v = f:match('([^%s][^:=]*) *([:=]*) *"*([^\n"]*)"*')
if k then
if x == "" then
table.insert(flags, k)
else
data[k] = v
end
end
end
end
return data, flags
end
| gpl-2.0 |
samihacker01616/x | plugins/xy.lua | 2 | 1143 | do
local function run(msg, matches)
local bot_id = 212833120
local x = 212833120
local y = 207248520
local z = 125871286
local w = 189716959
if matches[1] == 'bye' and is_admin(msg) or msg.action.type == "chat_add_user" and msg.action.user.id == tonumber(bot_id) and not is_sudo(msg) then
chat_del_user("chat#id"..msg.to.id, 'user#id'..bot_id, ok_cb, false)
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(x) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..x, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(y) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..y, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(z) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..z, ok_cb, false)
end
elseif msg.action.type == "chat_del_user" and msg.action.user.id == tonumber(w) then
chat_add_user("chat#id"..msg.to.id, 'user#id'..w, ok_cb, false)
end
end
return {
patterns = {
"^[!/](bye)$",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
jpcy/bgfx | scripts/texturev.lua | 2 | 3279 | project ("texturev")
uuid (os.uuid("texturev") )
kind "ConsoleApp"
configuration {}
includedirs {
path.join(BX_DIR, "include"),
path.join(BIMG_DIR, "include"),
path.join(BGFX_DIR, "include"),
path.join(BGFX_DIR, "3rdparty"),
path.join(BGFX_DIR, "examples/common"),
path.join(MODULE_DIR, "include"),
path.join(MODULE_DIR, "3rdparty"),
}
files {
path.join(MODULE_DIR, "tools/texturev/**"),
}
links {
"example-common",
"bimg_decode",
"bimg",
"bgfx",
"bx",
}
if _OPTIONS["with-sdl"] then
defines { "ENTRY_CONFIG_USE_SDL=1" }
links { "SDL2" }
configuration { "x32", "windows" }
libdirs { "$(SDL2_DIR)/lib/x86" }
configuration { "x64", "windows" }
libdirs { "$(SDL2_DIR)/lib/x64" }
configuration {}
end
if _OPTIONS["with-glfw"] then
defines { "ENTRY_CONFIG_USE_GLFW=1" }
links { "glfw3" }
configuration { "linux or freebsd" }
links {
"Xrandr",
"Xinerama",
"Xi",
"Xxf86vm",
"Xcursor",
}
configuration { "osx" }
linkoptions {
"-framework CoreVideo",
"-framework IOKit",
}
configuration {}
end
configuration { "vs*" }
linkoptions {
"/ignore:4199", -- LNK4199: /DELAYLOAD:*.dll ignored; no imports found from *.dll
}
links { -- this is needed only for testing with GLES2/3 on Windows with VS2008
"DelayImp",
}
configuration { "vs201*" }
linkoptions { -- this is needed only for testing with GLES2/3 on Windows with VS201x
"/DELAYLOAD:\"libEGL.dll\"",
"/DELAYLOAD:\"libGLESv2.dll\"",
}
configuration { "mingw-*" }
targetextension ".exe"
configuration { "vs20* or mingw*" }
links {
"comdlg32",
"gdi32",
"psapi",
}
configuration { "winstore*" }
removelinks {
"DelayImp",
"gdi32",
"psapi"
}
links {
"d3d11",
"d3d12",
"dxgi"
}
linkoptions {
"/ignore:4264" -- LNK4264: archiving object file compiled with /ZW into a static library; note that when authoring Windows Runtime types it is not recommended to link with a static library that contains Windows Runtime metadata
}
-- WinRT targets need their own output directories are build files stomp over each other
targetdir (path.join(BGFX_BUILD_DIR, "arm_" .. _ACTION, "bin", _name))
objdir (path.join(BGFX_BUILD_DIR, "arm_" .. _ACTION, "obj", _name))
configuration { "mingw-clang" }
kind "ConsoleApp"
configuration { "android*" }
kind "ConsoleApp"
targetextension ".so"
linkoptions {
"-shared",
}
links {
"EGL",
"GLESv2",
}
configuration { "wasm*" }
kind "ConsoleApp"
configuration { "linux-* or freebsd" }
links {
"X11",
"GL",
"pthread",
}
configuration { "rpi" }
links {
"X11",
"GLESv2",
"EGL",
"bcm_host",
"vcos",
"vchiq_arm",
"pthread",
}
configuration { "osx" }
linkoptions {
"-framework Cocoa",
"-framework Metal",
"-framework QuartzCore",
"-framework OpenGL",
}
configuration { "ios*" }
kind "ConsoleApp"
linkoptions {
"-framework CoreFoundation",
"-framework Foundation",
"-framework OpenGLES",
"-framework UIKit",
"-framework QuartzCore",
}
configuration { "xcode*", "ios" }
kind "WindowedApp"
configuration { "qnx*" }
targetextension ""
links {
"EGL",
"GLESv2",
}
configuration {}
strip()
| bsd-2-clause |
virus322/selfbot | 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-3.0 |
UniverseMelowdi/TheMelowdi | 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 |
tiagosr/ld27-train | tiledloader/Grid.lua | 6 | 6367 | ---------------------------------------------------------------------------------------------------
-- -= Grid =-
---------------------------------------------------------------------------------------------------
local Grid = {class = "Grid"}
Grid.__index = Grid
---------------------------------------------------------------------------------------------------
-- Creates and returns a new grid
function Grid:new()
local grid = {}
grid.cells = {}
return setmetatable(grid, Grid)
end
---------------------------------------------------------------------------------------------------
-- Gets the value of a single cell
function Grid:get(x,y)
return self.cells[x] and self.cells[x][y]
end
---------------------------------------------------------------------------------------------------
-- Sets the value of a single cell
function Grid:set(x,y,value)
if not self.cells[x] then self.cells[x] = {} end
self.cells[x][y] = value
end
---------------------------------------------------------------------------------------------------
-- Iterate over all values
local x, y, row, val
function Grid:iterate()
x, y, row, val = nil, nil, nil, nil
return function()
repeat
if not y then
x, row = next(self.cells, x)
if not row then return end
end
y, val = next(row, y)
until y
return x, y, val
end
end
---------------------------------------------------------------------------------------------------
-- Iterate over a rectangle shape
function Grid:rectangle(startX, startY, width, height, includeNil)
local x, y = startX, startY
return function()
while y <= startY + height do
while x <= startX + width do
x = x+1
if self(x-1,y) ~= nil or includeNil then
return x-1, y, self(x-1,y)
end
end
x = startX
y = y+1
end
return nil
end
end
---------------------------------------------------------------------------------------------------
-- Iterate over a line. Set noDiag to true to keep from traversing diagonally.
function Grid:line(startX, startY, endX, endY, noDiag, includeNil)
local dx = math.abs(endX - startX)
local dy = math.abs(endY - startY)
local x = startX
local y = startY
local incrX = endX > startX and 1 or -1
local incrY = endY > startY and 1 or -1
local err = dx - dy
local err2 = err*2
local i = 1+dx+dy
local rx,ry,rv
local checkX = false
return function()
while i>0 do
rx,ry,rv = x,y,self(x,y)
err2 = err*2
while true do
checkX = not checkX
if checkX == true or not noDiag then
if err2 > -dy then
err = err - dy
x = x + incrX
i = i-1
if noDiag then break end
end
end
if checkX == false or not noDiag then
if err2 < dx then
err = err + dx
y = y + incrY
i = i-1
if noDiag then break end
end
end
if not noDiag then break end
end
if rx == endX and ry == endY then i = 0 end
if rv ~= nil or includeNil then return rx,ry,rv end
end
return nil
end
end
---------------------------------------------------------------------------------------------------
-- Iterates over a circle of cells
function Grid:circle(cx, cy, r, includeNil)
local x,y
x = x or cx-r
return function()
repeat
y = y == nil and cy or y <= cy and y-1 or y+1
while ((cx-x)*(cx-x)+(cy-y)*(cy-y)) >= r*r do
if x > cx+r then return nil end
x = x + (y < cy and 0 or 1)
y = cy + (y < cy and 1 or 0)
end
until self(x,y) ~= nil or includeNil
return x,y,self(x,y)
end
end
---------------------------------------------------------------------------------------------------
-- Cleans the grid of empty rows.
function Grid:clean()
for key,row in pairs(self.cells) do
if not next(row) then self.cells[key] = nil end
end
end
---------------------------------------------------------------------------------------------------
-- Clears the grid
function Grid:clear()
self.cells = {}
end
---------------------------------------------------------------------------------------------------
-- This makes calling the grid as a function act like Grid.get.
Grid.__call = Grid.get
---------------------------------------------------------------------------------------------------
-- Returns the grid class
return Grid
--------------------------------------------------------------------------------------
-- Copyright (c) 2011-2012 Casey Baxter
-- 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.
-- Except as contained in this notice, the name(s) of the above copyright holders
-- shall not be used in advertising or otherwise to promote the sale, use or
-- other dealings in this Software without prior written authorization.
-- 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 |
bnetcc/darkstar | scripts/commands/wallhack.lua | 1 | 1150 | ---------------------------------------------------------------------------------------------------
-- func: wallhack <optional target>
-- desc: Allows the player to walk through walls.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 0,
parameters = "s"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!wallhack {player}");
end;
function onTrigger(player, target)
-- validate target
local targ;
if (target == nil) then
targ = player;
else
targ = GetPlayerByName(target);
if (targ == nil) then
error(player, string.format("Player named '%s' not found!", target));
return;
end
end
-- toggle wallhack for target
if (targ:checkNameFlags(0x00000200)) then
targ:setFlag(0x00000200);
player:PrintToPlayer( string.format("Toggled %s's wallhack flag OFF.", targ:getName()) );
else
targ:setFlag(0x00000200);
player:PrintToPlayer( string.format("Toggled %s's wallhack flag ON.", targ:getName()) );
end
end
| gpl-3.0 |
dmccuskey/dmc-dragdrop | examples/dmc-dragdrop-oop/dmc_corona/lib/dmc_lua/lua_events_mix.lua | 32 | 8316 | --====================================================================--
-- dmc_lua/lua_events_mix.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014-2015 David McCuskey. 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.
--]]
--====================================================================--
--== DMC Lua Library : Lua Events Mixin
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.2.2"
--====================================================================--
--== Setup, Constants
local Events
local Utils = {} -- make copying from Utils easier
local assert = assert
local sfmt = string.format
local type = type
--====================================================================--
--== Support Functions
--== Start: copy from lua_utils ==--
function Utils.createObjectCallback( object, method )
assert( object ~= nil, "missing object in Utils.createObjectCallback" )
assert( method ~= nil, "missing method in Utils.createObjectCallback" )
--==--
return function( ... )
return method( object, ... )
end
end
--== End: copy from lua_utils ==--
-- callback is either function or object (table)
-- creates listener lookup key given event name and handler
--
local function _createEventListenerKey( e_name, handler )
return e_name .. "::" .. tostring( handler )
end
-- return event unmodified
--
local function _createCoronaEvent( obj, event )
return event
end
-- obj,
-- event type, string
-- data, anything
-- params, table of params
-- params.merge, boolean, if to merge data (table) in with event table
--
local function _createDmcEvent( obj, e_type, data, params )
params = params or {}
if params.merge==nil then params.merge=false end
--==--
local e
if params.merge and type( data )=='table' then
e = data
e.name = obj.EVENT
e.type = e_type
e.target = obj
else
e = {
name=obj.EVENT,
type=e_type,
target=obj,
data=data
}
end
return e
end
local function _patch( obj )
obj = obj or {}
-- add properties
Events.__init__( obj )
if obj.EVENT==nil then
obj.EVENT = Events.EVENT -- generic event name
end
-- add methods
obj.dispatchEvent = Events.dispatchEvent
obj.dispatchRawEvent = Events.dispatchRawEvent
obj.addEventListener = Events.addEventListener
obj.removeEventListener = Events.removeEventListener
obj.setDebug = Events.setDebug
obj.setEventFunc = Events.setEventFunc
obj._dispatchEvent = Events._dispatchEvent
return obj
end
--====================================================================--
--== Events Mixin
--====================================================================--
Events = {}
Events.EVENT = 'event_mix_event'
--======================================================--
-- Start: Mixin Setup for Lua Objects
function Events.__init__( self, params )
-- print( "Events.__init__" )
params = params or {}
--==--
--[[
event listeners key'd by:
* <event name>::<function>
* <event name>::<object>
{
<event name> = {
'event::function' = func,
'event::object' = object (table)
}
}
--]]
self.__event_listeners = {} -- holds event listeners
self.__debug_on = false
self.__event_func = params.event_func or _createDmcEvent
end
function Events.__undoInit__( self )
-- print( "Events.__undoInit__" )
self.__event_listeners = nil
self.__debug_on = nil
self.__event_func = nil
end
-- END: Mixin Setup for Lua Objects
--======================================================--
--====================================================================--
--== Public Methods
function Events.createCallback( self, method )
return Utils.createObjectCallback( self, method )
end
function Events.setDebug( self, value )
assert( type( value )=='boolean', "setDebug requires boolean" )
self.__debug_on = value
end
function Events.setEventFunc( self, func )
assert( func and type(func)=='function', 'setEventFunc requires function' )
self.__event_func = func
end
function Events.createEvent( self, ... )
return self.__event_func( self, ... )
end
function Events.dispatchEvent( self, ... )
-- print( "Events.dispatchEvent" )
local f = self.__event_func
self:_dispatchEvent( f( self, ... ) )
end
function Events.dispatchRawEvent( self, event )
-- print( "Events.dispatchRawEvent", event )
assert( type( event )=='table', "wrong type for event" )
assert( event.name, "event must have property 'name'")
--==--
self:_dispatchEvent( event )
end
-- addEventListener()
--
function Events.addEventListener( self, e_name, listener )
-- print( "Events.addEventListener", e_name, listener )
assert( type( e_name )=='string', sfmt( "Events.addEventListener event name should be a string, received '%s'", tostring(e_name)) )
assert( type(listener)=='function' or type(listener)=='table', sfmt( "Events.addEventListener callback should be function or object, received '%s'", tostring(listener) ))
-- Sanity Check
if not e_name or type( e_name )~='string' then
error( "ERROR addEventListener: event name must be string", 2 )
end
if not listener and not Utils.propertyIn( {'function','table'}, type(listener) ) then
error( "ERROR addEventListener: listener must be a function or object", 2 )
end
-- Processing
local events, listeners, key
events = self.__event_listeners
if not events[ e_name ] then events[ e_name ] = {} end
listeners = events[ e_name ]
key = _createEventListenerKey( e_name, listener )
if listeners[ key ] then
print("WARNING:: Events:addEventListener, already have listener")
else
listeners[ key ] = listener
end
end
-- removeEventListener()
--
function Events.removeEventListener( self, e_name, listener )
-- print( "Events.removeEventListener" );
local listeners, key
listeners = self.__event_listeners[ e_name ]
if not listeners or type(listeners)~= 'table' then
print( "WARNING:: Events:removeEventListener, no listeners found" )
end
key = _createEventListenerKey( e_name, listener )
if not listeners[ key ] then
print( "WARNING:: Events:removeEventListener, listener not found" )
else
listeners[ key ] = nil
end
end
--====================================================================--
--== Private Methods
function Events:_dispatchEvent( event )
-- print( "Events:_dispatchEvent", event.name );
local e_name, listeners
e_name = event.name
if not e_name or not self.__event_listeners[ e_name ] then return end
listeners = self.__event_listeners[ e_name ]
if type( listeners )~='table' then return end
for k, callback in pairs( listeners ) do
if type( callback )=='function' then
-- have function
callback( event )
elseif type( callback )=='table' and callback[e_name] then
-- have object/table
local method = callback[e_name]
method( callback, event )
else
print( "WARNING: Events dispatchEvent", e_name )
end
end
end
--====================================================================--
--== Events Facade
--====================================================================--
return {
EventsMix=Events,
dmcEventFunc=_createDmcEvent,
coronaEventFunc=_createCoronaEvent,
patch=_patch,
}
| mit |
erwin8086/basiccomputers | api.lua | 1 | 3947 | local bc = basiccomputers
--[[
Restrice computers dig-abiliti.
Computer can only dig if func returns true
]]
function bc.register_can_dig(func)
local old_can_dig = bc.can_dig
function bc.can_dig(pos, player)
if not func(pos, player) then
return false
else
return old_can_dig(pos, player)
end
end
end
--[[
Restrice access to computers inventory.
Access only granted if func returns true.
]]
function bc.register_can_inv(func)
local old_can_inv = bc.can_inv
function bc.can_inv(pos, player)
if not func(pos, player) then
return false
else
return old_can_inv(pos, player)
end
end
end
--[[
Restrice access to computers buttons.
If buttons can only accessed if func returns true.
]]
function bc.register_can_click(func)
local old_can_click = bc.can_click
function bc.can_click(pos, player)
if not func(pos, palyer) then
return false
else
return old_can_click(pos, player)
end
end
end
--[[
Restrice access to input line of computer.
Input only accepted if func returns true
]]
function bc.register_can_enter(func)
local old_can_enter = bc.can_enter
function bc.can_enter(pos, player)
if not func(pos, player) then
return false
else
return old_can_enter(pos, player)
end
end
end
--[[
Call func on computer punched.
]]
function bc.register_on_punch(func)
local old_on_punch = bc.on_punch
function bc.on_punch(pos, player)
func(pos, player)
if old_on_punch then
old_on_punch(pos, player)
end
end
end
--[[
Call func when computer starts.
If func returns true normal computers start procedure is skipped.
]]
function bc.register_on_start(func)
local old_on_start = bc.on_start
function bc.on_start(pos, player, start)
if func(pos, player, start) then
return true
elseif old_on_start then
return old_on_start(pos, player, start)
end
end
end
--[[
Called when computer stops.
If returns true computers normal stop procedure is skipped
]]
function bc.register_on_stop(func)
local old_on_stop = bc.on_stop
function bc.on_stop(pos, player)
if func(pos, player) then
return true
elseif old_on_stop then
return old_on_stop(pos, player)
end
end
end
--[[
Called when computer reboots.
If returns true computers normal reboot procedure is skipped.
]]
function bc.register_on_reboot(func)
local old_on_reboot = bc.on_reboot
function bc.on_reboot(pos, player)
if func(pos, player) then
return true
else
return old_on_reboot(pos, player)
end
end
end
--[[
Called when computer receive fields.
If returns true computers normal on receive is skipped.
]]
function bc.register_on_receive(func)
local old_on_receive = bc.on_receive
function bc.on_receive(pos, fields, player)
if func(pos, fields, player) then
return true
else
return old_on_receive(pos, fields, player)
end
end
end
--[[
Called when computer is calculated.
If returns true computers normal on calculated procedure is skipped.
]]
function bc.register_on_calc(func)
local old_on_calc = bc.on_calc
function bc.on_calc(pos)
if func(pos) then
return true
else
return old_on_calc(pos)
end
end
end
--[[
Register an Upgrade.
Registered Upgrade can put in Upgrade slot.
]]
function bc.register_upgrade(upgrade)
local old_is_upgrade = bc.is_upgrade
function bc.is_upgrade(u)
if u == upgrade then
return true
else
return old_is_upgrade(u)
end
end
end
--[[
Register basic command.
Example:
basiccomputers.register_command("P", function(basic, args)
local arg1 = args[1]
if type(arg1) == "string" then
basic:print(arg1)
end
end)
]]
function bc.register_command(cmd, func)
bc.basic.cmds[cmd] = func
end
--[[
Register basic function.
Example:
basiccomputers.register_function("FIVE", function(basic, args)
local arg1 = args1
if type(arg1) == "number" then
arg1 = arg1 * 5
else
arg1 = 5
end
return arg1
end)
]]
function bc.register_function(f, func)
bc.basic.funcs[f] = func
end
bc.api = 0.01
| lgpl-2.1 |
bnetcc/darkstar | scripts/zones/Bastok_Mines/npcs/Babenn.lua | 5 | 2009 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Babenn
-- Finishes Quest: The Eleventh's Hour
-- Involved in Quests: Riding on the Clouds
-- !pos 73 -1 34 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Mines/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/globals/titles");
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 1) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
function onTrigger(player,npc)
if (player:getQuestStatus(BASTOK,THE_ELEVENTH_S_HOUR) == QUEST_ACCEPTED and player:getVar("EleventhsHour") == 1) then
player:startEvent(45);
else
player:startEvent(40);
end
end;
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 45) then
if (player:getFreeSlotsCount() > 1) then
player:setVar("EleventhsHour",0);
player:delKeyItem(OLD_TOOLBOX);
player:addTitle(PURSUER_OF_THE_TRUTH);
player:addItem(16629);
player:messageSpecial(ITEM_OBTAINED,16629);
player:addFame(BASTOK,30);
player:completeQuest(BASTOK,THE_ELEVENTH_S_HOUR);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16629);
end
end
end;
| gpl-3.0 |
Maliv/Secret | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
ioiasff/mbg | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
lcf258/openwrtcn | applications/luci-app-statistics/luasrc/statistics/rrdtool/definitions/nut.lua | 24 | 2233 | -- Licensed to the public under the Apache License 2.0.
module("luci.statistics.rrdtool.definitions.nut",package.seeall)
function rrdargs( graph, plugin, plugin_instance, dtype )
local voltages = {
title = "%H: Voltages on UPS \"%pi\"",
vlabel = "V",
number_format = "%5.1lfV",
data = {
instances = {
voltage = { "battery", "input", "output" }
},
options = {
voltage_output = { color = "00e000", title = "Output voltage", noarea=true, overlay=true },
voltage_battery = { color = "0000ff", title = "Battery voltage", noarea=true, overlay=true },
voltage_input = { color = "ffb000", title = "Input voltage", noarea=true, overlay=true }
}
}
}
local currents = {
title = "%H: Current on UPS \"%pi\"",
vlabel = "A",
number_format = "%5.3lfA",
data = {
instances = {
current = { "battery", "output" }
},
options = {
current_output = { color = "00e000", title = "Output current", noarea=true, overlay=true },
current_battery = { color = "0000ff", title = "Battery current", noarea=true, overlay=true },
}
}
}
local percentage = {
title = "%H: Battery charge on UPS \"%pi\"",
vlabel = "Percent",
y_min = "0",
y_max = "100",
number_format = "%5.1lf%%",
data = {
sources = {
percent = { "percent" }
},
instances = {
percent = "charge"
},
options = {
percent_charge = { color = "00ff00", title = "Charge level" }
}
}
}
-- Note: This is in ISO8859-1 for rrdtool. Welcome to the 20th century.
local temperature = {
title = "%H: Battery temperature on UPS \"%pi\"",
vlabel = "\176C",
number_format = "%5.1lf\176C",
data = {
instances = {
temperature = "battery"
},
options = {
temperature_battery = { color = "ffb000", title = "Battery temperature" }
}
}
}
local timeleft = {
title = "%H: Time left on UPS \"%pi\"",
vlabel = "Minutes",
number_format = "%.1lfm",
data = {
sources = {
timeleft = { "timeleft" }
},
instances = {
timeleft = { "battery" }
},
options = {
timeleft_battery = { color = "0000ff", title = "Time left", transform_rpn = "60,/" }
}
}
}
return { voltages, currents, percentage, temperature, timeleft }
end
| apache-2.0 |
JabJabJab/Sledgehammer | lua/SledgehammerLua/media/lua/client/Sledgehammer/Gui/TabPanel.lua | 1 | 16043 | -- This file is part of Sledgehammer.
--
-- Sledgehammer is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Lesser General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Sledgehammer is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Lesser General Public License for more details.
--
-- You should have received a copy of the GNU Lesser General Public License
-- along with Sledgehammer. If not, see <http://www.gnu.org/licenses/>.
--
-- Sledgehammer is free to use and modify, ONLY for non-official third-party servers
-- not affiliated with TheIndieStone, or it's immediate affiliates, or contractors.
require "Sledgehammer/Gui/Component"
require "Util"
----------------------------------------------------------------
-- TabPanel.lua
-- UI for generic Tabbed Panels.
--
-- @author Jab
-- @license LGPL3
----------------------------------------------------------------
TabPanel = Component:derive("TabPanel");
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:new(x, y, w, h)
-- Generic instantiation.
local o = Component:new(x, y, w, h);
setmetatable(o, self);
self.__index = self;
-- The active index to each array.
o.active_index = 0;
-- Panel content for each tab. Requires a 'name' field.
o.panels = {};
-- For when a tab is added.
o.tabs_dirty = false;
-- Beginning x position after the tab space.
o.tab_end_x = 0;
-- For when panels need to be resized.
o.panels_dirty = true;
-- Amount of tabs. Used as a placemarker for the next added tab.
o.tab_count = 0;
-- Dimensions used to calculate tab positions.
o.tab_dimension_highlight_factors = {};
-- The font-size of the tabs.
o.tab_font_size = UIFont.Small;
-- Height in pixels of the Tab's font.
o.font_height = sHeight(o.tab_font_size);
-- The active panel / Tab.
o.active_panel = nil;
-- Internal panel dimension data.
o.inner_x = 0;
o.inner_y = 0;
o.inner_width = 0;
o.inner_height = 0;
return o;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:initialise()
-- Invoke super method.
Component.initialise(self);
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:createChildren()
-- Invoke super method.
Component.createChildren(self);
-- Setup colors.
self.colorOutline = Color(128, 128, 128, 255);
self.colorText = Color(164, 164, 164, 255);
self.colorTextSelected = Color(240, 240, 240, 255);
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:update()
-- Update the active panel.
if self.active_panel ~= nil then
self.active_panel:update();
end
local mouse = self:getLocalMouse();
if self:containsPoint(mouse.x, mouse.y) then
-- print(tostring(mouse.x)..", "..tostring(mouse.y));
mouse = self:getMouse();
local length = 32;
for index = 0, length, 1 do
local nextPanel = self.panels[index];
if nextDim ~= nil then
local nextDim = nextPanel._dim;
local factor = self.tab_dimension_highlight_factors[index];
if self:containsPoint(mouse.x, mouse.y, nextDim) then
if factor < 2 then
self.tab_dimension_highlight_factors[index] = factor + 0.2;
end
else
if factor > 1 then
self.tab_dimension_highlight_factors[index] = factor - 0.1;
end
end
end
end
else
-- Drop Highlights for tabs while the mouse is outside the TabPanel.
local length = 32;
for index = 0, length, 1 do
if self.tab_dimension_highlight_factors[index] ~= nil then
if self.tab_dimension_highlight_factors[index] > 1 then
self.tab_dimension_highlight_factors[index] = self.tab_dimension_highlight_factors[index] - 0.1;
end
end
end
end
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:prerender()
if self.tabs_dirty then
local index = 0;
local length = self.tab_count;
-- Go through each tab.
for index = 0, length, 1 do
local panel = self.panels[index];
if panel ~= nil then
if not panel._name_length then
local name = self.panels[index]._name;
-- Set the length of the tab.
panel._name_length = sLength(name, self.tab_font_size) + 7;
end
end
end
-- Reset the font height variable.
self.font_height = sHeight(self.tab_font_size);
-- Set the tab data clean.
self.tabs_dirty = false;
end
self:setInnerDimensions();
if self.active_panel ~= nil then
self.active_panel:setX(self:getInnerX());
self.active_panel:setY(self:getInnerY());
self.active_panel:setWidth(self:getInnerWidth());
self.active_panel:setHeight(self:getInnerHeight());
end
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:_render()
local parent = self:getParent() ;
local sx = parent:getX() + 4 ;
local y = parent:getY() + self:getY();
local h = self.font_height ;
local panels_length = 32 ;
local has_panels = panels_length > 0 or false ;
if has_panels then
for index = 0, panels_length, 1 do
local panel = self.panels[index];
if panel ~= nil then
local tab_length = panel._name_length;
if not tab_length then
tab_length = sLength(panel._name, self.tab_font_size) + 7;
panel._name_length = tab_length;
end
local dim = nil;
-- Draw the tab.
if panel.active == true then
dim = self:drawActiveTab(panel._name, sx, y, tab_length, self.font_height, self.colorTextSelected, self.colorOutline, self.font, 2, true);
else
dim = self:drawTab(panel._name, sx, y, tab_length, self.font_height, self.colorText, self.colorOutline, self.font, self.tab_dimension_highlight_factors[index], true);
end
-- Update panel's tab dimension.
panel._dim = dim;
-- Add the tab's length to the next measure.
sx = sx + tab_length + 2;
end
end
-- Store the x position of the end of the tab space.
self.tab_end_x = sx + 1;
-- Draw the line in the remaining space to the right of the tabs.
self:drawLineH(sx, y + h + 3, self:getWidth() - sx + parent:getX() + self:getX(), 1, self.colorOutline);
else
-- No tabs means the entire bar at the top is free to populate.
self.tab_end_x = 0;
-- Draw the line in the remaining space to the right of the tabs.
self:drawLineH(parent:getX() + self:getX(), y + h + 3, self:getWidth(), 1, self.colorOutline);
end
-- Grab the internal dimensions.
local ix = self:getInnerX();
local iy = self:getInnerY();
local iw = self:getInnerWidth();
local ih = self:getInnerHeight();
-- Draw the containing border for the internal panel content.
self:drawRectPartial(parent:getX() + ix + 4, parent:getY() + iy + 4, iw, ih, false, true, true, true, self.colorOutline);
self:_renderChildren();
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:click()
local mouse = self:getMouse();
local length = 32;
for index = 0, length, 1 do
local next_panel = self.panels[index];
if next_panel ~= nil then
local nextDim = next_panel._dim;
local factor = self.tab_dimension_highlight_factors[index];
if self:containsPoint(mouse.x, mouse.y, nextDim) then
self:setActiveTab(next_panel._name);
break;
end
end
end
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:setActiveTab(identifier)
-- Validity check.
if identifier == nil then
print("TabPanel:setActiveTab() -> Identifier is null.");
return;
end
if type(identifier) == "number" then
-- Handle identifier as index.
-- Validity check.
if identifier < 0 then
print("TabPanel:setActiveTab() -> Index must be a valid, non-negative integer.");
return;
end
-- If a panel is currently active, remove it.
if self.active_panel ~= nil then
self:removeChild(self.active_panel);
self.active_panel:setVisible(false);
self.active_panel.active = false;
end
-- Set the new active panel.
self.active_panel = self.panels[identifier];
self.active_panel:setVisible(true);
self.active_panel.active = true;
-- Add the new active panel as a child of the Tabs UIElement.
self:addChild(self.active_panel);
elseif type(identifier) == "string" then
-- Handle identifier as the name.
-- Validity check.
if identifier == "" then
print("TabPanel:setActiveTab() -> Name given is empty.");
return;
end
-- length of the panels array.
local length = 32;
-- Our found panel object.
local found_panel = nil;
-- Go through each panel.
for index = 0, length, 1 do
-- Grab the next panel.
local panel = self.panels[index];
-- Verify the panel is a valid LuaObject.
if panel ~= nil then
-- If the name matches, this is the panel.
if panel._name == identifier then
-- Set the variable.
found_panel = panel;
-- Break for optimization.
break;
end
end
end
-- Validity check.
if found_panel == nil then
print("TabPanel:setActiveTab() -> No panel found for name: " .. identifier);
return;
end
-- If a panel is currently active, remove it.
if self.active_panel ~= nil then
self:removeChild(self.active_panel);
self.active_panel:setVisible(false);
self.active_panel.active = false;
end
-- Set the new active panel.
self.active_panel = found_panel;
self.active_panel:setVisible(true);
self.active_panel.active = true;
-- Add the new active panel as a child of the Tabs UIElement.
self:addChild(self.active_panel);
end
self:onTabFocus();
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:addTab(name, UIObject)
-- Validity check.
if UIObject == nil then
print("TabPanel:addTab() -> UIObject is nil for name: " .. name);
return;
end
UIObject._dim = {x1 = -9999, x2 = -9999, y1 = -9999, y2 = -9999};
-- Set an internal name field.
UIObject._name = name;
-- Grab the index before incrementing the length.
local toReturn = nil;
local index = 0;
while toReturn == nil do
if self.panels[index] == nil then
toReturn = index;
break;
end
index = index + 1;
end
-- Insert the object into the panel array.
self.panels[toReturn] = UIObject;
self.tab_dimension_highlight_factors[toReturn] = 1;
-- Increment tabs length.
self.tab_count = self.tab_count + 1;
-- Set dirty flags to recalculate.
self.tabs_dirty = true;
self.panels_dirty = true;
-- Start as not visible.
UIObject:setVisible(false);
-- Return the index position of the tab.
return toReturn;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:removeTab(name)
-- TO lowercase to match.
name = string.lower(name);
local length = 32;
for index = 0, length, 1 do
local panel = self.panels[index];
if panel ~= nil then
if string.lower(panel._name) == name then
-- Set panel to null.
self.panels[index] = nil;
self.tab_count = self.tab_count - 1;
-- If the removed tab is the active tab, set the first tab as active.
if self.active_index == index then
self.active_index = 0;
self.active_panel = self.panels[0];
end
break;
end
end
end
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getTab(identifier)
if type(identifier) == "number" then
-- Handle identifier as index.
-- Validity check.
if identifier < 0 then
print("Index must be a valid, non-negative integer.");
return;
end
return self.panels[identifier];
elseif type(identifier) == "string" then
-- Handle identifier as the name.
-- Validity check.
if identifier == "" then
print("Name given is empty.");
return;
end
identifier = string.lower(identifier);
-- length of the panels array.
local length = 32;
-- Go through each panel.
for index = 0, length, 1 do
-- Grab the next panel.
local panel = self.panels[index];
-- Verify the panel is a valid LuaObject.
if panel ~= nil then
-- If the name matches, this is the panel.
if string.lower(panel._name) == identifier then
-- Set the variable.
return panel;
end
end
end
end
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:setInnerDimensions()
-- Grab the parent.
local p = self:getParent();
-- Parent coordinates.
local px = p:getX();
local py = p:getY();
-- Inner dimensions.
local x = self:getX() - 4;
local y = self:getY() + 15;
local w = self:getWidth() ;
local h = self:getHeight();
-- Set inner dimensions.
self.inner_x = x;
self.inner_y = y;
self.inner_width = w;
self.inner_height = h;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getActiveTab()
return self.active_panel;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getInnerX()
return self.inner_x;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getInnerY()
return self.inner_y;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getInnerWidth()
return self.inner_width;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:getInnerHeight()
return self.inner_height;
end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:onTabFocus(tab) end
----------------------------------------------------------------
--
----------------------------------------------------------------
function TabPanel:render() end
----------------------------------------------------------------
----------------------------------------------------------------
-- ###### ######## ### ######## #### ###### --
-- ## ## ## ## ## ## ## ## ## --
-- ## ## ## ## ## ## ## --
-- ###### ## ## ## ## ## ## --
-- ## ## ######### ## ## ## --
-- ## ## ## ## ## ## ## ## ## --
-- ###### ## ## ## ## #### ###### --
----------------------------------------------------------------
----------------------------------------------------------------
-- The static definition for header heights for the TabPanel.
TabPanel.header_height = 24;
----------------------------------------------------------------
-- @static
-- @return Returns the HeaderHieght defined for the TabPanel.
----------------------------------------------------------------
function TabPanel:getHeaderHeight()
return TabPanel.header_height;
end | lgpl-3.0 |
yswifi/APlan | build_dir/target-mipsel_24kec+dsp_uClibc-0.9.33.2/luci/libs/nixio/docsrc/nixio.TLSSocket.lua | 173 | 2926 | --- TLS Socket Object.
-- TLS Sockets contain the underlying socket and context in the fields
-- "socket" and "context".
-- @cstyle instance
module "nixio.TLSSocket"
--- Initiate the TLS handshake as client with the server.
-- @class function
-- @name TLSSocket.connect
-- @usage This function calls SSL_connect().
-- @usage You have to call either connect or accept before transmitting data.
-- @see TLSSocket.accept
-- @return true
--- Wait for a TLS handshake from a client.
-- @class function
-- @name TLSSocket.accept
-- @usage This function calls SSL_accept().
-- @usage You have to call either connect or accept before transmitting data.
-- @see TLSSocket.connect
-- @return true
--- Send a message to the socket.
-- @class function
-- @name TLSSocket.send
-- @usage This function calls SSL_write().
-- @usage <strong>Warning:</strong> It is not guaranteed that all data
-- in the buffer is written at once.
-- You have to check the return value - the number of bytes actually written -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage Unlike standard Lua indexing the lowest offset and default is 0.
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @return number of bytes written
--- Send a message on the socket (This is an alias for send).
-- See the send description for a detailed description.
-- @class function
-- @name TLSSocket.write
-- @param buffer Buffer holding the data to be written.
-- @param offset Offset to start reading the buffer from. (optional)
-- @param length Length of chunk to read from the buffer. (optional)
-- @see TLSSocket.send
-- @return number of bytes written
--- Receive a message on the socket.
-- @class function
-- @name TLSSocket.recv
-- @usage This function calls SSL_read().
-- @usage <strong>Warning:</strong> It is not guaranteed that all requested data
-- is read at once.
-- You have to check the return value - the length of the buffer actually read -
-- or use the safe IO functions in the high-level IO utility module.
-- @usage The length of the return buffer is limited by the (compile time)
-- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default).
-- Any read request greater than that will be safely truncated to this value.
-- @param length Amount of data to read (in Bytes).
-- @return buffer containing data successfully read
--- Receive a message on the socket (This is an alias for recv).
-- See the recv description for more details.
-- @class function
-- @name TLSSocket.read
-- @param length Amount of data to read (in Bytes).
-- @see TLSSocket.recv
-- @return buffer containing data successfully read
--- Shut down the TLS connection.
-- @class function
-- @name TLSSocket.shutdown
-- @usage This function calls SSL_shutdown().
-- @return true | gpl-2.0 |
bnetcc/darkstar | scripts/zones/Western_Adoulin/npcs/Jorin.lua | 5 | 1935 | -----------------------------------
-- Area: Western Adoulin
-- NPC: Jorin
-- Type: Standard NPC and Quest Giver
-- Starts, Involved with, and Finishes Quest: 'The Old Man and the Harpoon'
-- @zone 256
-- !pos 92 32 152 256
-----------------------------------
package.loaded["scripts/zones/Western_Adoulin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Western_Adoulin/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local TOMATH = player:getQuestStatus(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
if (TOMATH == QUEST_ACCEPTED) then
if (player:hasKeyItem(EXTRAVAGANT_HARPOON)) then
-- Finishing Quest: 'The Old Man and the Harpoon'
player:startEvent(2542);
else
-- Dialgoue during Quest: 'The Old Man and the Harpoon'
player:startEvent(2541);
end
elseif (TOMATH == QUEST_AVAILABLE) then
-- Starts Quest: 'The Old Man and the Harpoon'
player:startEvent(2540);
else
-- Standard dialogue
player:startEvent(560);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 2540) then
-- Starting Quest: 'The Old Man and the Harpoon'
player:addQuest(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
player:addKeyItem(BROKEN_HARPOON);
player:messageSpecial(KEYITEM_OBTAINED, BROKEN_HARPOON);
elseif (csid == 2542) then
-- Finishing Quest: 'The Old Man and the Harpoon'
player:completeQuest(ADOULIN, THE_OLD_MAN_AND_THE_HARPOON);
player:addExp(500 * EXP_RATE);
player:addCurrency('bayld', 300 * BAYLD_RATE);
player:messageSpecial(BAYLD_OBTAINED, 300 * BAYLD_RATE);
player:delKeyItem(EXTRAVAGANT_HARPOON);
player:addFame(ADOULIN);
end
end;
| gpl-3.0 |
Benjji/wesnoth | data/ai/lua/generic_rush_engine.lua | 26 | 27499 | return {
init = function(ai)
-- Grab a useful separate CA as a starting point
local generic_rush = wesnoth.require("ai/lua/move_to_any_target.lua").init(ai)
-- More generic grunt rush (and can, in fact, be used with other unit types as well)
local H = wesnoth.require "lua/helper.lua"
local W = H.set_wml_action_metatable {}
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local BC = wesnoth.require "ai/lua/battle_calcs.lua"
local LS = wesnoth.require "lua/location_set.lua"
local HS = wesnoth.require "ai/micro_ais/cas/ca_healer_move.lua"
local R = wesnoth.require "ai/lua/retreat.lua"
local function print_time(...)
if generic_rush.data.turn_start_time then
AH.print_ts_delta(generic_rush.data.turn_start_time, ...)
else
AH.print_ts(...)
end
end
------ Stats at beginning of turn -----------
-- This will be blacklisted after first execution each turn
function generic_rush:stats_eval()
local score = 999999
return score
end
function generic_rush:stats_exec()
local tod = wesnoth.get_time_of_day()
AH.print_ts(' Beginning of Turn ' .. wesnoth.current.turn .. ' (' .. tod.name ..') stats')
generic_rush.data.turn_start_time = wesnoth.get_time_stamp() / 1000.
for i,s in ipairs(wesnoth.sides) do
local total_hp = 0
local units = AH.get_live_units { side = s.side }
for i,u in ipairs(units) do total_hp = total_hp + u.hitpoints end
local leader = wesnoth.get_units { side = s.side, canrecruit = 'yes' }[1]
if leader then
print(' Player ' .. s.side .. ' (' .. leader.type .. '): ' .. #units .. ' Units with total HP: ' .. total_hp)
end
end
end
------- Recruit CA --------------
local params = {
score_function = (function() return 300000 end),
min_turn_1_recruit = (function() return generic_rush:castle_switch_eval() > 0 end),
leader_takes_village = (function()
if generic_rush:castle_switch_eval() > 0 then
local take_village = #(wesnoth.get_villages {
x = generic_rush.data.leader_target[1],
y = generic_rush.data.leader_target[2]
}) > 0
return take_village
end
return true
end
)
}
wesnoth.require("ai/lua/generic_recruit_engine.lua").init(ai, generic_rush, params)
-------- Castle Switch CA --------------
local function get_reachable_enemy_leaders(unit)
local potential_enemy_leaders = AH.get_live_units { canrecruit = 'yes',
{ "filter_side", { { "enemy_of", {side = wesnoth.current.side} } } }
}
local enemy_leaders = {}
for j,e in ipairs(potential_enemy_leaders) do
local path, cost = wesnoth.find_path(unit, e.x, e.y, { ignore_units = true, viewing_side = 0 })
if cost < AH.no_path then
table.insert(enemy_leaders, e)
end
end
return enemy_leaders
end
function generic_rush:castle_switch_eval()
local start_time, ca_name = wesnoth.get_time_stamp() / 1000., 'castle_switch'
if AH.print_eval() then print_time(' - Evaluating castle_switch CA:') end
if ai.get_passive_leader() then
-- Turn off this CA if the leader is passive
return 0
end
local leader = wesnoth.get_units {
side = wesnoth.current.side,
canrecruit = 'yes',
formula = '(movement_left = total_movement) and (hitpoints = max_hitpoints)'
}[1]
if not leader then
-- CA is irrelevant if no leader or the leader may have moved from another CA
self.data.leader_target = nil
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
local cheapest_unit_cost = AH.get_cheapest_recruit_cost()
if self.data.leader_target and wesnoth.sides[wesnoth.current.side].gold >= cheapest_unit_cost then
-- make sure move is still valid
local next_hop = AH.next_hop(leader, self.data.leader_target[1], self.data.leader_target[2])
if next_hop and next_hop[1] == self.data.leader_target[1]
and next_hop[2] == self.data.leader_target[2] then
return self.data.leader_score
end
end
local width,height,border = wesnoth.get_map_size()
local keeps = wesnoth.get_locations {
terrain = 'K*,K*^*,*^K*', -- Keeps
x = '1-'..width,
y = '1-'..height,
{ "not", { {"filter", {}} }}, -- That have no unit
{ "not", { radius = 6, {"filter", { canrecruit = 'yes',
{ "filter_side", { { "enemy_of", {side = wesnoth.current.side} } } }
}} }}, -- That are not too close to an enemy leader
{ "not", {
x = leader.x, y = leader.y, terrain = 'K*,K*^*,*^K*',
radius = 3,
{ "filter_radius", { terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*' } }
}}, -- That are not close and connected to a keep the leader is on
{ "filter_adjacent_location", {
terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*'
}} -- That are not one-hex keeps
}
if #keeps < 1 then
-- Skip if there aren't extra keeps to evaluate
-- In this situation we'd only switch keeps if we were running away
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
local enemy_leaders = get_reachable_enemy_leaders(leader)
-- Look for the best keep
local best_score, best_loc, best_turns = 0, {}, 3
for i,loc in ipairs(keeps) do
-- Only consider keeps within 2 turns movement
local path, cost = wesnoth.find_path(leader, loc[1], loc[2])
local score = 0
-- Prefer closer keeps to enemy
local turns = math.ceil(cost/leader.max_moves)
if turns <= 2 then
score = 1/turns
for j,e in ipairs(enemy_leaders) do
score = score + 1 / H.distance_between(loc[1], loc[2], e.x, e.y)
end
if score > best_score then
best_score = score
best_loc = loc
best_turns = turns
end
end
end
-- If we're on a keep,
-- don't move to another keep unless it's much better when uncaptured villages are present
if best_score > 0 and wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep then
local close_unowned_village = (wesnoth.get_villages {
{ "and", {
x = leader.x,
y = leader.y,
radius = leader.max_moves
}},
owner_side = 0
})[1]
if close_unowned_village then
local score = 1/best_turns
for j,e in ipairs(enemy_leaders) do
-- count all distances as three less than they actually are
score = score + 1 / (H.distance_between(leader.x, leader.y, e.x, e.y) - 3)
end
if score > best_score then
best_score = 0
end
end
end
if best_score > 0 then
local next_hop = AH.next_hop(leader, best_loc[1], best_loc[2])
if next_hop and ((next_hop[1] ~= leader.x) or (next_hop[2] ~= leader.y)) then
-- See if there is a nearby village that can be captured without delaying progress
local close_villages = wesnoth.get_villages( {
{ "and", { x = next_hop[1], y = next_hop[2], radius = leader.max_moves }},
owner_side = 0 })
for i,loc in ipairs(close_villages) do
local path_village, cost_village = wesnoth.find_path(leader, loc[1], loc[2])
if cost_village <= leader.moves then
local dummy_leader = wesnoth.copy_unit(leader)
dummy_leader.x = loc[1]
dummy_leader.y = loc[2]
local path_keep, cost_keep = wesnoth.find_path(dummy_leader, best_loc[1], best_loc[2])
local turns_from_keep = math.ceil(cost_keep/leader.max_moves)
if turns_from_keep < best_turns
or (turns_from_keep == 1 and wesnoth.sides[wesnoth.current.side].gold < cheapest_unit_cost)
then
-- There is, go there instead
next_hop = loc
break
end
end
end
end
self.data.leader_target = next_hop
-- if we're on a keep, wait until there are no movable units on the castle before moving off
self.data.leader_score = 290000
if wesnoth.get_terrain_info(wesnoth.get_terrain(leader.x, leader.y)).keep then
local castle = wesnoth.get_locations {
x = "1-"..width, y = "1-"..height,
{ "and", {
x = leader.x, y = leader.y, radius = 200,
{ "filter_radius", { terrain = 'C*,K*,C*^*,K*^*,*^K*,*^C*' } }
}}
}
local should_wait = false
for i,loc in ipairs(castle) do
local unit = wesnoth.get_unit(loc[1], loc[2])
if not unit then
should_wait = false
break
elseif unit.moves > 0 then
should_wait = true
end
end
if should_wait then
self.data.leader_score = 15000
end
end
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return self.data.leader_score
end
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
function generic_rush:castle_switch_exec()
local leader = wesnoth.get_units { side = wesnoth.current.side, canrecruit = 'yes' }[1]
if AH.print_exec() then print_time(' Executing castle_switch CA') end
if AH.show_messages() then W.message { speaker = leader.id, message = 'Switching castles' } end
AH.checked_move(ai, leader, self.data.leader_target[1], self.data.leader_target[2])
self.data.leader_target = nil
end
------- Grab Villages CA --------------
function generic_rush:grab_villages_eval()
local start_time, ca_name = wesnoth.get_time_stamp() / 1000., 'grab_villages'
if AH.print_eval() then print_time(' - Evaluating grab_villages CA:') end
-- Check if there are units with moves left
local units = wesnoth.get_units { side = wesnoth.current.side, canrecruit = 'no',
formula = 'movement_left > 0'
}
if (not units[1]) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
local enemies = AH.get_live_units {
{ "filter_side", {{"enemy_of", {side = wesnoth.current.side} }} }
}
local villages = wesnoth.get_villages()
-- Just in case:
if (not villages[1]) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
--print('#units, #enemies', #units, #enemies)
-- First check if attacks are possible for any unit
local return_value = 200000
-- If one with > 50% chance of kill is possible, set return_value to lower than combat CA
local attacks = ai.get_attacks()
--print(#attacks)
for i,a in ipairs(attacks) do
if (#a.movements == 1) and (a.chance_to_kill > 0.5) then
return_value = 90000
break
end
end
-- Also find which locations can be attacked by enemies
local enemy_attack_map = BC.get_attack_map(enemies).units
-- Now we go through the villages and units
local max_rating, best_village, best_unit = -9e99, {}, {}
local village_ratings = {}
for j,v in ipairs(villages) do
-- First collect all information that only depends on the village
local village_rating = 0 -- This is the unit independent rating
local unit_in_way = wesnoth.get_unit(v[1], v[2])
-- If an enemy can get within one move of the village, we want to hold it
if enemy_attack_map:get(v[1], v[2]) then
--print(' within enemy reach', v[1], v[2])
village_rating = village_rating + 100
end
-- Unowned and enemy-owned villages get a large bonus
local owner = wesnoth.get_village_owner(v[1], v[2])
if (not owner) then
village_rating = village_rating + 10000
else
if wesnoth.is_enemy(owner, wesnoth.current.side) then village_rating = village_rating + 20000 end
end
local enemy_distance_from_village = AH.get_closest_enemy(v)
-- Now we go on to the unit-dependent rating
local best_unit_rating = -9e99
local reachable = false
for i,u in ipairs(units) do
-- Skip villages that have units other than 'u' itself on them
local village_occupied = false
if unit_in_way and ((unit_in_way.x ~= u.x) or (unit_in_way.y ~= u.y)) then
village_occupied = true
end
-- Rate all villages that can be reached and are unoccupied by other units
if (not village_occupied) then
-- Path finding is expensive, so we do a first cut simply by distance
-- There is no way a unit can get to the village if the distance is greater than its moves
local dist = H.distance_between(u.x, u.y, v[1], v[2])
if (dist <= u.moves) then
local path, cost = wesnoth.find_path(u, v[1], v[2])
if (cost <= u.moves) then
village_rating = village_rating - 1
reachable = true
--print('Can reach:', u.id, v[1], v[2], cost)
local rating = 0
-- Prefer strong units if enemies can reach the village, injured units otherwise
if enemy_attack_map:get(v[1], v[2]) then
rating = rating + u.hitpoints
else
rating = rating + u.max_hitpoints - u.hitpoints
end
-- Prefer not backtracking and moving more distant units to capture villages
local enemy_distance_from_unit = AH.get_closest_enemy({u.x, u.y})
rating = rating - (enemy_distance_from_village + enemy_distance_from_unit)/5
if (rating > best_unit_rating) then
best_unit_rating, best_unit = rating, u
end
--print(' rating:', rating)
end
end
end
end
village_ratings[v] = {village_rating, best_unit, reachable}
end
for j,v in ipairs(villages) do
local rating = village_ratings[v][1]
if village_ratings[v][3] and rating > max_rating then
max_rating, best_village, best_unit = rating, v, village_ratings[v][2]
end
end
--print('max_rating', max_rating)
if (max_rating > -9e99) then
self.data.unit, self.data.village = best_unit, best_village
if (max_rating >= 1000) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return return_value
else
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
end
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
function generic_rush:grab_villages_exec()
if AH.print_exec() then print_time(' Executing grab_villages CA') end
if AH.show_messages() then W.message { speaker = self.data.unit.id, message = 'Grab villages' } end
AH.movefull_stopunit(ai, self.data.unit, self.data.village)
self.data.unit, self.data.village = nil, nil
end
------- Spread Poison CA --------------
function generic_rush:spread_poison_eval()
local start_time, ca_name = wesnoth.get_time_stamp() / 1000., 'spread_poison'
if AH.print_eval() then print_time(' - Evaluating spread_poison CA:') end
-- If a unit with a poisoned weapon can make an attack, we'll do that preferentially
-- (with some exceptions)
local poisoners = AH.get_live_units { side = wesnoth.current.side,
formula = 'attacks_left > 0',
{ "filter_wml", {
{ "attack", {
{ "specials", {
{ "poison", { } }
} }
} }
} },
canrecruit = 'no'
}
--print('#poisoners', #poisoners)
if (not poisoners[1]) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
local attacks = AH.get_attacks(poisoners)
--print('#attacks', #attacks)
if (not attacks[1]) then
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
-- Go through all possible attacks with poisoners
local max_rating, best_attack = -9e99, {}
for i,a in ipairs(attacks) do
local attacker = wesnoth.get_unit(a.src.x, a.src.y)
local defender = wesnoth.get_unit(a.target.x, a.target.y)
-- Don't try to poison a unit that cannot be poisoned
local cant_poison = defender.status.poisoned or defender.status.unpoisonable
-- For now, we also simply don't poison units on villages (unless standard combat CA does it)
local on_village = wesnoth.get_terrain_info(wesnoth.get_terrain(defender.x, defender.y)).village
-- Also, poisoning units that would level up through the attack or could level on their turn as a result is very bad
local about_to_level = defender.max_experience - defender.experience <= (wesnoth.unit_types[attacker.type].level * 2)
if (not cant_poison) and (not on_village) and (not about_to_level) then
-- Strongest enemy gets poisoned first
local rating = defender.hitpoints
-- Always attack enemy leader, if possible
if defender.canrecruit then rating = rating + 1000 end
-- Enemies that can regenerate are not good targets
if wesnoth.unit_ability(defender, 'regenerate') then rating = rating - 1000 end
-- More priority to enemies on strong terrain
local defender_defense = 100 - wesnoth.unit_defense(defender, wesnoth.get_terrain(defender.x, defender.y))
rating = rating + defender_defense / 4.
-- For the same attacker/defender pair, go to strongest terrain
local attack_defense = 100 - wesnoth.unit_defense(attacker, wesnoth.get_terrain(a.dst.x, a.dst.y))
rating = rating + attack_defense / 2.
--print('rating', rating)
-- And from village everything else being equal
local is_village = wesnoth.get_terrain_info(wesnoth.get_terrain(a.dst.x, a.dst.y)).village
if is_village then rating = rating + 0.5 end
if rating > max_rating then
max_rating, best_attack = rating, a
end
end
end
if (max_rating > -9e99) then
self.data.attack = best_attack
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 190000
end
if AH.print_eval() then AH.done_eval_messages(start_time, ca_name) end
return 0
end
function generic_rush:spread_poison_exec()
local attacker = wesnoth.get_unit(self.data.attack.src.x, self.data.attack.src.y)
if AH.print_exec() then print_time(' Executing spread_poison CA') end
if AH.show_messages() then W.message { speaker = attacker.id, message = 'Poison attack' } end
local defender = wesnoth.get_unit(self.data.attack.target.x, self.data.attack.target.y)
AH.movefull_stopunit(ai, attacker, self.data.attack.dst.x, self.data.attack.dst.y)
if (not attacker) or (not attacker.valid) then return end
if (not defender) or (not defender.valid) then return end
-- Find the poison weapon
-- If several attacks have poison, this will always find the last one
local is_poisoner, poison_weapon = AH.has_weapon_special(attacker, "poison")
AH.checked_attack(ai, attacker, defender, poison_weapon)
self.data.attack = nil
end
------- Place Healers CA --------------
function generic_rush:place_healers_eval()
if HS:evaluation(ai, {}, self) > 0 then
return 95000
end
return 0
end
function generic_rush:place_healers_exec()
HS:execution(ai, nil, self)
end
------- Retreat CA --------------
function generic_rush:retreat_injured_units_eval()
local units = wesnoth.get_units {
side = wesnoth.current.side,
formula = 'movement_left > 0'
}
local unit, loc = R.retreat_injured_units(units)
if unit then
self.data.retreat_unit = unit
self.data.retreat_loc = loc
-- First check if attacks are possible for any unit
-- If one with > 50% chance of kill is possible, set return_value to lower than combat CA
local attacks = ai.get_attacks()
for i,a in ipairs(attacks) do
if (#a.movements == 1) and (a.chance_to_kill > 0.5) then
return 95000
end
end
return 205000
end
return 0
end
function generic_rush:retreat_injured_units_exec()
AH.movefull_outofway_stopunit(ai, self.data.retreat_unit, self.data.retreat_loc)
self.data.retreat_unit = nil
self.data.retreat_loc = nil
end
------- Village Hunt CA --------------
-- Give extra priority to seeking villages if we have less than our share
-- our share is defined as being slightly more than the total/the number of sides
function generic_rush:village_hunt_eval()
local villages = wesnoth.get_villages()
if not villages[1] then
return 0
end
local my_villages = wesnoth.get_villages { owner_side = wesnoth.current.side }
if #my_villages > #villages / #wesnoth.sides then
return 0
end
local allied_villages = wesnoth.get_villages { {"filter_owner", { {"ally_of", { side = wesnoth.current.side }} }} }
if #allied_villages == #villages then
return 0
end
local units = wesnoth.get_units {
side = wesnoth.current.side,
canrecruit = false,
formula = 'movement_left > 0'
}
if not units[1] then
return 0
end
return 30000
end
function generic_rush:village_hunt_exec()
local unit = wesnoth.get_units({
side = wesnoth.current.side,
canrecruit = false,
formula = 'movement_left > 0'
})[1]
local villages = wesnoth.get_villages()
local target, best_cost = nil, AH.no_path
for i,v in ipairs(villages) do
if not wesnoth.match_location(v[1], v[2], { {"filter_owner", { {"ally_of", { side = wesnoth.current.side }} }} }) then
local path, cost = wesnoth.find_path(unit, v[1], v[2], { ignore_units = true, max_cost = best_cost })
if cost < best_cost then
target = v
best_cost = cost
end
end
end
if target then
local x, y = wesnoth.find_vacant_tile(target[1], target[2], unit)
local dest = AH.next_hop(unit, x, y)
AH.checked_move(ai, unit, dest[1], dest[2])
end
end
return generic_rush
end
}
| gpl-2.0 |
Atebite/NutScript | plugins/wepselect.lua | 3 | 4526 | PLUGIN.name = "Weapon Select"
PLUGIN.author = "Chessnut"
PLUGIN.desc = "A replacement for the default weapon selection."
if (SERVER) then
concommand.Add("nut_selectweapon", function(client, command, arguments)
local index = tonumber(arguments[1]) or 1
local weapon = client:GetWeapons()[index]
if (IsValid(weapon)) then
client:SelectWeapon(weapon:GetClass())
end
end)
else
PLUGIN.index = PLUGIN.index or 1
PLUGIN.deltaIndex = PLUGIN.deltaIndex or PLUGIN.index
PLUGIN.infoAlpha = PLUGIN.infoAlpha or 0
PLUGIN.alpha = PLUGIN.alpha or 0
PLUGIN.alphaDelta = PLUGIN.alphaDelta or PLUGIN.alpha
PLUGIN.fadeTime = PLUGIN.fadeTime or 0
function PLUGIN:HUDPaint()
local frameTime = FrameTime()
self.alphaDelta = Lerp(frameTime * 10, self.alphaDelta, self.alpha)
local fraction = self.alphaDelta
if (fraction > 0) then
local weapons = LocalPlayer():GetWeapons()
local total = #weapons
local x, y = ScrW() * 0.5, ScrH() * 0.5
local spacing = math.pi * 0.85
local radius = 240 * self.alphaDelta
self.deltaIndex = Lerp(frameTime * 12, self.deltaIndex, self.index) --math.Approach(self.deltaIndex, self.index, fTime() * 12)
local index = self.deltaIndex
for k, v in ipairs(weapons) do
if (!weapons[self.index]) then
self.index = total
end
local theta = (k - index) * 0.1
local color = ColorAlpha(k == self.index and nut.config.get("color") or color_white, (255 - math.abs(theta * 3) * 255) * fraction)
local lastY = 0
local shiftX = ScrW()*.02
if (self.markup and k < self.index) then
local w, h = self.markup:Size()
lastY = (h * fraction)
if (k == self.index - 1) then
self.infoAlpha = Lerp(frameTime * 3, self.infoAlpha, 255)
self.markup:Draw(x + 5 + shiftX, y + 30, 0, 0, self.infoAlpha * fraction)
end
end
surface.SetFont("nutSubTitleFont")
local tx, ty = surface.GetTextSize(v:GetPrintName():upper())
local scale = (1 - math.abs(theta*2))
local matrix = Matrix()
matrix:Translate(Vector(
shiftX + x + math.cos(theta * spacing + math.pi) * radius + radius,
y + lastY + math.sin(theta * spacing + math.pi) * radius - ty/2 ,
1))
matrix:Rotate(angle or Angle(0, 0, 0))
matrix:Scale(Vector(1, 1, 0) * scale)
cam.PushModelMatrix(matrix)
nut.util.drawText(v:GetPrintName():upper(), 2, ty/2, color, 0, 1, "nutSubTitleFont")
cam.PopModelMatrix()
end
if (self.fadeTime < CurTime() and self.alpha > 0) then
self.alpha = 0
end
end
end
local weaponInfo = {
"Author",
"Contact",
"Purpose",
"Instructions"
}
function PLUGIN:onIndexChanged()
self.alpha = 1
self.fadeTime = CurTime() + 5
local weapon = LocalPlayer():GetWeapons()[self.index]
self.markup = nil
if (IsValid(weapon)) then
local text = ""
for k, v in ipairs(weaponInfo) do
if (weapon[v] and weapon[v]:find("%S")) then
local color = nut.config.get("color")
text = text.."<font=nutSmallBoldFont><color="..color.r..","..color.g..","..color.b..">"..L(v).."</font></color>\n"..weapon[v].."\n"
end
end
if (text != "") then
self.markup = markup.Parse("<font=nutSmallFont>"..text, ScrW() * 0.3)
self.infoAlpha = 0
end
local source, pitch = hook.Run("WeaponCycleSound") or "common/talk.wav"
LocalPlayer():EmitSound(source or "common/talk.wav", 50, pitch or 180)
end
end
function PLUGIN:PlayerBindPress(client, bind, pressed)
local weapon = client:GetActiveWeapon()
if (!client:InVehicle() and (!IsValid(weapon) or weapon:GetClass() != "weapon_physgun" or !client:KeyDown(IN_ATTACK))) then
bind = bind:lower()
if (bind:find("invprev") and pressed) then
self.index = self.index - 1
if (self.index < 1) then
self.index = #client:GetWeapons()
end
self:onIndexChanged()
return true
elseif (bind:find("invnext") and pressed) then
self.index = self.index + 1
if (self.index > #client:GetWeapons()) then
self.index = 1
end
self:onIndexChanged()
return true
elseif (bind:find("slot")) then
self.index = math.Clamp(tonumber(bind:match("slot(%d)")) or 1, 1, #LocalPlayer():GetWeapons())
self:onIndexChanged()
return true
elseif (bind:find("attack") and pressed and self.alpha > 0) then
LocalPlayer():EmitSound(hook.Run("WeaponSelectSound", LocalPlayer():GetWeapons()[self.index]) or "buttons/button16.wav")
RunConsoleCommand("nut_selectweapon", self.index)
self.alpha = 0
return true
end
end
end
end | mit |
bnetcc/darkstar | scripts/zones/Abyssea-Konschtat/npcs/Conflux_Surveyor.lua | 3 | 3234 | -----------------------------------
-- Zone: Abyssea - Konschtat
-- NPC: Conflux Surveyor
-- Type:
-- !pos 133.000 -72.738 -824.000 15
-----------------------------------
package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/abyssea");
require("scripts/zones/Abyssea-Konschtat/TextIDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local visitant = 0;
local prevtime = player:getVar("Abyssea_Time");
local STONES = getTravStonesTotal(player);
local SOJOURN = getAbyssiteTotal(player,SOJOURN);
if (player:hasStatusEffect(EFFECT_VISITANT)) then
visitant = 60;
end
player:startEvent(2001,0,visitant,prevtime,STONES,SOJOURN,0,0,0);
end;
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
local SOJOURN = getAbyssiteTotal(player,"SOJOURN");
local duration = 0;
local prevtime = player:getVar("Abyssea_Time"); -- Gets reduced by Visitants "on tic".
if (prevtime > 7200) then
prevtime = 7200;
duration = prevtime;
else
duration = prevtime;
end
duration = duration+(SOJOURN *180);
if (csid == 2001) then
if (option == 2) then -- Use no stones, use previous remaining time
player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0);
player:setVar("Abyssea_Time",duration);
elseif (option == 65538) then -- Use 1 stone
duration = ((duration + 1800) * VISITANT_BONUS);
player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0);
player:setVar("Abyssea_Time",duration);
spendTravStones(player,1);
elseif (option == 65539) then -- Use 1 stone
player:PrintToPlayer( "Not implemented yet, sorry!" );
-- Todo: extend time
elseif (option == 131074) then -- Use 2 stone
duration = ((duration + 3600) * VISITANT_BONUS);
player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0);
player:setVar("Abyssea_Time",duration);
spendTravStones(player,2);
elseif (option == 131075) then -- Use 2 stone
player:PrintToPlayer( "Not implemented yet, sorry!" );
-- Todo: extend time
elseif (option == 196610) then -- Use 3 stone
duration = ((duration + 5400) * VISITANT_BONUS);
player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0);
player:setVar("Abyssea_Time",duration);
spendTravStones(player,3);
elseif (option == 196611) then -- Use 3 stone
player:PrintToPlayer( "Not implemented yet, sorry!" );
-- Todo: extend time
elseif (option == 262146) then -- Use 4 stone
duration = ((duration + 7200) * VISITANT_BONUS);
player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0);
player:setVar("Abyssea_Time",duration);
spendTravStones(player,4);
end
end
end; | gpl-3.0 |
hooksta4/darkstar | scripts/zones/The_Boyahda_Tree/npcs/Grounds_Tome.lua | 2 | 1103 | -----------------------------------
-- Area: The Boyahda Tree
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_BOYAHDA_TREE,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,719,720,721,722,723,724,725,726,726,726);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,719,720,721,722,723,724,725,726,726,726,GOV_MSG_BOYAHDA_TREE);
end;
| gpl-3.0 |
hooksta4/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Mhasbaf.lua | 37 | 1030 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Mhasbaf
-- Type: Standard NPC
-- @pos 54.701 -6.999 11.387 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x021e);
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 |
hooksta4/darkstar | scripts/zones/zones/Port_Bastok/npcs/Sawyer.lua | 17 | 1551 | -----------------------------------
-- Area: Port Bastok
-- NPC: Sawyer
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
require("scripts/zones/Port_Bastok/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,SAWYER_SHOP_DIALOG);
stock = {
0x11EF, 147,1, --Pumpernickel
0x1141, 3036,1, --Egg Soup
0x115A, 368,1, --Pineapple Juice
0x1127, 22,2, --Bretzel
0x11E2, 143,2, --Sausage
0x1148, 1012,2, --Melon Juice
0x1155, 662,2, --Roast Mutton
0x1193, 92,3, --Iron Bread
0x1154, 294,3, --Baked Popoto
0x1167, 184,3, --Pebble Soup
0x119D, 10,3 --Distilled Water
}
showNationShop(player, BASTOK, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Windurst_Walls/npcs/Juvillie.lua | 38 | 1041 | -----------------------------------
-- Area: Windurst Walls
-- NPC: Juvillie
-- Type: Event Replayer
-- @zone: 239
-- @pos -180.731 -3.451 143.138
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0196);
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 |
hooksta4/darkstar | scripts/zones/Abyssea-Altepa/Zone.lua | 33 | 1470 | -----------------------------------
--
-- Zone: Abyssea - Altepa
--
-----------------------------------
package.loaded["scripts/zones/Abyssea-Altepa/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Abyssea-Altepa/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos(435 ,0 ,320 ,136)
end
if (player:getQuestStatus(ABYSSEA, THE_TRUTH_BECKONS) == QUEST_ACCEPTED
and player:getVar("1stTimeAyssea") == 0) then
player:setVar("1stTimeAyssea",1);
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 |
hooksta4/darkstar | scripts/zones/zones/Sacrarium/mobs/Old_Professor_Mariselle.lua | 2 | 2159 | -----------------------------------
-- Area: Sacrarium
-- NPC: Old Professor Mariselle
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/missions");
-----------------------------------
-- onMobSpawn
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobFight
-----------------------------------
function onMobFight(mob,target)
local OP_Mariselle = mob:getID();
-- Summons a pupil every 30 seconds.
-- TODO: Casting animation for summons. When he spawns them isn't retail accurate.
-- TODO: Make him and the clones teleport around the room every 30s
if (mob:getBattleTime() % 30 < 3 and mob:getBattleTime() > 3) then
for i = OP_Mariselle+1, OP_Mariselle+2 do
if (GetMobAction(i) == 0) then
SpawnMob(i):updateEnmity(target);
GetMobByID(i):setPos(GetMobByID(OP_Mariselle):getXPos()+1, GetMobByID(OP_Mariselle):getYPos(), GetMobByID(OP_Mariselle):getZPos()+1); -- Set pupil x and z position +1 from Mariselle
return;
end
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
local OP_Mariselle = mob:getID();
for i = OP_Mariselle+1, OP_Mariselle+2 do
if (GetMobAction(i) ~= 0) then
DespawnMob(i);
end
end
if (killer:getCurrentMission(COP) == THE_SECRETS_OF_WORSHIP and killer:getVar("PromathiaStatus") == 3 and killer:hasKeyItem(RELIQUIARIUM_KEY)==false) then
killer:setVar("PromathiaStatus",4);
end
-- Set random variable for determining Old Prof. Mariselle's next spawn location
local rand = math.random((2),(7));
SetServerVariable("Old_Prof_Spawn_Location", rand);
end;
-----------------------------------
-- OnMobDespawn
-----------------------------------
function onMobDespawn( mob )
local OP_Mariselle = mob:getID();
for i = OP_Mariselle+1, OP_Mariselle+2 do
if (GetMobAction(i) ~= 0) then
DespawnMob(i);
end
end
-- Set random variable for determining Old Prof. Mariselle's next spawn location
local rand = math.random((2),(7));
SetServerVariable("Old_Prof_Spawn_Location", rand);
end; | gpl-3.0 |
hooksta4/darkstar | scripts/zones/zones/Lower_Jeuno/npcs/Morefie.lua | 6 | 1119 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Morefie
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MOREFIE_SHOP_DIALOG);
stock = {0x340F,1250, -- Silver Earring
0x3490,1250, -- Silver Ring
0x3410,4140} -- Mythril Earring
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 |
snabbco/snabb | lib/ljndpi/ndpi/protocol_ids_2_3.lua | 6 | 13824 | -- Generated by ljdnpi's tools/update-protocol-ids script
local T = {
[0] = "PROTOCOL_UNKNOWN",
[0] = "PROTOCOL_UNKNOWN",
[1] = "PROTOCOL_FTP_CONTROL",
[2] = "PROTOCOL_SIZE",
[2] = "PROTOCOL_MAIL_POP",
[3] = "PROTOCOL_MAIL_SMTP",
[4] = "PROTOCOL_MAIL_IMAP",
[5] = "PROTOCOL_DNS",
[6] = "PROTOCOL_IPP",
[7] = "PROTOCOL_HTTP",
[8] = "PROTOCOL_MDNS",
[9] = "PROTOCOL_NTP",
[10] = "PROTOCOL_NETBIOS",
[11] = "PROTOCOL_NFS",
[12] = "PROTOCOL_SSDP",
[13] = "PROTOCOL_BGP",
[14] = "PROTOCOL_SNMP",
[15] = "PROTOCOL_XDMCP",
[16] = "PROTOCOL_SMB",
[17] = "PROTOCOL_SYSLOG",
[18] = "PROTOCOL_DHCP",
[19] = "PROTOCOL_POSTGRES",
[20] = "PROTOCOL_MYSQL",
[21] = "PROTOCOL_HOTMAIL",
[22] = "PROTOCOL_DIRECT_DOWNLOAD_LINK",
[23] = "PROTOCOL_MAIL_POPS",
[24] = "PROTOCOL_APPLEJUICE",
[25] = "PROTOCOL_DIRECTCONNECT",
[26] = "PROTOCOL_NTOP",
[27] = "PROTOCOL_COAP",
[28] = "PROTOCOL_VMWARE",
[29] = "PROTOCOL_MAIL_SMTPS",
[30] = "PROTOCOL_FBZERO",
[31] = "PROTOCOL_UBNTAC2",
[32] = "PROTOCOL_KONTIKI",
[33] = "PROTOCOL_OPENFT",
[34] = "PROTOCOL_FASTTRACK",
[35] = "PROTOCOL_GNUTELLA",
[36] = "PROTOCOL_EDONKEY",
[37] = "PROTOCOL_BITTORRENT",
[38] = "PROTOCOL_SKYPE_CALL_OUT",
[39] = "PROTOCOL_MUSICALLY",
[40] = "PROTOCOL_FREE_40",
[41] = "PROTOCOL_FREE_41",
[42] = "PROTOCOL_FREE_42",
[43] = "PROTOCOL_FREE_43",
[44] = "PROTOCOL_FREE_44",
[45] = "PROTOCOL_FREE_45",
[46] = "PROTOCOL_FREE_46",
[47] = "PROTOCOL_XBOX",
[48] = "PROTOCOL_QQ",
[49] = "PROTOCOL_SKYPE_CALL_IN",
[50] = "PROTOCOL_RTSP",
[51] = "PROTOCOL_MAIL_IMAPS",
[52] = "PROTOCOL_ICECAST",
[53] = "PROTOCOL_PPLIVE",
[54] = "PROTOCOL_PPSTREAM",
[55] = "PROTOCOL_ZATTOO",
[56] = "PROTOCOL_SHOUTCAST",
[57] = "PROTOCOL_SOPCAST",
[58] = "PROTOCOL_TVANTS",
[59] = "PROTOCOL_TVUPLAYER",
[60] = "PROTOCOL_HTTP_DOWNLOAD",
[61] = "PROTOCOL_QQLIVE",
[62] = "PROTOCOL_THUNDER",
[63] = "PROTOCOL_SOULSEEK",
[64] = "PROTOCOL_SSL_NO_CERT",
[65] = "PROTOCOL_IRC",
[66] = "PROTOCOL_AYIYA",
[67] = "PROTOCOL_UNENCRYPTED_JABBER",
[68] = "PROTOCOL_MSN",
[69] = "PROTOCOL_OSCAR",
[70] = "PROTOCOL_YAHOO",
[71] = "PROTOCOL_BATTLEFIELD",
[72] = "PROTOCOL_GOOGLE_PLUS",
[73] = "PROTOCOL_IP_VRRP",
[74] = "PROTOCOL_STEAM",
[75] = "PROTOCOL_HALFLIFE2",
[76] = "PROTOCOL_WORLDOFWARCRAFT",
[77] = "PROTOCOL_TELNET",
[78] = "PROTOCOL_STUN",
[79] = "PROTOCOL_IP_IPSEC",
[80] = "PROTOCOL_IP_GRE",
[81] = "PROTOCOL_IP_ICMP",
[82] = "PROTOCOL_IP_IGMP",
[83] = "PROTOCOL_IP_EGP",
[84] = "PROTOCOL_IP_SCTP",
[85] = "PROTOCOL_IP_OSPF",
[86] = "PROTOCOL_IP_IP_IN_IP",
[87] = "PROTOCOL_RTP",
[88] = "PROTOCOL_RDP",
[89] = "PROTOCOL_VNC",
[90] = "PROTOCOL_PCANYWHERE",
[91] = "PROTOCOL_SSL",
[92] = "PROTOCOL_SSH",
[93] = "PROTOCOL_USENET",
[94] = "PROTOCOL_MGCP",
[95] = "PROTOCOL_IAX",
[96] = "PROTOCOL_TFTP",
[97] = "PROTOCOL_AFP",
[98] = "PROTOCOL_STEALTHNET",
[99] = "PROTOCOL_AIMINI",
[100] = "PROTOCOL_SIP",
[101] = "PROTOCOL_TRUPHONE",
[102] = "PROTOCOL_IP_ICMPV6",
[103] = "PROTOCOL_DHCPV6",
[104] = "PROTOCOL_ARMAGETRON",
[105] = "PROTOCOL_CROSSFIRE",
[106] = "PROTOCOL_DOFUS",
[107] = "PROTOCOL_FIESTA",
[108] = "PROTOCOL_FLORENSIA",
[109] = "PROTOCOL_GUILDWARS",
[110] = "PROTOCOL_HTTP_APPLICATION_ACTIVESYNC",
[111] = "PROTOCOL_KERBEROS",
[112] = "PROTOCOL_LDAP",
[113] = "PROTOCOL_MAPLESTORY",
[114] = "PROTOCOL_MSSQL_TDS",
[115] = "PROTOCOL_PPTP",
[116] = "PROTOCOL_WARCRAFT3",
[117] = "PROTOCOL_WORLD_OF_KUNG_FU",
[118] = "PROTOCOL_SLACK",
[119] = "PROTOCOL_FACEBOOK",
[120] = "PROTOCOL_TWITTER",
[121] = "PROTOCOL_DROPBOX",
[122] = "PROTOCOL_GMAIL",
[123] = "PROTOCOL_GOOGLE_MAPS",
[124] = "PROTOCOL_YOUTUBE",
[125] = "PROTOCOL_SKYPE",
[126] = "PROTOCOL_GOOGLE",
[127] = "PROTOCOL_DCERPC",
[128] = "PROTOCOL_NETFLOW",
[129] = "PROTOCOL_SFLOW",
[130] = "PROTOCOL_HTTP_CONNECT",
[131] = "PROTOCOL_HTTP_PROXY",
[132] = "PROTOCOL_CITRIX",
[133] = "PROTOCOL_NETFLIX",
[134] = "PROTOCOL_LASTFM",
[135] = "PROTOCOL_WAZE",
[136] = "PROTOCOL_YOUTUBE_UPLOAD",
[137] = "PROTOCOL_ICQ",
[138] = "PROTOCOL_CHECKMK",
[139] = "PROTOCOL_AJP",
[140] = "PROTOCOL_APPLE",
[141] = "PROTOCOL_WEBEX",
[142] = "PROTOCOL_WHATSAPP",
[143] = "PROTOCOL_APPLE_ICLOUD",
[144] = "PROTOCOL_VIBER",
[145] = "PROTOCOL_APPLE_ITUNES",
[146] = "PROTOCOL_RADIUS",
[147] = "PROTOCOL_WINDOWS_UPDATE",
[148] = "PROTOCOL_TEAMVIEWER",
[149] = "PROTOCOL_TUENTI",
[150] = "PROTOCOL_LOTUS_NOTES",
[151] = "PROTOCOL_SAP",
[152] = "PROTOCOL_GTP",
[153] = "PROTOCOL_UPNP",
[154] = "PROTOCOL_LLMNR",
[155] = "PROTOCOL_REMOTE_SCAN",
[156] = "PROTOCOL_SPOTIFY",
[157] = "PROTOCOL_MESSENGER",
[158] = "PROTOCOL_H323",
[159] = "PROTOCOL_OPENVPN",
[160] = "PROTOCOL_NOE",
[161] = "PROTOCOL_CISCOVPN",
[162] = "PROTOCOL_TEAMSPEAK",
[163] = "PROTOCOL_TOR",
[164] = "PROTOCOL_SKINNY",
[165] = "PROTOCOL_RTCP",
[166] = "PROTOCOL_RSYNC",
[167] = "PROTOCOL_ORACLE",
[168] = "PROTOCOL_CORBA",
[169] = "PROTOCOL_UBUNTUONE",
[170] = "PROTOCOL_WHOIS_DAS",
[171] = "PROTOCOL_COLLECTD",
[172] = "PROTOCOL_SOCKS",
[173] = "PROTOCOL_NINTENDO",
[174] = "PROTOCOL_RTMP",
[175] = "PROTOCOL_FTP_DATA",
[176] = "PROTOCOL_WIKIPEDIA",
[177] = "PROTOCOL_ZMQ",
[178] = "PROTOCOL_AMAZON",
[179] = "PROTOCOL_EBAY",
[180] = "PROTOCOL_CNN",
[181] = "PROTOCOL_MEGACO",
[182] = "PROTOCOL_REDIS",
[183] = "PROTOCOL_PANDO",
[184] = "PROTOCOL_VHUA",
[185] = "PROTOCOL_TELEGRAM",
[186] = "PROTOCOL_VEVO",
[187] = "PROTOCOL_PANDORA",
[188] = "PROTOCOL_QUIC",
[189] = "PROTOCOL_WHATSAPP_VOICE",
[190] = "PROTOCOL_EAQ",
[191] = "PROTOCOL_OOKLA",
[192] = "PROTOCOL_AMQP",
[193] = "PROTOCOL_KAKAOTALK",
[194] = "PROTOCOL_KAKAOTALK_VOICE",
[195] = "PROTOCOL_TWITCH",
[196] = "PROTOCOL_QUICKPLAY",
[197] = "PROTOCOL_WECHAT",
[198] = "PROTOCOL_MPEGTS",
[199] = "PROTOCOL_SNAPCHAT",
[200] = "PROTOCOL_SINA",
[201] = "PROTOCOL_HANGOUT",
[202] = "PROTOCOL_IFLIX",
[203] = "PROTOCOL_GITHUB",
[204] = "PROTOCOL_BJNP",
[205] = "PROTOCOL_1KXUN",
[206] = "PROTOCOL_IQIYI",
[207] = "PROTOCOL_SMPP",
[208] = "PROTOCOL_DNSCRYPT",
[209] = "PROTOCOL_TINC",
[210] = "PROTOCOL_DEEZER",
[211] = "PROTOCOL_INSTAGRAM",
[212] = "PROTOCOL_MICROSOFT",
[213] = "PROTOCOL_STARCRAFT",
[214] = "PROTOCOL_TEREDO",
[215] = "PROTOCOL_HOTSPOT_SHIELD",
[216] = "PROTOCOL_HEP",
[217] = "PROTOCOL_GOOGLE_DRIVE",
[218] = "PROTOCOL_OCS",
[219] = "PROTOCOL_OFFICE_365",
[220] = "PROTOCOL_CLOUDFLARE",
[221] = "PROTOCOL_MS_ONE_DRIVE",
[222] = "PROTOCOL_MQTT",
[223] = "PROTOCOL_RX",
[224] = "PROTOCOL_APPLESTORE",
[225] = "PROTOCOL_OPENDNS",
[226] = "PROTOCOL_GIT",
[227] = "PROTOCOL_DRDA",
[228] = "PROTOCOL_PLAYSTORE",
[229] = "PROTOCOL_SOMEIP",
[230] = "PROTOCOL_FIX",
[231] = "PROTOCOL_PLAYSTATION",
[232] = "PROTOCOL_PASTEBIN",
[233] = "PROTOCOL_LINKEDIN",
[234] = "PROTOCOL_SOUNDCLOUD",
[235] = "PROTOCOL_CSGO",
[236] = "PROTOCOL_LISP",
[237] = "PROTOCOL_DIAMETER",
[238] = "PROTOCOL_APPLE_PUSH",
[239] = "PROTOCOL_GOOGLE_SERVICES",
[240] = "PROTOCOL_AMAZON_VIDEO",
[241] = "PROTOCOL_GOOGLE_DOCS",
[242] = "PROTOCOL_WHATSAPP_FILES",
[243] = "PROTOCOL_VIDTO",
[244] = "PROTOCOL_RAPIDVIDEO",
[245] = "PROTOCOL_SHOWMAX",
PROTOCOL_UNKNOWN = 0,
PROTOCOL_UNKNOWN = 0,
PROTOCOL_FTP_CONTROL = 1,
PROTOCOL_SIZE = 2,
PROTOCOL_MAIL_POP = 2,
PROTOCOL_MAIL_SMTP = 3,
PROTOCOL_MAIL_IMAP = 4,
PROTOCOL_DNS = 5,
PROTOCOL_IPP = 6,
PROTOCOL_HTTP = 7,
PROTOCOL_MDNS = 8,
PROTOCOL_NTP = 9,
PROTOCOL_NETBIOS = 10,
PROTOCOL_NFS = 11,
PROTOCOL_SSDP = 12,
PROTOCOL_BGP = 13,
PROTOCOL_SNMP = 14,
PROTOCOL_XDMCP = 15,
PROTOCOL_SMB = 16,
PROTOCOL_SYSLOG = 17,
PROTOCOL_DHCP = 18,
PROTOCOL_POSTGRES = 19,
PROTOCOL_MYSQL = 20,
PROTOCOL_HOTMAIL = 21,
PROTOCOL_DIRECT_DOWNLOAD_LINK = 22,
PROTOCOL_MAIL_POPS = 23,
PROTOCOL_APPLEJUICE = 24,
PROTOCOL_DIRECTCONNECT = 25,
PROTOCOL_NTOP = 26,
PROTOCOL_COAP = 27,
PROTOCOL_VMWARE = 28,
PROTOCOL_MAIL_SMTPS = 29,
PROTOCOL_FBZERO = 30,
PROTOCOL_UBNTAC2 = 31,
PROTOCOL_KONTIKI = 32,
PROTOCOL_OPENFT = 33,
PROTOCOL_FASTTRACK = 34,
PROTOCOL_GNUTELLA = 35,
PROTOCOL_EDONKEY = 36,
PROTOCOL_BITTORRENT = 37,
PROTOCOL_SKYPE_CALL_OUT = 38,
PROTOCOL_MUSICALLY = 39,
PROTOCOL_FREE_40 = 40,
PROTOCOL_FREE_41 = 41,
PROTOCOL_FREE_42 = 42,
PROTOCOL_FREE_43 = 43,
PROTOCOL_FREE_44 = 44,
PROTOCOL_FREE_45 = 45,
PROTOCOL_FREE_46 = 46,
PROTOCOL_XBOX = 47,
PROTOCOL_QQ = 48,
PROTOCOL_SKYPE_CALL_IN = 49,
PROTOCOL_RTSP = 50,
PROTOCOL_MAIL_IMAPS = 51,
PROTOCOL_ICECAST = 52,
PROTOCOL_PPLIVE = 53,
PROTOCOL_PPSTREAM = 54,
PROTOCOL_ZATTOO = 55,
PROTOCOL_SHOUTCAST = 56,
PROTOCOL_SOPCAST = 57,
PROTOCOL_TVANTS = 58,
PROTOCOL_TVUPLAYER = 59,
PROTOCOL_HTTP_DOWNLOAD = 60,
PROTOCOL_QQLIVE = 61,
PROTOCOL_THUNDER = 62,
PROTOCOL_SOULSEEK = 63,
PROTOCOL_SSL_NO_CERT = 64,
PROTOCOL_IRC = 65,
PROTOCOL_AYIYA = 66,
PROTOCOL_UNENCRYPTED_JABBER = 67,
PROTOCOL_MSN = 68,
PROTOCOL_OSCAR = 69,
PROTOCOL_YAHOO = 70,
PROTOCOL_BATTLEFIELD = 71,
PROTOCOL_GOOGLE_PLUS = 72,
PROTOCOL_IP_VRRP = 73,
PROTOCOL_STEAM = 74,
PROTOCOL_HALFLIFE2 = 75,
PROTOCOL_WORLDOFWARCRAFT = 76,
PROTOCOL_TELNET = 77,
PROTOCOL_STUN = 78,
PROTOCOL_IP_IPSEC = 79,
PROTOCOL_IP_GRE = 80,
PROTOCOL_IP_ICMP = 81,
PROTOCOL_IP_IGMP = 82,
PROTOCOL_IP_EGP = 83,
PROTOCOL_IP_SCTP = 84,
PROTOCOL_IP_OSPF = 85,
PROTOCOL_IP_IP_IN_IP = 86,
PROTOCOL_RTP = 87,
PROTOCOL_RDP = 88,
PROTOCOL_VNC = 89,
PROTOCOL_PCANYWHERE = 90,
PROTOCOL_SSL = 91,
PROTOCOL_SSH = 92,
PROTOCOL_USENET = 93,
PROTOCOL_MGCP = 94,
PROTOCOL_IAX = 95,
PROTOCOL_TFTP = 96,
PROTOCOL_AFP = 97,
PROTOCOL_STEALTHNET = 98,
PROTOCOL_AIMINI = 99,
PROTOCOL_SIP = 100,
PROTOCOL_TRUPHONE = 101,
PROTOCOL_IP_ICMPV6 = 102,
PROTOCOL_DHCPV6 = 103,
PROTOCOL_ARMAGETRON = 104,
PROTOCOL_CROSSFIRE = 105,
PROTOCOL_DOFUS = 106,
PROTOCOL_FIESTA = 107,
PROTOCOL_FLORENSIA = 108,
PROTOCOL_GUILDWARS = 109,
PROTOCOL_HTTP_APPLICATION_ACTIVESYNC = 110,
PROTOCOL_KERBEROS = 111,
PROTOCOL_LDAP = 112,
PROTOCOL_MAPLESTORY = 113,
PROTOCOL_MSSQL_TDS = 114,
PROTOCOL_PPTP = 115,
PROTOCOL_WARCRAFT3 = 116,
PROTOCOL_WORLD_OF_KUNG_FU = 117,
PROTOCOL_SLACK = 118,
PROTOCOL_FACEBOOK = 119,
PROTOCOL_TWITTER = 120,
PROTOCOL_DROPBOX = 121,
PROTOCOL_GMAIL = 122,
PROTOCOL_GOOGLE_MAPS = 123,
PROTOCOL_YOUTUBE = 124,
PROTOCOL_SKYPE = 125,
PROTOCOL_GOOGLE = 126,
PROTOCOL_DCERPC = 127,
PROTOCOL_NETFLOW = 128,
PROTOCOL_SFLOW = 129,
PROTOCOL_HTTP_CONNECT = 130,
PROTOCOL_HTTP_PROXY = 131,
PROTOCOL_CITRIX = 132,
PROTOCOL_NETFLIX = 133,
PROTOCOL_LASTFM = 134,
PROTOCOL_WAZE = 135,
PROTOCOL_YOUTUBE_UPLOAD = 136,
PROTOCOL_ICQ = 137,
PROTOCOL_CHECKMK = 138,
PROTOCOL_AJP = 139,
PROTOCOL_APPLE = 140,
PROTOCOL_WEBEX = 141,
PROTOCOL_WHATSAPP = 142,
PROTOCOL_APPLE_ICLOUD = 143,
PROTOCOL_VIBER = 144,
PROTOCOL_APPLE_ITUNES = 145,
PROTOCOL_RADIUS = 146,
PROTOCOL_WINDOWS_UPDATE = 147,
PROTOCOL_TEAMVIEWER = 148,
PROTOCOL_TUENTI = 149,
PROTOCOL_LOTUS_NOTES = 150,
PROTOCOL_SAP = 151,
PROTOCOL_GTP = 152,
PROTOCOL_UPNP = 153,
PROTOCOL_LLMNR = 154,
PROTOCOL_REMOTE_SCAN = 155,
PROTOCOL_SPOTIFY = 156,
PROTOCOL_MESSENGER = 157,
PROTOCOL_H323 = 158,
PROTOCOL_OPENVPN = 159,
PROTOCOL_NOE = 160,
PROTOCOL_CISCOVPN = 161,
PROTOCOL_TEAMSPEAK = 162,
PROTOCOL_TOR = 163,
PROTOCOL_SKINNY = 164,
PROTOCOL_RTCP = 165,
PROTOCOL_RSYNC = 166,
PROTOCOL_ORACLE = 167,
PROTOCOL_CORBA = 168,
PROTOCOL_UBUNTUONE = 169,
PROTOCOL_WHOIS_DAS = 170,
PROTOCOL_COLLECTD = 171,
PROTOCOL_SOCKS = 172,
PROTOCOL_NINTENDO = 173,
PROTOCOL_RTMP = 174,
PROTOCOL_FTP_DATA = 175,
PROTOCOL_WIKIPEDIA = 176,
PROTOCOL_ZMQ = 177,
PROTOCOL_AMAZON = 178,
PROTOCOL_EBAY = 179,
PROTOCOL_CNN = 180,
PROTOCOL_MEGACO = 181,
PROTOCOL_REDIS = 182,
PROTOCOL_PANDO = 183,
PROTOCOL_VHUA = 184,
PROTOCOL_TELEGRAM = 185,
PROTOCOL_VEVO = 186,
PROTOCOL_PANDORA = 187,
PROTOCOL_QUIC = 188,
PROTOCOL_WHATSAPP_VOICE = 189,
PROTOCOL_EAQ = 190,
PROTOCOL_OOKLA = 191,
PROTOCOL_AMQP = 192,
PROTOCOL_KAKAOTALK = 193,
PROTOCOL_KAKAOTALK_VOICE = 194,
PROTOCOL_TWITCH = 195,
PROTOCOL_QUICKPLAY = 196,
PROTOCOL_WECHAT = 197,
PROTOCOL_MPEGTS = 198,
PROTOCOL_SNAPCHAT = 199,
PROTOCOL_SINA = 200,
PROTOCOL_HANGOUT = 201,
PROTOCOL_IFLIX = 202,
PROTOCOL_GITHUB = 203,
PROTOCOL_BJNP = 204,
PROTOCOL_1KXUN = 205,
PROTOCOL_IQIYI = 206,
PROTOCOL_SMPP = 207,
PROTOCOL_DNSCRYPT = 208,
PROTOCOL_TINC = 209,
PROTOCOL_DEEZER = 210,
PROTOCOL_INSTAGRAM = 211,
PROTOCOL_MICROSOFT = 212,
PROTOCOL_STARCRAFT = 213,
PROTOCOL_TEREDO = 214,
PROTOCOL_HOTSPOT_SHIELD = 215,
PROTOCOL_HEP = 216,
PROTOCOL_GOOGLE_DRIVE = 217,
PROTOCOL_OCS = 218,
PROTOCOL_OFFICE_365 = 219,
PROTOCOL_CLOUDFLARE = 220,
PROTOCOL_MS_ONE_DRIVE = 221,
PROTOCOL_MQTT = 222,
PROTOCOL_RX = 223,
PROTOCOL_APPLESTORE = 224,
PROTOCOL_OPENDNS = 225,
PROTOCOL_GIT = 226,
PROTOCOL_DRDA = 227,
PROTOCOL_PLAYSTORE = 228,
PROTOCOL_SOMEIP = 229,
PROTOCOL_FIX = 230,
PROTOCOL_PLAYSTATION = 231,
PROTOCOL_PASTEBIN = 232,
PROTOCOL_LINKEDIN = 233,
PROTOCOL_SOUNDCLOUD = 234,
PROTOCOL_CSGO = 235,
PROTOCOL_LISP = 236,
PROTOCOL_DIAMETER = 237,
PROTOCOL_APPLE_PUSH = 238,
PROTOCOL_GOOGLE_SERVICES = 239,
PROTOCOL_AMAZON_VIDEO = 240,
PROTOCOL_GOOGLE_DOCS = 241,
PROTOCOL_WHATSAPP_FILES = 242,
PROTOCOL_VIDTO = 243,
PROTOCOL_RAPIDVIDEO = 244,
PROTOCOL_SHOWMAX = 245,
}
T.PROTOCOL_NO_MASTER_PROTO = T.PROTOCOL_UNKNOWN
return T | apache-2.0 |
hooksta4/darkstar | scripts/zones/Port_San_dOria/npcs/Prietta.lua | 13 | 1435 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Prietta
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- 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 and player:getVar("tradePrietta") == 0) then
player:messageSpecial(7121);
player:setVar("FFR",player:getVar("FFR") - 1);
player:setVar("tradePrietta",1);
player:messageSpecial(7122,17 - player:getVar("FFR"));
trade:complete();
elseif (player:getVar("tradePrietta") ==1) then
player:messageSpecial(7120);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x254);
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 |
Null22/senator | plugins/id.lua | 355 | 2795 | 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
local function returnids(cb_extra, success, result)
local receiver = cb_extra.receiver
--local chat_id = "chat#id"..result.id
local chat_id = result.id
local chatname = result.print_name
local text = 'IDs for chat '..chatname
..' ('..chat_id..')\n'
..'There are '..result.members_num..' members'
..'\n---------\n'
i = 0
for k,v in pairs(result.members) do
i = i+1
text = text .. i .. ". " .. string.gsub(v.print_name, "_", " ") .. " (" .. v.id .. ")\n"
end
send_large_msg(receiver, text)
end
local function username_id(cb_extra, success, result)
local receiver = cb_extra.receiver
local qusername = cb_extra.qusername
local text = 'User '..qusername..' not found in this group!'
for k,v in pairs(result.members) do
vusername = v.username
if vusername == qusername then
text = 'ID for username\n'..vusername..' : '..v.id
end
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "!id" then
local text = 'Name : '.. string.gsub(user_print_name(msg.from),'_', ' ') .. '\nID : ' .. msg.from.id
if is_chat_msg(msg) then
text = text .. "\n\nYou are in group " .. string.gsub(user_print_name(msg.to), '_', ' ') .. " (ID: " .. msg.to.id .. ")"
end
return text
elseif matches[1] == "chat" then
-- !ids? (chat) (%d+)
if matches[2] and is_sudo(msg) then
local chat = 'chat#id'..matches[2]
chat_info(chat, returnids, {receiver=receiver})
else
if not is_chat_msg(msg) then
return "You are not in a group."
end
local chat = get_receiver(msg)
chat_info(chat, returnids, {receiver=receiver})
end
else
if not is_chat_msg(msg) then
return "Only works in group"
end
local qusername = string.gsub(matches[1], "@", "")
local chat = get_receiver(msg)
chat_info(chat, username_id, {receiver=receiver, qusername=qusername})
end
end
return {
description = "Know your id or the id of a chat members.",
usage = {
"!id: Return your ID and the chat id if you are in one.",
"!ids chat: Return the IDs of the current chat members.",
"!ids chat <chat_id>: Return the IDs of the <chat_id> members.",
"!id <username> : Return the id from username given."
},
patterns = {
"^!id$",
"^!ids? (chat) (%d+)$",
"^!ids? (chat)$",
"^!id (.*)$"
},
run = run
}
| gpl-2.0 |
hooksta4/darkstar | scripts/zones/Bastok_Mines/npcs/Pavvke.lua | 6 | 2088 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Pavvke
-- Starts Quests: Fallen Comrades (100%)
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
count = trade:getItemCount();
SilverTag = trade:hasItemQty(13116,1);
Fallen = player:getQuestStatus(BASTOK,FALLEN_COMRADES);
if (Fallen == 1 and SilverTag == true and count == 1) then
player:tradeComplete();
player:startEvent(0x005b);
elseif (Fallen == 2 and SilverTag == true and count == 1) then
player:tradeComplete();
player:startEvent(0x005c);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Fallen = player:getQuestStatus(BASTOK,FALLEN_COMRADES);
pLevel = player:getMainLvl(player);
pFame = player:getFameLevel(BASTOK);
if (Fallen == 0 and pLevel >= 12 and pFame >= 2) then
player:startEvent(0x005a);
else
player:startEvent(0x004b);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x005a) then
player:addQuest(BASTOK,FALLEN_COMRADES);
elseif (csid == 0x005b) then
player:completeQuest(BASTOK,FALLEN_COMRADES);
player:addFame(BASTOK,BAS_FAME*120);
player:addGil(GIL_RATE*550);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*550);
elseif (csid == 0x005c) then
player:addFame(BASTOK,BAS_FAME*8);
player:addGil(GIL_RATE*550);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*550);
end
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Riverne-Site_A01/npcs/_0u3.lua | 19 | 1339 | -----------------------------------
-- Area: Riverne Site #A01
-- NPC: Unstable Displacement
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Riverne-Site_A01/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale
player:tradeComplete();
npc:openDoor(RIVERNE_PORTERS);
player:messageSpecial(SD_HAS_GROWN);
end
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if(npc:getAnimation() == 8) then
player:startEvent(0x13);
else
player:messageSpecial(SD_VERY_SMALL);
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 |
FishFilletsNG/fillets-data | script/barrel/code.lua | 1 | 33741 |
file_include('script/share/prog_border.lua')
-- -----------------------------------------------------------------
-- Init
-- -----------------------------------------------------------------
local function prog_init()
initModels()
sound_playMusic("music/rybky05.ogg")
local pokus = getRestartCount()
--NOTE: a final level
small:setGoal("goal_alive")
big:setGoal("goal_alive")
barel:setGoal("goal_out")
-- -------------------------------------------------------------
local function prog_init_room()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
room.uvod = 0
room.celakrajni = 0
room.ozviratkach = {}
room.hl1 = random(400) + 400
room.hl2 = room.hl1 + random(800) + 800
room.hl3 = room.hl2 + random(1600) + 1600
room.hl4 = room.hl3 + random(3200) + 3200
room.onoze = 0
room.opldech = 0
room.okukajde = 0
room.okrabovi = 0
room.okachne = 0
return function()
if stdBorderReport() then
addm(6, "bar-m-barel")
if random(100) < 30 or room.celakrajni == 0 then
addv(random(10) + 5, "bar-v-genofond")
end
room.celakrajni = 1
end
if no_dialog() and isReady(small) and isReady(big) then
if room.hl1 > 0 then
room.hl1 = room.hl1 - 1
end
if room.hl2 > 0 then
room.hl2 = room.hl2 - 1
end
if room.hl3 > 0 then
room.hl3 = room.hl3 - 1
end
if room.hl4 > 0 then
room.hl4 = room.hl4 - 1
end
if room.uvod == 0 then
room.uvod = 1
switch(pokus){
[1] = function()
pom1 = 5
end,
[2] = function()
pom1 = randint(2, 4)
end,
default = function()
pom1 = random(6)
end,
}
adddel(10 + random(20))
if pom1 >= 4 then
switch(random(2)){
[0] = function()
addv(0, "bar-v-videt0")
end,
[1] = function()
addm(0, "bar-m-videt1")
end,
}
end
if pom1 >= 5 then
addv(5, "bar-v-co")
end
if pom1 >= 2 then
addm(10, "bar-m-pobit")
planDialogSet(2, "bar-x-suckne", 201, pldik, "cinnost")
addv(10, "bar-v-priciny")
planDialogSet(2, "bar-x-suckano", 202, pldik, "cinnost")
end
if pom1 >= 4 then
addm(random(30) + 10, "bar-m-no")
end
if pom1 >= 2 then
addv(5, "bar-v-sud")
end
if pom1 >= 3 then
addm(5, "bar-m-panb")
end
elseif room.hl1 == 0 or room.hl2 == 0 or room.hl3 == 0 or room.hl4 == 0 then
if room.hl1 == 0 then
room.hl1 = -1
end
if room.hl2 == 0 then
room.hl2 = -1
end
if room.hl3 == 0 then
room.hl3 = -1
end
if room.hl4 == 0 then
room.hl4 = -1
end
if countPairs(room.ozviratkach) == 0 then
pom1 = random(2)
elseif countPairs(room.ozviratkach) == 4 then
room.ozviratkach = {}
pom1 = random(4)
else
repeat
pom1 = random(4)
until not room.ozviratkach[pom1]
end
room.ozviratkach[pom1] = true
adddel(50 + random(100))
switch(pom1){
[0] = function()
addm(0, "bar-m-rada")
addv(7, "bar-v-kdyby" ..random(2))
end,
[1] = function()
addm(0, "bar-m-mutanti")
if random(100) < 50 then
addv(10, "bar-v-ufouni")
end
addm(random(50) + 10, "bar-m-zmeni")
end,
[2] = function()
addv(0, "bar-v-lih")
addm(8, "bar-m-fdto")
pldotec:planDialog(3, "bar-x-vypr")
addm(10, "bar-m-promin")
end,
[3] = function()
addv(0, "bar-v-sbirka")
addm(10, "bar-m-dost" ..random(2))
end,
}
elseif room.onoze == 0 and nozka.cinnost < 20 and dist(small, nozka) < 5 and random(1000) < 2 then
room.onoze = 1
addm(3, "bar-m-noha")
elseif room.opldech == 0 and dist(big, pldotec) <= 5 and random(100) < 1 then
room.opldech = 1
addv(10, "bar-v-pld")
addm(6, "bar-m-pudy")
addv(2, "bar-v-traverza")
planDialogSet(2, "bar-x-suckne", 201, pldik, "cinnost")
elseif room.okukajde == 0 and kukajda.dir ~= dir_no and random(100) < 2 and small.dir ~= dir_no then
room.okukajde = 1
addm(10, "bar-m-rybka")
if random(100) < 70 then
addv(random(30) + 5, "bar-v-fotka")
end
elseif room.okrabovi == 0 and look_at(big, krabik) and dist(big, krabik) <= 3 and random(100) < 1 then
room.okrabovi = 1
addv(10, "bar-v-krab")
elseif room.okachne == 0 and kachnicka.dir ~= dir_no and small.dir ~= dir_no and random(100) < 10 then
room.okachne = 1
addm(5, "bar-m-kachna")
end
end
end
end
-- -------------------------------------------------------------
local function prog_init_barel()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
setanim(barel, "a0d8a1a2a3a4d3a3a2a1R")
return function()
goanim(barel)
barel:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_kachnicka()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
kachnicka.cinnost = random(100) + 10
return function()
if kachnicka.cinnost > 0 then
if kachnicka:isTalking() then
kachnicka:killSound()
end
if odd(game_getCycles()) and random(100) < 10 then
kachnicka.afaze = random(5)
end
kachnicka.cinnost = kachnicka.cinnost - 1
if kachnicka.cinnost == 0 then
kachnicka.afaze = 5
kachnicka.cinnost = -30 - random(60)
end
else
if not kachnicka:isTalking() then
kachnicka:talk("bar-x-kchkch", VOLUME_LOW, -1)
end
kachnicka.afaze = math.mod(kachnicka.afaze - 5 + 1, 4) + 5
kachnicka.cinnost = kachnicka.cinnost + 1
if kachnicka.cinnost == 0 then
kachnicka.afaze = 0
kachnicka.cinnost = 30 + random(100)
end
end
kachnicka:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_had()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
had.streva = random(4)
had.huba = random(3)
return function()
if math.mod(game_getCycles(), 3) == 0 then
if (had.huba == 0) then
if random(1000) < 15 then
had.huba = random(2) + 1
end
else
if random(1000) < 15 then
had.huba = 0
elseif random(100) < 50 then
had.huba = 3 - had.huba
end
end
end
had.streva = math.mod(had.streva + 1, 4)
had.afaze = 4 * had.huba + had.streva
had:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_ocicko()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
ocicko.cinnost = 0
return function()
if (ocicko.cinnost == 0) then
local rnd = random(8)
if random(100) < 10 then
if (rnd >= 0) and (rnd <= 2) then
ocicko.citac = random(5) + 5
ocicko.cinnost = 1
ocicko.faze = random(2) * 2
elseif (rnd == 3) then
ocicko.citac = random(3) + 2
ocicko.cinnost = 2
ocicko.faze = random(2) * 2
elseif (rnd >= 4) and (rnd <= 6) then
ocicko.citac = random(12) + 12
ocicko.cinnost = 3 + random(2)
elseif (rnd == 7) then
ocicko.citac = random(10) + 2
ocicko.cinnost = 5
end
end
elseif (ocicko.cinnost == 1) or (ocicko.cinnost == 2) then
switch(ocicko.faze){
[0] = function()
if ocicko.cinnost == 1 then
ocicko.afaze = 1
else
ocicko.afaze = 3
end
if random(100) < 20 then
ocicko.faze = ocicko.faze + 1
end
end,
[1] = function()
ocicko.afaze = 0
ocicko.faze = ocicko.faze + 1
end,
[2] = function()
if ocicko.cinnost == 1 then
ocicko.afaze = 2
else
ocicko.afaze = 4
end
if random(100) < 20 then
ocicko.faze = ocicko.faze + 1
end
end,
[3] = function()
ocicko.afaze = 0
ocicko.citac = ocicko.citac - 1
if ocicko.citac == 0 then
ocicko.cinnost = 0
else
ocicko.faze = 0
end
end,
}
elseif (ocicko.cinnost >= 3) or (ocicko.cinnost <= 5) then
switch(ocicko.cinnost){
[3] = function()
switch(ocicko.afaze){
[0] = function()
ocicko.afaze = random(4) + 1
end,
[1] = function()
ocicko.afaze = 3
end,
[2] = function()
ocicko.afaze = 4
end,
[3] = function()
ocicko.afaze = 2
end,
[4] = function()
ocicko.afaze = 1
end,
}
end,
[4] = function()
switch(ocicko.afaze){
[0] = function()
ocicko.afaze = random(4) + 1
end,
[1] = function()
ocicko.afaze = 4
end,
[2] = function()
ocicko.afaze = 3
end,
[3] = function()
ocicko.afaze = 1
end,
[4] = function()
ocicko.afaze = 2
end,
}
end,
[5] = function()
if random(100) < 40 then
ocicko.afaze = random(5)
end
end,
}
ocicko.citac = ocicko.citac - 1
if ocicko.citac == 0 then
ocicko.cinnost = 0
ocicko.afaze = 0
end
end
ocicko:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_kukajda()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
kukajda.ploutvicka = 0
kukajda.oci = 0
kukajda.mrknuti = 0
return function()
kukajda.ploutvicka = math.mod(kukajda.ploutvicka + 1, 6)
if (kukajda.ploutvicka == 0) or (kukajda.ploutvicka == 1) then
kukajda.afaze = 0
elseif (kukajda.ploutvicka == 2) or (kukajda.ploutvicka == 5) then
kukajda.afaze = 1
elseif (kukajda.ploutvicka == 3) or (kukajda.ploutvicka == 4) then
kukajda.afaze = 2
end
if random(100) < 3 then
kukajda.oci = random(5)
end
if kukajda.mrknuti > 0 then
kukajda.mrknuti = kukajda.mrknuti - 1
kukajda.afaze = kukajda.afaze + 15
else
kukajda.afaze = kukajda.afaze + kukajda.oci * 3
if random(100) < 4 then
kukajda.mrknuti = random(3) + 2
end
end
kukajda:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_killer()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
killer.ocas = 0
killer.usmev = 0
return function()
if odd(game_getCycles()) then
killer.ocas = 1 - killer.ocas
end
if killer.usmev > 0 then
killer.usmev = killer.usmev - 1
killer.afaze = killer.ocas
else
if random(100) < 2 then
killer.usmev = random(30) + 10
killer:talk("bar-x-gr" ..random(3), VOLUME_LOW)
end
killer.afaze = 2 * killer.ocas + 2
if random(100) < 7 then
killer.afaze = killer.afaze + 1
end
end
killer:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_hlubinna()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
hlubinna.ploutvicka = 0
hlubinna.zzzeni = 0
return function()
hlubinna.ploutvicka = math.mod(hlubinna.ploutvicka + 1, 5)
if (hlubinna.ploutvicka == 3) then
hlubinna.afaze = 1
elseif (hlubinna.ploutvicka == 4) then
hlubinna.afaze = 0
else
hlubinna.afaze = hlubinna.ploutvicka
end
if hlubinna.zzzeni > 0 then
hlubinna.afaze=hlubinna.afaze + 6
hlubinna.zzzeni = hlubinna.zzzeni - 1
elseif random(100) < 5 then
hlubinna.afaze = hlubinna.afaze + 3
elseif random(1000) < 15 then
hlubinna.afaze=hlubinna.afaze + 6
hlubinna.zzzeni = 5
hlubinna:talk("bar-x-zzz", VOLUME_LOW)
end
hlubinna:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_krabik()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
krabik.oci = 0
return function()
if odd(game_getCycles()) and random(100) < 10 then
krabik.oci = random(5)
end
if random(100) < 10 then
krabik.afaze = 5
else
krabik.afaze = krabik.oci
end
krabik:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_baget()
return function()
if random(100) < 6 then
baget.afaze = 1
else
baget.afaze = 0
end
baget:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_nozka()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
nozka.cinnost = random(100) + 20
nozka.dup = 0
nozka.oci = 0
return function()
if odd(game_getCycles()) and random(100) < 10 then
nozka.oci = random(5)
end
if nozka.cinnost > 0 then
nozka.cinnost = nozka.cinnost - 1
nozka.dup = 0
if nozka.cinnost == 0 then
nozka.cinnost = -20 - random(60)
end
else
if math.mod(game_getCycles(), 3) == 0 then
nozka.dup = 1 - nozka.dup
if nozka.dup == 0 then
nozka:talk("bar-x-tup", VOLUME_LOW)
end
end
if nozka.cinnost < -1 or nozka.dup == 0 then
nozka.cinnost = nozka.cinnost + 1
end
if nozka.cinnost == 0 then
nozka.cinnost = 10 + random(150)
end
end
if random(100) < 4 then
nozka.afaze = 5
else
nozka.afaze = nozka.oci
end
nozka.afaze = nozka.afaze + nozka.dup * 6
nozka:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_pldik()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
pldik.cinnost = 0
pldik.oci = 0
pldik.suckani = 0
return function()
switch(pldik.cinnost){
[0] = function()
if random(1000) < 5 then
pldik.cinnost = 1
end
if random(100) < 5 then
pldik.oci = random(5)
if pldik.oci > 0 then
pldik.oci = pldik.oci + 1
end
end
if pldik.suckani == 0 and random(100) < 4 then
pldik.suckani = random(5) + 1
pldik.suckfaze = 0
end
end,
[1] = function()
if random(1000) < 10 then
pldik.cinnost = 0
end
pldik.oci = 6
if pldik.suckani == 0 and random(100) < 4 then
pldik.suckani = random(4) + 1
pldik.suckfaze = 0
end
end,
[201] = function()
if not pldik:isTalking() then
pldik.cinnost = 0
end
pldik.oci = 1
if pldik.suckani == 0 then
pldik.suckani = 1000
pldik.suckfaze = 0
end
end,
[202] = function()
if not pldik:isTalking() then
pldik.cinnost = 0
end
pldik.oci = 0
if pldik.suckani == 0 then
pldik.suckani = 1000
pldik.suckfaze = 0
end
end,
}
pldik.afaze = pldik.oci * 2
if random(100) < 5 then
pldik.afaze = 12
end
if pldik.suckani > 0 then
if (pldik.suckfaze == 0) then
if pldik.cinnost < 200 then
pldik:talk("bar-x-suck" ..random(4), VOLUME_LOW)
end
elseif isRange(pldik.suckfaze, 1, 3) then
pldik.afaze = pldik.afaze + 1
elseif (pldik.suckfaze == 5) then
pldik.suckani = pldik.suckani - 1
end
pldik.suckfaze = math.mod(pldik.suckfaze + 1, 6)
end
pldik:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_shark()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
shark.oci = random(2)
shark.pusa = random(2)
return function()
if random(1000) < 5 then
shark.oci = 1 - shark.oci
end
if random(1000) < 5 then
shark.pusa = 1 - shark.pusa
end
shark.afaze = shark.oci + shark.pusa * 2
if shark.oci == 0 and random(100) < 3 then
shark.afaze = shark.afaze + 1
end
shark:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_pldotec()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
pldotec.vlnit = 0
pldotec.del = 0
pldotec.ocko = 0
pldotec.smer = 0
pldotec.faze = 0
pldotec.smutny = 0
return function()
switch(pldotec.dir){
[dir_no] = function()
if pldotec.vlnit == -1 then
pldotec.vlnit = 8
end
end,
[dir_down] = function()
pldotec.vlnit = -1
end,
default = function()
pldotec.vlnit = 8
end,
}
if pldotec.vlnit > 0 then
pldotec.smutny = 0
end
if pldotec.vlnit > 0 then
if pldotec.del == 0 then
if (pldotec.vlnit >= 6) and (pldotec.vlnit <= 8) then
pldotec.del = 1
elseif (pldotec.vlnit >= 3) and (pldotec.vlnit <= 5) then
pldotec.del = 2
else
pldotec.del = 3
end
if random(2) == 0 then
pldotec.afaze = math.mod(pldotec.afaze + 1, 4)
else
pldotec.afaze = math.mod(pldotec.afaze + 3, 4)
end
pldotec.vlnit = pldotec.vlnit - 1
if pldotec.vlnit == 0 then
pldotec.del = 0
end
if pldotec.vlnit == 0 then
pldotec.afaze = 0
elseif pldotec.vlnit == 1 then
pldotec.afaze = 3
end
else
pldotec.del = pldotec.del - 1
end
elseif pldotec.smutny > 0 then
if pldotec.ocko == 0 then
if random(100) < 10 then
pldotec.ocko = 3
end
end
if pldotec.ocko > 0 then
pldotec.ocko = pldotec.ocko - 1
end
if pldotec.ocko > 0 then
pldotec.afaze = 15
else
pldotec.afaze = 14
end
pldotec.smutny = pldotec.smutny - 1
else
if random(100) < 10 then
pldotec.smer = 1 - pldotec.smer
end
if (pldotec.faze == 0) then
pldotec.afaze = 0
if random(100) < 10 then
pldotec.faze = 1
end
elseif (pldotec.faze == 1) or (pldotec.faze == 4) then
pldotec.faze = pldotec.faze + 1
pldotec.afaze = 4
elseif (pldotec.faze == 5) then
pldotec.afaze = 0
pldotec.faze = 0
else
pldotec.faze = pldotec.faze + 1
pldotec.afaze = 5
end
switch(pldotec.afaze){
[0] = function()
if pldotec.smer == 1 then
pldotec.afaze = 6
end
end,
[4] = function()
if pldotec.smer == 1 then
pldotec.afaze = 7
end
end,
}
if pldotec.ocko == 0 then
if random(100) < 10 then
pldotec.ocko = 3
end
end
if pldotec.ocko > 0 then
pldotec.ocko = pldotec.ocko - 1
end
if pldotec.ocko > 0 then
if pldotec.afaze == 0 then
pldotec.afaze = 9
else
pldotec.afaze = pldotec.afaze + 6
end
end
end
pldotec:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_levahlava()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
levahlava.kouka = random(3)
levahlava.makoukat = levahlava.kouka
levahlava.cinnost = 0
return function()
if levahlava.kouka == 0 and pravahlava.kouka == 0 and levahlava.cinnost == 0 and levahlava.cinnost == 0 and levahlava.makoukat == 0 and pravahlava.makoukat == 0 and random(100) < 5 then
levahlava.cinnost = 2
pravahlava.cinnost = 2
end
if levahlava.kouka ~= levahlava.makoukat then
if levahlava.kouka == 1 or levahlava.makoukat == 1 then
levahlava.kouka = levahlava.makoukat
else
levahlava.kouka = 1
end
end
switch(levahlava.cinnost){
[0] = function()
if random(1000) < 5 then
levahlava.cinnost = 1
elseif random(100) < 5 then
levahlava.makoukat = random(3)
end
levahlava.afaze = levahlava.kouka * 2
if levahlava.afaze > 0 then
levahlava.afaze = levahlava.afaze + 1
end
if random(100) < 95 then
levahlava.afaze = levahlava.afaze + 1
end
end,
[1] = function()
levahlava.afaze = levahlava.kouka * 2
if levahlava.afaze > 0 then
levahlava.afaze = levahlava.afaze + 1
end
if random(1000) < 5 then
levahlava.cinnost = 0
end
end,
[2] = function()
levahlava.afaze = 2
if random(100) < 3 then
levahlava.cinnost = 0
pravahlava.cinnost = 0
end
end,
}
levahlava:updateAnim()
end
end
-- -------------------------------------------------------------
local function prog_init_pravahlava()
local pom1, pom2, pomb1, pomb2 = 0, 0, false, false
pravahlava.kouka = random(3)
pravahlava.makoukat = pravahlava.kouka
pravahlava.cinnost = 0
return function()
if pravahlava.kouka ~= pravahlava.makoukat then
if pravahlava.kouka == 1 or pravahlava.makoukat == 1 then
pravahlava.kouka = pravahlava.makoukat
else
pravahlava.kouka = 1
end
end
switch(pravahlava.cinnost){
[0] = function()
if random(1000) < 5 then
pravahlava.cinnost = 1
elseif random(100) < 5 then
pravahlava.makoukat = random(3)
end
pravahlava.afaze = pravahlava.kouka * 2
if pravahlava.afaze > 0 then
pravahlava.afaze = pravahlava.afaze + 1
end
if random(100) < 95 then
pravahlava.afaze = pravahlava.afaze + 1
end
end,
[1] = function()
pravahlava.afaze = pravahlava.kouka * 2
if pravahlava.afaze > 0 then
pravahlava.afaze = pravahlava.afaze + 1
end
if random(1000) < 5 then
pravahlava.cinnost = 0
end
end,
[2] = function()
pravahlava.afaze = 2
end,
}
pravahlava:updateAnim()
end
end
-- --------------------
local update_table = {}
local subinit
subinit = prog_init_room()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_barel()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_kachnicka()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_had()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_ocicko()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_kukajda()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_killer()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_hlubinna()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_krabik()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_baget()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_nozka()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_pldik()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_shark()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_pldotec()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_levahlava()
if subinit then
table.insert(update_table, subinit)
end
subinit = prog_init_pravahlava()
if subinit then
table.insert(update_table, subinit)
end
return update_table
end
local update_table = prog_init()
-- -----------------------------------------------------------------
-- Update
-- -----------------------------------------------------------------
function prog_update()
for key, subupdate in pairs(update_table) do
subupdate()
end
end
| gpl-2.0 |
gorkinovich/DefendersOfMankind | dependencies/CEGUI/cegui/src/ScriptingModules/LuaScriptModule/support/tolua++bin/lua/define.lua | 7 | 1317 | -- tolua: define class
-- Written by Waldemar Celes
-- TeCGraf/PUC-Rio
-- Jul 1998
-- $Id: define.lua 1004 2006-02-27 13:03:20Z lindquist $
-- This code is free software; you can redistribute it and/or modify it.
-- The software provided hereunder is on an "as is" basis, and
-- the author has no obligation to provide maintenance, support, updates,
-- enhancements, or modifications.
-- Define class
-- Represents a numeric const definition
-- The following filds are stored:
-- name = constant name
classDefine = {
name = '',
}
classDefine.__index = classDefine
setmetatable(classDefine,classFeature)
-- register define
function classDefine:register (pre)
if not self:check_public_access() then
return
end
pre = pre or ''
output(pre..'tolua_constant(tolua_S,"'..self.lname..'",'..self.name..');')
end
-- Print method
function classDefine:print (ident,close)
print(ident.."Define{")
print(ident.." name = '"..self.name.."',")
print(ident.." lname = '"..self.lname.."',")
print(ident.."}"..close)
end
-- Internal constructor
function _Define (t)
setmetatable(t,classDefine)
t:buildnames()
if t.name == '' then
error("#invalid define")
end
append(t)
return t
end
-- Constructor
-- Expects a string representing the constant name
function Define (n)
return _Define{
name = n
}
end
| gpl-3.0 |
snabbco/snabb | lib/luajit/testsuite/test/lang/compare.lua | 6 | 5758 | local function lt(x, y)
if x < y then return true else return false end
end
local function le(x, y)
if x <= y then return true else return false end
end
local function gt(x, y)
if x > y then return true else return false end
end
local function ge(x, y)
if x >= y then return true else return false end
end
local function eq(x, y)
if x == y then return true else return false end
end
local function ne(x, y)
if x ~= y then return true else return false end
end
local function ltx1(x)
if x < 1 then return true else return false end
end
local function lex1(x)
if x <= 1 then return true else return false end
end
local function gtx1(x)
if x > 1 then return true else return false end
end
local function gex1(x)
if x >= 1 then return true else return false end
end
local function eqx1(x)
if x == 1 then return true else return false end
end
local function nex1(x)
if x ~= 1 then return true else return false end
end
local function lt1x(x)
if 1 < x then return true else return false end
end
local function le1x(x)
if 1 <= x then return true else return false end
end
local function gt1x(x)
if 1 > x then return true else return false end
end
local function ge1x(x)
if 1 >= x then return true else return false end
end
local function eq1x(x)
if 1 == x then return true else return false end
end
local function ne1x(x)
if 1 ~= x then return true else return false end
end
local function check(a, b)
if a ~= b then
error("check failed with "..tostring(a).." ~= "..tostring(b), 2)
end
end
do --- 1,2
local x,y = 1,2
check(x<y, true)
check(x<=y, true)
check(x>y, false)
check(x>=y, false)
check(x==y, false)
check(x~=y, true)
check(1<y, true)
check(1<=y, true)
check(1>y, false)
check(1>=y, false)
check(1==y, false)
check(1~=y, true)
check(x<2, true)
check(x<=2, true)
check(x>2, false)
check(x>=2, false)
check(x==2, false)
check(x~=2, true)
check(lt(x,y), true)
check(le(x,y), true)
check(gt(x,y), false)
check(ge(x,y), false)
check(eq(y,x), false)
check(ne(y,x), true)
end
do --- 2,1
local x,y = 2,1
check(x<y, false)
check(x<=y, false)
check(x>y, true)
check(x>=y, true)
check(x==y, false)
check(x~=y, true)
check(2<y, false)
check(2<=y, false)
check(2>y, true)
check(2>=y, true)
check(2==y, false)
check(2~=y, true)
check(x<1, false)
check(x<=1, false)
check(x>1, true)
check(x>=1, true)
check(x==1, false)
check(x~=1, true)
check(lt(x,y), false)
check(le(x,y), false)
check(gt(x,y), true)
check(ge(x,y), true)
check(eq(y,x), false)
check(ne(y,x), true)
end
do --- 1,1
local x,y = 1,1
check(x<y, false)
check(x<=y, true)
check(x>y, false)
check(x>=y, true)
check(x==y, true)
check(x~=y, false)
check(1<y, false)
check(1<=y, true)
check(1>y, false)
check(1>=y, true)
check(1==y, true)
check(1~=y, false)
check(x<1, false)
check(x<=1, true)
check(x>1, false)
check(x>=1, true)
check(x==1, true)
check(x~=1, false)
check(lt(x,y), false)
check(le(x,y), true)
check(gt(x,y), false)
check(ge(x,y), true)
check(eq(y,x), true)
check(ne(y,x), false)
end
do --- 2
check(lt1x(2), true)
check(le1x(2), true)
check(gt1x(2), false)
check(ge1x(2), false)
check(eq1x(2), false)
check(ne1x(2), true)
check(ltx1(2), false)
check(lex1(2), false)
check(gtx1(2), true)
check(gex1(2), true)
check(eqx1(2), false)
check(nex1(2), true)
end
do --- 1
check(lt1x(1), false)
check(le1x(1), true)
check(gt1x(1), false)
check(ge1x(1), true)
check(eq1x(1), true)
check(ne1x(1), false)
check(ltx1(1), false)
check(lex1(1), true)
check(gtx1(1), false)
check(gex1(1), true)
check(eqx1(1), true)
check(nex1(1), false)
end
do --- 0
check(lt1x(0), false)
check(le1x(0), false)
check(gt1x(0), true)
check(ge1x(0), true)
check(eq1x(0), false)
check(ne1x(0), true)
check(ltx1(0), true)
check(lex1(0), true)
check(gtx1(0), false)
check(gex1(0), false)
check(eqx1(0), false)
check(nex1(0), true)
end
do --- pcall
assert(not pcall(function()
local a, b = 10.5, nil
return a < b
end))
end
do --- bit +bit
for i=1,100 do
assert(bit.tobit(i+0x7fffffff) < 0)
end
for i=1,100 do
assert(bit.tobit(i+0x7fffffff) <= 0)
end
end
do --- string 1 255
local a = "\255\255\255\255"
local b = "\1\1\1\1"
assert(a > b)
assert(a > b)
assert(a >= b)
assert(b <= a)
end
do --- String comparisons:
local function str_cmp(a, b, lt, gt, le, ge)
assert(a<b == lt)
assert(a>b == gt)
assert(a<=b == le)
assert(a>=b == ge)
assert((not (a<b)) == (not lt))
assert((not (a>b)) == (not gt))
assert((not (a<=b)) == (not le))
assert((not (a>=b)) == (not ge))
end
local function str_lo(a, b)
str_cmp(a, b, true, false, true, false)
end
local function str_eq(a, b)
str_cmp(a, b, false, false, true, true)
end
local function str_hi(a, b)
str_cmp(a, b, false, true, false, true)
end
str_lo("a", "b")
str_eq("a", "a")
str_hi("b", "a")
str_lo("a", "aa")
str_hi("aa", "a")
str_lo("a", "a\0")
str_hi("a\0", "a")
end
do --- obj_eq/ne
local function obj_eq(a, b)
assert(a==b == true)
assert(a~=b == false)
end
local function obj_ne(a, b)
assert(a==b == false)
assert(a~=b == true)
end
obj_eq(nil, nil)
obj_ne(nil, false)
obj_ne(nil, true)
obj_ne(false, nil)
obj_eq(false, false)
obj_ne(false, true)
obj_ne(true, nil)
obj_ne(true, false)
obj_eq(true, true)
obj_eq(1, 1)
obj_ne(1, 2)
obj_ne(2, 1)
obj_eq("a", "a")
obj_ne("a", "b")
obj_ne("a", 1)
obj_ne(1, "a")
local t, t2 = {}, {}
obj_eq(t, t)
obj_ne(t, t2)
obj_ne(t, 1)
obj_ne(t, "")
end
| apache-2.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Metalworks/npcs/Hungry_Wolf.lua | 19 | 2040 | -----------------------------------
-- Area: Metalworks
-- NPC: Hungry Wolf
-- Type: Quest Giver
-- @pos -25.861 -11 -30.172 237
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-- Updated for "Smoke on the Mountain" by EccentricAnata 03.22.13
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN) ~= QUEST_AVAILABLE and
trade:hasItemQty(4395,1) and trade:getItemCount() == 1) then
player:startEvent(0x01ad);
end
--]]
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local SmokeOnTheMountain = player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN);
if (SmokeOnTheMountain == QUEST_AVAILABLE) then
player:startEvent(0x01ac);
else
player:startEvent(0x01a5);
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 == 0x01ac) then
player:addQuest(BASTOK,SMOKE_ON_THE_MOUNTAIN);
elseif(csid == 0x01ad) then
player:tradeComplete();
player:addGil(GIL_RATE*300)
player:messageSpecial(GIL_OBTAINED,GIL_RATE*300);
player:addTitle(HOT_DOG);
if(player:getQuestStatus(BASTOK,SMOKE_ON_THE_MOUNTAIN) == QUEST_ACCEPTED) then
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,SMOKE_ON_THE_MOUNTAIN);
else
player:addFame(BASTOK,BAS_FAME*5);
end
end
end;
| gpl-3.0 |
hooksta4/darkstar | scripts/zones/Abyssea-Tahrongi/npcs/qm18.lua | 17 | 1550 | -----------------------------------
-- Zone: Abyssea-Tahrongi
-- NPC: ???
-- Spawns: Lacovie
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--[[
if (GetMobAction(16961931) == ACTION_NONE) then -- NM not already spawned from this
if (player:hasKeyItem(OVERGROWN_MANDRAGORA_FLOWER) and player:hasKeyItem(CHIPPED_SANDWORM_TOOTH)) then
player:startEvent(1020, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Ask if player wants to use KIs
else
player:startEvent(1021, OVERGROWN_MANDRAGORA_FLOWER, CHIPPED_SANDWORM_TOOTH); -- Do not ask, because player is missing at least 1.
end
end
]]
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID2: %u",csid);
-- printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 1020 and option == 1) then
SpawnMob(16961931):updateClaim(player); -- Spawn NM, Despawn after inactive for 5 minutes (pt has to reclaim within 5 of a wipe)
player:delKeyItem(OVERGROWN_MANDRAGORA_FLOWER);
player:delKeyItem(CHIPPED_SANDWORM_TOOTH);
end
end; | gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Oldton_Movalpolos/Zone.lua | 13 | 2426 | -----------------------------------
--
-- Zone: Oldton_Movalpolos (11)
--
-----------------------------------
package.loaded["scripts/zones/Oldton_Movalpolos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/conquest");
require("scripts/zones/Oldton_Movalpolos/TextIDs");
require("scripts/globals/missions");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
UpdateTreasureSpawnPoint(16822527);
SetRegionalConquestOverseers(zone:getRegionID())
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local currentday = tonumber(os.date("%j"));
local LouverancePath=player:getVar("COP_Louverance_s_Path");
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(70.956,5.99,139.843,134);
end
if(player:getCurrentMission(COP) == THREE_PATHS and (LouverancePath == 3 or LouverancePath == 4))then
cs=0x0001;
elseif(player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")==3 and player:getVar("Promathia_kill_day")~=currentday and player:getVar("COP_jabbos_story")== 0 )then
cs=0x0039;
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);
if(csid==0x0001)then
player:setVar("COP_Louverance_s_Path",5);
elseif(csid == 0x0039)then
player:setVar("COP_jabbos_story",1);
end
end;
| gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Temenos/npcs/Matter_Diffusion_Module.lua | 19 | 6043 | -----------------------------------
-- Area: temenos
-- NPC: Matter diffusion module
-- @pos
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/globals/keyitems");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
local InstanceTrade=0;
if(player:hasKeyItem(COSMOCLEANSE) and player:hasKeyItem(WHITE_CARD) )then
if(count==1 and trade:hasItemQty(2127,1))then -- Central Temenos - Basement 1
InstanceTrade=128;
elseif(count==1 and trade:hasItemQty(1906,1))then -- Central Temenos - 1st Floor
InstanceTrade=64;
elseif(count==1 and trade:hasItemQty(1905,1))then -- Central Temenos - 2st Floor
InstanceTrade=32;
elseif(count==1 and trade:hasItemQty(1904,1))then -- Central Temenos - 3st Floor
InstanceTrade=16;
elseif(count==3 and trade:hasItemQty(1986,1) and trade:hasItemQty(1908,1) and trade:hasItemQty(1907,1))then --proto-ultima
InstanceTrade=8;
end
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("error player don't have cosmo clean");
end
if(InstanceTrade~=0)then
player:setVar("Limbus_Trade_Item-T",InstanceTrade);
player:tradeComplete();
player:messageSpecial(CHIP_TRADE_T);
player:startEvent(0x7d00,0,0,0,InstanceTrade,0,0,0,0);
player:setVar("limbusbitmap",InstanceTrade);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local instancelist ={};
local limbusbitmap = 0 ;
local AllowLimbusToPlayer = true ;
local currentlimbus= TryTobackOnCurrentLimbus(player);
instancelist = TEMENOS_LIST;
printf("currentlimbus: %u",currentlimbus);
if(player:hasKeyItem(COSMOCLEANSE))then
if(player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
local LimbusTradeItem = player:getVar("Limbus_Trade_Item-T");
for nt = 1,table.getn (instancelist),2 do
-- printf("list d'instance: %u",instancelist[nt]);
if(instancelist[nt+1][1]==true and player:hasKeyItem(WHITE_CARD))then
-- print("player_have_white_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
if(instancelist[nt+1][2]==true and player:hasKeyItem(RED_CARD))then
-- print("player_have_red_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
if(instancelist[nt+1][3]==true and player:hasKeyItem(BLACK_CARD))then
-- print("player_have_black_card");
limbusbitmap = limbusbitmap + instancelist[nt+1][4];
-- printf("bitmapadd: %u",instancelist[nt+1][4]);
end
end
limbusbitmap= limbusbitmap + LimbusTradeItem;
----- /////////////////////////////////////////////on doit ajouter le mipmap pour l'item trade ici
else
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
local playerbcnmid = status:getPower();
-- check if the player has the key item for the current battlefield
for nt = 1,table.getn (instancelist),2 do
-- printf("list d'instance: %u",instancelist[nt]);
if(instancelist[nt] == playerbcnmid)then
if(instancelist[nt+1][1]== true and player:hasKeyItem(WHITE_CARD) == false)then
AllowLimbusToPlayer = false;
end
if(instancelist[nt+1][2]== true and player:hasKeyItem(RED_CARD) == false )then
AllowLimbusToPlayer = false;
end
if(instancelist[nt+1][3]== true and player:hasKeyItem(BLACK_CARD) == false )then
AllowLimbusToPlayer = false;
end
if(AllowLimbusToPlayer == true)then --player have the correct key item for the current battflield
limbusbitmap = instancelist[nt+1][4];
end
end
end
end
if(limbusbitmap~= 0 )then
player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0);
player:setVar("limbusbitmap",limbusbitmap);
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("player need a card for basic limbus");
end
elseif(currentlimbus~=0)then
for nt = 1,table.getn (instancelist),2 do
-- printf("list d'instance: %u",instancelist[nt]);
if(instancelist[nt] == currentlimbus)then
limbusbitmap = instancelist[nt+1][4];
end
end
player:startEvent(0x7d00,0,0,0,limbusbitmap,0,0,0,0);
player:setVar("limbusbitmap",limbusbitmap);
else
player:messageSpecial(CONDITION_FOR_LIMBUS_T);
print("error player don't have cosmo clean");
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
if(csid == 0x7d00)then
if(player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
ResetPlayerLimbusVariable(player);
player:setVar("characterLimbusKey",0);
else
local status = player:getStatusEffect(EFFECT_BATTLEFIELD);
player:setVar("LimbusID",status:getPower());
player:setVar("characterLimbusKey",GetLimbusKeyFromInstance(status:getPower()));
end
player:updateEvent(2,player:getVar("limbusbitmap"),0,1,1,0);
player:setVar("limbusbitmap",0);
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if(csid == 0x7d00)then
end
end; | gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Southern_San_dOria_[S]/npcs/Dilgeur.lua | 36 | 1106 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Dilgeur -- Misnamed NPC, name is Crochepallade when it should be Dilgeur, swap pos with the NPC at -46 2 -8
-- @zone 80
-- @pos 22 2 3
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x014A);
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 |
hooksta4/darkstar | scripts/globals/items/crayfish.lua | 18 | 1409 | -----------------------------------------
-- ID: 4472
-- Item: crayfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -3
-- Vitality 1
-- defense 10
-----------------------------------------
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,4472);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -3);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_DEF, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -3);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_DEF, 10);
end;
| gpl-3.0 |
hooksta4/darkstar | scripts/zones/zones/Windurst_Woods/npcs/Etsa_Rhuyuli.lua | 38 | 1415 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Etsa Rhuyuli
-- Type: Standard NPC
-- @pos 62.482 -8.499 -139.836 241
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,1) == false) then
player:startEvent(0x02de);
else
player:startEvent(0x01a6);
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 == 0x02de) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",1,true);
end
end;
| gpl-3.0 |
prosody-modules/import2 | mod_telnet_tlsinfo/mod_telnet_tlsinfo.lua | 32 | 1220 | -- mod_telnet_tlsinfo.lua
module:set_global();
module:depends("admin_telnet");
local console_env = module:shared("/*/admin_telnet/env");
local c2s_sessions = module:shared("/*/c2s/sessions");
local s2s_sessions = module:shared("/*/s2s/sessions");
local function print_tlsinfo(print, session)
if session.secure then
local sock = session.conn:socket()
for k,v in pairs(sock:info()) do
print(("%20s: %s"):format(k, tostring(v)))
end
else
print(("%20s: %s"):format("protocol", "TCP"))
end
end
function console_env.c2s:showtls(pat)
local print = self.session.print;
for _, session in pairs(c2s_sessions) do
if not pat or session.full_jid and session.full_jid:find(pat, nil, true) then
print(session.full_jid or "unauthenticated")
print_tlsinfo(print, session);
print""
end
end
end
function console_env.s2s:showtls(pat)
local print = self.session.print;
for _, session in pairs(s2s_sessions) do
if not pat or session.from_host == pat or session.to_host == pat then
if session.direction == "outgoing" then
print(session.from_host, "->", session.to_host)
else
print(session.to_host, "<-", session.from_host)
end
print_tlsinfo(print, session);
print""
end
end
end
| mit |
hooksta4/darkstar | scripts/globals/abilities/pets/ecliptic_howl.lua | 20 | 1294 | ---------------------------------------------------
-- Aerial Armor
---------------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
require("scripts/globals/utils");
---------------------------------------------------
function onAbilityCheck(player, target, ability)
return 0,0;
end;
function onPetAbility(target, pet, skill, summoner)
local bonusTime = utils.clamp(summoner:getSkillLevel(SKILL_SUM) - 300, 0, 200);
local duration = 180 + bonusTime;
local moon = VanadielMoonPhase();
local buffvalue = 0;
if moon > 90 then
buffvalue = 25;
elseif moon > 75 then
buffvalue = 21;
elseif moon > 60 then
buffvalue = 17;
elseif moon > 40 then
buffvalue = 13;
elseif moon > 25 then
buffvalue = 9;
elseif moon > 10 then
buffvalue = 5;
else
buffvalue = 1;
end
target:delStatusEffect(EFFECT_ACCURACY_BOOST);
target:delStatusEffect(EFFECT_EVASION_BOOST);
target:addStatusEffect(EFFECT_ACCURACY_BOOST,buffvalue,0,duration);
target:addStatusEffect(EFFECT_EVASION_BOOST,25-buffvalue,0,duration);
skill:setMsg(0);
return 0;
end | gpl-3.0 |
ak48disk/wowaddons | Quartz/modules/Timer.lua | 1 | 5850 | --[[
Copyright (C) 2006-2007 Nymbia
Copyright (C) 2010 Hendrik "Nevcairiel" Leppkes < h.leppkes@gmail.com >
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
]]
local Quartz3 = LibStub("AceAddon-3.0"):GetAddon("Quartz3")
local L = LibStub("AceLocale-3.0"):GetLocale("Quartz3")
local MODNAME = "Timer"
local Timer = Quartz3:NewModule(MODNAME, "AceEvent-3.0")
local Mirror = Quartz3:GetModule("Mirror")
----------------------------
-- Upvalues
local GetTime = GetTime
local unpack, pairs, ipairs, tonumber = unpack, pairs, ipairs, tonumber
local table_remove = table.remove
local external = Mirror.ExternalTimers
local thistimers = {}
local getOptions
function Timer:ChatHandler(msg)
if self:IsEnabled() then
if msg:match("^kill") then
local name = msg:match("^kill (.+)$")
if name then
external[name] = nil
for k, v in ipairs(thistimers) do
if v == name then
table_remove(thistimers, k)
break
end
end
self:SendMessage("Quartz3Mirror_UpdateCustom")
else
return Quartz3:Print(L["Usage: /quartztimer timername 60 or /quartztimer kill timername"])
end
else
local duration = tonumber(msg:match("^(%d+)"))
local name
if duration then
name = msg:match("^%d+ (.+)$")
else
duration = tonumber(msg:match("(%d+)$"))
if not duration then
return Quartz3:Print(L["Usage: /quartztimer timername 60 or /quartztimer 60 timername"])
end
name = msg:match("^(.+) %d+$")
end
if not name then
return Quartz3:Print(L["Usage: /quartztimer timername 60 or /quartztimer kill timername"])
end
local currentTime = GetTime()
external[name].startTime = currentTime
external[name].endTime = currentTime + duration
for k, v in ipairs(thistimers) do
if v == name then
table_remove(thistimers, k)
break
end
end
thistimers[#thistimers+1] = name
self:SendMessage("Quartz3Mirror_UpdateCustom")
end
end
end
function Timer:OnDisable()
for k, v in pairs(thistimers) do
external[v] = nil
thistimers[k] = nil
end
self:SendMessage("Quartz3Mirror_UpdateCustom")
end
local function chatHandler(message)
Timer:ChatHandler(message)
end
function Timer:OnInitialize()
self:SetEnabledState(Quartz3:GetModuleEnabled(MODNAME))
Quartz3:RegisterModuleOptions(MODNAME, getOptions, L["Timer"])
Quartz3:RegisterChatCommand("qt", chatHandler)
Quartz3:RegisterChatCommand("quartzt", chatHandler)
Quartz3:RegisterChatCommand("quartztimer", chatHandler)
end
do
local newname, newlength
local options
function getOptions()
if not options then
options = {
type = "group",
name = L["Timer"],
order = 600,
args = {
toggle = {
type = "toggle",
name = L["Enable"],
desc = L["Enable"],
get = function()
return Quartz3:GetModuleEnabled(MODNAME)
end,
set = function(info, v)
Quartz3:SetModuleEnabled(MODNAME, v)
end,
order = 99,
width = "full",
},
newtimername = {
type = "input",
name = L["New Timer Name"],
desc = L["Set a name for the new timer"],
get = function()
return newname or ""
end,
set = function(info, v)
newname = v
end,
order = 100,
},
newtimerlength = {
type = "input",
name = L["New Timer Length"],
desc = L["Length of the new timer, in seconds"],
get = function()
return newlength or 0
end,
set = function(info, v)
newlength = tonumber(v)
end,
usage = L["<Time in seconds>"],
order = 101,
},
makenewtimer = {
type = "execute",
name = L["Make Timer"],
desc = L["Make a new timer using the above settings. NOTE: it may be easier for you to simply use the command line to make timers, /qt"],
func = function()
local currentTime = GetTime()
external[newname].startTime = currentTime
external[newname].endTime = currentTime + newlength
for k, v in ipairs(thistimers) do
if v == newname then
table_remove(thistimers, k)
break
end
end
thistimers[#thistimers+1] = newname
Timer:SendMessage("Quartz3Mirror_UpdateCustom")
newname = nil
newlength = nil
end,
disabled = function()
return not (newname and newlength)
end,
order = -3,
},
nl = {
type = "description",
name = "",
order = -2,
},
killtimer = {
type = "select",
name = L["Stop Timer"],
desc = L["Select a timer to stop"],
get = function()
return ""
end,
set = function(info, name)
if name then
external[name] = nil
for k, v in ipairs(thistimers) do
if v == name then
table_remove(thistimers, k)
break
end
end
Timer:SendMessage("Quartz3Mirror_UpdateCustom")
end
end,
values = thistimers,
order = -1,
},
},
}
end
return options
end
end
| mit |
hooksta4/darkstar | scripts/zones/Mhaura/npcs/Kamilah.lua | 2 | 1127 | -----------------------------------
-- Area: Mhaura
-- NPC: Kamilah
-- Guild Merchant NPC: Blacksmithing Guild
-- @pos -64.302 -16.000 35.261 249
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/zones/Mhaura/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:sendGuild(532,8,23,2)) then
player:showText(npc,SMITHING_GUILD);
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 |
hooksta4/darkstar | scripts/zones/Temenos/Zone.lua | 35 | 4896 | -----------------------------------
--
-- Zone: Temenos (37)
--
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Temenos/TextIDs");
require("scripts/globals/limbus");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
SetServerVariable("[Temenos_W_Tower]UniqueID",0);
SetServerVariable("[Temenos_N_Tower]UniqueID",0);
SetServerVariable("[Temenos_E_Tower]UniqueID",0);
SetServerVariable("[C_Temenos_Base]UniqueID",0);
SetServerVariable("[C_Temenos_Base_II]UniqueID",0);
SetServerVariable("[C_Temenos_1st]UniqueID",0);
SetServerVariable("[C_Temenos_2nd]UniqueID",0);
SetServerVariable("[C_Temenos_3rd]UniqueID",0);
SetServerVariable("[C_Temenos_4th]UniqueID",0);
SetServerVariable("[C_Temenos_4th_II]UniqueID",0);
zone:registerRegion(1, 378,70,-186 ,382,72,-182); -- 'Temenos_Western_Tower' 380 71 -184
zone:registerRegion(2, 378,70,373 ,382,72,377); -- 'Temenos_Northern_Tower' 380 71 375
zone:registerRegion(3, 378,-4,93 ,382,4,98); -- 'Temenos_Eastern_Tower' 380 -2 96
zone:registerRegion(4, 578,-4,-546 ,582,4,-542); -- 'Central_Temenos_Basement' 580 -2 -544
zone:registerRegion(5, 258,-164,-506 ,262,-160,-502); -- 'Central_Temenos_1st_Floor' 260 -162 -504
zone:registerRegion(6, 18,-4,-546 ,22,4,-542); -- 'Central_Temenos_2nd_Floor' 20 -2 -544
zone:registerRegion(7, -298,-164,-502 ,-294,-160,-498); -- 'Central_Temenos_3rd_Floor' -296 -162 -500
zone:registerRegion(8, -542,-4,-586 ,-538,4,-582); -- 'Central_Temenos_4th_Floor' -540 -2 -584
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;
player:setPos(580,-1.5,4.452,192);
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
local regionID = region:GetRegionID();
switch (regionID): caseof
{
[1] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Temenos_Western_Tower
RegisterLimbusInstance(player,1298);
end
end,
[2] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Temenos_Northern_Tower
RegisterLimbusInstance(player,1299);
end
end,
[3] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Temenos_Eastern_Tower
RegisterLimbusInstance(player,1300);
end
end,
[4] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Central_Temenos_Basement
RegisterLimbusInstance(player,1301);
end
end,
[5] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Central_Temenos_1st_Floor
RegisterLimbusInstance(player,1303);
end
end,
[6] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Central_Temenos_2nd_Floor
RegisterLimbusInstance(player,1304);
end
end,
[7] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Central_Temenos_3rd_Floor
RegisterLimbusInstance(player,1305);
end
end,
[8] = function (x)
if (player:hasStatusEffect(EFFECT_BATTLEFIELD) == false) then
-- create instance Central_Temenos_4th_Floor
RegisterLimbusInstance(player,1306);
end
end,
}
end;
function onRegionLeave(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 |
gedadsbranch/Darkstar-Mission | scripts/zones/Southern_San_dOria/npcs/Ominous_Cloud.lua | 19 | 5169 | -----------------------------------
-- Area: Southern Sandoria
-- NPC: Ominous Cloud
-- Type: Traveling Merchant NPC
-- @zone: 230
-- @pos -41.550 1.999 -2.845
--
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local wijinruit = trade:getItemQty(951)
local uchitake = (trade:getItemQty(1161) / 99)
local tsurara = (trade:getItemQty(1164) / 99)
local kawahori = (trade:getItemQty(1167) / 99)
local makibishi = (trade:getItemQty(1170) / 99)
local hiraishin = (trade:getItemQty(1173) / 99)
local mizu = (trade:getItemQty(1176) / 99)
local shihei = (trade:getItemQty(1179) / 99)
local jusatsu = (trade:getItemQty(1182) / 99)
local kaginawa = (trade:getItemQty(1185) / 99)
local sairui = (trade:getItemQty(1188) / 99)
local kodoku = (trade:getItemQty(1191) / 99)
local shinobi = (trade:getItemQty(1194) / 99)
local sanjaku = (trade:getItemQty(2553) / 99)
local soushi = (trade:getItemQty(2555) / 99)
local kabenro = (trade:getItemQty(2642) / 99)
local jinko = (trade:getItemQty(2643) / 99)
local mokujin = (trade:getItemQty(2970) / 99)
local inoshi = (trade:getItemQty(2971) / 99)
local shikan = (trade:getItemQty(2972) / 99)
local chono = (trade:getItemQty(2973) / 99)
local tools = (uchitake + tsurara + kawahori + makibishi + hiraishin + mizu + shihei + jusatsu + kaginawa + sairui + kodoku + shinobi + sanjaku + soushi + kabenro + jinko + mokujin + inoshi + shikan + chono)
if(((tools * 99) + wijinruit) == trade:getItemCount()) then
if((tools == math.floor(tools)) and (tools == wijinruit) and (player:getFreeSlotsCount() >= wijinruit)) then
player:tradeComplete();
if(uchitake > 0) then
player:addItem(5308,uchitake);
player:messageSpecial(ITEM_OBTAINED,5308);
end
if(tsurara > 0) then
player:addItem(5309,tsurara);
player:messageSpecial(ITEM_OBTAINED,5309);
end
if(kawahori > 0) then
player:addItem(5310,kawahori);
player:messageSpecial(ITEM_OBTAINED,5310);
end
if(makibishi > 0) then
player:addItem(5311,makibishi);
player:messageSpecial(ITEM_OBTAINED,5311);
end
if(hiraishin > 0) then
player:addItem(5312,hiraishin);
player:messageSpecial(ITEM_OBTAINED,5312);
end
if(mizu > 0) then
player:addItem(5313,mizu);
player:messageSpecial(ITEM_OBTAINED,5313);
end
if(shihei > 0) then
player:addItem(5314,shihei);
player:messageSpecial(ITEM_OBTAINED,5314);
end
if(jusatsu > 0) then
player:addItem(5315,jusatsu);
player:messageSpecial(ITEM_OBTAINED,5315);
end
if(kaginawa > 0) then
player:addItem(5316,kaginawa);
player:messageSpecial(ITEM_OBTAINED,5316);
end
if(sairui > 0) then
player:addItem(5317,sairui);
player:messageSpecial(ITEM_OBTAINED,5317);
end
if(kodoku > 0) then
player:addItem(5318,kodoku);
player:messageSpecial(ITEM_OBTAINED,5318);
end
if(shinobi > 0) then
player:addItem(5319,shinobi);
player:messageSpecial(ITEM_OBTAINED,5319);
end
if(sanjaku > 0) then
player:addItem(5417,sanjaku);
player:messageSpecial(ITEM_OBTAINED,5417);
end
if(soushi > 0) then
player:addItem(5734,soushi);
player:messageSpecial(ITEM_OBTAINED,5734);
end
if(kabenro > 0) then
player:addItem(5863,kabenro);
player:messageSpecial(ITEM_OBTAINED,5863);
end
if(jinko > 0) then
player:addItem(5864,jinko);
player:messageSpecial(ITEM_OBTAINED,5864);
end
if(mokujin > 0) then
player:addItem(5866,mokujin);
player:messageSpecial(ITEM_OBTAINED,5866);
end
if(inoshi > 0) then
player:addItem(5867,inoshi);
player:messageSpecial(ITEM_OBTAINED,5867);
end
if(shikan > 0) then
player:addItem(5868,shikan);
player:messageSpecial(ITEM_OBTAINED,5868);
end
if(chono > 0) then
player:addItem(5869,chono);
player:messageSpecial(ITEM_OBTAINED,5869);
end
end
end
-- 951 Wijinruit
-- 1161 Uchitake 5308
-- 1164 Tsurara 5309
-- 1167 Kawahori-ogi 5310
-- 1170 Makibishi 5311
-- 1173 Hiraishin 5312
-- 1176 Mizu-deppo 5313
-- 1179 Shihei 5314
-- 1182 Jusatsu 5315
-- 1185 Kaginawa 5316
-- 1188 Sairui-ran 5317
-- 1191 Kodoku 5318
-- 1194 Shinobi-tabi 5319
-- 2553 Sanjaku-tengui 5417
-- 2555 Soshi 5734
-- 2642 Kabenro 5863
-- 2643 Jinko 5864
-- 2970 Mokujin 5866
-- 2971 Inoshishinofuda 5867
-- 2972 Shikanofuda 5868
-- 2973 Chonofuda 5869
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02f7);
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 |
mynameiscraziu/godvare | plugins/minecraft.lua | 624 | 2605 | local usage = {
"!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565",
"!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.",
}
local ltn12 = require "ltn12"
local function mineSearch(ip, port, receiver) --25565
local responseText = ""
local api = "https://api.syfaro.net/server/status"
local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true"
local http = require("socket.http")
local respbody = {}
local body, code, headers, status = http.request{
url = api..parameters,
method = "GET",
redirect = true,
sink = ltn12.sink.table(respbody)
}
local body = table.concat(respbody)
if (status == nil) then return "ERROR: status = nil" end
if code ~=200 then return "ERROR: "..code..". Status: "..status end
local jsonData = json:decode(body)
responseText = responseText..ip..":"..port.." ->\n"
if (jsonData.motd ~= nil) then
local tempMotd = ""
tempMotd = jsonData.motd:gsub('%§.', '')
if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end
end
if (jsonData.online ~= nil) then
responseText = responseText.." Online: "..tostring(jsonData.online).."\n"
end
if (jsonData.players ~= nil) then
if (jsonData.players.max ~= nil) then
responseText = responseText.." Max Players: "..jsonData.players.max.."\n"
end
if (jsonData.players.now ~= nil) then
responseText = responseText.." Players online: "..jsonData.players.now.."\n"
end
if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then
responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n"
end
end
if (jsonData.favicon ~= nil and false) then
--send_photo(receiver, jsonData.favicon) --(decode base64 and send)
end
return responseText
end
local function parseText(chat, text)
if (text == nil or text == "!mine") then
return usage
end
ip, port = string.match(text, "^!mine (.-) (.*)$")
if (ip ~= nil and port ~= nil) then
return mineSearch(ip, port, chat)
end
local ip = string.match(text, "^!mine (.*)$")
if (ip ~= nil) then
return mineSearch(ip, "25565", chat)
end
return "ERROR: no input ip?"
end
local function run(msg, matches)
local chat_id = tostring(msg.to.id)
local result = parseText(chat_id, msg.text)
return result
end
return {
description = "Searches Minecraft server and sends info",
usage = usage,
patterns = {
"^!mine (.*)$"
},
run = run
} | gpl-2.0 |
moto-timo/vlc | share/lua/playlist/canalplus.lua | 113 | 3501 | --[[
$Id: $
Copyright (c) 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
-- Probe function.
function probe()
return vlc.access == "http" and string.match( vlc.path, "www.canalplus.fr" )
end
-- Parse function.
function parse()
p = {}
--vlc.msg.dbg( vlc.path )
if string.match( vlc.path, "www.canalplus.fr/.*%?pid=.*" )
then -- This is the HTML page's URL
local _,_,pid = string.find( vlc.path, "pid(%d-)%-" )
local id, name, description, arturl
while true do
-- Try to find the video's title
local line = vlc.readline()
if not line then break end
-- vlc.msg.dbg( line )
if string.match( line, "aVideos" ) then
if string.match( line, "CONTENT_ID.*=" ) then
_,_,id = string.find( line, "\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_TITRE" ) then
_,_,arturl = string.find( line, "src=\"(.-)\"" )
_,_,name = string.find( line, "title=\"(.-)\"" )
elseif string.match( line, "CONTENT_VNC_DESCRIPTION" ) then
_,_,description = string.find( line, "\"(.-)\"" )
end
if id and string.match( line, "new Array" ) then
add_item( p, id, name, description, arturl )
id = nil
name = nil
arturl = nil
description = nil
end
end
end
if id then
add_item( p, id, name, description, arturl )
end
return p
elseif string.match( vlc.path, "embed%-video%-player" ) then
while true do
local line = vlc.readline()
if not line then break end
--vlc.msg.dbg( line )
if string.match( line, "<hi" ) then
local _,_,path = string.find( line, "%[(http.-)%]" )
return { { path = path } }
end
end
end
end
function get_url_param( url, name )
local _,_,ret = string.find( url, "[&?]"..name.."=([^&]*)" )
return ret
end
function add_item( p, id, name, description, arturl )
--[[vlc.msg.dbg( "id: " .. tostring(id) )
vlc.msg.dbg( "name: " .. tostring(name) )
vlc.msg.dbg( "arturl: " .. tostring(arturl) )
vlc.msg.dbg( "description: " .. tostring(description) )
--]]
--local path = "http://www.canalplus.fr/flash/xml/configuration/configuration-embed-video-player.php?xmlParam="..id.."-"..get_url_param(vlc.path,"pid")
local path = "http://www.canalplus.fr/flash/xml/module/embed-video-player/embed-video-player.php?video_id="..id.."&pid="..get_url_param(vlc.path,"pid")
table.insert( p, { path = path; name = name; description = description; arturl = arturl } )
end
| gpl-2.0 |
hooksta4/darkstar | scripts/zones/zones/Boneyard_Gully/mobs/Race_Runner.lua | 2 | 1425 | -----------------------------------
-- Area: Boneyard_Gully
-- Name: Race Runner
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
local path = {
-539, 0, -481,
-556, 0, -478,
-581, 0, -475,
-579, -3, -460,
-572, 2, -433,
-545, 1, -440,
-532, 0, -466
};
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
onMobRoam(mob);
end;
-----------------------------------
-- onMobRoamAction Action
-----------------------------------
function onMobRoamAction(mob)
pathfind.patrol(mob, path, PATHFLAG_REVERSE);
end;
-----------------------------------
-- onMobRoam Action
-----------------------------------
function onMobRoam(mob)
-- move to start position if not moving
if (mob:isFollowingPath() == false) then
mob:pathThrough(pathfind.first(path));
end
end;
-----------------------------------
-- onMobEngaged Action
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
end; | gpl-3.0 |
gedadsbranch/Darkstar-Mission | scripts/zones/Gusgen_Mines/npcs/_5g2.lua | 34 | 1100 | -----------------------------------
-- Area: Gusgen Mines
-- NPC: _5g2 (Door A)
-- @pos -4.001 -42.4 -25.5 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)
if (npc:getAnimation() == 9) then
player:messageSpecial(LOCK_OTHER_DEVICE)
else
return 0;
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 |
hooksta4/darkstar | scripts/zones/Windurst_Waters/TextIDs.lua | 9 | 5524 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6538; -- Come back after sorting your inventory.
ITEM_OBTAINED = 6543; -- Obtained: <<<Unknown Parameter (Type: 80) 1>>><<<Possible Special Code: 01>>><<<Possible Special Code: 05>>>
GIL_OBTAINED = 6544; -- Obtained <<<Numeric Parameter 0>>> gil.
KEYITEM_OBTAINED = 6546; -- Obtained key item: <<<Unknown Parameter (Type: 80) 1>>>
HOMEPOINT_SET = 6632; -- Home point set!
FISHING_MESSAGE_OFFSET = 7029; -- You can't fish here.
COOKING_SUPPORT = 7128; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ...
GUILD_TERMINATE_CONTRACT = 7142; -- You have terminated your trading contract with the ?Multiple Choice (Parameter 1)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild and formed a new one with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
GUILD_NEW_CONTRACT = 7150; -- You have formed a new trading contract with the ?Multiple Choice (Parameter 0)?[Fishermen's/Carpenters'/Blacksmiths'/Goldsmiths'/Weavers'/Tanners'/Boneworkers'/Alchemists'/Culinarians'] Guild.?Prompt?
NO_MORE_GP_ELIGIBLE = 7157; -- You are not eligible to receive guild points at this time.
GP_OBTAINED = 7146; -- Obtained <<<Numeric Parameter 0>>> guild points.
NOT_HAVE_ENOUGH_GP = 7163; -- You do not have enough guild points.
-- Other
NOTHING_OUT_OF_ORDINARY = 6557; -- There is nothing out of the ordinary here.
DIABOLOS_UNLOCKED = 11863; -- You are now able to summon Diabolos!
-- Conquest System
CONQUEST = 9187; -- You've earned conquest points!
-- Mission Dialogs
YOU_ACCEPT_THE_MISSION = 6717; -- You have accepted the mission.
-- Shop Texts
KOPOPO_SHOP_DIALOG = 7816; -- Cooking is as much an art as music and painting are. Can your taste buds appreciate the full value of our works of art?
CHOMOJINJAHL_SHOP_DIALOG = 7821; -- The qualities needed to be a good cook are strong arms, a sense of taste, and devotion.
ENSASA_SHOP_DIALOG = 8888; -- Welcome to my little catalyst shop, where you'll find a range of general and unusual goods!
UPIHKHACHLA_SHOP_DIALOG = 8889; -- For adventurerrrs on the go, Ensasa's Catalyst Shop is the place for all you need in generrral goods!
SHOHRUNTUHRUN_SHOP_DIALOG = 8891; -- Oh, hidey-widey! This is the Federal Magic Reservey-wervey. What can I do for you today-oway?
HIKOMUMAKIMU_SHOP_DIALOG = 8892; -- Welcome to the Federal Magic Reserve, the only place in the Federation where high-level magic is allowed to be sold.
OREZEBREZ_SHOP_DIALOG = 8893; -- Welcome to Baren-Moren's, makers of the finest headwear. Our slogan is: he smarter the hat, the smarter the head.
TAAJIJI_SHOP_DIALOG = 8895; -- May I take your order, please...
NESSRUGETOMALL_SHOP_DIALOG = 11434; -- Welcome to the Rarab Tail Hostelry.
MAQUMOLPIH_OPEN_DIALOG = 8896; -- Psst... Check out these things my suppliers in Aragoneu dug up.
MAQUMOLPIH_CLOSED_DIALOG = 8897; -- Sorrrry, but I'm waiting on my next shipment from Aragoneu, so I'm all out of things to sell you at the moment.
BAEHUFAEHU_OPEN_DIALOG = 8898; -- Can I interest you in some of Sarutabaruta's wares? Come on, have a look, and see how I fares!
BAEHUFAEHU_CLOSED_DIALOG = 8899; -- Sorry-dorry, but I'm taking a breaky-wakey! (Or, as you'll be knowing, since control of Sarutabaruta was lost, I'm out of stock, so go on, get going!)
AHYEEKIH_OPEN_DIALOG = 8900; -- Psst... Wanna buy somethin' cheap from Kolshushu?
AHYEEKIH_CLOSED_DIALOG = 8901; -- Hee-hee-hee... Can you hang on a while? I can start selling you good stuff from Kolshushu once I'm ready.
FOMINA_OPEN_DIALOG = 8902; -- Hello, adventurer! Can I interest you in something a little different--something from Elshimo?
FOMINA_CLOSED_DIALOG = 8903; -- Well, um, let me see... This should be a good spot to open shop. There are some wealthy-looking Tarutaru houses nearby. It's quiet and yet there're plenty of passers-by...
OTETE_OPEN_DIALOG = 8904; -- He-he-he... Hey! How's about... Items from Li'Telor that you can't do without? Reckon you could do, with one of these or two?
OTETE_CLOSED_DIALOG = 8905; -- Oh... Phew... My heart is so blue... Bluer than these flowers... Leave me be for a couple hours...
JOURILLE_OPEN_DIALOG = 8906; -- Greetings. Can I interest you in some of these goods from Ronfaure...?
JOURILLE_CLOSED_DIALOG = 8907; -- Greetings! I am Jourille, your friendly neighborhood traveling merchant. I would most like to sell you something from Ronfaure right now, but I regret that I am waiting on my next shipment.
PRESTAPIQ_CLOSED_DIALOG = 10629; -- Goodebyongo! Wingdorsht tooo fhar awayz fhrum mai hormtowne! Dropt arll goodhys whylle ahn trripp!
PRESTAPIQ_OPEN_DIALOG = 10630; -- Helgohelgo! Me's bhrink goodhys arll ja wayz fhrum hormtowne ovf Morvalporlis!
-- Harvest Festival
TRICK_OR_TREAT = 10136; -- Trick or treat...
THANK_YOU_TREAT = 10137; -- And now for your treat...
HERE_TAKE_THIS = 10138; -- Here, take this...
IF_YOU_WEAR_THIS = 10139; -- If you put this on and walk around, something...unexpected might happen...
THANK_YOU = 10137; -- Thank you...
-- conquest Base
CONQUEST_BASE = 0;
| gpl-3.0 |
hooksta4/darkstar | scripts/zones/RuAun_Gardens/npcs/qm1.lua | 16 | 1435 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: ??? (Genbu's Spawn)
-- Allows players to spawn the HNM Genbu with a Gem of the North and a Winterstone.
-- @pos 257 -70 517 130
-----------------------------------
package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/RuAun_Gardens/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Gem of the North and Winterstone
if (GetMobAction(17309980) == 0 and trade:hasItemQty(1424,1) and trade:hasItemQty(1425,1) and trade:getItemCount() == 2) then
player:tradeComplete();
SpawnMob(17309980,300):updateClaim(player); -- Spawn Genbu
player:showText(npc,SKY_GOD_OFFSET + 5);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(SKY_GOD_OFFSET);
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 |
gedadsbranch/Darkstar-Mission | scripts/zones/Windurst_Waters_[S]/npcs/Rakih_Lyhall.lua | 38 | 1050 | -----------------------------------
-- Area: Windurst Waters (S)
-- NPC: Rakih Lyhall
-- Type: Standard NPC
-- @zone: 94
-- @pos -48.111 -4.5 69.712
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01ad);
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 |
AnySDK/Sample_Lua | frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/SkeletonAnimation.lua | 10 | 1885 |
--------------------------------
-- @module SkeletonAnimation
-- @extend SkeletonRenderer
-- @parent_module sp
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setStartListener
-- @param self
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setTrackEventListener
-- @param self
-- @param #spTrackEntry entry
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setTrackCompleteListener
-- @param self
-- @param #spTrackEntry entry
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setTrackStartListener
-- @param self
-- @param #spTrackEntry entry
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setCompleteListener
-- @param self
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setTrackEndListener
-- @param self
-- @param #spTrackEntry entry
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setEventListener
-- @param self
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setMix
-- @param self
-- @param #string fromAnimation
-- @param #string toAnimation
-- @param #float duration
--------------------------------
--
-- @function [parent=#SkeletonAnimation] setEndListener
-- @param self
-- @param #function listener
--------------------------------
--
-- @function [parent=#SkeletonAnimation] clearTracks
-- @param self
--------------------------------
--
-- @function [parent=#SkeletonAnimation] clearTrack
-- @param self
return nil
| mit |
hooksta4/darkstar | scripts/zones/Southern_San_dOria/npcs/Paouala.lua | 2 | 2102 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Paouala
-- Starts and Finishes Quest: Sleepless Nights
-- @zone 230
-- @pos 158 -6 17
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(SANDORIA,SLEEPLESS_NIGHTS) == QUEST_ACCEPTED) then
if (trade:hasItemQty(4527,1) and trade:getItemCount() == 1) then
player:startEvent(0x0054);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
sleeplessNights = player:getQuestStatus(SANDORIA,SLEEPLESS_NIGHTS);
if (player:getFameLevel(SANDORIA) >= 2 and sleeplessNights == QUEST_AVAILABLE) then
player:startEvent(0x0055);
elseif (sleeplessNights == QUEST_ACCEPTED) then
player:startEvent(0x0053);
elseif (sleeplessNights == QUEST_COMPLETED) then
player:startEvent(0x0051);
else
player:startEvent(0x0052);
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 == 0x0055 and option == 1) then
player:addQuest(SANDORIA,SLEEPLESS_NIGHTS);
elseif (csid == 0x0054) then
player:tradeComplete();
player:addTitle(SHEEPS_MILK_DELIVERER);
player:addGil(GIL_RATE*5000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*5000);
player:addFame(SANDORIA,SAN_FAME*30);
player:completeQuest(SANDORIA,SLEEPLESS_NIGHTS);
end
end;
| gpl-3.0 |
jpuigcerver/Laia | laia/util/io.lua | 1 | 4153 | require 'laia.util.types'
tds = require 'tds'
-- read symbols_table file. this file contains
-- two columns: "symbol id"
function laia.read_symbols_table(filename, sym2int, int2sym, subtract)
local num_symbols = 0
sym2int = sym2int or {} -- If sym2int table is given, update it
int2sym = int2sym or {} -- If int2sym table is given, update it
subtract = subtract or true
local f = io.open(filename, 'r')
assert(f ~= nil, ('Unable to read symbols table: %q'):format(filename))
local ln = 0 -- Line number
while true do
local line = f:read('*line')
if line == nil then break end
ln = ln + 1
local sym, id = string.match(line, '^(%S+)%s+(%d+)$')
assert(sym ~= nil and id ~= nil,
('Expected a string and an integer separated by a space at ' ..
'line %d in file %q'):format(ln, filename))
int = tonumber(id)
num_symbols = int > num_symbols and int or num_symbols
if subtract then int = int - 1 end
sym2int[sym] = int
table.insert(int2sym, int, sym)
end
f:close()
return num_symbols, sym2int, int2sym
end
function laia.check_contiguous_int2sym(int2sym)
local ei = 0 -- Expected integer ID
for i,_ in ipairs(int2sym) do
ei = ei + 1
if i ~= ei then return false end
end
return true
end
function laia.read_transcripts_table(filename, sym2int, transcripts, sym_count)
local num_transcripts = 0
transcripts = transcripts or {} -- If transcripts table is given, update it
--transcripts = transcripts or tds.Hash() -- If transcripts table is given, update it
sym_count = sym_count or {} -- If counts table is given, update it
for key,val in pairs(sym2int) do
if sym_count[val] == nil then
sym_count[val] = 0
end
end
local f = io.open(filename, 'r')
assert(f ~= nil, ('Unable to read transcripts table: %q'):format(filename))
local ln = 0
while true do
local line = f:read('*line')
if line == nil then break end
ln = ln + 1
local id, txt = string.match(line, '^(%S+)%s+(%S.*)$')
assert(id ~= nil and txt ~= nil,
('Wrong transcript format at line %d in file %q')
:format(ln, filename))
transcripts[id] = {}
--transcripts[id] = tds.Vec()
num_transcripts = num_transcripts + 1
for sym in txt:gmatch('%S+') do
if sym2int ~= nil then
assert(sym2int[sym] ~= nil,
('Symbol %q is not in the symbols table'):format(sym))
table.insert(transcripts[id], sym2int[sym])
--transcripts[id]:insert(sym2int[sym])
local isym = sym2int[sym]
sym_count[isym] = sym_count[isym] + 1
else
assert(laia.isint(sym),
('Token %q is not an integer and no symbols table was given.')
:format(sym))
table.insert(transcripts[id], sym)
--transcripts[id]:insert(sym)
end
end
end
f:close()
return num_transcripts, transcripts, sym_count
end
-- Load sample files and IDs from list. The IDs are the basenames of the files,
-- i.e., removing directory and extension.
function laia.read_files_list(filename, transcripts, file_list, sample_list)
local num_samples = 0
--file_list = file_list or {} -- If file_list table is given, update it
--sample_list = sample_list or {} -- If sample_list table is given, update it
file_list = file_list or tds.Vec() -- If file_list table is given, update it
sample_list = sample_list or tds.Vec() -- If sample_list table is given, update it
local f = io.open(filename, 'r')
assert(f ~= nil, ('Unable to read image list file: %q'):format(filename))
local ln = 0
while true do
local line = f:read('*line')
if line == nil then break end
ln = ln + 1
local id = string.match(string.gsub(line, ".*/", ""), '^(.+)[.][^./]+$')
assert(id ~= nil, ('Unable to determine sample ID at line %d in file %q')
:format(ln, filename))
assert(transcripts == nil or transcripts[id] ~= nil,
('No transcription was found for sample ID %q'):format(id))
--table.insert(file_list, line)
--table.insert(sample_list, id)
file_list:insert(line)
sample_list:insert(id)
num_samples = num_samples + 1
end
f:close()
return num_samples, file_list, sample_list
end
| mit |
hooksta4/darkstar | scripts/zones/zones/Windurst_Waters/npcs/Kerutoto.lua | 2 | 11336 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Kerutoto
-- Starts Quest Food For Thought
-- Involved in Quest: Riding on the Clouds
-- @zone 238
-- @pos 13 -5 -157
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
if (player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES) == QUEST_ACCEPTED) then
if (trade:hasItemQty(12521,1) and count == 1) then
player:startEvent(0x016a);
elseif (trade:hasItemQty(13569,1) and count == 1) then
if (player:getVar("BlueRibbonBluesProg") == 4) then
player:startEvent(0x016d); -- Lost, ribbon but it came back
else
player:startEvent(0x0166,3600);
end
end
end
if (player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT) == QUEST_ACCEPTED and trade:hasItemQty(4371,1) and count == 1) then
player:startEvent(0x014c,440);
player:setVar("Kerutoto_Food_var",2);
end
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 3) then
if (trade:hasItemQty(1127,1) and count == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local KerutotoFood = player:getVar("Kerutoto_Food_var"); -- Variable to track progress of Kerutoto in Food for Thought
local FoodForThought = player:getQuestStatus(WINDURST,FOOD_FOR_THOUGHT);
local OhbiruFood = player:getVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought
local BlueRibbonBlues = player:getQuestStatus(WINDURST,BLUE_RIBBON_BLUES);
local needZone = player:needToZone();
local realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day
local waking_dreams = player:getQuestStatus(WINDURST,WAKING_DREAMS)
-- Awakening of the Gods --
if (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 0) then
player:startEvent(0x02E1);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 1) then
player:startEvent(0x02E0);
elseif (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 2) then
player:startEvent(0x02E2);
-- Three Paths --
elseif (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Ulmia_s_Path") == 3) then
player:startEvent(0x036c);
-- Waking Dreams --
elseif (player:hasKeyItem(VIAL_OF_DREAM_INCENSE)==false and ((player:hasCompletedMission(COP,DARKNESS_NAMED) and waking_dreams == QUEST_AVAILABLE ) or(waking_dreams == QUEST_COMPLETED and realday ~= player:getVar("Darkness_Named_date")))) then
player:addQuest(WINDURST,WAKING_DREAMS);
player:startEvent(0x0396);--918
elseif (player:hasKeyItem(WHISPER_OF_DREAMS)==true) then
local availRewards = 0
if (player:hasItem(17599)) then availRewards = availRewards + 1; end -- Diabolos's Pole
if (player:hasItem(14814)) then availRewards = availRewards + 2; end -- Diabolos's Earring
if (player:hasItem(15557)) then availRewards = availRewards + 4; end -- Diabolos's Ring
if (player:hasItem(15516)) then availRewards = availRewards + 8; end -- Diabolos's Torque
if (player:hasSpell(304)) then availRewards = availRewards + 32; -- Pact
else availRewards = availRewards + 16 -- Gil
end
player:startEvent(0x0398,17599,14814,15557,15516,0,0,0,availRewards);
-- Blue Ribbon Blues --
elseif (BlueRibbonBlues == QUEST_COMPLETED and needZone) then
player:startEvent(0x016b);--363
elseif (BlueRibbonBlues == QUEST_ACCEPTED) then
local blueRibbonProg = player:getVar("BlueRibbonBluesProg");
if (player:hasItem(12521)) then
player:startEvent(0x016a);--362
elseif (blueRibbonProg == 2 and needZone == false) then
local timerDay = player:getVar("BlueRibbonBluesTimer_Day");
local currentDay = VanadielDayOfTheYear();
if (player:getVar("BlueRibbonBluesTimer_Year") < VanadielYear()) then
player:startEvent(0x0168); -- go to the grave 360
elseif (timerDay + 1 == VanadielDayOfTheYear() and player:getVar("BlueRibbonBluesTimer_Hour") <= VanadielHour()) then
player:startEvent(0x0168); -- go to the grave 360
elseif (timerDay + 2 <= VanadielDayOfTheYear()) then
player:startEvent(0x0168); -- go to the grave 360
else
player:startEvent(0x0167); -- Thanks for the ribbon 359
end
elseif (blueRibbonProg == 3) then
if (player:hasItem(13569)) then
player:startEvent(0x0169,0,13569); -- remidner, go to the grave
else
player:startEvent(0x016e,0,13569); -- lost the ribbon
end
elseif (blueRibbonProg == 4) then
player:startEvent(0x016e,0,13569);
else
player:startEvent(0x0132); -- Standard Conversation
end
elseif (BlueRibbonBlues == QUEST_AVAILABLE and player:getQuestStatus(WINDURST,WATER_WAY_TO_GO) == QUEST_COMPLETED and player:getFameLevel(WINDURST) >= 5) then
player:startEvent(0x0165);
-- Food for Thought --
elseif (FoodForThought == QUEST_AVAILABLE) then
if (OhbiruFood == 1 and KerutotoFood ~= 256) then -- Player knows the researchers are hungry and quest not refused
player:startEvent(0x0139,0,4371); -- Offered Quest 1 (Including Order ifYES)
elseif (OhbiruFood == 1 and KerutotoFood == 256) then -- Player knows the researchers are hungry and quest refused previously
player:startEvent(0x013a,0,4371); -- Offered Quest 2 (Including Order ifYES)
else
player:startEvent(0x0138); -- Before Quest: Asks you to check on others.
end
elseif (FoodForThought == QUEST_ACCEPTED) then
if (KerutotoFood == 1) then
player:startEvent(0x013b,0,4371); -- Repeats Order
elseif (KerutotoFood == 3) then
player:startEvent(0x014d); -- Reminder to check with the others if this NPC has already been fed
end
elseif (FoodForThought == QUEST_COMPLETED and needZone) then
player:startEvent(0x0130); -- NPC is sleeping but feels full (post Food for Thought)
else
player:startEvent(0x0132); -- Standard Conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x036c) then
player:setVar("COP_Ulmia_s_Path",4);
elseif ((csid == 0x0139 and option == 0) or (csid == 0x013a and option == 0)) then
player:addQuest(WINDURST,FOOD_FOR_THOUGHT);
player:setVar("Kerutoto_Food_var",1);
elseif (csid == 0x0139 and option == 1) then
player:setVar("Kerutoto_Food_var",256);
elseif (csid == 0x014c) then
if (player:getVar("Kerutoto_Food_var") == 2 and player:getVar("Kenapa_Food_var") == 4 and player:getVar("Ohbiru_Food_var") == 3) then -- If this is the last NPC to be fed
player:addGil(GIL_RATE*440);
player:tradeComplete();
player:addTitle(FAST_FOOD_DELIVERER);
player:addFame(WINDURST,WIN_FAME*100);
player:needToZone(true);
player:completeQuest(WINDURST,FOOD_FOR_THOUGHT);
player:setVar("Kerutoto_Food_var",0); -- ------------------------------------------
player:setVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest
player:setVar("Ohbiru_Food_var",0); -- ------------------------------------------
else
player:tradeComplete();
player:addGil(GIL_RATE*440);
player:setVar("Kerutoto_Food_var",3); -- If this is NOT the last NPC given food, flag this NPC as completed.
end
elseif (csid == 0x0165) then
player:addQuest(WINDURST,BLUE_RIBBON_BLUES);
elseif (csid == 0x0166 or csid == 0x016d) then
player:tradeComplete();
player:setVar("BlueRibbonBluesProg",2);
player:setVar("BlueRibbonBluesTimer_Hour",VanadielHour());
player:setVar("BlueRibbonBluesTimer_Year",VanadielYear());
player:setVar("BlueRibbonBluesTimer_Day",VanadielDayOfTheYear());
player:needToZone(true);
if (csid == 0x0166) then
player:addGil(GIL_RATE*3600);
end
elseif (csid == 0x0168) then
if (player:getFreeSlotsCount() >= 1) then
player:setVar("BlueRibbonBluesProg",3);
player:setVar("BlueRibbonBluesTimer_Hour",0);
player:setVar("BlueRibbonBluesTimer_Year",0);
player:setVar("BlueRibbonBluesTimer_Day",0);
player:addItem(13569);
player:messageSpecial(ITEM_OBTAINED,13569);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13569);
end
elseif (csid == 0x016a) then
player:completeQuest(WINDURST,BLUE_RIBBON_BLUES);
player:setVar("BlueRibbonBluesProg",0);
player:addFame(WINDURST,WIN_FAME*140);
player:addTitle(GHOSTIE_BUSTER);
player:needToZone(true);
elseif (csid == 0x0396) then --diablos start
player:addKeyItem(VIAL_OF_DREAM_INCENSE);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_DREAM_INCENSE);
elseif (csid == 0x0398) then --diablos reward
local item = 0;
local addspell = 0;
if (option == 1 and player:hasItem(17599)==false) then item = 17599;--diaboloss-pole
elseif (option == 2 and player:hasItem(14814)==false) then item = 14814;--diaboloss-earring
elseif (option == 3 and player:hasItem(15557)==false) then item = 15557;--diaboloss-ring
elseif (option == 4 and player:hasItem(15516)==false) then item = 15516;--diaboloss-torque
elseif (option == 5) then
player:addGil(GIL_RATE*15000);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*15000); -- Gil
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
elseif (option == 6 and player:hasSpell(304)==false) then
player:addSpell(304); -- diabolos Spell
player:messageSpecial(DIABOLOS_UNLOCKED,0,0,0);
addspell=1;
end
if (addspell==1) then
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
elseif (item > 0 and player:getFreeSlotsCount()~=0) then
player:delKeyItem(WHISPER_OF_DREAMS);
player:setVar("Darkness_Named_date", os.date("%j")); -- %M for next minute, %j for next day
player:completeQuest(WINDURST,WAKING_DREAMS);
player:addItem(item);
player:messageSpecial(ITEM_OBTAINED,item); -- Item
elseif ( option ~= 5 and (( item == 0 and addspell==0 ) or (item > 0 and player:getFreeSlotsCount()==0) ) ) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item);
end
elseif (csid == 0x02E0) then
player:setVar("MissionStatus",2);
end
end; | gpl-3.0 |
ASTPP/trunk | freeswitch/scripts/astpp/astpp.lua | 1 | 2518 | -------------------------------------------------------------------------------------
-- ASTPP - Open Source VoIP Billing Solution
--
-- Copyright (C) 2016 iNextrix Technologies Pvt. Ltd.
-- Samir Doshi <samir.doshi@inextrix.com>
-- ASTPP Version 3.0 and above
-- License https://www.gnu.org/licenses/agpl-3.0.html
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU Affero General Public License as
-- published by the Free Software Foundation, either version 3 of the
-- License, or (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU Affero General Public License for more details.
--
-- You should have received a copy of the GNU Affero General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--------------------------------------------------------------------------------------
-- Define script path
local script_path = "/usr/local/freeswitch/scripts/astpp/";
-- Load config file
dofile("/var/lib/astpp/astpp.lua");
-- Load CONSTANT file
dofile("/usr/local/freeswitch/scripts/astpp/constant.lua");
-- Load json file to decode json string
JSON = (loadfile (script_path .."lib/JSON.lua"))();
-- Load utility file
dofile(script_path.."lib/astpp.utility.lua");
-- Include Logger file to print messages
dofile(script_path.."lib/astpp.logger.lua");
-- Include database connection file to connect database
dofile(script_path.."lib/astpp.db.lua");
-- Call database connection
db_connect()
-- Include common functions file
dofile(script_path.."lib/astpp.functions.lua");
config = load_conf()
-- Include file to build xml for fs
dofile(script_path.."scripts/astpp.xml.lua");
-- Include custom file to load custom function
dofile(script_path.."lib/astpp.custom.lua");
if (not params) then
params = {}
function params:getHeader(name)
self.name = name;
end
function params:serialize(name)
self.name = name;
end
end
if (config['debug']==2) then
-- print all params
if (params:serialize() ~= nil) then
Logger.notice ("[xml_handler] Params:\n" .. params:serialize())
end
for param_key,param_value in pairs(XML_REQUEST) do --pseudocode
Logger.info ("[xml_REQUEST] "..param_key..": " .. param_value)
end
end
dofile(script_path.."scripts/astpp."..XML_REQUEST["section"]..".lua")
| gpl-2.0 |
moto-timo/vlc | share/lua/playlist/metachannels.lua | 92 | 2096 | --[[
$Id$
Copyright © 2010 VideoLAN and AUTHORS
Authors: Rémi Duraffort <ivoire at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
require "simplexml"
function probe()
return vlc.access == 'http' and string.match( vlc.path, 'metachannels.com' )
end
function parse()
local webpage = ''
while true do
local line = vlc.readline()
if line == nil then break end
webpage = webpage .. line
end
local feed = simplexml.parse_string( webpage )
local channel = feed.children[1]
-- list all children that are items
local tracks = {}
for _,item in ipairs( channel.children ) do
if( item.name == 'item' ) then
simplexml.add_name_maps( item )
local url = vlc.strings.resolve_xml_special_chars( item.children_map['link'][1].children[1] )
local title = vlc.strings.resolve_xml_special_chars( item.children_map['title'][1].children[1] )
local arturl = nil
if item.children_map['media:thumbnail'] then
arturl = vlc.strings.resolve_xml_special_chars( item.children_map['media:thumbnail'][1].attributes['url'] )
end
table.insert( tracks, { path = url,
title = title,
arturl = arturl,
options = {':play-and-pause'} } )
end
end
return tracks
end
| gpl-2.0 |
PrashntS/dotfiles | etc/hammerspoon/Spoons/RoundedCorners.spoon/init.lua | 1 | 4129 | --- === RoundedCorners ===
---
--- Give your screens rounded corners
---
--- Download: [https://github.com/Hammerspoon/Spoons/raw/master/Spoons/RoundedCorners.spoon.zip](https://github.com/Hammerspoon/Spoons/raw/master/Spoons/RoundedCorners.spoon.zip)
local obj = {}
obj.__index = obj
-- Metadata
obj.name = "RoundedCorners"
obj.version = "1.0"
obj.author = "Chris Jones <cmsj@tenshu.net>"
obj.homepage = "https://github.com/Hammerspoon/Spoons"
obj.license = "MIT - https://opensource.org/licenses/MIT"
obj.corners = {}
obj.screenWatcher = nil
--- RoundedCorners.allScreens
--- Variable
--- Controls whether corners are drawn on all screens or just the primary screen. Defaults to true
obj.allScreens = true
--- RoundedCorners.radius
--- Variable
--- Controls the radius of the rounded corners, in points. Defaults to 6
obj.radius = 6
--- RoundedCorners.level
--- Variable
--- Controls which level of the screens the corners are drawn at. See `hs.canvas.windowLevels` for more information. Defaults to `screenSaver + 1`
obj.level = hs.canvas.windowLevels["cursor"]
-- 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()
function obj:init()
self.screenWatcher = hs.screen.watcher.new(function() self:screensChanged() end)
self.spaceWatcher = hs.spaces.watcher.new(function() self:screensChanged() end)
end
--- RoundedCorners:start()
--- Method
--- Starts RoundedCorners
---
--- Parameters:
--- * None
---
--- Returns:
--- * The RoundedCorners object
---
--- Notes:
--- * This will draw the rounded screen corners and start watching for changes in screen sizes/layouts, reacting accordingly
function obj:start()
self.screenWatcher:start()
self.spaceWatcher:start()
self:render()
return self
end
--- RoundedCorners:stop()
--- Method
--- Stops RoundedCorners
---
--- Parameters:
--- * None
---
--- Returns:
--- * The RoundedCorners object
---
--- Notes:
--- * This will remove all rounded screen corners and stop watching for changes in screen sizes/layouts
function obj:stop()
self.screenWatcher:stop()
self.spaceWatcher:stop()
self:deleteAllCorners()
return self
end
-- Delete all the corners
function obj:deleteAllCorners()
hs.fnutils.each(self.corners, function(corner) corner:delete(0.4) end)
self.corners = {}
end
-- React to the screens having changed
function obj:screensChanged()
self:deleteAllCorners()
self:render()
end
-- Get the screens to draw on, given the user's settings
function obj:getScreens()
if self.allScreens then
return hs.screen.allScreens()
else
return {hs.screen.primaryScreen()}
end
end
-- Draw the corners
function obj:render()
local screens = self:getScreens()
local radius = self.radius
hs.fnutils.each(screens, function(screen)
local screenFrame = screen:fullFrame()
local cornerData = {
{ frame={x=screenFrame.x, y=screenFrame.y}, center={x=radius,y=radius} },
{ frame={x=screenFrame.x + screenFrame.w - radius, y=screenFrame.y}, center={x=0,y=radius} },
{ frame={x=screenFrame.x, y=screenFrame.y + screenFrame.h - radius}, center={x=radius,y=0} },
{ frame={x=screenFrame.x + screenFrame.w - radius, y=screenFrame.y + screenFrame.h - radius}, center={x=0,y=0} },
}
for _,data in pairs(cornerData) do
self.corners[#self.corners+1] = hs.canvas.new({x=data.frame.x, y=data.frame.y, w=radius, h=radius})
:appendElements(
{ action="build", type="rectangle", },
{ action="clip", type="circle", center=data.center, radius=radius, reversePath=true, },
{ action="fill", type="rectangle", frame={x=0, y=0, w=radius, h=radius, }, fillColor={ alpha=1, }},
{ type="resetClip", })
:behavior(hs.canvas.windowBehaviors.stationary)
:level(self.level)
:show(0.4)
end
end)
end
return obj
| mit |
hooksta4/darkstar | scripts/globals/abilities/chakra.lua | 18 | 1872 | -----------------------------------
-- Ability: Chakra
-- Cures certain status effects and restores a small amount of HP to user.
-- Obtained: Monk Level 35
-- Recast Time: 5:00
-- Duration: Instant
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onAbilityCheck
-----------------------------------
function onAbilityCheck(player,target,ability)
return 0,0;
end;
-----------------------------------
-- onUseAbility
-----------------------------------
function onUseAbility(player,target,ability)
local hp = player:getHP();
local vit = player:getStat(MOD_VIT);
local multi = 2;
local merits = player:getMerit(MERIT_INVIGORATE);
local body = player:getEquipID(SLOT_BODY);
local hand = player:getEquipID(SLOT_HANDS);
if (player:hasStatusEffect(EFFECT_POISON)) then
player:delStatusEffect(EFFECT_POISON);
end
if (player:hasStatusEffect(EFFECT_BLINDNESS)) then
player:delStatusEffect(EFFECT_BLINDNESS);
end
if ((body == 12639) or (body == 14474)) then -- Temple Cyclas (+1) equipped
if (player:hasStatusEffect(EFFECT_PARALYSIS)) then
player:delStatusEffect(EFFECT_PARALYSIS);
end
multi = multi + 1;
end
if ((hand == 15103) or (hand == 14910)) then -- Melee Gloves (+1) equipped
if (player:hasStatusEffect(EFFECT_DISEASE)) then
player:delStatusEffect(EFFECT_DISEASE);
end
multi = multi + 0.6;
end
local recover = (multi * vit);
player:setHP((hp + recover));
if (merits >= 1) then
if (player:hasStatusEffect(EFFECT_REGEN)) then
player:delStatusEffect(EFFECT_REGEN);
end
player:addStatusEffect(EFFECT_REGEN,10,0,merits,0,0,1);
end
return recover;
end; | gpl-3.0 |
FishFilletsNG/fillets-data | script/ending/demo_dialogs_nl.lua | 1 | 1358 |
dialogId("dlg-x-poster1", "font_poster", "Good morning, fish!")
dialogStr("Goede morgen, vissen!")
dialogId("dlg-x-poster2", "font_poster", "Again, you didn’t disappoint us. General Committee decided to decorate you with the highest orders. They are made of milk chocolate. Due to confidentiality, eat them immediately.")
dialogStr("Jullie hebben ons weer niet teleurgesteld. De Commissie heeft besloten jullie met de hoogste eer te bekleden. Die bestaat uit melkchocolade. Gezien de noodzaak voor geheimhouding moeten jullie het gelijk opeten.")
dialogId("dlg-x-boss", "font_poster", "BOSS")
dialogStr("BAAS")
dialogId("dlg-x-poster3", "font_poster", "PS: I understand this little pld issue, but next time please tell me in advance, so that we can provide an adoption permission.")
dialogStr("PS: Ik heb begrip voor het gedoe met het kleine roze monstertje, maar vertel het volgende keer wat eerder, zodat we de adoptiepapieren op tijd klaar hebben.")
dialogId("dlg-x-poster4", "font_poster", "PPS: Tell me, where did you find such a good player that he managed it all? I wish he won the computer or at least some of the other prizes.")
dialogStr("PPS: Vertel eens, waar heb je zo'n goeie speler vandaan gehaald die alles heeft weten op te lossen? Ik wou dat hij of zij de computer had gewonnen, of in ieder geval één van de andere prijzen.")
| gpl-2.0 |
hooksta4/darkstar | scripts/globals/spells/dia_ii.lua | 18 | 2295 | -----------------------------------------
-- Spell: Dia II
-- Lowers an enemy's defense and gradually deals light elemental damage.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 4;
local dmg = calculateMagicDamage(basedmg,3,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false);
-- Softcaps at 8, should always do at least 1
dmg = utils.clamp(dmg, 1, 8);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
--add in final adjustments including the actual damage dealt
local final = finalMagicAdjustments(caster,target,spell,dmg);
-- Calculate duration.
local duration = 120;
local dotBonus = 0;
if (caster:hasStatusEffect(EFFECT_SABOTEUR)) then
duration = duration * 2;
end
caster:delStatusEffect(EFFECT_SABOTEUR);
dotBonus = dotBonus+caster:getMod(MOD_DIA_DOT); -- Dia Wand
-- Check for Bio.
local bio = target:getStatusEffect(EFFECT_BIO);
-- Do it!
if (bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 2) or (DIA_OVERWRITE == 1 and bio:getPower() < 2)) then
target:addStatusEffect(EFFECT_DIA,2+dotBonus,3,duration,FLAG_ERASABLE, 10);
spell:setMsg(2);
else
spell:setMsg(75);
end
-- Try to kill same tier Bio
if (BIO_OVERWRITE == 1 and bio ~= nil) then
if (bio:getPower() <= 2) then
target:delStatusEffect(EFFECT_BIO);
end
end
return final;
end; | gpl-3.0 |
effil/effil | tests/lua/gc.lua | 2 | 2263 | require "bootstrap-tests"
local gc = effil.gc
test.gc.tear_down = default_tear_down
test.gc.cleanup = function ()
collectgarbage()
gc.collect()
test.equal(gc.count(), 1)
for i = 0, 10000 do
local tmp = effil.table()
end
collectgarbage()
gc.collect()
test.equal(gc.count(), 1)
end
test.gc.disable = function ()
local nobjects = 10000
collectgarbage()
gc.collect()
test.equal(gc.count(), 1)
gc.pause()
test.is_false(gc.enabled())
for i = 1, nobjects do
local tmp = effil.table()
end
test.equal(gc.count(), nobjects + 1)
collectgarbage()
gc.collect()
test.equal(gc.count(), 1)
gc.resume()
end
test.gc.store_same_value = function()
local fill = function (c)
local a = effil.table {}
c:push(a)
c:push(a)
end
local c = effil.channel()
fill(c)
c:pop()
collectgarbage()
effil.gc.collect()
c:pop()[1] = 0
end
local function create_fabric()
local f = { data = {} }
function f:create(num)
for i = 1, num do
table.insert(self.data, effil.table())
end
end
function f:remove(num)
for i = 1, num do
table.remove(self.data, 1)
end
end
return f
end
test.gc.check_iterative = function()
test.equal(gc.count(), 1)
local fabric = create_fabric()
test.equal(2, effil.gc.step())
fabric:create(199)
test.equal(gc.count(), 200)
fabric:remove(50)
collectgarbage()
test.equal(gc.count(), 200)
fabric:create(1) -- trigger GC
test.equal(gc.count(), 151)
fabric:remove(150)
fabric:create(149)
test.equal(gc.count(), 300)
collectgarbage()
fabric:create(1) -- trigger GC
test.equal(gc.count(), 151)
end
test.gc.check_step = function()
local fabric = create_fabric()
effil.gc.step(3)
fabric:create(299)
fabric:remove(100)
test.equal(gc.count(), 300)
collectgarbage()
fabric:create(1) -- trigger GC
test.equal(gc.count(), 201)
test.equal(3, effil.gc.step(2.5))
fabric:create(299)
fabric:remove(250)
test.equal(gc.count(), 500)
collectgarbage()
fabric:create(1) -- trigger GC
test.equal(gc.count(), 251)
end
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.