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 |
|---|---|---|---|---|---|
Fenix-XI/Fenix | scripts/globals/items/silver_shark.lua | 18 | 1319 | -----------------------------------------
-- ID: 4451
-- Item: silver_shark
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 4
-- Mind -6
-----------------------------------------
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,4451);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -6);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -6);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Jugner_Forest/npcs/Takamoto_IM.lua | 13 | 3315 | -----------------------------------
-- Area: Jugner Forest
-- NPC: Takamoto, I.M.
-- Outpost Conquest Guards
-- @pos 60.087 -0.602 -11.847 104
-----------------------------------
package.loaded["scripts/zones/Jugner_Forest/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Jugner_Forest/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = NORVALLEN;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Alzadaal_Undersea_Ruins/npcs/_20d.lua | 11 | 1240 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- Door: Gilded Doors (South)
-- !pos 180 0 -39 62 72
-----------------------------------
require("scripts/globals/keyitems")
local ID = require("scripts/zones/Alzadaal_Undersea_Ruins/IDs")
-----------------------------------
function onTrigger(player, npc)
if player:hasKeyItem(dsp.keyItem.NYZUL_ISLE_ASSAULT_ORDERS) then
player:messageSpecial(ID.text.CANNOT_LEAVE, dsp.keyItem.NYZUL_ISLE_ASSAULT_ORDERS)
elseif player:getZPos() >= -39.1 and player:getZPos() <= -37 then
player:messageSpecial(ID.text.STAGING_POINT_NYZUL)
player:messageSpecial(ID.text.IMPERIAL_CONTROL)
player:startEvent(115)
elseif player:getZPos() >= -42 and player:getZPos() <= -40 then
player:messageSpecial(ID.text.STAGING_POINT_NYZUL)
player:messageSpecial(ID.text.IMPERIAL_CONTROL)
player:startEvent(114)
else
player:messageSpecial(ID.text.MOVE_CLOSER)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
--[[ if csid == 114 and option == 0 then
Todo add function that when entering staging point that a player looses all agro on mobs
end]]
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Temenos/mobs/Cryptonberry_Skulker.lua | 7 | 1127 | -----------------------------------
-- Area: Temenos N T
-- NPC: Cryptonberry_Skulker
-----------------------------------
package.loaded["scripts/zones/Temenos/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Temenos/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer,ally)
if (IsMobDead(16928816)==true and IsMobDead(16928817)==true ) then
GetNPCByID(16928768+38):setPos(-412,-78,426);
GetNPCByID(16928768+38):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+172):setPos(-415,-78,427);
GetNPCByID(16928768+172):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+214):setPos(-412,-78,422);
GetNPCByID(16928768+214):setStatus(STATUS_NORMAL);
GetNPCByID(16928770+455):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
fegimanam/smp | bot/bot.lua | 2 | 7098 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '0.14.6'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
print('\27[36mNot valid: Telegram message\27[39m')
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
if plugins[disabled_plugin].hidden then
print('Plugin '..disabled_plugin..' is disabled on this chat')
else
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
end
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"echo",
"get",
"google",
"groupmanager",
"help",
"id",
"images",
"img_google",
"location",
"media",
"plugins",
"vip",
"channels",
"set",
"stats",
"time",
"version",
"weather",
"youtube",
"media_handler",
"moderation"},
sudo_users = {118333567,75213323},
disabled_channels = {},
moderation = {data = 'data/moderation.json'}
}
serialize_to_file(config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 5 mins
postpone (cron_plugins, false, 5*60.0)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
8devices/carambola2-luci | protocols/ppp/luasrc/model/cbi/admin_network/proto_l2tp.lua | 59 | 1868 | --[[
LuCI - Lua Configuration Interface
Copyright 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
]]--
local map, section, net = ...
local server, username, password
local ipv6, defaultroute, metric, peerdns, dns, mtu
server = section:taboption("general", Value, "server", translate("L2TP Server"))
server.datatype = "host"
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", Flag, "ipv6",
translate("Enable IPv6 negotiation on the PPP link"))
ipv6.default = ipv6.disabled
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
Fenix-XI/Fenix | scripts/zones/Windurst_Walls/npcs/HomePoint#2.lua | 27 | 1270 | -----------------------------------
-- Area: Windurst Walls
-- NPC: HomePoint#2
-- @pos -212 0.001 -99 239
-----------------------------------
package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Windurst_Walls/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fd, 20);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fd) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
maikerumine/extreme_survival_mini | mods/tnt/init.lua | 1 | 9942 | --[[
-- Default to enabled in singleplayer and disabled in multiplayer
local singleplayer = minetest.is_singleplayer()
local setting = minetest.setting_getbool("enable_tnt")
if (not singleplayer and setting ~= true) or
(singleplayer and setting == false) then
return
end
]]
-- loss probabilities array (one in X will be lost)
local loss_prob = {}
loss_prob["default:cobble"] = 3
loss_prob["default:dirt"] = 4
local radius = tonumber(minetest.setting_get("tnt_radius") or 3)
-- Fill a list with data for content IDs, after all nodes are registered
local cid_data = {}
minetest.after(0, function()
for name, def in pairs(minetest.registered_nodes) do
cid_data[minetest.get_content_id(name)] = {
name = name,
drops = def.drops,
flammable = def.groups.flammable,
on_blast = def.on_blast,
groups = def.groups,
}
end
end)
local function rand_pos(center, pos, radius)
local def
local reg_nodes = minetest.registered_nodes
local i = 0
repeat
-- Give up and use the center if this takes too long
if i > 4 then
pos.x, pos.z = center.x, center.z
break
end
pos.x = center.x + math.random(-radius, radius)
pos.z = center.z + math.random(-radius, radius)
def = reg_nodes[minetest.get_node(pos).name]
i = i + 1
until def and not def.walkable
end
local function eject_drops(drops, pos, radius)
local drop_pos = vector.new(pos)
for _, item in pairs(drops) do
local count = item:get_count()
local max = item:get_stack_max()
if count > max then
item:set_count(max)
end
while count > 0 do
if count < max then
item:set_count(count)
end
rand_pos(pos, drop_pos, radius)
local obj = minetest.add_item(drop_pos, item)
if obj then
obj:get_luaentity().collect = true
obj:setacceleration({x=0, y=-10, z=0})
obj:setvelocity({x=math.random(-3, 3), y=10,
z=math.random(-3, 3)})
end
count = count - max
end
end
end
local function add_drop(drops, item)
item = ItemStack(item)
local name = item:get_name()
if loss_prob[name] ~= nil and math.random(1, loss_prob[name]) == 1 then
return
end
local drop = drops[name]
if drop == nil then
drops[name] = item
else
drop:set_count(drop:get_count() + item:get_count())
end
end
local fire_node = {name="fire:basic_flame"}
local function destroy(drops, pos, cid)
if minetest.is_protected(pos, "") then
return
end
local def = cid_data[cid]
-- bedrock
if def and def.groups.immortal ~= nil then
return
end
-- obsidian
if def and def.name == "default:obsidian" then
return
end
local def = cid_data[cid]
if def and def.on_blast then
def.on_blast(vector.new(pos), 1)
return
end
if def and def.flammable then
minetest.set_node(pos, fire_node)
else
minetest.remove_node(pos)
if def then
local node_drops = minetest.get_node_drops(def.name, "")
for _, item in ipairs(node_drops) do
add_drop(drops, item)
end
end
end
end
local function calc_velocity(pos1, pos2, old_vel, power)
local vel = vector.direction(pos1, pos2)
vel = vector.normalize(vel)
vel = vector.multiply(vel, power)
-- Divide by distance
local dist = vector.distance(pos1, pos2)
dist = math.max(dist, 1)
vel = vector.divide(vel, dist)
-- Add old velocity
vel = vector.add(vel, old_vel)
return vel
end
local function entity_physics(pos, radius)
-- Make the damage radius larger than the destruction radius
radius = radius * 2
local objs = minetest.get_objects_inside_radius(pos, radius)
for _, obj in pairs(objs) do
local obj_pos = obj:getpos()
local obj_vel = obj:getvelocity()
local dist = math.max(1, vector.distance(pos, obj_pos))
if obj_vel ~= nil then
obj:setvelocity(calc_velocity(pos, obj_pos,
obj_vel, radius * 10))
end
local damage = (4 / dist) * radius
obj:set_hp(obj:get_hp() - damage)
end
end
local function add_effects(pos, radius)
minetest.add_particlespawner({
amount = 128,
time = 1,
minpos = vector.subtract(pos, radius / 2),
maxpos = vector.add(pos, radius / 2),
minvel = {x=-20, y=-20, z=-20},
maxvel = {x=20, y=20, z=20},
minacc = vector.new(),
maxacc = vector.new(),
minexptime = 1,
maxexptime = 3,
minsize = 8,
maxsize = 16,
texture = "tnt_smoke.png",
})
end
local function burn(pos)
local name = minetest.get_node(pos).name
if name == "tnt:tnt" then
minetest.sound_play("tnt_ignite", {pos=pos})
minetest.set_node(pos, {name="tnt:tnt_burning"})
minetest.get_node_timer(pos):start(1)
elseif name == "tnt:gunpowder" then
minetest.sound_play("tnt_gunpowder_burning", {pos=pos, gain=2})
minetest.set_node(pos, {name="tnt:gunpowder_burning"})
minetest.get_node_timer(pos):start(1)
end
end
local function explode(pos, radius)
local pos = vector.round(pos)
local vm = VoxelManip()
local pr = PseudoRandom(os.time())
local p1 = vector.subtract(pos, radius)
local p2 = vector.add(pos, radius)
local minp, maxp = vm:read_from_map(p1, p2)
local a = VoxelArea:new({MinEdge = minp, MaxEdge = maxp})
local data = vm:get_data()
local drops = {}
local p = {}
local c_air = minetest.get_content_id("air")
for z = -radius, radius do
for y = -radius, radius do
local vi = a:index(pos.x + (-radius), pos.y + y, pos.z + z)
for x = -radius, radius do
if (x * x) + (y * y) + (z * z) <=
(radius * radius) + pr:next(-radius, radius) then
local cid = data[vi]
p.x = pos.x + x
p.y = pos.y + y
p.z = pos.z + z
if cid ~= c_air then
destroy(drops, p, cid)
end
end
vi = vi + 1
end
end
end
return drops
end
local function boom(pos)
minetest.sound_play("tnt_explode", {pos=pos, gain=1.5, max_hear_distance=2*64})
minetest.set_node(pos, {name="tnt:boom"})
minetest.get_node_timer(pos):start(0.5)
local drops = explode(pos, radius)
entity_physics(pos, radius)
eject_drops(drops, pos, radius)
add_effects(pos, radius)
end
minetest.register_node("tnt:tnt", {
description = "TNT",
tiles = {"tnt_top.png", "tnt_bottom.png", "tnt_side.png"},
is_ground_content = false,
groups = {dig_immediate=2, mesecon=2},
sounds = default.node_sound_wood_defaults(),
on_punch = function(pos, node, puncher)
if puncher:get_wielded_item():get_name() == "default:torch" then
minetest.sound_play("tnt_ignite", {pos=pos})
minetest.set_node(pos, {name="tnt:tnt_burning"})
end
end,
on_blast = function(pos, intensity)
burn(pos)
end,
mesecons = {effector = {action_on = boom}},
})
minetest.register_node("tnt:tnt_burning", {
tiles = {
{
name = "tnt_top_burning_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1,
}
},
"tnt_bottom.png", "tnt_side.png"},
light_source = 5,
drop = "",
sounds = default.node_sound_wood_defaults(),
on_construct = function(pos)
minetest.get_node_timer(pos):start(4)
end,
on_timer = boom,
-- unaffected by explosions
on_blast = function() end,
})
minetest.register_node("tnt:boom", {
drawtype = "plantlike",
tiles = {"tnt_boom.png"},
light_source = default.LIGHT_MAX,
walkable = false,
drop = "",
groups = {dig_immediate=3},
on_timer = function(pos, elapsed)
minetest.remove_node(pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
minetest.register_node("tnt:gunpowder", {
description = "Gun Powder",
drawtype = "raillike",
paramtype = "light",
is_ground_content = false,
sunlight_propagates = true,
walkable = false,
tiles = {"tnt_gunpowder_straight.png", "tnt_gunpowder_curved.png", "tnt_gunpowder_t_junction.png", "tnt_gunpowder_crossing.png"},
inventory_image = "tnt_gunpowder_inventory.png",
wield_image = "tnt_gunpowder_inventory.png",
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
groups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group("gunpowder")},
sounds = default.node_sound_leaves_defaults(),
on_punch = function(pos, node, puncher)
if puncher:get_wielded_item():get_name() == "default:torch" then
burn(pos)
end
end,
on_blast = function(pos, intensity)
burn(pos)
end,
})
minetest.register_node("tnt:gunpowder_burning", {
drawtype = "raillike",
paramtype = "light",
sunlight_propagates = true,
walkable = false,
light_source = 5,
tiles = {{
name = "tnt_gunpowder_burning_straight_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1,
}
},
{
name = "tnt_gunpowder_burning_curved_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1,
}
},
{
name = "tnt_gunpowder_burning_t_junction_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1,
}
},
{
name = "tnt_gunpowder_burning_crossing_animated.png",
animation = {
type = "vertical_frames",
aspect_w = 16,
aspect_h = 16,
length = 1,
}
}},
selection_box = {
type = "fixed",
fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2},
},
drop = "",
groups = {dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group("gunpowder")},
sounds = default.node_sound_leaves_defaults(),
on_timer = function(pos, elapsed)
for dx = -1, 1 do
for dz = -1, 1 do
for dy = -1, 1 do
if not (dx == 0 and dz == 0) then
burn({
x = pos.x + dx,
y = pos.y + dy,
z = pos.z + dz,
})
end
end
end
end
minetest.remove_node(pos)
end,
-- unaffected by explosions
on_blast = function() end,
})
minetest.register_abm({
nodenames = {"tnt:tnt", "tnt:gunpowder"},
neighbors = {"fire:basic_flame", "default:lava_source", "default:lava_flowing"},
interval = 4,
chance = 1,
action = burn,
})
minetest.register_craft({
output = "tnt:gunpowder",
type = "shapeless",
recipe = {"default:coal_lump", "default:gravel"}
})
minetest.register_craft({
output = "tnt:tnt",
recipe = {
{"", "group:wood", ""},
{"group:wood", "tnt:gunpowder", "group:wood"},
{"", "group:wood", ""}
}
})
| lgpl-2.1 |
DarkstarProject/darkstar | scripts/globals/spells/bluemagic/infrasonics.lua | 12 | 1346 | -----------------------------------------
-- Spell: Infrasonics
-- Lowers the evasion of enemies within a fan-shaped area originating from the caster
-- Spell cost: 42 MP
-- Monster Type: Lizards
-- Spell Type: Magical (Ice)
-- Blue Magic Points: 4
-- Stat Bonus: INT+1
-- Level: 65
-- Casting Time: 5 seconds
-- Recast Time: 120 seconds
-- Magic Bursts on: Induration, Distortion, Darkness
-- Combos: None
-----------------------------------------
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 = dsp.mod.INT
params.skillType = dsp.skill.BLUE_MAGIC
params.effect = dsp.effect.EVASION_DOWN
local resist = applyResistance(caster, target, spell, params)
local duration = 60 * resist
local power = 20
if (resist > 0.5) then -- Do it!
if (target:addStatusEffect(params.effect,power,0,duration)) then
spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS)
else
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
else
spell:setMsg(dsp.msg.basic.MAGIC_RESIST)
end
return params.effect
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/items/bowl_of_moogurt.lua | 18 | 1371 | -----------------------------------------
-- ID: 5935
-- Item: Bowl of Moogurt
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP % 20 Cap 20
-- Vitality 3
-- HP Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,1800,5935);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 20);
target:addMod(MOD_FOOD_HP_CAP, 20);
target:addMod(MOD_VIT, 3);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 20);
target:delMod(MOD_FOOD_HP_CAP, 20);
target:delMod(MOD_VIT, 3);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
perfectstrong/Puzzle17 | globalData.lua | 1 | 1654 | --[[This contains all global parameters]]
local M = {}
-- Font overall
M.font = {
default = "InknutAntiqua-Light.ttf",
defaultBold = "InknutAntiqua-ExtraBold.ttf",
size = {
normal = display.contentHeight * 0.03,
large = display.contentHeight * 0.05,
xlarge = display.contentHeight * 0.075,
small = display.contentHeight * 0.01,
},
}
-- About the table of pieces of picture to play
M.gamePreconfig = {
leftPadding = display.contentWidth * 0.1,
rightPadding = display.contentWidth * 0.1,
topPadding = display.contentHeight * 0.2,
bottomPadding = display.contentHeight * 0.2,
}
-- The level chosen by user
M.gameSetting = {
imageRoot = "img/game/",
imagePath = nil,
rowNum = 3,
colNum = 3,
rowNumMin = 3,
rowNumMax = 10,
colNumMin = 3,
colNumMax = 10,
}
M.fade = {
effect = "fade",
time = 500
}
M.sound = {
bravo = audio.loadSound("audio/applause.mp3"),
}
M.bgm = audio.loadStream("audio/bgm.mp3")
M.bgmChannel = 1
M.nobgm = false
M.soundiconsSheet = "img/volume.png"
M.soundiconsOptions = {
width = 200,
height = 200,
numFrames = 2
}
M.reshuffle = "img/refresh.png"
M.background = "img/background.png"
M.backgroundColor = {178/255, 45/255, 126/255, 1.0}
M.defaultColor = {
normalText = {2/255, 195/255, 154/255},
title = {5/255, 102/255, 141/255},
h2 = {2/255, 128/255, 144/255},
indicativeText = {0, 168/255, 150/255},
gray = {0, 0, 0, 0.5},
black = {0, 0, 0, 1},
stroke = {1, 0, 0}
}
M.labelColor = {
default = {2/255, 195/255, 154/255, 1.0},
over = {247/255, 142/255, 105/255, 1.0}
}
M.buttonColor = {
default = {240/255, 243/255, 189/255, 1.0},
over = {240/255, 243/255, 189/255, 0.7}
}
return M | mit |
Fenix-XI/Fenix | scripts/zones/Port_Windurst/npcs/Shanruru.lua | 13 | 2884 | -----------------------------------
-- Area: Port Windurst
-- NPC: Shanruru
-- Involved in Quest: Riding on the Clouds
-- @zone 240
-- @pos -1 -6 187
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_4") == 5) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_4",0);
player:tradeComplete();
player:addKeyItem(SPIRITED_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SPIRITED_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
if (player:getQuestStatus(WINDURST,THE_PROMISE) == QUEST_COMPLETED) then
Message = math.random(0,1)
if (Message == 1) then
player:startEvent(0x0211);
else
player:startEvent(0x021d);
end
elseif (player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS) == QUEST_ACCEPTED) then
player:startEvent(0x01f8);
elseif (OnionRings == QUEST_COMPLETED) then
player:startEvent(0x01be);
elseif (OnionRings == QUEST_ACCEPTED ) then
player:startEvent(0x01b7);
elseif (InspectorsGadget == QUEST_COMPLETED) then
player:startEvent(0x01ac);
elseif (InspectorsGadget == QUEST_ACCEPTED) then
player:startEvent(0x01a4);
elseif (player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS) == QUEST_COMPLETED) then
player:startEvent(0x019c);
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
player:startEvent(0x0180);
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0179);
else
player:startEvent(0x016f);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
asdofindia/prosody-modules | mod_sift/mod_sift.lua | 32 | 6448 |
local st = require "util.stanza";
local jid_bare = require "util.jid".bare;
-- advertise disco features
module:add_feature("urn:xmpp:sift:1");
-- supported features
module:add_feature("urn:xmpp:sift:stanzas:iq");
module:add_feature("urn:xmpp:sift:stanzas:message");
module:add_feature("urn:xmpp:sift:stanzas:presence");
module:add_feature("urn:xmpp:sift:recipients:all");
module:add_feature("urn:xmpp:sift:senders:all");
-- allowed values of 'sender' and 'recipient' attributes
local senders = {
["all"] = true;
["local"] = true;
["others"] = true;
["remote"] = true;
["self"] = true;
};
local recipients = {
["all"] = true;
["bare"] = true;
["full"] = true;
};
-- this function converts a <message/>, <presence/> or <iq/> element in
-- the SIFT namespace into a hashtable, for easy lookup
local function to_hashtable(element)
if element ~= nil then
local hash = {};
-- make sure the sender and recipient attributes has a valid value
hash.sender = element.attr.sender or "all";
if not senders[hash.sender] then return false; end -- bad value, returning false
hash.recipient = element.attr.recipient or "all";
if not recipients[hash.recipient] then return false; end -- bad value, returning false
-- next we loop over all <allow/> elements
for _, tag in ipairs(element) do
if tag.name == "allow" and tag.attr.xmlns == "urn:xmpp:sift:1" then
-- make sure the element is valid
if not tag.attr.name or not tag.attr.ns then return false; end -- missing required attributes, returning false
hash[tag.attr.ns.."|"..tag.attr.name] = true;
hash.allowed = true; -- just a flag indicating we have some elements allowed
end
end
return hash;
end
end
local data = {}; -- table with all our data
-- handle SIFT set
module:hook("iq/self/urn:xmpp:sift:1:sift", function(event)
local origin, stanza = event.origin, event.stanza;
if stanza.attr.type == "set" then
local sifttag = stanza.tags[1]; -- <sift/>
-- first, get the elements we are interested in
local message = sifttag:get_child("message");
local presence = sifttag:get_child("presence");
local iq = sifttag:get_child("iq");
-- for quick lookup, convert the elements into hashtables
message = to_hashtable(message);
presence = to_hashtable(presence);
iq = to_hashtable(iq);
-- make sure elements were valid
if message == false or presence == false or iq == false then
origin.send(st.error_reply(stanza, "modify", "bad-request"));
return true;
end
local existing = data[origin.full_jid] or {}; -- get existing data, if any
data[origin.full_jid] = { presence = presence, message = message, iq = iq }; -- store new data
origin.send(st.reply(stanza)); -- send back IQ result
if not existing.presence and not origin.presence and presence then
-- TODO send probes
end
return true;
end
end);
-- handle user disconnect
module:hook("resource-unbind", function(event)
data[event.session.full_jid] = nil; -- discard data
end);
-- IQ handler
module:hook("iq/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if stanza.attr.type == "get" or stanza.attr.type == "set" then
if siftdata and siftdata.iq then -- we seem to have an IQ filter
local tag = stanza.tags[1]; -- the IQ child
if not siftdata.iq[(tag.attr.xmlns or "jabber:client").."|"..tag.name] then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end
end
end, 50);
-- Message to full JID handler
module:hook("message/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if siftdata and siftdata.message then -- we seem to have an message filter
local allowed = false;
for _, childtag in ipairs(stanza.tags) do
if siftdata.message[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
if not allowed then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
-- FIXME maybe send to offline storage
return true;
end
end
end, 50);
-- Message to bare JID handler
module:hook("message/bare", function(event)
local origin, stanza = event.origin, event.stanza;
local user = bare_sessions[jid_bare(stanza.attr.to)];
local allowed = false;
for _, session in pairs(user and user.sessions or {}) do
local siftdata = data[session.full_jid];
if siftdata and siftdata.message then -- we seem to have an message filter
for _, childtag in ipairs(stanza.tags) do
if siftdata.message[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
else
allowed = true;
end
end
if user and not allowed then
-- element not allowed; sending back generic error
origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
-- FIXME maybe send to offline storage
return true;
end
end, 50);
-- Presence to full JID handler
module:hook("presence/full", function(event)
local origin, stanza = event.origin, event.stanza;
local siftdata = data[stanza.attr.to];
if siftdata and siftdata.presence then -- we seem to have an presence filter
local allowed = false;
for _, childtag in ipairs(stanza.tags) do
if siftdata.presence[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
if not allowed then
-- element not allowed; sending back generic error
--origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end
end, 50);
-- Presence to bare JID handler
module:hook("presence/bare", function(event)
local origin, stanza = event.origin, event.stanza;
local user = bare_sessions[jid_bare(stanza.attr.to)];
local allowed = false;
for _, session in pairs(user and user.sessions or {}) do
local siftdata = data[session.full_jid];
if siftdata and siftdata.presence then -- we seem to have an presence filter
for _, childtag in ipairs(stanza.tags) do
if siftdata.presence[(childtag.attr.xmlns or "jabber:client").."|"..childtag.name] then
allowed = true;
end
end
else
allowed = true;
end
end
if user and not allowed then
-- element not allowed; sending back generic error
--origin.send(st.error_reply(stanza, "cancel", "service-unavailable"));
return true;
end
end, 50);
| mit |
oTibia/UnderLight-AK47 | data/npc/scripts/runes.lua | 2 | 1532 | -- This is an example NPC script that can be used on Jiddo's NPC system
local keywordHandler = KeywordHandler:new()
local npcHandler = NpcHandler:new(keywordHandler)
NpcSystem.parseParameters(npcHandler)
-- OTServ event handling functions start
function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end
function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end
function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end
function onThink() npcHandler:onThink() end
-- OTServ event handling functions end
local shopModule = ShopModule:new()
npcHandler:addModule(shopModule)
shopModule:addBuyableItem({'light wand', 'lightwand'}, 2163, 500, 'magic light wand')
shopModule:addBuyableItem({'mana fluid', 'manafluid'}, 11396, 100, 7, 'mana fluid')
shopModule:addBuyableItem({'life fluid', 'lifefluid'}, 11396, 80, 10, 'life fluid')
shopModule:addBuyableItem({'heavy magic missile', 'hmm'}, 2311, 125, 10, 'heavy magic missile rune')
shopModule:addBuyableItem({'great fireball', 'gfb'}, 2304, 180, 4, 'great fireball rune')
shopModule:addBuyableItem({'explo', 'xpl'}, 2313, 250, 6, 'explosion rune')
shopModule:addBuyableItem({'ultimate healing', 'uh'}, 2273, 175, 2, 'ultimate healing rune')
shopModule:addBuyableItem({'sudden death', 'sd'}, 2268, 325, 2, 'sudden death rune')
shopModule:addBuyableItem({'blank', 'rune'}, 2260, 10, 'blank rune')
npcHandler:addModule(FocusModule:new()) | gpl-2.0 |
gamenew09/GMod-Jailbreak | gamemode/init.lua | 1 | 7485 | include("shared.lua")
local PLAYER = getmetatable("Player")
local SpawnPoints = {
{
ClassName = "info_player_terrorist",
Team = 1
},
{
ClassName = "info_player_counterterrorist",
Team = 2
}
}
AddCSLuaFile( "cl_init.lua" ) -- Make sure clientside
AddCSLuaFile( "shared.lua" ) -- and shared scripts are sent.
AddCSLuaFile( "cl_hud.lua" ) -- and shared scripts are sent.
include("sh_player.lua")
print(TEAM_PRISONERS .. " ".. TEAM_GUARDS)
util.AddNetworkString("WardenPoint")
util.AddNetworkString("DropWeapon")
-- Setup Net Hooks --
net.Receive( "WardenPoint", function (len, ply)
if not ply:IsWarden() then return end
--pcall(function () -- Hopefully prevents the hit pos from being nil.
CreateWardenPoint(ply:GetEyeTrace().HitPos)
--end)
end)
net.Receive( "DropWeapon", function (len, ply)
pcall(function () -- Hopefully prevents the hit pos from being nil.
if(ply:GetActiveWeapon():GetClass() == "weapon_fists")then return end -- Never drop your hands. That sounds very odd.
ply:DropWeapon(ply:GetActiveWeapon())
end)
end)
hook.Add( "PlayerNoClip", "jb_default_noclip", function( ply, desiredState )
local ret = false
if ( desiredState == false ) then -- the player wants to turn noclip off
ret = true -- always allow
elseif ( ply:IsAdmin() ) then
ret = true -- allow administrators to enter noclip
end
local word = "disallowed"
if ret then
word = "allowed"
end
print("Noclip for "..ply:GetName().. " was "..tostring(word)..".")
return ret
end )
local count = 1
local WardenPoints = {}
function GM:GetWardenPoints()
return WardenPoints
end
function GM:PlayerSelectSpawn( pl )
for i,v in pairs(SpawnPoints)do
local className = v.ClassName
local teamNum = v.Team
print(pl:GetName())
print(pl:Team() .. " == ".. teamNum.. " is ".. tostring(pl:Team() == teamNum))
if pl:Team() == teamNum then
local spawns = ents.FindByClass(className)
return spawns[math.random(#spawns)]
end
end
print("Resulting to first team's spawn class.")
local spawns = ents.FindByClass(SpawnPoints[1].ClassName) -- Gets the first team's spawn
return spawns[math.random(#spawns)]
end
function CreateWardenPoint(vec)
if(count >= 10) then return end
local ent = ents.Create( 'jb_wardenpoint' )
print("HI!")
ent:SetPos( vec )
ent:Spawn()
ent:Activate()
table.insert(WardenPoints, point)
print('YAY!')
count = count + 1
local curCount = count
timer.Create( "DeletePoint".. count, 5, 1, function ()
print("Destroying...")
count = count - 1
ent:Remove()
table.remove(WardenPoints, curCount)
end)
end
function ChangeMyTeam( ply, cmd, args )
if ply == nil then
print("Only players can run this command.")
return
end
ply:SetTeam( args[1] )
ply:Spawn()
end
concommand.Add( "jb_set_team", ChangeMyTeam )
-- Choose the model for hands according to their player model.
function GM:PlayerSetHandsModel( ply, ent )
local simplemodel = player_manager.TranslateToPlayerModelName( ply:GetModel() )
local info = player_manager.TranslatePlayerHands( simplemodel )
if ( info ) then
ent:SetModel( info.model )
ent:SetSkin( info.skin )
ent:SetBodyGroups( info.body )
end
end
function GM:PlayerInitialSpawn(ply)
//ply:SetTeam(TEAM_PRISONERS)
end
function GM:PlayerSetModel( ply )
if(not ply:Alive())then return end
if(ply:Team() == TEAM_GUARDS)then
ply:SetModel("models/player/police.mdl" )
else
ply:SetModel("models/player/Group01/Male_01.mdl" )
end
print("Set player's model.")
end
function GM:GetFallDamage( ply, speed )
vel = speed - 580
return (vel*(100/(1024-580)))
end
function GM:PlayerSpawn( ply )
--player_manager.SetPlayerClass( ply, "player_default" )
ply:SetNoCollideWithTeammates( true )
self:PlayerSetModel( ply )
print("Player Spawned!")
self:PlayerLoadout(ply)
ply:SetupHands()
end
function GM:PlayerLoadout(ply)
ply:StripWeapons()
ply:Give("weapon_fists")
if ply:Team() == TEAM_PRISONERS then
if math.random(1, 100) > 75 then
ply:PrintMessage(HUD_PRINTTALK, "Hey, you spawned with a knife!")
ply:Give("ptp_cs_knife")
end
if math.random(1, 250) > 200 then
ply:PrintMessage(HUD_PRINTTALK, "Hey, you spawned with a CV-47!")
ply:Give("ptp_cs_ak47")
ply:GiveAmmo(590, "smg1", true)
end
ply:SelectWeapon("weapon_fists")
end
if ply:Team() == TEAM_GUARDS then
ply:Give("weapon_weaponchecker")
ply:Give("ptp_cs_knife")
ply:Give("ptp_cs_ak47")
ply:GiveAmmo(9999, "smg1", true)
end
print("Player Loaded!")
end
hook.Add("ShowTeam", "jb_Show", function (ply)
umsg.Start( "ChangeTeamsGUI", ply ) -- Sending a message to the client.
umsg.End()
end)
function SpawnAllPlayers()
for i,v in pairs(player.GetAll())do
v:Spawn()
end
end
function GM:PlayerDeathThink( ply )
if(JB_CONFIG.ConfigMode == false)then
GAMEMODE:PlayerSpawnAsSpectator( ply )
end
end
function GM:PlayerDeath( victm, inflictor, killer )
victm:ShouldDropWeapon( true )
--victm:SetNWBool("warden", false)
end
function OnChat( ply, text, public )
if string.sub(text, 1,1) == "!" then
text = string.lower(text)
if (string.sub(text, 2, 11) == "whoswarden") then
local warden = GetWarden()
if warden == nil then
ply:ChatPrint("No one is warden.")
else
local addon = ""
if ply:IsAdmin() then
addon = " Warden's SteamID is "..warden:SteamID()
end
ply:ChatPrint(warden:GetName() .. " is warden."..addon)
end
end
if (string.sub(text, 2, 15) == "splitprisoners")then
print("Called splitprisoners.")
if(not ply:IsWarden())then
ply:PrintMessage( HUD_PRINTTALK, "Only wardens can split prisoners into teams." )
return false
end
if(#GetAlivePlayers(TEAM_PRISONERS) <= 1)then
ply:PrintMessage( HUD_PRINTTALK, "There is only one prisoner, what is the point?" )
return false
end
for i,v in pairs(GetAlivePlayers(TEAM_PRISONERS))do
if math.random(1, 100) < 50 then
v:SetColor(Color(255, 0, 0, 255))
else
v:SetColor(Color(0, 0, 255, 255))
end
end
end
if (string.sub(text, 2, 5) == "roll")then
if not ply:IsWarden() then
ply:PrintMessage( HUD_PRINTTALK, "Only wardens can roll numbers." )
return false
end
text = string.Explode( " ", text )
local max = 10
if #text > 1 then
max = tonumber(text[2])
if max > 200 then
ply:PrintMessage( HUD_PRINTTALK, "You can't roll above a 200!" )
return false
end
PrintMessage( HUD_PRINTTALK, ply:GetName().." rolled a "..math.random(1, max).."." )
end
end
if (string.sub(text, 2, 12) == "setaswarden")then
print(ply:Name() .." with SteamID of "..ply:SteamID().. " is trying to call "..string.sub(text, 2))
if not ply:IsAdmin() then
ply:PrintMessage( HUD_PRINTTALK, "Only admins can set players as the warden." )
return false
end
text = string.Explode( " ", text )
local max = 10
if #text > 1 then
local p = GetPlayerByName(text[2])
if p == nil then
ply:PrintMessage( HUD_PRINTTALK, "That player doesn't exist." )
return false
end
if not IsValid(p) then
ply:PrintMessage( HUD_PRINTTALK, "That player doesn't exist." )
return false
end
local warden = GetWarden()
if warden == nil then
p:SetAsWarden()
else
warden:SetNWBool("warden", false)
p:SetAsWarden()
end
return false
else
ply:PrintMessage( HUD_PRINTTALK, "You must specify a player to set as warden." )
return false
end
end
return false
end
return true
end
hook.Add( "PlayerSay", "OnChat", OnChat ) | gpl-2.0 |
SkzKatsushiro/OpenRA | lua/stacktraceplus.lua | 59 | 12006 | -- tables
local _G = _G
local string, io, debug, coroutine = string, io, debug, coroutine
-- functions
local tostring, print, require = tostring, print, require
local next, assert = next, assert
local pcall, type, pairs, ipairs = pcall, type, pairs, ipairs
local error = error
assert(debug, "debug table must be available at this point")
local io_open = io.open
local string_gmatch = string.gmatch
local string_sub = string.sub
local table_concat = table.concat
local _M = {
max_tb_output_len = 70 -- controls the maximum length of the 'stringified' table before cutting with ' (more...)'
}
-- this tables should be weak so the elements in them won't become uncollectable
local m_known_tables = { [_G] = "_G (global table)" }
local function add_known_module(name, desc)
local ok, mod = pcall(require, name)
if ok then
m_known_tables[mod] = desc
end
end
add_known_module("string", "string module")
add_known_module("io", "io module")
add_known_module("os", "os module")
add_known_module("table", "table module")
add_known_module("math", "math module")
add_known_module("package", "package module")
add_known_module("debug", "debug module")
add_known_module("coroutine", "coroutine module")
-- lua5.2
add_known_module("bit32", "bit32 module")
-- luajit
add_known_module("bit", "bit module")
add_known_module("jit", "jit module")
local m_user_known_tables = {}
local m_known_functions = {}
for _, name in ipairs{
-- Lua 5.2, 5.1
"assert",
"collectgarbage",
"dofile",
"error",
"getmetatable",
"ipairs",
"load",
"loadfile",
"next",
"pairs",
"pcall",
"print",
"rawequal",
"rawget",
"rawlen",
"rawset",
"require",
"select",
"setmetatable",
"tonumber",
"tostring",
"type",
"xpcall",
-- Lua 5.1
"gcinfo",
"getfenv",
"loadstring",
"module",
"newproxy",
"setfenv",
"unpack",
-- TODO: add table.* etc functions
} do
if _G[name] then
m_known_functions[_G[name]] = name
end
end
local m_user_known_functions = {}
local function safe_tostring (value)
local ok, err = pcall(tostring, value)
if ok then return err else return ("<failed to get printable value>: '%s'"):format(err) end
end
-- Private:
-- Parses a line, looking for possible function definitions (in a very naïve way)
-- Returns '(anonymous)' if no function name was found in the line
local function ParseLine(line)
assert(type(line) == "string")
--print(line)
local match = line:match("^%s*function%s+(%w+)")
if match then
--print("+++++++++++++function", match)
return match
end
match = line:match("^%s*local%s+function%s+(%w+)")
if match then
--print("++++++++++++local", match)
return match
end
match = line:match("^%s*local%s+(%w+)%s+=%s+function")
if match then
--print("++++++++++++local func", match)
return match
end
match = line:match("%s*function%s*%(") -- this is an anonymous function
if match then
--print("+++++++++++++function2", match)
return "(anonymous)"
end
return "(anonymous)"
end
-- Private:
-- Tries to guess a function's name when the debug info structure does not have it.
-- It parses either the file or the string where the function is defined.
-- Returns '?' if the line where the function is defined is not found
local function GuessFunctionName(info)
--print("guessing function name")
if type(info.source) == "string" and info.source:sub(1,1) == "@" then
local file, err = io_open(info.source:sub(2), "r")
if not file then
print("file not found: "..tostring(err)) -- whoops!
return "?"
end
local line
for i = 1, info.linedefined do
line = file:read("*l")
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
else
local line
local lineNumber = 0
for l in string_gmatch(info.source, "([^\n]+)\n-") do
lineNumber = lineNumber + 1
if lineNumber == info.linedefined then
line = l
break
end
end
if not line then
print("line not found") -- whoops!
return "?"
end
return ParseLine(line)
end
end
---
-- Dumper instances are used to analyze stacks and collect its information.
--
local Dumper = {}
Dumper.new = function(thread)
local t = { lines = {} }
for k,v in pairs(Dumper) do t[k] = v end
t.dumping_same_thread = (thread == coroutine.running())
-- if a thread was supplied, bind it to debug.info and debug.get
-- we also need to skip this additional level we are introducing in the callstack (only if we are running
-- in the same thread we're inspecting)
if type(thread) == "thread" then
t.getinfo = function(level, what)
if t.dumping_same_thread and type(level) == "number" then
level = level + 1
end
return debug.getinfo(thread, level, what)
end
t.getlocal = function(level, loc)
if t.dumping_same_thread then
level = level + 1
end
return debug.getlocal(thread, level, loc)
end
else
t.getinfo = debug.getinfo
t.getlocal = debug.getlocal
end
return t
end
-- helpers for collecting strings to be used when assembling the final trace
function Dumper:add (text)
self.lines[#self.lines + 1] = text
end
function Dumper:add_f (fmt, ...)
self:add(fmt:format(...))
end
function Dumper:concat_lines ()
return table_concat(self.lines)
end
---
-- Private:
-- Iterates over the local variables of a given function.
--
-- @param level The stack level where the function is.
--
function Dumper:DumpLocals (level)
local prefix = "\t "
local i = 1
if self.dumping_same_thread then
level = level + 1
end
local name, value = self.getlocal(level, i)
if not name then
return
end
self:add("\tLocal variables:\r\n")
while name do
if type(value) == "number" then
self:add_f("%s%s = number: %g\r\n", prefix, name, value)
elseif type(value) == "boolean" then
self:add_f("%s%s = boolean: %s\r\n", prefix, name, tostring(value))
elseif type(value) == "string" then
self:add_f("%s%s = string: %q\r\n", prefix, name, value)
elseif type(value) == "userdata" then
self:add_f("%s%s = %s\r\n", prefix, name, safe_tostring(value))
elseif type(value) == "nil" then
self:add_f("%s%s = nil\r\n", prefix, name)
elseif type(value) == "table" then
if m_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_known_tables[value])
elseif m_user_known_tables[value] then
self:add_f("%s%s = %s\r\n", prefix, name, m_user_known_tables[value])
else
local txt = "{"
for k,v in pairs(value) do
txt = txt..safe_tostring(k)..":"..safe_tostring(v)
if #txt > _M.max_tb_output_len then
txt = txt.." (more...)"
break
end
if next(value, k) then txt = txt..", " end
end
self:add_f("%s%s = %s %s\r\n", prefix, name, safe_tostring(value), txt.."}")
end
elseif type(value) == "function" then
local info = self.getinfo(value, "nS")
local fun_name = info.name or m_known_functions[value] or m_user_known_functions[value]
if info.what == "C" then
self:add_f("%s%s = C %s\r\n", prefix, name, (fun_name and ("function: " .. fun_name) or tostring(value)))
else
local source = info.short_src
if source:sub(2,7) == "string" then
source = source:sub(9)
end
--for k,v in pairs(info) do print(k,v) end
fun_name = fun_name or GuessFunctionName(info)
self:add_f("%s%s = Lua function '%s' (defined at line %d of chunk %s)\r\n", prefix, name, fun_name, info.linedefined, source)
end
elseif type(value) == "thread" then
self:add_f("%sthread %q = %s\r\n", prefix, name, tostring(value))
end
i = i + 1
name, value = self.getlocal(level, i)
end
end
---
-- Public:
-- Collects a detailed stack trace, dumping locals, resolving function names when they're not available, etc.
-- This function is suitable to be used as an error handler with pcall or xpcall
--
-- @param thread An optional thread whose stack is to be inspected (defaul is the current thread)
-- @param message An optional error string or object.
-- @param level An optional number telling at which level to start the traceback (default is 1)
--
-- Returns a string with the stack trace and a string with the original error.
--
function _M.stacktrace(thread, message, level)
if type(thread) ~= "thread" then
-- shift parameters left
thread, message, level = nil, thread, message
end
thread = thread or coroutine.running()
level = level or 1
local dumper = Dumper.new(thread)
local original_error
if type(message) == "table" then
dumper:add("an error object {\r\n")
local first = true
for k,v in pairs(message) do
if first then
dumper:add(" ")
first = false
else
dumper:add(",\r\n ")
end
dumper:add(safe_tostring(k))
dumper:add(": ")
dumper:add(safe_tostring(v))
end
dumper:add("\r\n}")
original_error = dumper:concat_lines()
elseif type(message) == "string" then
dumper:add(message)
original_error = message
end
dumper:add("\r\n")
dumper:add[[
Stack Traceback
===============
]]
--print(error_message)
local level_to_show = level
if dumper.dumping_same_thread then level = level + 1 end
local info = dumper.getinfo(level, "nSlf")
while info do
if info.what == "main" then
if string_sub(info.source, 1, 1) == "@" then
dumper:add_f("(%d) main chunk of file '%s' at line %d\r\n", level_to_show, string_sub(info.source, 2), info.currentline)
else
dumper:add_f("(%d) main chunk of %s at line %d\r\n", level_to_show, info.short_src, info.currentline)
end
elseif info.what == "C" then
--print(info.namewhat, info.name)
--for k,v in pairs(info) do print(k,v, type(v)) end
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name or tostring(info.func)
dumper:add_f("(%d) %s C function '%s'\r\n", level_to_show, info.namewhat, function_name)
--dumper:add_f("%s%s = C %s\r\n", prefix, name, (m_known_functions[value] and ("function: " .. m_known_functions[value]) or tostring(value)))
elseif info.what == "tail" then
--print("tail")
--for k,v in pairs(info) do print(k,v, type(v)) end--print(info.namewhat, info.name)
dumper:add_f("(%d) tail call\r\n", level_to_show)
dumper:DumpLocals(level)
elseif info.what == "Lua" then
local source = info.short_src
local function_name = m_user_known_functions[info.func] or m_known_functions[info.func] or info.name
if source:sub(2, 7) == "string" then
source = source:sub(9)
end
local was_guessed = false
if not function_name or function_name == "?" then
--for k,v in pairs(info) do print(k,v, type(v)) end
function_name = GuessFunctionName(info)
was_guessed = true
end
-- test if we have a file name
local function_type = (info.namewhat == "") and "function" or info.namewhat
if info.source and info.source:sub(1, 1) == "@" then
dumper:add_f("(%d) Lua %s '%s' at file '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
elseif info.source and info.source:sub(1,1) == '#' then
dumper:add_f("(%d) Lua %s '%s' at template '%s:%d'%s\r\n", level_to_show, function_type, function_name, info.source:sub(2), info.currentline, was_guessed and " (best guess)" or "")
else
dumper:add_f("(%d) Lua %s '%s' at line %d of chunk '%s'\r\n", level_to_show, function_type, function_name, info.currentline, source)
end
dumper:DumpLocals(level)
else
dumper:add_f("(%d) unknown frame %s\r\n", level_to_show, info.what)
end
level = level + 1
level_to_show = level_to_show + 1
info = dumper.getinfo(level, "nSlf")
end
return dumper:concat_lines(), original_error
end
--
-- Adds a table to the list of known tables
function _M.add_known_table(tab, description)
if m_known_tables[tab] then
error("Cannot override an already known table")
end
m_user_known_tables[tab] = description
end
--
-- Adds a function to the list of known functions
function _M.add_known_function(fun, description)
if m_known_functions[fun] then
error("Cannot override an already known function")
end
m_user_known_functions[fun] = description
end
return _M
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Grand_Palace_of_HuXzoi/mobs/Ixaern_MNK.lua | 9 | 2302 | -----------------------------------
-- Area: Grand Palace of HuXzoi
-- Mob: Ix'aern MNK
-----------------------------------
local ID = require("scripts/zones/Grand_Palace_of_HuXzoi/IDs");
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
function onMobSpawn(mob)
-- adjust drops based on number of HQ Aern Organs traded to QM
local qm = GetNPCByID(ID.npc.IXAERN_MNK_QM);
local chance = qm:getLocalVar("[SEA]IxAern_DropRate");
if (math.random(0,1) > 0) then
SetDropRate(4398, 1851, chance * 10); -- Deed Of Placidity
SetDropRate(4398, 1901, 0);
else
SetDropRate(4398, 1851, 0);
SetDropRate(4398, 1901, chance * 10); -- Vice of Antipathy
end
qm:setLocalVar("[SEA]IxAern_DropRate", 0);
mob:AnimationSub(1); -- Reset the subanim - otherwise it will respawn with bracers on. Note that Aerns are never actually supposed to be in subanim 0.
end;
function onMobFight(mob,target)
-- The mob gains a huge boost when it 2hours to attack speed and attack.
-- It forces the minions to 2hour as well. Wiki says 50% but all videos show 60%.
if (mob:getLocalVar("BracerMode") == 0) then
if (mob:getHPP() < math.random(50,60)) then
-- Go into bracer mode
mob:setLocalVar("BracerMode", 1);
mob:AnimationSub(2);
mob:addMod(dsp.mod.ATT, 200);
mob:addMod(dsp.mod.HASTE_ABILITY, 1500);
mob:useMobAbility(3411); -- Hundred Fists
-- Force minions to 2hour
for i = 1, 2 do
local minion = GetMobByID(mob:getID() + i);
if (minion:getCurrentAction() ~= dsp.act.NONE) then
minion:useMobAbility(3411 + i); -- Chainspell or Benediction
end
end
end
end
end;
function onMobDeath(mob, player, isKiller)
DespawnMob(mob:getID()+1);
DespawnMob(mob:getID()+2);
end;
function onMobDespawn(mob)
DespawnMob(mob:getID()+1);
DespawnMob(mob:getID()+2);
local qm = GetNPCByID(ID.npc.IXAERN_MNK_QM);
if (math.random(0,1) == 1) then
qm:setPos(380,0,540,0); -- G-7
else
qm:setPos(460,0,540,0); -- I-7
end;
qm:updateNPCHideTime(FORCE_SPAWN_QM_RESET_TIME);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/items/hedgehog_pie.lua | 18 | 1973 | -----------------------------------------
-- ID: 5146
-- Item: hedgehog_pie
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 55
-- Strength 6
-- Vitality 2
-- Intelligence -3
-- Mind 3
-- Magic Regen While Healing 2
-- Attack % 18
-- Attack Cap 90
-- Accuracy 5
-- Ranged ATT % 18
-- Ranged ATT Cap 90
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5146);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 55);
target:addMod(MOD_STR, 6);
target:addMod(MOD_VIT, 2);
target:addMod(MOD_INT, -3);
target:addMod(MOD_MND, 3);
target:addMod(MOD_MPHEAL, 2);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 90);
target:addMod(MOD_ACC, 5);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 90);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 55);
target:delMod(MOD_STR, 6);
target:delMod(MOD_VIT, 2);
target:delMod(MOD_INT, -3);
target:delMod(MOD_MND, 3);
target:delMod(MOD_MPHEAL, 2);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 90);
target:delMod(MOD_ACC, 5);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 90);
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Southern_San_dOria/npcs/Diary.lua | 9 | 2458 | -----------------------------------
-- Area: South San d'Oria
-- NPC: Diary
-- Involved in Quest: To Cure a Cough, Over The Hills And Far Away
-- !pos -75 -12 65 230
-----------------------------------
require("scripts/globals/settings")
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local aSquiresTestII = player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.A_SQUIRE_S_TEST_II)
local medicineWoman = player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.THE_MEDICINE_WOMAN)
local toCureaCough = player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.TO_CURE_A_COUGH)
local diaryPage = player:getCharVar("DiaryPage")
if diaryPage == 0 then
player:startEvent(639) -- see diary, option to read (reads page 1)
elseif diaryPage == 1 then
player:startEvent(640) -- reads page 2
elseif diaryPage == 2 then
if medicineWoman == QUEST_COMPLETED and aSquiresTestII == QUEST_COMPLETED then
if toCureaCough == QUEST_ACCEPTED then
player:startEvent(641) -- reads page 3
else
player:startEvent(640) -- reads page 2
end
elseif medicineWoman == QUEST_AVAILABLE and aSquiresTestII == QUEST_AVAILABLE then
player:startEvent(641) -- reads page 3
else
player:startEvent(640) -- reads page 2
end
elseif diaryPage >= 3 then
player:startEvent(722) -- reads page 4
--elseif diaryPage >= 4 then
-- player:startEvent(723) -- read last page
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
local diaryPage = player:getCharVar("DiaryPage")
if option >= diaryPage then
if csid == 639 and option == 0 then
player:setCharVar("DiaryPage", 1) -- has read page 1
elseif csid == 640 and option == 2 then
player:setCharVar("DiaryPage", 2) -- has read page 2
elseif csid == 641 and option == 3 then
player:setCharVar("DiaryPage", 3) -- has read page 3
elseif csid == 722 and option == 4 then
player:setCharVar("DiaryPage", 4) -- has read page 4
--elseif csid == 723 and option == 5 then
-- player:setCharVar("DiaryPage", 5) -- has read the last page
end
end
end
| gpl-3.0 |
crunchuser/prosody-modules | mod_lastlog/mod_lastlog.lua | 32 | 2636 | local datamanager = require "util.datamanager";
local jid = require "util.jid";
local time = os.time;
local log_ip = module:get_option_boolean("lastlog_ip_address", false);
local host = module.host;
module:hook("authentication-success", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "login";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("resource-unbind", function(event)
local session = event.session;
if session.username then
datamanager.store(session.username, host, "lastlog", {
event = "logout";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end
end);
module:hook("user-registered", function(event)
local session = event.session;
datamanager.store(event.username, host, "lastlog", {
event = "registered";
timestamp = time(),
ip = log_ip and session and session.ip or nil,
});
end);
if module:get_host_type() == "component" then
module:hook("message/bare", function(event)
local room = jid.split(event.stanza.attr.to);
if room then
datamanager.store(room, module.host, "lastlog", {
event = "message";
timestamp = time(),
});
end
end);
elseif module:get_option_boolean("lastlog_stamp_offline") then
local datetime = require"util.datetime".datetime;
local function offline_stamp(event)
local stanza = event.stanza;
local node, to_host = jid.split(stanza.attr.from);
if to_host == host and event.origin == hosts[host] and stanza.attr.type == "unavailable" then
local data = datamanager.load(node, host, "lastlog");
local timestamp = data and data.timestamp;
if timestamp then
stanza:tag("delay", {
xmlns = "urn:xmpp:delay",
from = host,
stamp = datetime(timestamp),
}):up();
end
end
end
module:hook("pre-presence/bare", offline_stamp);
module:hook("pre-presence/full", offline_stamp);
end
function module.command(arg)
if not arg[1] or arg[1] == "--help" then
require"util.prosodyctl".show_usage([[mod_lastlog <user@host>]], [[Show when user last logged in or out]]);
return 1;
end
local user, host = jid.prepped_split(table.remove(arg, 1));
require"core.storagemanager".initialize_host(host);
local lastlog = datamanager.load(user, host, "lastlog");
if lastlog then
print(("Last %s: %s"):format(lastlog.event or "login",
lastlog.timestamp and os.date("%Y-%m-%d %H:%M:%S", lastlog.timestamp) or "<unknown>"));
if lastlog.ip then
print("IP address: "..lastlog.ip);
end
else
print("No record found");
return 1;
end
return 0;
end
| mit |
Fenix-XI/Fenix | scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#1.lua | 27 | 1295 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: HomePoint#1
-- @pos -21.129 0.001 -20.944 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
homepointMenu( player, 0x21fc, 65);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpTeleport( player, option);
end
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/items/plate_of_squid_sushi_+1.lua | 17 | 1540 | -----------------------------------------
-- ID: 5162
-- Item: plate_of_squid_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 30
-- Dexterity 6
-- Agility 5
-- Accuracy % 16
-- Ranged ACC % 16
-- Sleep Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5162);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 30);
target:addMod(MOD_DEX, 6);
target:addMod(MOD_AGI, 5);
target:addMod(MOD_FOOD_ACCP, 16);
target:addMod(MOD_FOOD_RACCP, 16);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 30);
target:delMod(MOD_DEX, 6);
target:delMod(MOD_AGI, 5);
target:delMod(MOD_FOOD_ACCP, 16);
target:delMod(MOD_FOOD_RACCP, 16);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Upper_Jeuno/npcs/_6s1.lua | 13 | 4078 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Marble Bridge Eatery (Door)
-- @pos -96.6 -0.2 92.3 244
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/missions");
require("scripts/zones/Upper_Jeuno/TextIDs");
local RajasRing = 15543;
local SattvaRing = 15544;
local TamasRing = 15545;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local playerhaveCOPring=false;
local ringtakeNbr=player:getVar("COP-RingTakeNbr");
local currentday = tonumber(os.date("%j"));
local lastRingday =player:getVar("COP-lastRingday");
if (player:hasItem(RajasRing) or player:hasItem(SattvaRing) or player:hasItem(TamasRing)) then
playerhaveCOPring=true;
end
if (player:getCurrentMission(COP) == FOR_WHOM_THE_VERSE_IS_SUNG and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x271B);
elseif (player:getCurrentMission(COP) ==FLAMES_IN_THE_DARKNESS and player:getVar("PromathiaStatus")==3) then
player:startEvent(0x271C);
elseif (player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")== 4) then
player:startEvent(0x0081);
elseif ((player:getCurrentMission(COP) == DAWN and player:getVar("PromathiaStatus")> 4) or player:hasCompletedMission(COP,DAWN)) then
if (playerhaveCOPring == false ) then
if (ringtakeNbr==0) then
player:startEvent(0x0054,RajasRing,SattvaRing,TamasRing);
elseif (ringtakeNbr ==1) then -- First time you throw away
player:startEvent(0x00CC,RajasRing,SattvaRing,TamasRing);
elseif (ringtakeNbr >1 and (currentday-lastRingday)>26) then -- Ring was thrown away more than once
player:startEvent(0x00CC,RajasRing,SattvaRing,TamasRing);
end
end
else
return -1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
local currentday = tonumber(os.date("%j"));
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
local ringtakeNbr=player:getVar("COP-RingTakeNbr");
if (csid == 0x271B) then
player:setVar("PromathiaStatus",2);
elseif (csid == 0x271C) then
player:setVar("PromathiaStatus",0);
player:completeMission(COP,FLAMES_IN_THE_DARKNESS);
player:addMission(COP,FIRE_IN_THE_EYES_OF_MEN);
elseif (csid == 0x0081) then
player:setVar("PromathiaStatus",5);
elseif ((csid == 0x0054 or csid == 0x00CC) and option > 4 and player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,(option-5)+RajasRing);
elseif ((csid == 0x0054 or csid == 0x00CC)and option == 5) then--5 rajas
player:addItem(RajasRing);
player:messageSpecial(ITEM_OBTAINED,RajasRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
elseif ((csid == 0x0054 or csid == 0x00CC)and option == 6) then--6 Sattva
player:addItem(SattvaRing);
player:messageSpecial(ITEM_OBTAINED,SattvaRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
elseif ((csid == 0x0054 or csid == 0x00CC) and option == 7) then--7 Tamas
player:addItem(TamasRing);
player:messageSpecial(ITEM_OBTAINED,TamasRing);
player:setVar("COP-RingTakeNbr",ringtakeNbr+1);
player:setVar("COP-lastRingday",currentday);
end
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/West_Sarutabaruta/npcs/Signpost.lua | 13 | 1933 | -----------------------------------
-- Area: West Sarutabaruta
-- NPC: Signpost (18 total)
-----------------------------------
package.loaded["scripts/zones/West_Sarutabaruta/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/West_Sarutabaruta/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getID() == 17248823) or (npc:getID() == 17248824) then
player:messageSpecial(SIGN_1);
elseif (npc:getID() == 17248825) or (npc:getID() == 17248826) then
player:messageSpecial(SIGN_3);
elseif (npc:getID() == 17248827) or (npc:getID() == 17248828) then
player:messageSpecial(SIGN_5);
elseif (npc:getID() == 17248829) or (npc:getID() == 17248830) then
player:messageSpecial(SIGN_7);
elseif (npc:getID() == 17248831) or (npc:getID() == 17248832) then
player:messageSpecial(SIGN_9);
elseif (npc:getID() == 17248833) or (npc:getID() == 17248834) then
player:messageSpecial(SIGN_11);
elseif (npc:getID() == 17248835) or (npc:getID() == 17248836) then
player:messageSpecial(SIGN_13);
elseif (npc:getID() == 17248837) or (npc:getID() == 17248838) then
player:messageSpecial(SIGN_15);
elseif (npc:getID() == 17248839) or (npc:getID() == 17248840) then
player:messageSpecial(SIGN_17);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID: %u",csid);
--print("RESULT: %u",option);
end; | gpl-3.0 |
wangg12/fbcunn | fbcunn/AbstractParallel.lua | 8 | 7985 | -- Copyright 2004-present Facebook. All Rights Reserved.
require('cutorch')
local withDevice = cutorch.withDevice
local gpu_local_copy_buffers = {}
--[[
`nn.AbstractParallel` is the base class for modules controlling
data/model-parallel behaviour in Torch.
The key concept is that data/model-parallelism _splits_ along a
dimension, and this class controls the distribution of input and
merging of output along this dimension.
To extend this class, override `_distributeInput` as appropriate.
See `nn.DataParallel` and `nn.ModelParallel` for examples of usage.
]]
local AbstractParallel, parent = torch.class('nn.AbstractParallel',
'nn.Container')
function AbstractParallel:__init(dimension)
if not dimension then
error "must specify a dimension!"
end
parent.__init(self)
self.modules = {}
self.gpu_assignments = {}
self.size = torch.LongStorage()
self.dimension = dimension
self.container_gpuid = cutorch.getDevice()
self.input_gpu = {} -- inputs for each gpu
self.gradOutput_gpu = {} -- inputs for each gpu
self.gradInput_gpu = {} -- gradInput for each gpu
end
function AbstractParallel:_freeCaches()
self.input_gpu = {}
self.gradOutput_gpu = {}
self.gradInput_gpu = {}
end
--[[
This function yields the GPU id for the module to be added.
It can be used for load balancing. It assumes all GPUs are available.
]]
function AbstractParallel:nextGPU()
local gpuid = #self.gpu_assignments % cutorch.getDeviceCount() + 1
return gpuid
end
function AbstractParallel._getBuffer()
local device = cutorch.getDevice()
if not gpu_local_copy_buffers[device] then
gpu_local_copy_buffers[device] = torch.CudaTensor()
end
return gpu_local_copy_buffers[device]
end
function AbstractParallel:add(module, gpuid)
table.insert(self.modules, module)
local gpuid = gpuid or self:nextGPU()
table.insert(self.gpu_assignments, gpuid)
return self
end
function AbstractParallel:get(index)
return self.modules[index]
end
--[[
Asynchronous copy from dest to source.
Use with caution; there needs to be some sort of external synchronization to
prevent source from being modified after this copy is enqueued.
]]
function AbstractParallel:gpuSend(dest, source)
assert(torch.typename(dest) == 'torch.CudaTensor')
assert(torch.typename(source) == 'torch.CudaTensor')
local dest_gpuid = dest:getDevice()
local source_gpuid = source:getDevice()
if source_gpuid == dest_gpuid then
-- if both tensors are on the same gpu normal copy works
withDevice(dest_gpuid, function()
dest:copy(source)
end)
return
end
-- if both tensors are contiguous copy across gpus works
if source:isContiguous() and dest:isContiguous() then
withDevice(dest_gpuid, function() dest:copy(source) end)
return
end
local tmp_source = source
if not source:isContiguous() then
withDevice(source_gpuid, function()
self:_getBuffer():resizeAs(source)
self:_getBuffer():copy(source)
tmp_source = self:_getBuffer()
end)
end
withDevice(dest_gpuid, function()
-- if destination is not contiguous copy across gpus does not
-- work; we need to first copy the source to the dest gpu
if not dest:isContiguous() then
self:_getBuffer():resizeAs(tmp_source)
self:_getBuffer():copy(tmp_source)
dest:copy(self:_getBuffer())
else
dest:copy(tmp_source)
end
end)
end
function AbstractParallel:updateOutput(input)
local container_gpuid = cutorch.getDevice()
local outs = {}
-- distribute the input to GPUs
self:_distributeInput(input)
-- update output for each module.
for i, module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
assert(self.input_gpu[gpuid]:getDevice() ==
self.gpu_assignments[gpuid])
outs[i] = module:updateOutput(self.input_gpu[gpuid])
end)
end
-- find the size of the merged output.
assert(container_gpuid == self.gpu_assignments[1])
assert(outs[1].getDevice and
(outs[1]:getDevice() == 0 or
outs[1]:getDevice() == container_gpuid))
self.size:resize(outs[1]:dim()):copy(outs[1]:size())
for i=2,#outs do
self.size[self.dimension] =
self.size[self.dimension] + outs[i]:size(self.dimension)
end
-- merge (concatenate) the outputs
self.output:resize(self.size)
local offset = 1
for i=1,#outs do
local outputDim = outs[i]:size(self.dimension)
local output_narrowed =
self.output:narrow(self.dimension, offset, outputDim)
self:gpuSend(output_narrowed, outs[i])
offset = offset + outputDim
end
return self.output
end
function AbstractParallel:_distributeGradOutput(_input, gradOutput)
local container_gpuid = cutorch.getDevice()
-- distribute gradOutput chunks to modules
local offset = 1
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
local currentOutput = module.output
-- get the gradOutput chunk for this module
local currentGradOutput =
gradOutput:narrow(self.dimension, offset,
currentOutput:size(self.dimension))
self.gradOutput_gpu[i] = self.gradOutput_gpu[i] or torch.CudaTensor()
self.gradOutput_gpu[i]:resizeAs(currentGradOutput)
if gpuid == container_gpuid then
self.gradOutput_gpu[i]:copy(currentGradOutput)
else
-- copy gradoutput chunk to module's gpu
self:gpuSend(self.gradOutput_gpu[i], currentGradOutput)
end
offset = offset + currentOutput:size(self.dimension)
end)
end
end
function AbstractParallel:updateGradInput(_input, gradOutput)
error('Not implemented')
end
function AbstractParallel:_mixGrads()
end
function AbstractParallel:accGradParameters(_input, _gradOutput, scale)
scale = scale or 1
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
module:accGradParameters(self.input_gpu[gpuid],
self.gradOutput_gpu[i],
scale)
end)
end
-- Combine gradients for data parallel models
self:_mixGrads()
end
function AbstractParallel:accUpdateGradParameters(_input, _gradOutput, lr)
for i,module in ipairs(self.modules) do
local gpuid = self.gpu_assignments[i]
withDevice(gpuid, function()
module:accUpdateGradParameters(self.input_gpu[gpuid], self.gradOutput_gpu[i], lr)
end)
end
end
function AbstractParallel:zeroGradParameters()
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
module:zeroGradParameters()
end)
end
end
function AbstractParallel:updateParameters(learningRate)
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
module:updateParameters(learningRate)
end)
end
end
function AbstractParallel:share(mlp,...)
error("Share is not supported for the AbstractParallel layer.")
end
function AbstractParallel:clone()
local clone = parent.clone(self)
clone:cuda()
return clone
end
function AbstractParallel:reset(stdv)
for i,module in ipairs(self.modules) do
withDevice(self.gpu_assignments[i], function()
self.modules[i]:reset(stdv)
end)
end
end
| bsd-3-clause |
DarkstarProject/darkstar | scripts/zones/Tavnazian_Safehold/npcs/Komalata.lua | 11 | 1326 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Komalata
-- Standard Merchant NPC
-----------------------------------
local ID = require("scripts/zones/Tavnazian_Safehold/IDs")
require("scripts/globals/missions")
require("scripts/globals/shop")
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local stock =
{
4376, 110, -- Meat Jerky
936, 14, -- Rock Salt
611, 36, -- Rye Flour
4509, 10, -- Distilled Water
}
if player:getCurrentMission(COP) >= dsp.mission.id.cop.SHELTERING_DOUBT then
table.insert(stock, 625) -- Apple Vinegar
table.insert(stock, 91)
table.insert(stock, 4364) -- Black Bread
table.insert(stock, 110)
table.insert(stock, 610) -- San d'Orian Flour
table.insert(stock, 55)
table.insert(stock, 4389) -- San d'Orian Carrot
table.insert(stock, 29)
table.insert(stock, 629) -- Millioncorn
table.insert(stock, 44)
table.insert(stock, 1523) -- Apple Mint
table.insert(stock, 290)
end
player:showText(npc, ID.text.KOMALATA_SHOP_DIALOG)
dsp.shop.general(player, stock)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/King_Ranperres_Tomb/mobs/Vrtra.lua | 10 | 1801 | -----------------------------------
-- Area: King Ranperre's Tomb
-- NM: Vrtra
-----------------------------------
require("scripts/globals/status")
require("scripts/globals/titles")
-----------------------------------
local offsets = {1, 3, 5, 2, 4, 6}
function onMobEngaged(mob, target)
mob:resetLocalVars()
end
function onMobFight(mob, target)
local spawnTime = mob:getLocalVar("spawnTime")
local twohourTime = mob:getLocalVar("twohourTime")
local fifteenBlock = mob:getBattleTime() / 15
if twohourTime == 0 then
twohourTime = math.random(4, 6)
mob:setLocalVar("twohourTime", twohourTime)
end
if spawnTime == 0 then
spawnTime = math.random(3, 5)
mob:setLocalVar("spawnTime", spawnTime)
end
if fifteenBlock > twohourTime then
mob:useMobAbility(710)
mob:setLocalVar("twohourTime", fifteenBlock + math.random(4, 6))
elseif fifteenBlock > spawnTime then
local mobId = mob:getID()
for i, offset in ipairs(offsets) do
local pet = GetMobByID(mobId + offset)
if not pet:isSpawned() then
pet:spawn(60)
local pos = mob:getPos()
pet:setPos(pos.x, pos.y, pos.z)
pet:updateEnmity(target)
break
end
end
mob:setLocalVar("spawnTime", fifteenBlock + 4)
end
end
function onMobDisengage(mob, weather)
for i, offset in ipairs(offsets) do
DespawnMob(mob:getID()+offset)
end
end
function onMobDeath(mob, player, isKiller)
player:addTitle(dsp.title.VRTRA_VANQUISHER)
end
function onMobDespawn(mob)
-- Set Vrtra's spawnpoint and respawn time (3-5 days)
UpdateNMSpawnPoint(mob:getID())
mob:setRespawnTime(math.random(259200, 432000))
end
| gpl-3.0 |
alonikomax/RocketUp | liberies/anim8.lua | 1 | 8488 | local anim8 = {
_VERSION = 'anim8 v2.3.0',
_DESCRIPTION = 'An animation library for LÖVE',
_URL = 'https://github.com/kikito/anim8',
_LICENSE = [[
MIT LICENSE
Copyright (c) 2011 Enrique García Cota
Permission is hereby granted, free of charge, to any person obtaining a
copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be included
in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
]]
}
local Grid = {}
local _frames = {}
local function assertPositiveInteger(value, name)
if type(value) ~= 'number' then error(("%s should be a number, was %q"):format(name, tostring(value))) end
if value < 1 then error(("%s should be a positive number, was %d"):format(name, value)) end
if value ~= math.floor(value) then error(("%s should be an integer, was %d"):format(name, value)) end
end
local function createFrame(self, x, y)
local fw, fh = self.frameWidth, self.frameHeight
return love.graphics.newQuad(
self.left + (x-1) * fw + x * self.border,
self.top + (y-1) * fh + y * self.border,
fw,
fh,
self.imageWidth,
self.imageHeight
)
end
local function getGridKey(...)
return table.concat( {...} ,'-' )
end
local function getOrCreateFrame(self, x, y)
if x < 1 or x > self.width or y < 1 or y > self.height then
error(("There is no frame for x=%d, y=%d"):format(x, y))
end
local key = self._key
_frames[key] = _frames[key] or {}
_frames[key][x] = _frames[key][x] or {}
_frames[key][x][y] = _frames[key][x][y] or createFrame(self, x, y)
return _frames[key][x][y]
end
local function parseInterval(str)
if type(str) == "number" then return str,str,1 end
str = str:gsub('%s', '') -- remove spaces
local min, max = str:match("^(%d+)-(%d+)$")
assert(min and max, ("Could not parse interval from %q"):format(str))
min, max = tonumber(min), tonumber(max)
local step = min <= max and 1 or -1
return min, max, step
end
function Grid:getFrames(...)
local result, args = {}, {...}
local minx, maxx, stepx, miny, maxy, stepy
for i=1, #args, 2 do
minx, maxx, stepx = parseInterval(args[i])
miny, maxy, stepy = parseInterval(args[i+1])
for y = miny, maxy, stepy do
for x = minx, maxx, stepx do
result[#result+1] = getOrCreateFrame(self,x,y)
end
end
end
return result
end
local Gridmt = {
__index = Grid,
__call = Grid.getFrames
}
local function newGrid(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
assertPositiveInteger(frameWidth, "frameWidth")
assertPositiveInteger(frameHeight, "frameHeight")
assertPositiveInteger(imageWidth, "imageWidth")
assertPositiveInteger(imageHeight, "imageHeight")
left = left or 0
top = top or 0
border = border or 0
local key = getGridKey(frameWidth, frameHeight, imageWidth, imageHeight, left, top, border)
local grid = setmetatable(
{ frameWidth = frameWidth,
frameHeight = frameHeight,
imageWidth = imageWidth,
imageHeight = imageHeight,
left = left,
top = top,
border = border,
width = math.floor(imageWidth/frameWidth),
height = math.floor(imageHeight/frameHeight),
_key = key
},
Gridmt
)
return grid
end
-----------------------------------------------------------
local Animation = {}
local function cloneArray(arr)
local result = {}
for i=1,#arr do result[i] = arr[i] end
return result
end
local function parseDurations(durations, frameCount)
local result = {}
if type(durations) == 'number' then
for i=1,frameCount do result[i] = durations end
else
local min, max, step
for key,duration in pairs(durations) do
assert(type(duration) == 'number', "The value [" .. tostring(duration) .. "] should be a number")
min, max, step = parseInterval(key)
for i = min,max,step do result[i] = duration end
end
end
if #result < frameCount then
error("The durations table has length of " .. tostring(#result) .. ", but it should be >= " .. tostring(frameCount))
end
return result
end
local function parseIntervals(durations)
local result, time = {0},0
for i=1,#durations do
time = time + durations[i]
result[i+1] = time
end
return result, time
end
local Animationmt = { __index = Animation }
local nop = function() end
local function newAnimation(frames, durations, onLoop)
local td = type(durations);
if (td ~= 'number' or durations <= 0) and td ~= 'table' then
error("durations must be a positive number. Was " .. tostring(durations) )
end
onLoop = onLoop or nop
durations = parseDurations(durations, #frames)
local intervals, totalDuration = parseIntervals(durations)
return setmetatable({
frames = cloneArray(frames),
durations = durations,
intervals = intervals,
totalDuration = totalDuration,
onLoop = onLoop,
timer = 0,
position = 1,
status = "playing",
flippedH = false,
flippedV = false
},
Animationmt
)
end
function Animation:clone()
local newAnim = newAnimation(self.frames, self.durations, self.onLoop)
newAnim.flippedH, newAnim.flippedV = self.flippedH, self.flippedV
return newAnim
end
function Animation:flipH()
self.flippedH = not self.flippedH
return self
end
function Animation:flipV()
self.flippedV = not self.flippedV
return self
end
local function seekFrameIndex(intervals, timer)
local high, low, i = #intervals-1, 1, 1
while(low <= high) do
i = math.floor((low + high) / 2)
if timer > intervals[i+1] then low = i + 1
elseif timer <= intervals[i] then high = i - 1
else
return i
end
end
return i
end
function Animation:update(dt)
if self.status ~= "playing" then return end
self.timer = self.timer + dt
local loops = math.floor(self.timer / self.totalDuration)
if loops ~= 0 then
self.timer = self.timer - self.totalDuration * loops
local f = type(self.onLoop) == 'function' and self.onLoop or self[self.onLoop]
f(self, loops)
end
self.position = seekFrameIndex(self.intervals, self.timer)
end
function Animation:pause()
self.status = "paused"
end
function Animation:gotoFrame(position)
self.position = position
self.timer = self.intervals[self.position]
end
function Animation:pauseAtEnd()
self.position = #self.frames
self.timer = self.totalDuration
self:pause()
end
function Animation:pauseAtStart()
self.position = 1
self.timer = 0
self:pause()
end
function Animation:resume()
self.status = "playing"
end
function Animation:draw(image, x, y, r, sx, sy, ox, oy, kx, ky)
love.graphics.draw(image, self:getFrameInfo(x, y, r, sx, sy, ox, oy, kx, ky))
end
function Animation:getFrameInfo(x, y, r, sx, sy, ox, oy, kx, ky)
local frame = self.frames[self.position]
if self.flippedH or self.flippedV then
r,sx,sy,ox,oy,kx,ky = r or 0, sx or 1, sy or 1, ox or 0, oy or 0, kx or 0, ky or 0
local _,_,w,h = frame:getViewport()
if self.flippedH then
sx = sx * -1
ox = w - ox
kx = kx * -1
ky = ky * -1
end
if self.flippedV then
sy = sy * -1
oy = h - oy
kx = kx * -1
ky = ky * -1
end
end
return frame, x, y, r, sx, sy, ox, oy, kx, ky
end
function Animation:getDimensions()
local _,_,w,h = self.frames[self.position]:getViewport()
return w,h
end
-----------------------------------------------------------
anim8.newGrid = newGrid
anim8.newAnimation = newAnimation
return anim8
| mit |
DarkstarProject/darkstar | scripts/globals/spells/cure_iv.lua | 6 | 4999 | -----------------------------------------
-- Spell: Cure IV
-- Restores target's HP.
-----------------------------------------
require("scripts/globals/settings")
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 divisor = 0
local constant = 0
local basepower = 0
local power = 0
local basecure = 0
local final = 0
local minCure = 270
if (USE_OLD_CURE_FORMULA == true) then
power = getCurePowerOld(caster)
divisor = 0.6666
constant = 165
if (power > 460) then
divisor = 6.5
constant = 354.6666
elseif (power > 220) then
divisor = 2
constant = 275
end
else
power = getCurePower(caster)
if (power < 200) then
divisor = 1
constant = 270
basepower = 70
elseif (power < 300) then
divisor = 2
constant = 400
basepower = 200
elseif (power < 400) then
divisor = 10/7
constant = 450
basepower = 300
elseif (power < 700) then
divisor = 2.5
constant = 520
basepower = 400
else
divisor = 999999
constant = 640
basepower = 0
end
end
if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == dsp.objType.PC or target:getObjType() == dsp.objType.MOB)) then
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant)
else
basecure = getBaseCure(power,divisor,constant,basepower)
end
final = getCureFinal(caster,spell,basecure,minCure,false)
if (caster:hasStatusEffect(dsp.effect.AFFLATUS_SOLACE) and target:hasStatusEffect(dsp.effect.STONESKIN) == false) then
local solaceStoneskin = 0
local equippedBody = caster:getEquipID(dsp.slot.BODY)
if (equippedBody == 11186) then
solaceStoneskin = math.floor(final * 0.30)
elseif (equippedBody == 11086) then
solaceStoneskin = math.floor(final * 0.35)
else
solaceStoneskin = math.floor(final * 0.25)
end
solaceStoneskin = solaceStoneskin * (1 + caster:getMerit(dsp.merit.ANIMUS_SOLACE)/100)
target:addStatusEffect(dsp.effect.STONESKIN,solaceStoneskin,0,25,0,0,1)
end
final = final + (final * (target:getMod(dsp.mod.CURE_POTENCY_RCVD)/100))
--Applying server mods....
final = final * CURE_POWER
local diff = (target:getMaxHP() - target:getHP())
if (final > diff) then
final = diff
end
target:addHP(final)
target:wakeUp()
caster:updateEnmityFromCure(target,final)
else
if (target:isUndead()) then
spell:setMsg(dsp.msg.basic.MAGIC_DMG)
local params = {}
params.dmg = minCure
params.multiplier = 1
params.skillType = dsp.skill.HEALING_MAGIC
params.attribute = dsp.mod.MND
params.hasMultipleTargetReduction = false
local dmg = calculateMagicDamage(caster, target, spell, params)*0.5
local params = {}
params.diff = caster:getStat(dsp.mod.MND)-target:getStat(dsp.mod.MND)
params.attribute = dsp.mod.MND
params.skillType = dsp.skill.HEALING_MAGIC
params.bonus = 1.0
local resist = applyResistance(caster, target, spell, params)
dmg = dmg*resist
dmg = addBonuses(caster,spell,target,dmg)
dmg = adjustForTarget(target,dmg,spell:getElement())
dmg = finalMagicAdjustments(caster,target,spell,dmg)
final = dmg
target:takeDamage(final, caster, dsp.attackType.MAGICAL, dsp.damageType.LIGHT)
target:updateEnmityFromDamage(caster,final)
elseif (caster:getObjType() == dsp.objType.PC) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
else
-- e.g. monsters healing themselves.
if (USE_OLD_CURE_FORMULA == true) then
basecure = getBaseCureOld(power,divisor,constant)
else
basecure = getBaseCure(power,divisor,constant,basepower)
end
final = getCureFinal(caster,spell,basecure,minCure,false)
local diff = (target:getMaxHP() - target:getHP())
if (final > diff) then
final = diff
end
target:addHP(final)
end
end
local mpBonusPercent = (final*caster:getMod(dsp.mod.CURE2MP_PERCENT))/100
if (mpBonusPercent > 0) then
caster:addMP(mpBonusPercent)
end
return final
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Windurst_Woods/npcs/Bopa_Greso.lua | 9 | 1153 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Bopa Greso
-- Type: Standard NPC
-- !pos 59.773 -6.249 216.766 241
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player,npc,trade)
end
function onTrigger(player,npc)
local thickAsThieves = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.AS_THICK_AS_THIEVES)
local thickAsThievesCS = player:getCharVar("thickAsThievesCS")
if thickAsThieves == QUEST_ACCEPTED then
player:startEvent(506)
if thickAsThievesCS == 1 then
player:setCharVar("thickAsThievesCS", 2)
elseif thickAsThievesCS == 3 then
player:setCharVar("thickAsThievesCS", 4)
local rand1 = math.random(2, 7)
player:setCharVar("thickAsThievesGrapplingCS", rand1)
player:setCharVar("thickAsThievesGamblingCS", 1)
end
else
player:startEvent(77) -- standard cs
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
marcel-sch/luci | applications/luci-app-diag-devinfo/luasrc/model/cbi/luci_diag/smap_devinfo_config.lua | 61 | 1072 | -- Copyright 2009 Daniel Dickinson
-- Licensed to the public under the Apache License 2.0.
require("luci.controller.luci_diag.devinfo_common")
m = Map("luci_devinfo", translate("SIP Device Scanning Configuration"), translate("Configure scanning for supported SIP devices on specified networks. Decreasing \'Timeout\', \'Repeat Count\', and/or \'Sleep Between Requests\' may speed up scans, but also may fail to find some devices."))
s = m:section(SimpleSection, "", translate("Use Configuration"))
b = s:option(DummyValue, "_scans", translate("Perform Scans (this can take a few minutes)"))
b.value = ""
b.titleref = luci.dispatcher.build_url("admin", "status", "smap_devinfo")
scannet = m:section(TypedSection, "smap_scannet", translate("Scanning Configuration"), translate("Networks to scan for supported devices"))
scannet.addremove = true
scannet.anonymous = false
local ports
ports = scannet:option(Value, "ports", translate("Ports"))
ports.optional = true
ports.rmempty = true
luci.controller.luci_diag.devinfo_common.config_devinfo_scan(m, scannet)
return m
| apache-2.0 |
ungarscool1/HL2RP | hl2rp/gamemode/modules/language/sh_interface.lua | 13 | 4169 | DarkRP.addLanguage = DarkRP.stub{
name = "addLanguage",
description = "Create a language/translation.",
parameters = {
{
name = "Language name",
description = "The short name of the language (\"en\" is English). Make sure the language name fits a possible value for gmod_language!",
type = "string",
optional = false
},
{
name = "Language contents",
description = "A table that contains the translation sentences. Look at sh_english.lua for an example.",
type = "table",
optional = false
}
},
returns = {
},
metatable = DarkRP
}
DarkRP.addPhrase = DarkRP.stub{
name = "addPhrase",
description = "Add a phrase to the existing translation.",
parameters = {
{
name = "Language name",
description = "The short name of the language (\"en\" is English). Make sure the language name fits a possible value for gmod_language!",
type = "string",
optional = false
},
{
name = "key",
description = "The name of the translated phrase.",
type = "string",
optional = false
},
{
name = "translation",
description = "The translation of the phrase.",
type = "string",
optional = false
}
},
returns = {
},
metatable = DarkRP
}
DarkRP.getPhrase = DarkRP.stub{
name = "getPhrase",
description = "Get a phrase from the selected language.",
parameters = {
{
name = "key",
description = "The name of the translated phrase.",
type = "string",
optional = false
},
{
name = "Phrase parameters",
description = "Some phrases need extra information, like in \"PLAYERNAME just won the lottery!\". Not filling in the phrase parameters will cause errors.",
type = "vararg",
optional = false
}
},
returns = {
{
name = "phrase",
description = "The formatted phrase.",
type = "string"
}
},
metatable = DarkRP
}
DarkRP.getMissingPhrases = DarkRP.stub{
name = "getMissingPhrases",
description = "Get all the phrases a language is missing.",
parameters = {
{
name = "languageCode",
description = "The language code of the language. For English this is \"en\".",
type = "string",
optional = true
}
},
returns = {
{
name = "missingPhrases",
description = "All the missing phrases formatted in such way that you can copy and paste it in your language file.",
type = "string"
}
},
metatable = DarkRP
}
DarkRP.addChatCommandsLanguage = DarkRP.stub{
name = "addChatCommandsLanguage",
description = "Add a translation table for chat command descriptions. See darkrpmod/lua/darkrp_language/chatcommands.lua for an example.",
parameters = {
{
name = "languageCode",
description = "The language code of the language. For English this is \"en\".",
type = "string",
optional = false
},
{
name = "translations",
description = "Key-value table with chat command strings as keys and their translation as value.",
type = "table",
optional = false
}
},
returns = {
},
metatable = DarkRP
}
DarkRP.getChatCommandDescription = DarkRP.stub{
name = "getChatCommandDescription",
description = "Get the translated description of a chat command.",
parameters = {
{
name = "command",
description = "The chat command string.",
type = "string",
optional = false
}
},
returns = {
{
name = "description",
description = "The translated chat command description.",
type = "string"
}
},
metatable = DarkRP
}
| agpl-3.0 |
8devices/carambola2-luci | applications/luci-statistics/luasrc/model/cbi/luci_statistics/iwinfo.lua | 78 | 1089 | --[[
Luci configuration model for statistics - collectd interface plugin configuration
(c) 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 m, s, o
m = Map("luci_statistics",
translate("Wireless iwinfo Plugin Configuration"),
translate("The iwinfo plugin collects statistics about wireless signal strength, noise and quality."))
s = m:section(NamedSection, "collectd_iwinfo", "luci_statistics")
o = s:option(Flag, "enable", translate("Enable this plugin"))
o.default = 0
o = s:option(Value, "Interfaces", translate("Monitor interfaces"),
translate("Leave unselected to automatically determine interfaces to monitor."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
o:depends("enable", 1)
o = s:option(Flag, "IgnoreSelected", translate("Monitor all except specified"))
o.default = 0
o:depends("enable", 1)
return m
| apache-2.0 |
marcel-sch/luci | protocols/luci-proto-ppp/luasrc/model/cbi/admin_network/proto_ppp.lua | 47 | 3692 | -- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local map, section, net = ...
local device, username, password
local ipv6, defaultroute, metric, peerdns, dns,
keepalive_failure, keepalive_interval, demand, mtu
device = section:taboption("general", Value, "device", translate("Modem device"))
device.rmempty = false
local device_suggestions = nixio.fs.glob("/dev/tty*S*")
or nixio.fs.glob("/dev/tts/*")
if device_suggestions then
local node
for node in device_suggestions do
device:value(node)
end
end
username = section:taboption("general", Value, "username", translate("PAP/CHAP username"))
password = section:taboption("general", Value, "password", translate("PAP/CHAP password"))
password.password = true
if luci.model.network:has_ipv6() then
ipv6 = section:taboption("advanced", ListValue, "ipv6")
ipv6:value("auto", translate("Automatic"))
ipv6:value("0", translate("Disabled"))
ipv6:value("1", translate("Manual"))
ipv6.default = "auto"
end
defaultroute = section:taboption("advanced", Flag, "defaultroute",
translate("Use default gateway"),
translate("If unchecked, no default route is configured"))
defaultroute.default = defaultroute.enabled
metric = section:taboption("advanced", Value, "metric",
translate("Use gateway metric"))
metric.placeholder = "0"
metric.datatype = "uinteger"
metric:depends("defaultroute", defaultroute.enabled)
peerdns = section:taboption("advanced", Flag, "peerdns",
translate("Use DNS servers advertised by peer"),
translate("If unchecked, the advertised DNS server addresses are ignored"))
peerdns.default = peerdns.enabled
dns = section:taboption("advanced", DynamicList, "dns",
translate("Use custom DNS servers"))
dns:depends("peerdns", "")
dns.datatype = "ipaddr"
dns.cast = "string"
keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure",
translate("LCP echo failure threshold"),
translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures"))
function keepalive_failure.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^(%d+)[ ,]+%d+") or v)
end
end
keepalive_failure.placeholder = "0"
keepalive_failure.datatype = "uinteger"
keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval",
translate("LCP echo interval"),
translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold"))
function keepalive_interval.cfgvalue(self, section)
local v = m:get(section, "keepalive")
if v and #v > 0 then
return tonumber(v:match("^%d+[ ,]+(%d+)"))
end
end
function keepalive_interval.write(self, section, value)
local f = tonumber(keepalive_failure:formvalue(section)) or 0
local i = tonumber(value) or 5
if i < 1 then i = 1 end
if f > 0 then
m:set(section, "keepalive", "%d %d" %{ f, i })
else
m:del(section, "keepalive")
end
end
keepalive_interval.remove = keepalive_interval.write
keepalive_failure.write = keepalive_interval.write
keepalive_failure.remove = keepalive_interval.write
keepalive_interval.placeholder = "5"
keepalive_interval.datatype = "min(1)"
demand = section:taboption("advanced", Value, "demand",
translate("Inactivity timeout"),
translate("Close inactive connection after the given amount of seconds, use 0 to persist connection"))
demand.placeholder = "0"
demand.datatype = "uinteger"
mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU"))
mtu.placeholder = "1500"
mtu.datatype = "max(9200)"
| apache-2.0 |
Fenix-XI/Fenix | scripts/zones/Qufim_Island/npcs/Matica_RK.lua | 13 | 3323 | -----------------------------------
-- Area: Qufim Island
-- NPC: Matica, R.K.
-- Type: Border Conquest Guards
-- @pos 179.093 -21.575 -15.282 126
-----------------------------------
package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Qufim_Island/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = QUFIMISLAND;
local csid = 0x7ffa;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
gdewald/Sputter | dev/premake/premake/tests/test_string.lua | 84 | 1550 | --
-- tests/test_string.lua
-- Automated test suite for the new string functions.
-- Copyright (c) 2008 Jason Perkins and the Premake project
--
T.string = { }
--
-- string.endswith() tests
--
function T.string.endswith_ReturnsTrue_OnMatch()
test.istrue(string.endswith("Abcdef", "def"))
end
function T.string.endswith_ReturnsFalse_OnMismatch()
test.isfalse(string.endswith("Abcedf", "efg"))
end
function T.string.endswith_ReturnsFalse_OnLongerNeedle()
test.isfalse(string.endswith("Abc", "Abcdef"))
end
function T.string.endswith_ReturnsFalse_OnNilHaystack()
test.isfalse(string.endswith(nil, "ghi"))
end
function T.string.endswith_ReturnsFalse_OnNilNeedle()
test.isfalse(string.endswith("Abc", nil))
end
function T.string.endswith_ReturnsTrue_OnExactMatch()
test.istrue(string.endswith("/", "/"))
end
--
-- string.explode() tests
--
function T.string.explode_ReturnsParts_OnValidCall()
test.isequal({"aaa","bbb","ccc"}, string.explode("aaa/bbb/ccc", "/", true))
end
--
-- string.startswith() tests
--
function T.string.startswith_OnMatch()
test.istrue(string.startswith("Abcdef", "Abc"))
end
function T.string.startswith_OnMismatch()
test.isfalse(string.startswith("Abcdef", "ghi"))
end
function T.string.startswith_OnLongerNeedle()
test.isfalse(string.startswith("Abc", "Abcdef"))
end
function T.string.startswith_OnEmptyHaystack()
test.isfalse(string.startswith("", "Abc"))
end
function T.string.startswith_OnEmptyNeedle()
test.istrue(string.startswith("Abcdef", ""))
end
| mit |
gdewald/Sputter | dev/premake/premake/tests/actions/vstudio/vc2010/test_filters.lua | 47 | 4151 | --
-- tests/actions/vstudio/vc2010/test_filters.lua
-- Validate generation of filter blocks in Visual Studio 2010 C/C++ projects.
-- Copyright (c) 2011 Jason Perkins and the Premake project
--
T.vs2010_filters = { }
local suite = T.vs2010_filters
local vc2010 = premake.vstudio.vc2010
--
-- Setup/teardown
--
local sln, prj
local os_uuid
function suite.setup()
os_uuid = os.uuid
os.uuid = function() return "00112233-4455-6677-8888-99AABBCCDDEE" end
_ACTION = "vs2010"
sln, prj = test.createsolution()
end
function suite.teardown()
os.uuid = os_uuid
end
local function prepare()
premake.bake.buildconfigs()
sln.vstudio_configs = premake.vstudio.buildconfigs(sln)
end
--
-- Filter identifiers sections
--
function suite.UniqueIdentifiers_IsEmpty_OnRootFilesOnly()
files { "hello.c", "goodbye.c" }
prepare()
vc2010.filteridgroup(prj)
test.isemptycapture()
end
function suite.UniqueIdentifiers_MergeCommonSubfolders()
files { "src/hello.c", "src/goodbye.c" }
prepare()
vc2010.filteridgroup(prj)
test.capture [[
<ItemGroup>
<Filter Include="src">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
</ItemGroup>
]]
end
function suite.UniqueIdentifiers_ListAllSubfolders()
files { "src/hello.c", "src/departures/goodbye.c" }
prepare()
vc2010.filteridgroup(prj)
test.capture [[
<ItemGroup>
<Filter Include="src">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
<Filter Include="src\departures">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
</ItemGroup>
]]
end
function suite.UniqueIdentifiers_ListVpaths()
files { "hello.c", "goodbye.c" }
vpaths { ["Source Files"] = "**.c" }
prepare()
vc2010.filteridgroup(prj)
test.capture [[
<ItemGroup>
<Filter Include="Source Files">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
</ItemGroup>
]]
end
function suite.UniqueIdentifiers_ListRealAndVpaths()
files { "hello.h", "goodbye.c" }
vpaths { ["Source Files"] = "*.c", ["Header Files"] = "*.h" }
prepare()
vc2010.filteridgroup(prj)
test.capture [[
<ItemGroup>
<Filter Include="Header Files">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
<Filter Include="Source Files">
<UniqueIdentifier>{00112233-4455-6677-8888-99AABBCCDDEE}</UniqueIdentifier>
</Filter>
</ItemGroup>
]]
end
--
-- File/filter assignment tests
--
function suite.FileFilters_NoFilter_OnRootFile()
files { "hello.c", "goodbye.c" }
prepare()
vc2010.filefiltergroup(prj, "ClCompile")
test.capture [[
<ItemGroup>
<ClCompile Include="hello.c" />
<ClCompile Include="goodbye.c" />
</ItemGroup>
]]
end
function suite.FileFilters_NoFilter_OnRealPath()
files { "src/hello.c" }
prepare()
vc2010.filefiltergroup(prj, "ClCompile")
test.capture [[
<ItemGroup>
<ClCompile Include="src\hello.c">
<Filter>src</Filter>
</ClCompile>
</ItemGroup>
]]
end
function suite.FileFilters_HasFilter_OnVpath()
files { "src/hello.c" }
vpaths { ["Source Files"] = "**.c" }
prepare()
vc2010.filefiltergroup(prj, "ClCompile")
test.capture [[
<ItemGroup>
<ClCompile Include="src\hello.c">
<Filter>Source Files</Filter>
</ClCompile>
</ItemGroup>
]]
end
function suite.FileFilters_OnIncludeSection()
files { "hello.c", "hello.h", "hello.rc", "hello.txt" }
prepare()
vc2010.filefiltergroup(prj, "ClInclude")
test.capture [[
<ItemGroup>
<ClInclude Include="hello.h" />
</ItemGroup>
]]
end
function suite.FileFilters_OnResourceSection()
files { "hello.c", "hello.h", "hello.rc", "hello.txt" }
prepare()
vc2010.filefiltergroup(prj, "ResourceCompile")
test.capture [[
<ItemGroup>
<ResourceCompile Include="hello.rc" />
</ItemGroup>
]]
end
function suite.FileFilters_OnNoneSection()
files { "hello.c", "hello.h", "hello.rc", "hello.txt" }
prepare()
vc2010.filefiltergroup(prj, "None")
test.capture [[
<ItemGroup>
<None Include="hello.txt" />
</ItemGroup>
]]
end
| mit |
crunchuser/prosody-modules | mod_statsd/mod_statsd.lua | 32 | 2429 | -- Log common stats to statsd
--
-- Copyright (C) 2014 Daurnimator
--
-- This module is MIT/X11 licensed.
local socket = require "socket"
local iterators = require "util.iterators"
local jid = require "util.jid"
local options = module:get_option("statsd") or {}
-- Create UDP socket to statsd server
local sock = socket.udp()
sock:setpeername(options.hostname or "127.0.0.1", options.port or 8125)
-- Metrics are namespaced by ".", and seperated by newline
function clean(s) return (s:gsub("[%.:\n]", "_")) end
-- A 'safer' send function to expose
function send(s) return sock:send(s) end
-- prefix should end in "."
local prefix = (options.prefix or "prosody") .. "."
if not options.no_host then
prefix = prefix .. clean(module.host) .. "."
end
-- Track users as they bind/unbind
-- count bare sessions every time, as we have no way to tell if it's a new bare session or not
module:hook("resource-bind", function(event)
send(prefix.."bare_sessions:"..iterators.count(pairs(bare_sessions)).."|g")
send(prefix.."full_sessions:+1|g")
end, 1)
module:hook("resource-unbind", function(event)
send(prefix.."bare_sessions:"..iterators.count(pairs(bare_sessions)).."|g")
send(prefix.."full_sessions:-1|g")
end, 1)
-- Track MUC occupants as they join/leave
module:hook("muc-occupant-joined", function(event)
send(prefix.."n_occupants:+1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:+1|g")
end)
module:hook("muc-occupant-left", function(event)
send(prefix.."n_occupants:-1|g")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".occupants:-1|g")
end)
-- Misc other MUC
module:hook("muc-broadcast-message", function(event)
send(prefix.."broadcast-message:1|c")
local room_node = jid.split(event.room.jid)
send(prefix..clean(room_node)..".broadcast-message:1|c")
end)
module:hook("muc-invite", function(event)
-- Total count
send(prefix.."invite:1|c")
local room_node = jid.split(event.room.jid)
-- Counts per room
send(prefix..clean(room_node)..".invite:1|c")
-- Counts per recipient
send(prefix..clean(event.stanza.attr.to)..".invited:1|c")
end)
module:hook("muc-decline", function(event)
-- Total count
send(prefix.."decline:1|c")
local room_node = jid.split(event.room.jid)
-- Counts per room
send(prefix..clean(room_node)..".decline:1|c")
-- Counts per sender
send(prefix..clean(event.incoming.attr.from)..".declined:1|c")
end)
| mit |
Fenix-XI/Fenix | scripts/globals/items/bowl_of_witch_stew.lua | 18 | 1449 | -----------------------------------------
-- ID: 4344
-- Item: witch_stew
-- Food Effect: 4hours, All Races
-----------------------------------------
-- Magic Points 45
-- Strength -1
-- Mind 4
-- MP Recovered While Healing 4
-- Enmity -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4344);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 45);
target:addMod(MOD_STR, -1);
target:addMod(MOD_MND, 4);
target:addMod(MOD_MPHEAL, 4);
target:addMod(MOD_ENMITY, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 45);
target:delMod(MOD_STR, -1);
target:delMod(MOD_MND, 4);
target:delMod(MOD_MPHEAL, 4);
target:delMod(MOD_ENMITY, -4);
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Lower_Jeuno/npcs/Zauko.lua | 1 | 5484 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Zauko
-- Involved in Quests: Save the Clock Tower, Community Service
-- @zone 245
-- @pos -3 0 11
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/titles");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
----- Save The Clock Tower Quest -----
if (trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz2"); -- NPC Zone2
if (a == 0 or (a ~= 256 and a ~= 288 and a ~= 320 and a ~= 384 and a ~= 768 and a ~= 352 and a ~= 896 and a ~= 416 and
a ~= 832 and a ~= 448 and a ~= 800 and a ~= 480 and a ~= 864 and a ~= 928 and a ~= 960 and a ~= 992)) then
player:startEvent(0x0032,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hour = VanadielHour();
local cService = player:getVar("cService");
questServerVar = GetServerVariable("[JEUNO]CommService");
----- Community Service Quest -----
-- The reason for all the Default Dialogue "else"s is because of all the different checks needed and to keep default dialogue
-- If they're not there then the player will keep triggering the Quest Complete (Repeat) Cutscene
-- Please leave them here unless you can find a way to fix this but the quest as it should do.
-- Quest Start --
if (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_AVAILABLE and player:getFameLevel(JEUNO) >=1) then
if (hour >= 18 and hour < 21) then
if (questServerVar == 0) then
player:startEvent(0x0074,questServerVar+1); -- Quest Start Dialogue (NOTE: The Cutscene says somebody else is working on it but it still adds the quest)
else
player:startEvent(0x0074,questServerVar);
end
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_ACCEPTED) then
if (cService >= 1 and cService < 12 == true) then -- If the quest is accepted but all lamps are NOT lit
if (hour >= 18 and hour < 23) then
player:startEvent(0x0077); -- Task Failed Dialogue
else
player:startEvent(0x0076);
end
-- Quest Complete --
else
player:startEvent(0x0075); -- Quest Complete Dialogue
end
-- Repeat Quest --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 18) then
if (hour >= 18 and hour < 21) then
player:startEvent(0x0074,1) -- Quest Start (Repeat)
else
player:startEvent(0x0076); -- Default Dialogue
end
-- Repeat Quest Task Failed --
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED) then
if (cService >= 14 and cService < 24 == true) then
if (hour >= 18 and hour < 23) then -- If Quest Repeat is accepted but lamps are not lit
player:startEvent(0x0077); -- Task Failed Dialogue
end
elseif (player:getQuestStatus(JEUNO,COMMUNITY_SERVICE) == QUEST_COMPLETED and cService == 0) then
player:startEvent(0x0076);
-- Repeat Quest Complete --
else
player:startEvent(0x0071); -- Quest Complete (Repeat)
end
else
player:startEvent(0x0076);
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);
-- ClockTower Quest --
if (csid == 0x0032) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz2",player:getVar("saveTheClockTowerNPCz2") + 256);
---- Community Service Quest ----
elseif (csid == 0x0074 and option == 0) then -- Quest Start
if (questServerVar == 0) then
player:addQuest(JEUNO,COMMUNITY_SERVICE);
SetServerVariable("[JEUNO]CommService",1);
end
elseif (csid == 0x0075) then -- Quest Finish
player:completeQuest(JEUNO,COMMUNITY_SERVICE);
player:addFame(JEUNO,30);
player:setVar("cService",13)
player:addTitle(TORCHBEARER);
elseif (csid == 0x0071) then -- Quest Finish (Repeat)
player:addKeyItem(LAMP_LIGHTERS_MEMBERSHIP_CARD); -- Lamp Lighter's Membership Card
player:messageSpecial(KEYITEM_OBTAINED,LAMP_LIGHTERS_MEMBERSHIP_CARD);
player:addFame(JEUNO,15);
player:setVar("cService",0);
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Upper_Jeuno/npcs/Zekobi-Morokobi.lua | 13 | 1053 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Zekobi-Morokobi
-- Type: Standard NPC
-- @zone: 244
-- @pos 41.258 -5.999 -74.105
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0057);
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 |
eugeneia/snabbswitch | lib/ljsyscall/syscall/netbsd/fcntl.lua | 24 | 1318 | -- NetBSD fcntl
local require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string =
require, error, assert, tonumber, tostring,
setmetatable, pairs, ipairs, unpack, rawget, rawset,
pcall, type, table, string
local function init(types)
local c = require "syscall.netbsd.constants"
local ffi = require "ffi"
local t, pt, s = types.t, types.pt, types.s
local h = require "syscall.helpers"
local ctobool, booltoc = h.ctobool, h.booltoc
local fcntl = {
commands = {
[c.F.SETFL] = function(arg) return c.O[arg] end,
[c.F.SETFD] = function(arg) return c.FD[arg] end,
[c.F.GETLK] = t.flock,
[c.F.SETLK] = t.flock,
[c.F.SETLKW] = t.flock,
[c.F.SETNOSIGPIPE] = function(arg) return booltoc(arg) end,
},
ret = {
[c.F.DUPFD] = function(ret) return t.fd(ret) end,
[c.F.DUPFD_CLOEXEC] = function(ret) return t.fd(ret) end,
[c.F.GETFD] = function(ret) return tonumber(ret) end,
[c.F.GETFL] = function(ret) return tonumber(ret) end,
[c.F.GETOWN] = function(ret) return tonumber(ret) end,
[c.F.GETLK] = function(ret, arg) return arg end,
[c.F.MAXFD] = function(ret) return tonumber(ret) end,
[c.F.GETNOSIGPIPE] = function(ret) return ctobool(ret) end,
}
}
return fcntl
end
return {init = init}
| apache-2.0 |
Fenix-XI/Fenix | scripts/zones/Cape_Teriggan/npcs/Salimardi_RK.lua | 13 | 3309 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Bright Moon
-- Type: Outpost Conquest Guards
-- @pos -185 7 -63 113
-----------------------------------
package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Cape_Teriggan/TextIDs");
local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = VOLLBOW;
local csid = 0x7ffb;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
U-MA/mal | lua/step9_try.lua | 40 | 5971 | #!/usr/bin/env lua
local table = require('table')
local readline = require('readline')
local utils = require('utils')
local types = require('types')
local reader = require('reader')
local printer = require('printer')
local Env = require('env')
local core = require('core')
local List, Vector, HashMap = types.List, types.Vector, types.HashMap
-- read
function READ(str)
return reader.read_str(str)
end
-- eval
function is_pair(x)
return types._sequential_Q(x) and #x > 0
end
function quasiquote(ast)
if not is_pair(ast) then
return types.List:new({types.Symbol:new("quote"), ast})
elseif types._symbol_Q(ast[1]) and ast[1].val == 'unquote' then
return ast[2]
elseif is_pair(ast[1]) and
types._symbol_Q(ast[1][1]) and
ast[1][1].val == 'splice-unquote' then
return types.List:new({types.Symbol:new("concat"),
ast[1][2],
quasiquote(ast:slice(2))})
else
return types.List:new({types.Symbol:new("cons"),
quasiquote(ast[1]),
quasiquote(ast:slice(2))})
end
end
function is_macro_call(ast, env)
if types._list_Q(ast) and
types._symbol_Q(ast[1]) and
env:find(ast[1]) then
local f = env:get(ast[1])
return types._malfunc_Q(f) and f.ismacro
end
end
function macroexpand(ast, env)
while is_macro_call(ast, env) do
local mac = env:get(ast[1])
ast = mac.fn(unpack(ast:slice(2)))
end
return ast
end
function eval_ast(ast, env)
if types._symbol_Q(ast) then
return env:get(ast)
elseif types._list_Q(ast) then
return List:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._vector_Q(ast) then
return Vector:new(utils.map(function(x) return EVAL(x,env) end,ast))
elseif types._hash_map_Q(ast) then
local new_hm = {}
for k,v in pairs(ast) do
new_hm[EVAL(k, env)] = EVAL(v, env)
end
return HashMap:new(new_hm)
else
return ast
end
end
function EVAL(ast, env)
while true do
--print("EVAL: "..printer._pr_str(ast,true))
if not types._list_Q(ast) then return eval_ast(ast, env) end
-- apply list
ast = macroexpand(ast, env)
if not types._list_Q(ast) then return ast end
local a0,a1,a2,a3 = ast[1], ast[2],ast[3],ast[4]
local a0sym = types._symbol_Q(a0) and a0.val or ""
if 'def!' == a0sym then
return env:set(a1, EVAL(a2, env))
elseif 'let*' == a0sym then
local let_env = Env:new(env)
for i = 1,#a1,2 do
let_env:set(a1[i], EVAL(a1[i+1], let_env))
end
env = let_env
ast = a2 -- TCO
elseif 'quote' == a0sym then
return a1
elseif 'quasiquote' == a0sym then
ast = quasiquote(a1) -- TCO
elseif 'defmacro!' == a0sym then
local mac = EVAL(a2, env)
mac.ismacro = true
return env:set(a1, mac)
elseif 'macroexpand' == a0sym then
return macroexpand(a1, env)
elseif 'try*' == a0sym then
local exc, result = nil, nil
xpcall(function()
result = EVAL(a1, env)
end, function(err)
exc = err
end)
if exc ~= nil then
if types._malexception_Q(exc) then
exc = exc.val
end
if a2 and a2[1].val == 'catch*' then
result = EVAL(a2[3], Env:new(env, {a2[2]}, {exc}))
else
types.throw(exc)
end
end
return result
elseif 'do' == a0sym then
local el = eval_ast(ast:slice(2,#ast-1), env)
ast = ast[#ast] -- TCO
elseif 'if' == a0sym then
local cond = EVAL(a1, env)
if cond == types.Nil or cond == false then
if a3 then ast = a3 else return types.Nil end -- TCO
else
ast = a2 -- TCO
end
elseif 'fn*' == a0sym then
return types.MalFunc:new(function(...)
return EVAL(a2, Env:new(env, a1, arg))
end, a2, env, a1)
else
local args = eval_ast(ast, env)
local f = table.remove(args, 1)
if types._malfunc_Q(f) then
ast = f.ast
env = Env:new(f.env, f.params, args) -- TCO
else
return f(unpack(args))
end
end
end
end
-- print
function PRINT(exp)
return printer._pr_str(exp, true)
end
-- repl
local repl_env = Env:new()
function rep(str)
return PRINT(EVAL(READ(str),repl_env))
end
-- core.lua: defined using Lua
for k,v in pairs(core.ns) do
repl_env:set(types.Symbol:new(k), v)
end
repl_env:set(types.Symbol:new('eval'),
function(ast) return EVAL(ast, repl_env) end)
repl_env:set(types.Symbol:new('*ARGV*'), types.List:new(types.slice(arg,2)))
-- core.mal: defined using mal
rep("(def! not (fn* (a) (if a false true)))")
rep("(def! load-file (fn* (f) (eval (read-string (str \"(do \" (slurp f) \")\")))))")
rep("(defmacro! cond (fn* (& xs) (if (> (count xs) 0) (list 'if (first xs) (if (> (count xs) 1) (nth xs 1) (throw \"odd number of forms to cond\")) (cons 'cond (rest (rest xs)))))))")
rep("(defmacro! or (fn* (& xs) (if (empty? xs) nil (if (= 1 (count xs)) (first xs) `(let* (or_FIXME ~(first xs)) (if or_FIXME or_FIXME (or ~@(rest xs))))))))")
function print_exception(exc)
if exc then
if types._malexception_Q(exc) then
exc = printer._pr_str(exc.val, true)
end
print("Error: " .. exc)
print(debug.traceback())
end
end
if #arg > 0 and arg[1] == "--raw" then
readline.raw = true
table.remove(arg,1)
end
if #arg > 0 then
xpcall(function() rep("(load-file \""..arg[1].."\")") end,
print_exception)
os.exit(0)
end
while true do
line = readline.readline("user> ")
if not line then break end
xpcall(function() print(rep(line)) end,
print_exception)
end
| mpl-2.0 |
DarkstarProject/darkstar | scripts/globals/aftermath.lua | 11 | 15721 | -----------------------------------
-- Aftermath handling
-----------------------------------
require("scripts/globals/common")
require("scripts/globals/status")
require("scripts/globals/weaponskillids")
dsp = dsp or {}
dsp.aftermath = {}
dsp.aftermath.type =
{
RELIC = 1,
MYTHIC = 2,
EMPYREAN = 3,
} -- TODO: Add Aeonic
-------------------------------------
-- HELPERS : For aftermath eyes onry
-------------------------------------
local getTier1RelicDuration = function(tp)
return math.floor(tp * 0.02)
end
local getTier2RelicDuration = function(tp)
return math.floor(tp * 0.06)
end
dsp.aftermath.effects =
{
-----------------------------------
-- Tier 1 Relic
-----------------------------------
[1] = { mods = { dsp.mod.SUBTLE_BLOW, 10 }, duration = getTier1RelicDuration }, -- Spharai
[2] = { mods = { dsp.mod.CRITHITRATE, 5 }, duration = getTier1RelicDuration }, -- Mandau
[3] = { mods = { dsp.mod.REGEN, 10 }, duration = getTier1RelicDuration }, -- Excalibur
[4] = { mods = { dsp.mod.CRITHITRATE, 5 }, duration = getTier1RelicDuration }, -- Ragnarok
[5] = { mods = { dsp.mod.ATTP, 10 }, duration = getTier1RelicDuration }, -- Guttler
[6] = { mods = { dsp.mod.DMG, -20 }, duration = getTier1RelicDuration }, -- Bravura
[7] = { mods = { dsp.mod.HASTE_GEAR, 1000 }, duration = getTier1RelicDuration }, -- Apocalypse
[8] = { mods = { dsp.mod.SPIKES, dsp.subEffect.SHOCK_SPIKES, dsp.mod.SPIKES_DMG, 10 }, duration = getTier1RelicDuration }, -- Gungnir
[9] = { mods = { dsp.mod.SUBTLE_BLOW, 10 }, duration = getTier1RelicDuration }, -- Kikoku
[10] = { mods = { dsp.mod.STORETP, 7 }, duration = getTier1RelicDuration }, -- Amanomurakumo
[11] = { mods = { dsp.mod.ACC, 20 }, duration = getTier1RelicDuration }, -- Mjollnir
[12] = { mods = { dsp.mod.REFRESH, 8 }, duration = getTier1RelicDuration }, -- Claustrum
[13] = { mods = { dsp.mod.RACC, 20 }, duration = getTier1RelicDuration }, -- Yoichinoyumi
[14] = { mods = { dsp.mod.ENMITY, -20 }, duration = getTier1RelicDuration }, -- Annihilator
-----------------------------------
-- Tier 2 Relic
-----------------------------------
[15] = { mods = { dsp.mod.SUBTLE_BLOW, 10, dsp.mod.KICK_ATTACK, 15 }, duration = getTier2RelicDuration }, -- Spharai
[16] = { mods = { dsp.mod.CRITHITRATE, 5, dsp.mod.CRIT_DMG_INCREASE, 5 }, duration = getTier2RelicDuration }, -- Mandau
[17] = { mods = { dsp.mod.REGEN, 30, dsp.mod.REFRESH, 3 }, duration = getTier2RelicDuration }, -- Excalibur
[18] = { mods = { dsp.mod.CRITHITRATE, 10, dsp.mod.ACC, 15 }, duration = getTier2RelicDuration }, -- Ragnarok
[19] = { mods = { dsp.mod.ATTP, 10 }, duration = getTier2RelicDuration, includePets = true }, -- Guttler
[20] = { mods = { dsp.mod.DMG, -20, dsp.mod.REGEN, 15 }, duration = getTier2RelicDuration }, -- Bravura
[21] = { mods = { dsp.mod.HASTE_ABILITY, 1000, dsp.mod.ACC, 15 }, duration = getTier2RelicDuration }, -- Apocalypse
[22] = { mods = { dsp.mod.SPIKES, dsp.subEffect.SHOCK_SPIKES, dsp.mod.SPIKES_DMG, 10, dsp.mod.ATTP, 5, dsp.mod.DOUBLE_ATTACK, 5 }, duration = getTier2RelicDuration }, -- Gungir
[23] = { mods = { dsp.mod.SUBTLE_BLOW, 10, dsp.mod.ATTP, 10 }, duration = getTier2RelicDuration }, -- Kikoku
[24] = { mods = { dsp.mod.STORETP, 10, dsp.mod.ZANSHIN, 10 }, duration = getTier2RelicDuration }, -- Amanomurakumo
[25] = { mods = { dsp.mod.ACC, 20, dsp.mod.MACC, 20, dsp.mod.REFRESH, 5 }, duration = getTier2RelicDuration }, -- Mjollnir
[26] = { mods = { dsp.mod.REFRESH, 15, dsp.mod.DMG, -20 }, duration = getTier2RelicDuration }, -- Claustrum
[27] = { mods = { dsp.mod.RACC, 30, dsp.mod.SNAP_SHOT, 5 }, duration = getTier2RelicDuration }, -- Yoichinoyumi
[28] = { mods = { dsp.mod.ENMITY, -25, dsp.mod.RATTP, 10 }, duration = getTier2RelicDuration }, -- Annihilator
-----------------------------------
-- Tier 1 Mythic
-----------------------------------
[29] = -- Conqueror, Glanzfaust, Vajra, Burtgang, Liberator, Aymur, Kogarasumaru, Nagi, Ryunohige, Nirvana, Kenkonken, Terpsichore
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.ATT, function(tp) return math.floor(2 * tp / 50 - 60) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end } },
duration = { 60, 90, 120 }
},
[30] = -- Yagrush, Carnwenhan
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.ACC, function(tp) return math.floor(tp / 100 - 10) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end } },
duration = { 180, 90, 120 }
},
[31] = -- Laevateinn, Murgleis, Tupsimati
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.MATT, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end } },
duration = { 180, 180, 120 }
},
[32] = -- Tizona
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.MACC, function(tp) return math.floor(tp / 100 - 10) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end } },
duration = { 60, 90, 120 }
},
[33] = -- Gastraphetes, Death Penalty
{
mods = { { dsp.mod.RACC, function(tp) return math.floor(tp / 100) end },
{ dsp.mod.RATT, function(tp) return math.floor(2 * tp / 50 - 60) end },
{ dsp.mod.REM_OCC_DO_DOUBLE_DMG_RANGED, function(tp) return 40 end } },
duration = { 60, 90, 120 }
},
-----------------------------------
-- Tier 2 Mythic
-----------------------------------
[34] = -- Conqueror, Glanzfaust, Vajra, Burtgang, Liberator, Aymur, Kogarasumaru, Nagi, Ryunohige, Nirvana, Kenkonken, Terpsichore
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(3 * tp / 200) end },
{ dsp.mod.ATT, function(tp) return math.floor(3 * tp / 50 - 90) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 60 end } },
duration = { 90, 120, 180 }
},
[35] = -- Yagrush, Carnwenhan
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(3 * tp / 200) end },
{ dsp.mod.ACC, function(tp) return math.floor(3 * tp / 200 - 15) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 60 end } },
duration = { 270, 120, 180 }
},
[36] = -- Laevateinn, Murgleis, Tupsimati
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(3 * tp / 200) end },
{ dsp.mod.MATT, function(tp) return math.floor(tp / 50 - 20) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 60 end } },
duration = { 270, 270, 180 }
},
[37] = -- Tizona
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(3 * tp / 200) end },
{ dsp.mod.MACC, function(tp) return math.floor(3 * tp / 200 - 15) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 60 end } },
duration = { 90, 120, 180 }
},
[38] = -- Gastraphetes, Death Penalty
{
mods = { { dsp.mod.RACC, function(tp) return math.floor(tp / 50) end },
{ dsp.mod.RATT, function(tp) return math.floor(3 * tp / 50 - 90) end },
{ dsp.mod.REM_OCC_DO_DOUBLE_DMG_RANGED, function(tp) return 60 end } },
duration = { 90, 120, 180 }
},
-----------------------------------
-- Tier 3 Mythic
-----------------------------------
[39] = -- Conqueror, Glanzfaust, Vajra, Burtgang, Liberator, Aymur, Kogarasumaru, Nagi, Ryunohige, Nirvana, Kenkonken, Terpsichore
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(tp / 50 + 10) end },
{ dsp.mod.ATT, function(tp) return math.floor(tp * 0.6 - 80) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end, dsp.mod.MYTHIC_OCC_ATT_THRICE, function(tp) return 20 end } },
duration = { 90, 120, 180 }
},
[40] = -- Yagrush, Carnwenhan
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(tp / 50 + 10) end },
{ dsp.mod.ACC, function(tp) return math.floor(tp / 50 - 10) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end, dsp.mod.MYTHIC_OCC_ATT_THRICE, function(tp) return 20 end } },
duration = { 270, 120, 180 }
},
[41] = -- Laevateinn, Murgleis, Tupsimati
{
mods = { { dsp.mod.MACC, function(tp) return math.floor(tp / 50 + 10) end },
{ dsp.mod.MATT, function(tp) return math.floor(tp / 50 - 10) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end, dsp.mod.MYTHIC_OCC_ATT_THRICE, function(tp) return 20 end } },
duration = { 270, 270, 180 }
},
[42] = -- Tizona
{
mods = { { dsp.mod.ACC, function(tp) return math.floor(tp / 50 + 10) end },
{ dsp.mod.MACC, function(tp) return math.floor(tp / 50 - 10) end },
{ dsp.mod.MYTHIC_OCC_ATT_TWICE, function(tp) return 40 end, dsp.mod.MYTHIC_OCC_ATT_THRICE, function(tp) return 20 end } },
duration = { 90, 120, 180 }
},
[43] = -- Gastraphetes, Death Penalty
{
mods = { { dsp.mod.RACC, function(tp) return math.floor(tp / 50 + 10) end },
{ dsp.mod.RATT, function(tp) return math.floor(tp * 0.6 - 80) end },
{ dsp.mod.REM_OCC_DO_DOUBLE_DMG_RANGED, function(tp) return 40 end, dsp.mod.REM_OCC_DO_TRIPLE_DMG_RANGED, function(tp) return 20 end } },
duration = { 90, 120, 180 }
},
-----------------------------------
-- Tier 1 Empyrean
-----------------------------------
[44] =
{
mod = dsp.mod.REM_OCC_DO_DOUBLE_DMG,
power = { 30, 40, 50 },
duration = { 30, 60, 90 }
},
-----------------------------------
-- Tier 2 Empyrean
-----------------------------------
[45] =
{
mod = dsp.mod.REM_OCC_DO_TRIPLE_DMG,
power = { 30, 40, 50 },
duration = { 60, 120, 180 }
}
}
dsp.aftermath.addStatusEffect = function(player, tp, weaponSlot, aftermathType)
local weapon = player:getStorageItem(0, 0, weaponSlot)
if not weapon then return end
local id = weapon:getMod(dsp.mod.AFTERMATH)
-- Verify the aftermath ID matches the aftermath Type
local invalid = false
switch (aftermathType) : caseof
{
-- Relic
[1] = function(x)
invalid = id > 28
end,
-- Mythic
[2] = function(x)
invalid = id < 29 or id > 43
end,
-- Empyrean
[3] = function(x)
invalid = id < 44
end
}
if invalid then return end
local aftermath = dsp.aftermath.effects[id]
if not aftermath then return end
if not dsp.aftermath.canOverwrite(player, tp, id, aftermathType) then return end
player:delStatusEffect(dsp.effect.AFTERMATH)
switch (aftermathType) : caseof
{
-- Relic
[1] = function(x)
player:addStatusEffect(dsp.effect.AFTERMATH, id, 0, aftermath.duration(tp), 0, tp, aftermathType)
end,
-- Mythic
[2] = function(x)
local tier = math.floor(tp / 1000)
local icon = dsp.effect["AFTERMATH_LV"..tier]
player:addStatusEffectEx(dsp.effect.AFTERMATH, icon, id, 0, aftermath.duration[tier], 0, tp, aftermathType)
end,
-- Empyrean
[3] = function(x)
local tier = math.floor(tp / 1000)
local icon = dsp.effect["AFTERMATH_LV"..tier]
player:addStatusEffectEx(dsp.effect.AFTERMATH, icon, id, 0, aftermath.duration[tier], 0, tp, aftermathType)
end
}
end
-----------------------------------
-- Effect Power = Aftermath ID
-- Effect SubPower = TP
-- Effect Tier = Aftermath Type
-----------------------------------
dsp.aftermath.onEffectGain = function(target, effect)
local aftermath = dsp.aftermath.effects[effect:getPower()]
switch (effect:getTier()) : caseof
{
-- Relic
[1] = function(x)
local pet = nil
if aftermath.includePets then pet = target:getPet() end
for i = 1, #aftermath.mods, 2 do
target:addMod(aftermath.mods[i], aftermath.mods[i + 1])
if pet then
pet:addMod(aftermath.mods[i], aftermath.mods[i + 1])
end
end
end,
-- Mythic
[2] = function(x)
local tp = effect:getSubPower()
local mods = aftermath.mods[math.floor(tp / 1000)]
local pet = target:getPet()
for i = 1, #mods, 2 do
target:addMod(mods[i], mods[i + 1](tp))
if pet then
pet:addMod(mods[i], mods[i + 1](tp))
end
end
end,
-- Empyrean
[3] = function(x)
target:addMod(aftermath.mod, aftermath.power[math.floor(effect:getSubPower() / 1000)])
end
}
end
dsp.aftermath.onEffectLose = function(target, effect)
local aftermath = dsp.aftermath.effects[effect:getPower()]
switch (effect:getTier()) : caseof
{
-- Relic
[1] = function(x)
local pet = nil
if aftermath.includePets then pet = target:getPet() end
for i = 1, #aftermath.mods, 2 do
target:delMod(aftermath.mods[i], aftermath.mods[i + 1])
if pet then
pet:delMod(aftermath.mods[i], aftermath.mods[i + 1])
end
end
end,
-- Mythic
[2] = function(x)
local tp = effect:getSubPower()
local mods = aftermath.mods[math.floor(tp / 1000)]
local pet = target:getPet()
for i = 1, #mods, 2 do
target:delMod(mods[i], mods[i + 1](tp))
if pet then
pet:delMod(mods[i], mods[i + 1](tp))
end
end
end,
-- Empyrean
[3] = function(x)
target:delMod(aftermath.mod, aftermath.power[math.floor(effect:getSubPower() / 1000)])
end
}
end
dsp.aftermath.canOverwrite = function(player, tp, aftermathId, aftermathType)
local effect = player:getStatusEffect(dsp.effect.AFTERMATH)
if not effect then
return true
end
-- Empyrean > Mythic > Relic 'cause why not?
if aftermathType < effect:getTier() then
return false
end
local canOverwrite = false
local aftermath = dsp.aftermath.effects[aftermathId]
switch (aftermathType) : caseof
{
-- Relic
[1] = function(x)
local newDuration = aftermath.duration(tp) * 1000
canOverwrite = newDuration > effect:getTimeRemaining()
end,
-- Mythic
[2] = function(x)
local currentLevel = math.floor(effect:getSubPower() / 1000)
local newLevel = math.floor(tp / 1000)
canOverwrite = currentLevel == 1 or currentLevel < newLevel
end,
-- Empyrean
[3] = function(x)
local currentLevel = math.floor(effect:getSubPower() / 1000)
local newLevel = math.floor(tp / 1000)
canOverwrite = currentLevel == 1 or currentLevel < newLevel
end,
}
return canOverwrite
end | gpl-3.0 |
dualface/killpests | src/framework/cc/components/behavior/StateMachine.lua | 22 | 9185 |
local Component = import("..Component")
local StateMachine = class("StateMachine", Component)
--[[--
port from Javascript State Machine Library
https://github.com/jakesgordon/javascript-state-machine
JS Version: 2.2.0
]]
StateMachine.VERSION = "2.2.0"
-- the event transitioned successfully from one state to another
StateMachine.SUCCEEDED = 1
-- the event was successfull but no state transition was necessary
StateMachine.NOTRANSITION = 2
-- the event was cancelled by the caller in a beforeEvent callback
StateMachine.CANCELLED = 3
-- the event is asynchronous and the caller is in control of when the transition occurs
StateMachine.PENDING = 4
-- the event was failure
StateMachine.FAILURE = 5
-- caller tried to fire an event that was innapropriate in the current state
StateMachine.INVALID_TRANSITION_ERROR = "INVALID_TRANSITION_ERROR"
-- caller tried to fire an event while an async transition was still pending
StateMachine.PENDING_TRANSITION_ERROR = "PENDING_TRANSITION_ERROR"
-- caller provided callback function threw an exception
StateMachine.INVALID_CALLBACK_ERROR = "INVALID_CALLBACK_ERROR"
StateMachine.WILDCARD = "*"
StateMachine.ASYNC = "ASYNC"
function StateMachine:ctor()
StateMachine.super.ctor(self, "StateMachine")
end
function StateMachine:setupState(cfg)
assert(type(cfg) == "table", "StateMachine:ctor() - invalid config")
-- cfg.initial allow for a simple string,
-- or an table with { state = "foo", event = "setup", defer = true|false }
if type(cfg.initial) == "string" then
self.initial_ = {state = cfg.initial}
else
self.initial_ = clone(cfg.initial)
end
self.terminal_ = cfg.terminal or cfg.final
self.events_ = cfg.events or {}
self.callbacks_ = cfg.callbacks or {}
self.map_ = {}
self.current_ = "none"
self.inTransition_ = false
if self.initial_ then
self.initial_.event = self.initial_.event or "startup"
self:addEvent_({name = self.initial_.event, from = "none", to = self.initial_.state})
end
for _, event in ipairs(self.events_) do
self:addEvent_(event)
end
if self.initial_ and not self.initial_.defer then
self:doEvent(self.initial_.event)
end
return self.target_
end
function StateMachine:isReady()
return self.current_ ~= "none"
end
function StateMachine:getState()
return self.current_
end
function StateMachine:isState(state)
if type(state) == "table" then
for _, s in ipairs(state) do
if s == self.current_ then return true end
end
return false
else
return self.current_ == state
end
end
function StateMachine:canDoEvent(eventName)
return not self.inTransition_
and (self.map_[eventName][self.current_] ~= nil or self.map_[eventName][StateMachine.WILDCARD] ~= nil)
end
function StateMachine:cannotDoEvent(eventName)
return not self:canDoEvent(eventName)
end
function StateMachine:isFinishedState()
return self:isState(self.terminal_)
end
function StateMachine:doEventForce(name, ...)
local from = self.current_
local map = self.map_[name]
local to = (map[from] or map[StateMachine.WILDCARD]) or from
local args = {...}
local event = {
name = name,
from = from,
to = to,
args = args,
}
if self.inTransition_ then self.inTransition_ = false end
self:beforeEvent_(event)
if from == to then
self:afterEvent_(event)
return StateMachine.NOTRANSITION
end
self.current_ = to
self:enterState_(event)
self:changeState_(event)
self:afterEvent_(event)
return StateMachine.SUCCEEDED
end
function StateMachine:doEvent(name, ...)
assert(self.map_[name] ~= nil, string.format("StateMachine:doEvent() - invalid event %s", tostring(name)))
local from = self.current_
local map = self.map_[name]
local to = (map[from] or map[StateMachine.WILDCARD]) or from
local args = {...}
local event = {
name = name,
from = from,
to = to,
args = args,
}
if self.inTransition_ then
self:onError_(event,
StateMachine.PENDING_TRANSITION_ERROR,
"event " .. name .. " inappropriate because previous transition did not complete")
return StateMachine.FAILURE
end
if self:cannotDoEvent(name) then
self:onError_(event,
StateMachine.INVALID_TRANSITION_ERROR,
"event " .. name .. " inappropriate in current state " .. self.current_)
return StateMachine.FAILURE
end
if self:beforeEvent_(event) == false then
return StateMachine.CANCELLED
end
if from == to then
self:afterEvent_(event)
return StateMachine.NOTRANSITION
end
event.transition = function()
self.inTransition_ = false
self.current_ = to -- this method should only ever be called once
self:enterState_(event)
self:changeState_(event)
self:afterEvent_(event)
return StateMachine.SUCCEEDED
end
event.cancel = function()
-- provide a way for caller to cancel async transition if desired
event.transition = nil
self:afterEvent_(event)
end
self.inTransition_ = true
local leave = self:leaveState_(event)
if leave == false then
event.transition = nil
event.cancel = nil
self.inTransition_ = false
return StateMachine.CANCELLED
elseif string.upper(tostring(leave)) == StateMachine.ASYNC then
return StateMachine.PENDING
else
-- need to check in case user manually called transition()
-- but forgot to return StateMachine.ASYNC
if event.transition then
return event.transition()
else
self.inTransition_ = false
end
end
end
function StateMachine:exportMethods()
self:exportMethods_({
"setupState",
"isReady",
"getState",
"isState",
"canDoEvent",
"cannotDoEvent",
"isFinishedState",
"doEventForce",
"doEvent",
})
return self.target_
end
function StateMachine:onBind_()
end
function StateMachine:onUnbind_()
end
function StateMachine:addEvent_(event)
local from = {}
if type(event.from) == "table" then
for _, name in ipairs(event.from) do
from[name] = true
end
elseif event.from then
from[event.from] = true
else
-- allow "wildcard" transition if "from" is not specified
from[StateMachine.WILDCARD] = true
end
self.map_[event.name] = self.map_[event.name] or {}
local map = self.map_[event.name]
for fromName, _ in pairs(from) do
map[fromName] = event.to or fromName
end
end
local function doCallback_(callback, event)
if callback then return callback(event) end
end
function StateMachine:beforeAnyEvent_(event)
return doCallback_(self.callbacks_["onbeforeevent"], event)
end
function StateMachine:afterAnyEvent_(event)
return doCallback_(self.callbacks_["onafterevent"] or self.callbacks_["onevent"], event)
end
function StateMachine:leaveAnyState_(event)
return doCallback_(self.callbacks_["onleavestate"], event)
end
function StateMachine:enterAnyState_(event)
return doCallback_(self.callbacks_["onenterstate"] or self.callbacks_["onstate"], event)
end
function StateMachine:changeState_(event)
return doCallback_(self.callbacks_["onchangestate"], event)
end
function StateMachine:beforeThisEvent_(event)
return doCallback_(self.callbacks_["onbefore" .. event.name], event)
end
function StateMachine:afterThisEvent_(event)
return doCallback_(self.callbacks_["onafter" .. event.name] or self.callbacks_["on" .. event.name], event)
end
function StateMachine:leaveThisState_(event)
return doCallback_(self.callbacks_["onleave" .. event.from], event)
end
function StateMachine:enterThisState_(event)
return doCallback_(self.callbacks_["onenter" .. event.to] or self.callbacks_["on" .. event.to], event)
end
function StateMachine:beforeEvent_(event)
if self:beforeThisEvent_(event) == false or self:beforeAnyEvent_(event) == false then
return false
end
end
function StateMachine:afterEvent_(event)
self:afterThisEvent_(event)
self:afterAnyEvent_(event)
end
function StateMachine:leaveState_(event, transition)
local specific = self:leaveThisState_(event, transition)
local general = self:leaveAnyState_(event, transition)
if specific == false or general == false then
return false
elseif string.upper(tostring(specific)) == StateMachine.ASYNC
or string.upper(tostring(general)) == StateMachine.ASYNC then
return StateMachine.ASYNC
end
end
function StateMachine:enterState_(event)
self:enterThisState_(event)
self:enterAnyState_(event)
end
function StateMachine:onError_(event, error, message)
printf("%s [StateMachine] ERROR: error %s, event %s, from %s to %s", tostring(self.target_), tostring(error), event.name, event.from, event.to)
printError(message)
end
return StateMachine
| mit |
Giorox/AngelionOT-Repo | data/actions/scripts/doc.lua | 1 | 1046 | local config = {
small_diamond_id = 2145,
documents = {7844, 7845, 7846}, -- follower, officer, leader
}
local levers = {
[15051] = {pos = {x=32784,y=32229,z=14}, item = config.documents[1]},
[15052] = {pos = {x=32782,y=32225,z=14}, item = config.documents[2]},
[15053] = {pos = {x=32785,y=32223,z=14}, item = config.documents[3]},
[15061] = {pos = {x=32836,y=32228,z=14}, item = config.documents[1]},
[15062] = {pos = {x=32834,y=32224,z=14}, item = config.documents[2]},
[15063] = {pos = {x=32837,y=32222,z=14}, item = config.documents[3]}
}
function onUse(cid, item, fromPosition, itemEx, toPosition)
if(item.itemid == 1945) then
local diam = getTileItemById(levers[item.actionid].pos,config.small_diamond_id);
if(diam.itemid < 10) then
doPlayerSendCancel(cid, "You have to place a diamonc in order to use it.");
return true;
end
doRemoveItem(diam.uid,1);
doCreateItem(levers[item.actionid].item,1,levers[item.actionid].pos);
end
doTransformItem(item.uid,item.itemid==1945 and 1946 or 1945);
return true;
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Port_San_dOria/npcs/Fiva.lua | 12 | 1856 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Fiva
-- Only sells when San d'Oria controls Kolshushu
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(KOLSHUSHU);
if (RegionOwner ~= SANDORIA) then
player:showText(npc,FIVA_CLOSED_DIALOG);
else
player:showText(npc,FIVA_OPEN_DIALOG);
stock = {0x1197,184, --Buburimu Grape
0x0460,1620, --Casablanca
0x1107,220, --Dhalmel Meat
0x0266,72, --Mhaura Garlic
0x115d,40} --Yagudo Cherry
showShop(player,SANDORIA,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Giorox/AngelionOT-Repo | data/actions/scripts/quests/dcq_dead.lua | 1 | 1210 | local config = {
storage = 16440,
key_id = 1988 -- Key ID
}
function onUse(cid, item, fromPosition, itemEx, toPosition)
if getPlayerStorageValue(cid, config.storage) == -1 then
setPlayerStorageValue(cid, config.storage, 1)
doPlayerSendTextMessage(cid,MESSAGE_INFO_DESCR, "You have found a backpack.")
key = doPlayerAddItem(cid, config.key_id, 1)
doAddContainerItem(key, 2648, 1)
doAddContainerItem(key, 2458, 1)
doAddContainerItem(key, 2397, 1)
local book = doAddContainerItem(key,1950,1)
doSetItemText(book,"I am doomed!\nI know that Hugo lurks somewhere in\nthe bushes in the North. I won't\nsurvive his deadly breath which would\nkill even the mightiest warrior!\nI have no clue how to trick the\ninfamous Hugo but there has to be a\nway! Perhaps alchemy is the key to\nsuccess. I will mix these two potions I\nbought from the travelling dwarf. We'll\nsee what is going to happen. Perhaps it\nmakes me invulnerable to the deadly\nbreath! Then the secrets of the\nNightmare Knights are at my grasp.")
else
doPlayerSendTextMessage(cid,MESSAGE_INFO_DESCR, "The dead human is empty.")
end
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Port_San_dOria/npcs/Meta.lua | 13 | 1352 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Meta
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x208);
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 |
SamuelePilleri/sysdig | userspace/sysdig/chisels/echo_fds.lua | 6 | 4115 | --[[
Copyright (C) 2013-2014 Draios inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
--]]
-- Chisel description
description = "Print the data read and written for any FD. Combine this script with a filter to restrict what it shows. This chisel is compatible with containers using the sysdig -pc or -pcontainer argument, otherwise no container information will be shown. (Blue represents [Write], and Red represents [Read] for all data except when the -pc or -pcontainer argument is used. If used the container.name and container.id will be represented as: Green [host], and Cyan [container]) Container information will contain '[]' around container.name and container.id.";
short_description = "Print the data read and written by processes.";
category = "I/O";
args =
{
{
name = "disable_color",
description = "Set to 'disable_colors' if you want to disable color output",
argtype = "string",
optional = true
},
}
require "common"
terminal = require "ansiterminal"
terminal.enable_color(true)
-- Argument notification callback
function on_set_arg(name, val)
if name == "disable_color" and val == "disable_color" then
terminal.enable_color(false)
end
return true
end
-- Initialization callback
function on_init()
-- Request the fields that we need
fbuf = chisel.request_field("evt.rawarg.data")
fisread = chisel.request_field("evt.is_io_read")
fres = chisel.request_field("evt.rawarg.res")
fname = chisel.request_field("fd.name")
fpname = chisel.request_field("proc.name")
fcontainername = chisel.request_field("container.name")
fcontainerid = chisel.request_field("container.id")
-- The -pc or -pcontainer options was supplied on the cmd line
print_container = sysdig.is_print_container_data()
-- increase the snaplen so we capture more of the conversation
sysdig.set_snaplen(2000)
-- set the filter
chisel.set_filter("evt.is_io=true and evt.dir=< and evt.rawres>0")
chisel.set_event_formatter("%evt.arg.data")
return true
end
-- Event parsing callback
function on_event()
local buf = evt.field(fbuf)
local isread = evt.field(fisread)
local res = evt.field(fres)
local name = evt.field(fname)
local pname = evt.field(fpname)
local containername = evt.field(fcontainername)
local containerid = evt.field(fcontainerid)
if name == nil then
name = "<NA>"
end
if res <= 0 then
return true
end
local container = ""
if print_container then
if containername == "host" then
-- Make host green
container = string.format("%s [%s] [%s]", terminal.green, containername, containerid );
else
-- Make container cyan
container = string.format("%s [%s] [%s]", terminal.cyan, containername, containerid );
end
end
if isread then
-- Because container info might be colored make the end of the line the same color as read (red)
name_pname = string.format("%s %s (%s)", terminal.red, name, pname );
-- When a read occurs show it in red
infostr = string.format("%s------ Read %s from %s %s", terminal.red, format_bytes(res), container, name_pname)
else
-- Because container info might be colored make the end of the line the same color as write (blue)
name_pname = string.format("%s %s (%s)", terminal.blue, name, pname );
-- When a write occurs show it in blue
infostr = string.format("%s------ Write %s to %s %s", terminal.blue, format_bytes(res), container, name_pname)
end
-- Print out the line (if -pc or -pcontainer sandwitch container color between either red of blue)
print(infostr)
return true
end
-- Called by the engine at the end of the capture (Ctrl-C)
function on_capture_end()
print(terminal.reset)
end
| gpl-2.0 |
dios-game/dios | templates/lua_cocos/resources/src/cocos/network/DeprecatedNetworkFunc.lua | 61 | 1123 | if nil == cc.XMLHttpRequest then
return
end
--tip
local function deprecatedTip(old_name,new_name)
print("\n********** \n"..old_name.." was deprecated please use ".. new_name .. " instead.\n**********")
end
--functions of WebSocket will be deprecated begin
local targetPlatform = CCApplication:getInstance():getTargetPlatform()
if (kTargetIphone == targetPlatform) or (kTargetIpad == targetPlatform) or (kTargetAndroid == targetPlatform) or (kTargetWindows == targetPlatform) then
local WebSocketDeprecated = { }
function WebSocketDeprecated.sendTextMsg(self, string)
deprecatedTip("WebSocket:sendTextMsg","WebSocket:sendString")
return self:sendString(string)
end
WebSocket.sendTextMsg = WebSocketDeprecated.sendTextMsg
function WebSocketDeprecated.sendBinaryMsg(self, table,tablesize)
deprecatedTip("WebSocket:sendBinaryMsg","WebSocket:sendString")
string.char(unpack(table))
return self:sendString(string.char(unpack(table)))
end
WebSocket.sendBinaryMsg = WebSocketDeprecated.sendBinaryMsg
end
--functions of WebSocket will be deprecated end
| mit |
chucksellick/factorio-bad-chest | src/prototypes/entities.lua | 1 | 5492 | data:extend({
{
type = "smart-container",
name = "blueprint-deployer",
icon = "__recursive-blueprints__/graphics/blueprint-deployer-icon.png",
flags = {"placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "blueprint-deployer"},
max_health = 150,
corpse = "small-remnants",
collision_box = {{-0.35, -0.35}, {0.35, 0.35}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
fast_replaceable_group = "container",
inventory_size = 1,
open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 },
close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 },
picture =
{
filename = "__recursive-blueprints__/graphics/blueprint-deployer-entity.png",
priority = "extra-high",
width = 39,
height = 47,
frame_count = 8,
animation_speed = 0.5,
shift = {0.1, -0.23}
},
circuit_wire_max_distance = 7.5
},
{
type = "smart-container",
name = "blueprint-destructive-deployer",
icon = "__recursive-blueprints__/graphics/blueprint-deployer-icon.png",
flags = {"placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "blueprint-destructive-deployer"},
max_health = 150,
corpse = "small-remnants",
collision_box = {{-0.35, -0.35}, {0.35, 0.35}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
fast_replaceable_group = "container",
inventory_size = 1,
open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 },
close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 },
picture =
{
filename = "__recursive-blueprints__/graphics/blueprint-deployer-entity.png",
priority = "extra-high",
width = 39,
height = 47,
frame_count = 8,
animation_speed = 0.5,
shift = {0.1, -0.23}
},
circuit_wire_max_distance = 7.5
},
{
type = "simple-entity",
name = "blueprint-anchor",
icon = "__recursive-blueprints__/graphics/blueprint-anchor-icon.png",
flags = {"placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "blueprint-anchor"},
max_health = 150,
corpse = "small-remnants",
collision_box = {{-0.35, -0.35}, {0.35, 0.35}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
fast_replaceable_group = "container",
inventory_size = 1,
open_sound = { filename = "__base__/sound/metallic-chest-open.ogg", volume=0.65 },
close_sound = { filename = "__base__/sound/metallic-chest-close.ogg", volume = 0.7 },
render_layer = "object",
picture =
{
filename = "__base__/graphics/entity/basic-beacon/basic-beacon-antenna.png",
width = 54,
height = 50,
line_length = 8,
frame_count = 32,
shift = {0, 0},
scale = 0.6,
animation_speed = 0.5
}
},
{
type = "assembling-machine",
name = "blueprint-printer",
icon = "__base__/graphics/icons/assembling-machine-2.png",
flags = {"placeable-neutral", "placeable-player", "player-creation"},
minable = {hardness = 0.2, mining_time = 0.5, result = "blueprint-printer"},
max_health = 250,
corpse = "small-remnants",
dying_explosion = "medium-explosion",
resistances =
{
{
type = "fire",
percent = 70
}
},
--[[fluid_boxes =
{
{
production_type = "input",
pipe_picture = assembler2pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = -1,
pipe_connections = {{ type="input", position = {0, -2} }}
},
{
production_type = "output",
pipe_picture = assembler2pipepictures(),
pipe_covers = pipecoverspictures(),
base_area = 10,
base_level = 1,
pipe_connections = {{ type="output", position = {0, 2} }}
},
off_when_no_fluid_recipe = true
},]]--
collision_box = {{-0.35, -0.35}, {0.35, 0.35}},
selection_box = {{-0.5, -0.5}, {0.5, 0.5}},
fast_replaceable_group = "blueprint-deployer",
animation =
{
filename = "__base__/graphics/entity/assembling-machine-2/assembling-machine-2.png",
priority = "high",
width = 113,
height = 99,
frame_count = 32,
line_length = 8,
shift = {0.4, -0.06},
scale = 0.33
},
open_sound = { filename = "__base__/sound/machine-open.ogg", volume = 0.85 },
close_sound = { filename = "__base__/sound/machine-close.ogg", volume = 0.75 },
vehicle_impact_sound = { filename = "__base__/sound/car-metal-impact.ogg", volume = 0.65 },
working_sound =
{
sound = {
{
filename = "__base__/sound/assembling-machine-t2-1.ogg",
volume = 0.8
},
{
filename = "__base__/sound/assembling-machine-t2-2.ogg",
volume = 0.8
},
},
idle_sound = { filename = "__base__/sound/idle1.ogg", volume = 0.6 },
apparent_volume = 1.5,
},
crafting_categories = {"blueprints"},
crafting_speed = 0.75,
energy_source =
{
type = "electric",
usage_priority = "secondary-input",
emissions = 0.04 / 2.5
},
energy_usage = "150kW",
ingredient_count = 4,
module_specification =
{
module_slots = 2
},
allowed_effects = {"consumption", "speed", "productivity", "pollution"}
},
}
)
| mit |
DarkstarProject/darkstar | scripts/zones/Horlais_Peak/bcnms/hostile_herbivores.lua | 9 | 1066 | -----------------------------------
-- Hostile Herbivores
-- Horlais Peak BCNM50, Comet Orb
-- !additem 1177
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Meriphataud_Mountains/npcs/Akane_IM.lua | 13 | 3343 | -----------------------------------
-- Area: Meriphataud Mountains
-- NPC: Akane, I.M.
-- Type: Outpost Conquest Guards
-- @pos -294.470 15.806 420.117 119
-----------------------------------
package.loaded["scripts/zones/Meriphataud_Mountains/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/conquest");
require("scripts/zones/Meriphataud_Mountains/TextIDs");
local guardnation = BASTOK; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
local region = ARAGONEU;
local csid = 0x7ff9;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then
if (supplyRunFresh(player) == 1) then
player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies !
else
player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use."
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region));
player:setVar("supplyQuest_region",0);
end
else
local arg1 = getArg1(guardnation, player) - 1;
if (arg1 >= 1792) then -- foreign, non-allied
player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0);
else -- citizen or allied
player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("OPTION: %u",option);
if (option == 1) then
local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGIL);
player:delStatusEffect(EFFECT_SANCTION);
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif (option == 2) then
player:delKeyItem(getSupplyKey(region));
player:addCP(supplyReward[region + 1])
player:messageSpecial(CONQUEST); -- "You've earned conquest points!"
if (hasOutpost(player, region+5) == 0) then
local supply_quests = 2^(region+5);
player:addNationTeleport(guardnation,supply_quests);
player:setVar("supplyQuest_region",0);
end
elseif (option == 4) then
if (player:delGil(giltosetHP(guardnation,player))) then
player:setHomePoint();
player:messageSpecial(CONQUEST + 94); -- "Your home point has been set."
else
player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here."
end
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Qulun_Dome/npcs/qm1.lua | 13 | 1386 | -----------------------------------
-- Area: Qulun Dome
-- NPC: qm1 (???)
-- Used In Quest: Whence Blows the Wind
-- @pos 261 39 79 148
-----------------------------------
package.loaded["scripts/zones/Qulun_Dome/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Qulun_Dome/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(JEUNO,WHENCE_BLOWS_THE_WIND) == QUEST_ACCEPTED and player:hasKeyItem(QUADAV_CREST) == false) then
player:addKeyItem(QUADAV_CREST);
player:messageSpecial(KEYITEM_OBTAINED, QUADAV_CREST);
else
player:messageSpecial(YOU_FIND_NOTHING);
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 |
Fenix-XI/Fenix | scripts/zones/Mount_Zhayolm/npcs/Bapokk.lua | 13 | 1456 | -----------------------------------
-- Area: Mount Zhayolm
-- NPC: Bapokk
-- Handles access to Alzadaal Ruins
-- @pos -20 -6 276 61
-----------------------------------
package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mount_Zhayolm/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(2185,1)) then -- Silver
player:tradeComplete();
player:setPos(-20,-6,0,192); -- using the pos method until the problem below is fixed
-- player:startEvent(163); -- << this CS goes black at the end, never fades in
return 1;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- Ruins -> Zhayolm
if (player:getZPos() > -280) then
player:startEvent(164);
-- Zhayolm -> Ruins
else
player:startEvent(162);
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 |
Fenix-XI/Fenix | scripts/zones/Northern_San_dOria/npcs/Olbergieut.lua | 12 | 2339 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Olbergieut
-- Type: Quest NPC
-- @zone 231
-- @pos 91 0 121
--
-- Starts and Finishes Quest: Gates of Paradise
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
gates = player:getQuestStatus(SANDORIA,GATES_TO_PARADISE);
if (player:hasKeyItem(SCRIPTURE_OF_WATER) == true) then
player:startEvent(0x026c);
elseif (gates == QUEST_ACCEPTED) then
player:showText(npc, OLBERGIEUT_DIALOG, SCRIPTURE_OF_WIND);
elseif (player:getFameLevel(SANDORIA) >= 2 and gates == QUEST_AVAILABLE) then
player:startEvent(0x026b);
else
player:startEvent(0x0264);
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 == 0x026b and option == 0) then
player:addQuest(SANDORIA, GATES_TO_PARADISE);
player:addKeyItem(SCRIPTURE_OF_WIND);
player:messageSpecial(KEYITEM_OBTAINED, SCRIPTURE_OF_WIND);
elseif (csid == 0x026c) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 13584);
else
player:completeQuest(SANDORIA,GATES_TO_PARADISE);
player:addFame(SANDORIA,30);
player:addTitle(THE_PIOUS_ONE);
player:delKeyItem(SCRIPTURE_OF_WATER);
player:addItem(13584,1);
player:messageSpecial(ITEM_OBTAINED,13584);
end;
end;
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Northern_San_dOria/npcs/Aivedoir.lua | 13 | 1041 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Aivedoir
-- Type: Standard Dialogue NPC
-- @zone: 231
-- @pos -123.119 7.999 134.490
--
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,AIVEDOIR_DIALOG);
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 |
DarkstarProject/darkstar | scripts/zones/San_dOria-Jeuno_Airship/npcs/qm1.lua | 11 | 1036 | -----------------------------------
-- Area: San d'Oria-Jeuno Airship
-- NPC: ???
-- Involved In Quest: The Stars Of Ifrit
-- !pos -9 -5 -13 223
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/globals/weather");
local ID = require("scripts/zones/San_dOria-Jeuno_Airship/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local TOTD = VanadielTOTD();
local TheStarsOfIfrit = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_STARS_OF_IFRIT);
if (TOTD == dsp.time.NIGHT and IsMoonFull()) then
if (TheStarsOfIfrit == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.CARRIER_PIGEON_LETTER) == false) then
player:addKeyItem(dsp.ki.CARRIER_PIGEON_LETTER);
player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.CARRIER_PIGEON_LETTER);
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Northern_San_dOria/npcs/Guilerme.lua | 11 | 1569 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Guillerme
-- Involved in Quest: Rosel the Armorer
-- !pos -4.500 0.000 99.000 231
-----------------------------------
local ID = require("scripts/zones/Northern_San_dOria/IDs");
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local FlyerForRegine = player:getQuestStatus(SANDORIA,dsp.quest.id.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(ID.text.FLYER_REFUSED);
end
end
end;
function onTrigger(player,npc)
-- "Rosel the Armorer" quest status var
RoselTheArmorer = player:getQuestStatus(SANDORIA,dsp.quest.id.sandoria.ROSEL_THE_ARMORER);
-- "Rosel the Armorer" - turn in reciept to prince
if (RoselTheArmorer == QUEST_ACCEPTED and player:hasKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE)) then
player:startEvent(507);
else
player:showText(npc,ID.text.GUILERME_DIALOG);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
-- "Rosel the Armorer", give receipt to NPC:Guilerme
if (csid == 507) then
player:delKeyItem(dsp.ki.RECEIPT_FOR_THE_PRINCE);
end;
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Eastern_Altepa_Desert/npcs/qm.lua | 13 | 1620 | -----------------------------------
-- Area: Eastern Altepa Desert
-- NPC: ???
-- Involved In Quest: A Craftsman's Work
-- @pos 113 -7.972 -72 114
-----------------------------------
package.loaded["scripts/zones/Eastern_Altepa_Desert/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Eastern_Altepa_Desert/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Decurio_I_IIIKilled = player:getVar("Decurio_I_IIIKilled");
if (player:getVar("aCraftsmanWork") == 1 and Decurio_I_IIIKilled == 0) then
SpawnMob(17244523,300):updateClaim(player);
elseif (Decurio_I_IIIKilled == 1) then
player:addKeyItem(ALTEPA_POLISHING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,ALTEPA_POLISHING_STONE);
player:setVar("aCraftsmanWork",2);
player:setVar("Decurio_I_IIIKilled",0);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
alirezadeadly/sers | plugins/IP.lua | 6 | 4751 | local function run(msg, matches)
if matches[1]:lower() == "config" then
local data = http.request("http://ip-api.com/json/"..URL.escape(matches[2]).."?fields=262143")
local jdat = JSON.decode(data)
if jdat.status == "success" then
local text = "مشخصات آی اس پی شخص-دامنه مورد نظر:\n"
.."کشور: "..jdat.country.." - "..jdat.countryCode.."\n"
.."استان: "..jdat.regionName.."\n"
.."شهر: "..jdat.city.."\n"
.."زیپ کد: "..jdat.zip.."\n"
.."تایم زون: "..jdat.timezone.."\n"
.."مختصات جغرافیایی: "..jdat.lat..","..jdat.lon.."\n"
.."لینک گوگل مپ:\nhttps://www.google.com/maps/place/"..jdat.lat..","..jdat.lon.."\n"
.."شمار موبایل: "..(jdat.mobile or "-------").."\n"
.."آی پی پروکسی: "..(jdat.proxy or "-------").."\n"
.."آی پی: "..jdat.query.."\n"
.."اورگانیزیشن: "..jdat.org.."\n"
.."آی اس پی: "..jdat.isp.."\n"
.."آی اس: "..jdat.as
send_location(get_receiver(msg), jdat.lat, jdat.lon, ok_cb, false)
return text
else
return "مقدار وارد شد صحیح نیست"
end
elseif matches[1]:lower() == "ping" then
if matches[2] == "." then
return "64 bytes from 212.33.207.97: icmp_seq=1 ttl=48 time=107 ms"
else
local cmd = io.popen("ping -c1 "..matches[2]):read('*all')
if cmd == nil or cmd == "" or not cmd then
return "مقدار وارد شد صحیح نیست"
else
local char1 = cmd:find('data.')+5
local char2 = cmd:find('\n\n')
local text = cmd:sub(char1, char2)
local text = text:gsub(": ", "\n")
return text
end
end
elseif matches[1]:lower() == "whois" then
return io.popen("whois "..matches[2]):read('*all')
elseif matches[1]:lower() == "ip" then
return "براي مشاهده ي آي پي خود به لينک زير مراجعه کنيد\nhttp://umbrella.shayan-soft.ir/ip"
elseif matches[1]:lower() == "getip" then
if not matches[2] then
return 'آدرس زیر را به شخص مورد نظر بدهید و از او بخواهید وارد آن شود و توکن را با روش مهندسی اجتماعی (گول زدن شخص) از ایشان بگیرید و با یک فاصله با همین دستور وارد کنید تا آی پی وی را ببینید\nhttp://umbrella.shayan-soft.ir/get'
else
local getip = http.request("http://umbrella.shayan-soft.ir/get/umbrella"..matches[2]..".config")
if getip == "not found" then
return "توکن وارد شده صحیح نیست"
else
return "آی پی شخص مورد نظر:\n"..getip
end
end
end
end
return {
description = "IP and URL Information",
usagehtm = '<tr><td align="center">ip</td><td align="right">لینکی در اختیارتان قرار میدهد که با ورود به آن میتوانید آی پی خود را مشاهده کنید</td></tr>'
..'<tr><td align="center">getip</td><td align="right">لینک ارائه شده را به شخص مورد نظر بدهید و از آن توکنی که سایت به او میدهد را بخواهید. اگر آن توکن را با یک فاصله بعد از همین دستور وارد کنید، آی پی شخص مورد نظر نمایش داده میشد<br>http://umbrella.shayan-soft.ir/get</td></tr>'
..'<tr><td align="center">config آی پی یا لینک</td><td align="right">اطلاعاتی کلی راجع به آن لینک یا آی پی در اختیارتان قرار میدهد. دقت کنید لینک بدون اچ تی تی پی وارد شود</td></tr>'
..'<tr><td align="center">ping آی پی یا لینک</td><td align="right">از سرور با پورت های مختلف پینگ میگیرد. دقت کنید لینک بدون اچ تی تی پی وارد شود</td></tr>'
..'<tr><td align="center">whois لینک</td><td align="right">یک دامین را بررسی میکند و در صورتی که قبلا به ثبت رسیده باشد، مشخصات ثبت کننده را به اطلاع شما میرسان. دقت کنید لینک بدون اچ تی تی پی وارد شود</td></tr>',
usage = {
"ip : آي پي شما",
"getip : دریافت و ذخیره آی پی دیگران",
"getip (token) : نمایش ذخیره شده",
"config (ip|url) : مشخصات",
"ping (ip|url) : پينگ",
"whois (url) : بررسي دامنه",
},
patterns = {
"^([Ii]p)$",
"^([Gg]etip) (.*)$",
"^([Gg]etip)$",
"^([Cc]onfig) (.*)$",
"^([Pp]ing) (.*)$",
"^([Ww]hois) (.*)$",
},
run = run
}
| gpl-2.0 |
dualface/killpests | src/framework/cc/init.lua | 19 | 2233 | --[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--[[--
初始化 cc 扩展
cc 扩展在 cocos2dx C++ API 和 quick 基本模块的基础上,提供了符合脚本风格的事件接口、组件架构等扩展。
]]
local CURRENT_MODULE_NAME = ...
-- init base classes
cc.Registry = import(".Registry")
cc.GameObject = import(".GameObject")
cc.EventProxy = import(".EventProxy")
cc.Component = import(".components.Component")
-- init components
local components = {
"components.behavior.StateMachine",
"components.behavior.EventProtocol",
"components.ui.BasicLayoutProtocol",
"components.ui.LayoutProtocol",
"components.ui.DraggableProtocol",
}
for _, packageName in ipairs(components) do
cc.Registry.add(import("." .. packageName, CURRENT_MODULE_NAME), packageName)
end
-- cc = cc.GameObject.extend()
local GameObject = cc.GameObject
local ccmt = {}
ccmt.__call = function(self, target)
if target then
return GameObject.extend(target)
end
printError("cc() - invalid target")
end
setmetatable(cc, ccmt)
-- load MVC
cc.mvc = import(".mvc.init")
-- load more library
cc.ui = import(".ui.init")
-- load extensions
cc.uiloader = import(".uiloader.init")
| mit |
mrgloom/gtsrb.torch | dataset.lua | 1 | 7573 | local pl = (require 'pl.import_into')()
require 'torch'
require 'image'
torch.setdefaulttensortype('torch.FloatTensor')
local dataset = {}
-- Private function declaration
local generate_dataset
local prune_dataset
-- These paths should not be changed
dataset.path_remote_train = "http://benchmark.ini.rub.de/Dataset/GTSRB_Final_Training_Images.zip"
dataset.path_remote_test = "http://benchmark.ini.rub.de/Dataset/GTSRB_Final_Test_Images.zip"
dataset.path_remote_test_gt = "http://benchmark.ini.rub.de/Dataset/GTSRB_Final_Test_GT.zip"
dataset.train_dataset_bin = "train_dataset.bin"
dataset.test_dataset_bin = "test_dataset.bin"
-- This function will download the dataset in the './GTSRB' temp folder, and generate
-- binary files containing the dataset as torch tensors.
function dataset.download_generate_bin()
if not pl.path.isfile(dataset.train_dataset_bin) or
not pl.path.isfile(dataset.test_dataset_bin) then
if not pl.path.isdir('GTSRB') then
local tar_train = paths.basename(dataset.path_remote_train)
local tar_test = paths.basename(dataset.path_remote_test)
local tar_test_gt = paths.basename(dataset.path_remote_test_gt)
print('Downloading dataset...')
os.execute('wget ' .. dataset.path_remote_train .. '; ' ..
'unzip ' .. tar_train .. '; '..
'rm ' .. tar_train)
os.execute('wget ' .. dataset.path_remote_test .. '; ' ..
'unzip ' .. tar_test .. '; '..
'rm ' .. tar_test .. '; ' ..
'mkdir GTSRB/Final_Test/Images/final_test; ' ..
-- too many arguments for a plain mv...
[[find GTSRB/Final_Test/Images/ -maxdepth 1 -name '*.ppm' -exec sh -c 'mv "$@" "$0"' GTSRB/Final_Test/Images/final_test/ {} +;]] ..
'rm GTSRB/Final_Test/Images/GT-final_test.test.csv')
os.execute('wget ' .. dataset.path_remote_test_gt .. '; ' ..
'unzip ' .. tar_test_gt .. '; '..
'rm ' .. tar_test_gt .. '; ' ..
'mv GT-final_test.csv GTSRB/Final_Test/Images/final_test/GT-final_test.csv')
end
print('Generating bin of the dataset')
local train_set = generate_dataset('GTSRB/Final_Training/Images')
torch.save('train_dataset.bin', train_set)
train_set = nil
collectgarbage()
local test_set = generate_dataset('GTSRB/Final_Test/Images')
torch.save('test_dataset.bin', test_set)
test_set = nil
collectgarbage()
if paths.dirp('GTSRB') then
os.execute('rm -r GTSRB')
end
end
end
-------------------------------------------------
-- Main Interface
-------------------------------------------------
-- Returns the train dataset
-- nbr_examples is optional and allows to get only a subset of the training samples
-- Warning: if the number of examples is not limited, the dataset is ordered by class
-- If the number of examples is limited, the subset will be shuffled.
function dataset.get_train_dataset(nbr_examples)
dataset.download_generate_bin()
local train_dataset = torch.load(dataset.train_dataset_bin)
-- Limit the number of samples if required by the user
if nbr_examples and nbr_examples ~= -1 then
train_dataset = prune_dataset(train_dataset, nbr_examples)
end
return train_dataset
end
-- Returns the test dataset
-- nbr_examples is optional and allows to get only a subset of the testing samples
-- Warning: if the number of examples is not limited, the dataset is ordered by class
-- If the number of examples is limited, the subset will be shuffled.
function dataset.get_test_dataset(nbr_examples)
dataset.download_generate_bin()
local test_dataset = torch.load(dataset.test_dataset_bin)
-- Limit the number of samples if required by the user
if nbr_examples and nbr_examples ~= -1 then
test_dataset = prune_dataset(test_dataset, nbr_examples)
end
return test_dataset
end
-- Normalize the given dataset
-- You can specify the mean and std values, otherwise, they are computed on the given dataset
-- Return the mean and std values
function dataset.normalize_global(dataset, mean, std)
local std = std or dataset.data:std()
local mean = mean or dataset.data:mean()
dataset.data:add(-mean)
dataset.data:div(std)
return mean, std
end
-- Locally normalize the dataset
function dataset.normalize_local(dataset)
require 'image'
local norm_kernel = image.gaussian1D(7)
local norm = nn.SpatialContrastiveNormalization(3,norm_kernel)
local batch = 200 -- Can be reduced if you experience memory issues
local dataset_size = dataset.data:size(1)
for i=1,dataset_size,batch do
local local_batch = math.min(dataset_size,i+batch) - i
local normalized_images = norm:forward(dataset.data:narrow(1,i,local_batch))
dataset.data:narrow(1,i,local_batch):copy(normalized_images)
end
end
-------------------------------------------------
-- Private function
-------------------------------------------------
prune_dataset = function(dataset, nbr_examples)
-- Limit the number of samples if required by the user
assert(nbr_examples and nbr_examples > 1 and nbr_examples < dataset.data:size(1),
'Invalid number of examples required, not within dataset range.')
local randperm = torch.randperm(dataset.data:size(1))
local subset_data = torch.Tensor(nbr_examples, 3, 48, 48)
local subset_label = torch.Tensor(nbr_examples, 1)
for i=1,nbr_examples do
subset_data[i]:copy(dataset.data[randperm[i]])
subset_label[i]:copy(dataset.label[randperm[i]])
end
dataset.data = subset_data
dataset.label = subset_label
collectgarbage()
return dataset
end
-- This will generate a dataset as torch tensor from a directory of images
-- parent_path is a string of the path containing all the images
generate_dataset = function(parent_path)
assert(parent_path, "A parent path is needed to generate the dataset")
local main_dataset = {}
main_dataset.nbr_elements = 0
local images_directories = pl.dir.getdirectories(parent_path)
table.sort(images_directories)
for image_directory_id, image_directory in ipairs(images_directories) do
local csv_file_name = 'GT-' .. pl.path.basename(image_directory) .. '.csv'
local csv_file_path = pl.path.join(image_directory, csv_file_name)
local csv_content = pl.data.read(csv_file_path)
local filename_index = csv_content.fieldnames:index('Filename')
local class_id_index = csv_content.fieldnames:index('ClassId')
for image_index, image_metadata in ipairs(csv_content) do
local image_path = pl.path.join(image_directory, image_metadata[filename_index])
local image_data = image.load(image_path)
-- We do no transformation but a rescaling so all the images have the same size
image_data = image.scale(image_data, 48, 48)
local label = torch.Tensor{image_metadata[class_id_index]+1}
main_dataset.nbr_elements = main_dataset.nbr_elements + 1
main_dataset[main_dataset.nbr_elements] = {image_data, label}
if image_index % 50 == 0 then
collectgarbage()
end
end
end
-- Store everything as proper torch Tensor now that we know the total size
local main_data = torch.Tensor(main_dataset.nbr_elements, 3, 48, 48)
local main_label = torch.Tensor(main_dataset.nbr_elements, 1)
for i,pair in ipairs(main_dataset) do
main_data[i]:copy(main_dataset[i][1])
main_label[i]:copy(main_dataset[i][2])
end
main_dataset = {}
main_dataset.data = main_data
main_dataset.label = main_label
return main_dataset
end
-- Return the module
return dataset
| mit |
DarkstarProject/darkstar | scripts/globals/weaponskills/mystic_boon.lua | 10 | 1835 | -----------------------------------
-- Mystic Boon
-- Club weapon skill
-- Skill level: N/A
-- Converts damage dealt to own MP. Damage varies with TP. Yagrush: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (White Mage) quest.
-- Damage is significantly affected by Attack. Verification Needed
-- Not aligned with any "elemental gorgets" or elemental belts due to it's absence of Skillchain properties.
-- Element: None
-- Modifiers: STR:30% MND:70%
-- 100%TP 200%TP 300%TP
-- 2.5 4.0 7.0
-----------------------------------
require("scripts/globals/aftermath")
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/weaponskills")
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar)
local params = {}
params.numHits = 1
params.ftp100 = 1 params.ftp200 = 1.5 params.ftp300 = 2
params.str_wsc = 0.3 params.dex_wsc = 0.0 params.vit_wsc = 0.0 params.agi_wsc = 0.0 params.int_wsc = 0.0
params.mnd_wsc = 0.5 params.chr_wsc = 0.0
params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0
params.canCrit = false
params.acc100 = 0.0 params.acc200 = 0.0 params.acc300 = 0.0
params.atk100 = 1; params.atk200 = 1; params.atk300 = 1;
if USE_ADOULIN_WEAPON_SKILL_CHANGES then
params.ftp100 = 2.5 params.ftp200 = 4 params.ftp300 = 7
params.mnd_wsc = 0.7
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar)
player:addMP(damage)
-- Apply aftermath
if damage > 0 then
dsp.aftermath.addStatusEffect(player, tp, dsp.slot.MAIN, dsp.aftermath.type.MYTHIC)
end
return tpHits, extraHits, criticalHit, damage
end
| gpl-3.0 |
spamn/lain | widget/contrib/tpbat/init.lua | 2 | 4934 | --[[
tpbat.lua
Battery status widget for ThinkPad laptops that use SMAPI
lain.widget.contrib.tpbat
More on tp_smapi: http://www.thinkwiki.org/wiki/Tp_smapi
Licensed under GNU General Public License v2
* (c) 2013, Conor Heine
* (c) 2013, Luke Bonham
* (c) 2010-2012, Peter Hofmann
--]]
local debug = { getinfo = debug.getinfo }
local newtimer = require("lain.helpers").newtimer
local first_line = require("lain.helpers").first_line
local naughty = require("naughty")
local wibox = require("wibox")
local string = { format = string.format }
local math = { floor = math.floor }
local tostring = tostring
local setmetatable = setmetatable
package.path = debug.getinfo(1,"S").source:match[[^@?(.*[\/])[^\/]-$]] .. "?.lua;" .. package.path
local smapi = require("smapi")
-- ThinkPad SMAPI-enabled battery info widget
-- lain.widget.contrib.tpbat
local tpbat = {}
function tpbat.hide()
if not tpbat.notification then return end
naughty.destroy(tpbat.notification)
tpbat.notification = nil
end
function tpbat.show(t_out)
tpbat.hide()
local bat = tpbat.bat
if bat == nil or not bat:installed() then return end
local t_out = t_out or 0
local mfgr = bat:get('manufacturer') or "no_mfgr"
local model = bat:get('model') or "no_model"
local chem = bat:get('chemistry') or "no_chem"
local status = bat:get('state') or "nil"
local time = bat:remaining_time()
local msg = "\t"
if status ~= "idle" and status ~= "nil" then
if time == "N/A" then
msg = "...Calculating time remaining..."
else
msg = time .. (status == "charging" and " until charged" or " remaining")
end
else
msg = "On AC Power"
end
local str = string.format("%s : %s %s (%s)\n", bat.name, mfgr, model, chem)
.. string.format("\n%s \t\t\t %s", status:upper(), msg)
tpbat.notification = naughty.notify({
text = str,
timeout = t_out,
screen = client.focus and client.focus.screen or 1
})
end
function tpbat.register(args)
local args = args or {}
local timeout = args.timeout or 30
local battery = args.battery or "BAT0"
local settings = args.settings or function() end
tpbat.bat = smapi:battery(battery) -- Create a new battery
local bat = tpbat.bat
tpbat.widget = wibox.widget.textbox()
bat_notification_low_preset = {
title = "Battery low",
text = "Plug the cable!",
timeout = 15,
fg = "#202020",
bg = "#CDCDCD"
}
bat_notification_critical_preset = {
title = "Battery exhausted",
text = "Shutdown imminent",
timeout = 15,
fg = "#000000",
bg = "#FFFFFF"
}
if bat:get('state') == nil
then
local n = naughty.notify({
preset = bat_notification_low_preset,
title = "SMAPI Battery Warning: Unable to read battery state!",
text = "This widget is intended for ThinkPads. Is tp_smapi installed? Check your configs & paths.",
screen = client.focus and client.focus.screen or 1
})
end
function tpbat.update()
bat_now = {
status = "Not present",
perc = "N/A",
time = "N/A",
watt = "N/A"
}
if bat:installed()
then
bat_now.status = bat:status() or "N/A"
bat_now.perc = bat:percent()
bat_now.time = bat:remaining_time()
-- bat_now.watt = string.format("%.2fW", (VOLTS * AMPS) / 1e12)
-- notifications for low and critical states (when discharging)
if bat_now.status == "discharging"
then
if bat_now.perc <= 5
then
tpbat.id = naughty.notify({
preset = bat_notification_critical_preset,
replaces_id = tpbat.id,
screen = client.focus and client.focus.screen or 1
}).id
elseif bat_now.perc <= 15
then
tpbat.id = naughty.notify({
preset = bat_notification_low_preset,
replaces_id = tpbat.id,
screen = client.focus and client.focus.screen or 1
}).id
end
end
bat_now.perc = tostring(bat_now.perc)
end
widget = tpbat.widget
settings()
end
newtimer("tpbat-" .. bat.name, timeout, tpbat.update)
widget:connect_signal('mouse::enter', function () tpbat.show() end)
widget:connect_signal('mouse::leave', function () tpbat.hide() end)
return tpbat
end
return setmetatable(tpbat, { __call = function(_, ...) return tpbat.register(...) end })
| gpl-2.0 |
Fenix-XI/Fenix | scripts/globals/spells/bluemagic/blitzstrahl.lua | 25 | 1897 | -----------------------------------------
-- Spell: Blitzstrahl
-- Deals lightning damage to an enemy. Additional effect: "Stun"
-- Spell cost: 70 MP
-- Monster Type: Arcana
-- Spell Type: Magical (Lightning)
-- Blue Magic Points: 4
-- Stat Bonus: DEX+3
-- Level: 44
-- Casting Time: 4.5 seconds
-- Recast Time: 29.25 seconds
-- Magic Bursts on: Impaction, Fragmentation, Light
-- Combos: None
-----------------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/bluemagic");
-----------------------------------------
-- OnMagicCastingCheck
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0;
end;
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function onSpellCast(caster,target,spell)
local params = {};
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = 1.5625;
params.tMultiplier = 1.0;
params.duppercap = 61;
params.str_wsc = 0.0;
params.dex_wsc = 0.0;
params.vit_wsc = 0.0;
params.agi_wsc = 0.0;
params.int_wsc = 0.3;
params.mnd_wsc = 0.1;
params.chr_wsc = 0.0;
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED);
damage = BlueFinalAdjustments(caster, target, spell, damage, params);
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0);
if (damage > 0 and resist > 0.0625) then
local typeEffect = EFFECT_STUN;
target:delStatusEffect(typeEffect); -- Wiki says it can overwrite itself or other binds
target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect));
end
return damage;
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/PsoXja/npcs/_i98.lua | 9 | 1161 | -----------------------------------
-- Area: Pso'Xja
-- NPC: Stone Gate
-----------------------------------
local ID = require("scripts/zones/PsoXja/IDs");
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR and player:getCharVar("PromathiaStatus")==3 and not GetMobByID(ID.mob.NUNYUNUWI):isSpawned()) then
SpawnMob(ID.mob.NUNYUNUWI):updateClaim(player);
elseif ( (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR and player:getCharVar("PromathiaStatus")==4) or player:hasCompletedMission(COP,dsp.mission.id.cop.THE_ENDURING_TUMULT_OF_WAR) or player:hasCompletedMission(COP,dsp.mission.id.cop.THE_LAST_VERSE)) then
if (player:getZPos() < 318) then
player:startEvent(69);
else
player:startEvent(70);
end
else
player:messageSpecial(ID.text.DOOR_LOCKED);
end
return 1;
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/mobskills/head_butt_turtle.lua | 11 | 1053 | ---------------------------------------------------
-- Head Butt (Adamantoise)
-- Deals damage to single target. Additional effects: Accuracy Down and large knockback
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 3
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.BLUNT,info.hitslanded)
-- Large Knockdown ----------------------------
local typeEffect = dsp.effect.ACCURACY_DOWN
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 50, 0, 120)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.BLUNT)
return dmg
end
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/spells/bluemagic/bomb_toss.lua | 12 | 1246 | -----------------------------------------
-- Spell: Bomb Toss
-- Throws a bomb at an enemy
-- Spell cost: 42 MP
-- Monster Type: Beastmen
-- Spell Type: Magical (Fire)
-- Blue Magic Points: 3
-- Stat Bonus: STR+2
-- Level: 28
-- Casting Time: 3.75 seconds
-- Recast Time: 24.5 seconds
-- Magic Bursts on: Liquefaction, Fusion, Light
-- Combos: None
-----------------------------------------
require("scripts/globals/bluemagic")
require("scripts/globals/status")
require("scripts/globals/magic")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local params = {}
-- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage
params.multiplier = 1.625
params.tMultiplier = 1.0
params.duppercap = 40
params.str_wsc = 0.0
params.dex_wsc = 0.0
params.vit_wsc = 0.0
params.agi_wsc = 0.0
params.int_wsc = 0.2
params.mnd_wsc = 0.0
params.chr_wsc = 0.0
damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED)
damage = BlueFinalAdjustments(caster, target, spell, damage, params)
return damage
end | gpl-3.0 |
botFree/botFree | lock_bot.lua | 2 | 3089 | --[[
_ _ _ _ ___ ___ _
__ _| |__ ___ ___| | ___ __ ___ _ __ (_) __ _ / |/ _ \ / _ \| | __
/ _` | '_ \ / _ \/ __| |/ / '__/ _ \| '_ \ | |/ _` | | | | | | | | | |/ /
| (_| | |_) | (_) \__ \ <| | | (_) | |_) | | | (_| | | | |_| | |_| | <
\__,_|_.__/ \___/|___/_|\_\_| \___/| .__/ |_|\__, |____|_|\___/ \___/|_|\_\
|_| |_|_____|
—]]
local function isAntiBotEnabled (chatId)
local hash = 'bot:lock:'..chatId
local lock = redis:get(hash)
return lock
end
local function enableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:set(hash, true)
end
local function disableAntiBot (chatId)
local hash = 'bot:lock:'..chatId
redis:del(hash)
end
local function isABot (user)
local binFlagIsBot = 4096
local result = bit32.band(user.flags, binFlagIsBot)
return result == binFlagIsBot
end
local function isABotBadWay (user)
local username = user.username or ''
return username:match("[Bb]ot$")
end
local function kickUser(userId, chatId)
local channel = 'channel#id'..chatId
local user = 'user#id'..userId
channel_kick_user(channel, user, function (data, success, result)
if success ~= 1 then
print('I can\'t kick '..data.user..' but should be kicked')
end
end, {chat=chat, user=user})
end
local function run (msg, matches)
if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then
if msg.to.type ~= 'chat' and msg.to.type ~= 'channel' then
return nil
end
end
local chatId = msg.to.id
if matches[1] == 'قفل البوتات' then
enableAntiBot(chatId)
return ' <b> add bot loked </b> 💡'
end
if matches[1] == 'فتح البوتات' then
disableAntiBot(chatId)
return ' <b> add bot unloked </b>💡 '
end
if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then
local user = msg.action.user or msg.from
if isABotBadWay(user) then
print("It' a bot!")
if isAntiBotEnabled(chatId) then
print('bot is locked')
local userId = user.id
if not isBotAllowed(userId, chatId) then
kickUser(userId, chatId)
else
print('')
end
end
end
end
end
return {
description = 'Anti bot create by Mustafa ip',
usage = {
'/bot lock: locked add bots to supergroup',
'/bot unlock: unlock add bots to supergroup'
},
patterns = {
'^(قفل البوتات)$',
'^(فتح البوتات)$',
'^!!tgservice (chat_add_user)$',
'^!!tgservice (chat_add_user_link)$'
},
run = run
}
--[[
_ _ _ _ ___ ___ _
__ _| |__ ___ ___| | ___ __ ___ _ __ (_) __ _ / |/ _ \ / _ \| | __
/ _` | '_ \ / _ \/ __| |/ / '__/ _ \| '_ \ | |/ _` | | | | | | | | | |/ /
| (_| | |_) | (_) \__ \ <| | | (_) | |_) | | | (_| | | | |_| | |_| | <
\__,_|_.__/ \___/|___/_|\_\_| \___/| .__/ |_|\__, |____|_|\___/ \___/|_|\_\
|_| |_|_____|
—]] | gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Outer_Horutoto_Ruins/npcs/_ne4.lua | 13 | 2994 | -----------------------------------
-- Area: Outer Horutoto Ruins
-- NPC: Strange Apparatus
-- @pos: -574 0 739 194
-----------------------------------
package.loaded["scripts/zones/Outer_Horutoto_Ruins/TextIDs"] = nil;
require("scripts/zones/Outer_Horutoto_Ruins/TextIDs");
require("scripts/globals/strangeapparatus");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local trade = tradeToStrApp(player, trade);
if (trade ~= nil) then
if ( trade == 1) then -- good trade
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
end
player:startEvent(0x0042, drop, dropQty, INFINITY_CORE, 0, 0, 0, docStatus, 0);
else -- wrong chip, spawn elemental nm
spawnElementalNM(player);
delStrAppDocStatus(player);
player:messageSpecial(SYS_OVERLOAD);
player:messageSpecial(YOU_LOST_THE, trade);
end
else -- Invalid trade, lose doctor status
delStrAppDocStatus(player);
player:messageSpecial(DEVICE_NOT_WORKING);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local docStatus = 0; -- Assistant
if (hasStrAppDocStatus(player)) then
docStatus = 1; -- Doctor
else
player:setLocalVar( "strAppPass", 1);
end
player:startEvent(0x0040, docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, player:getZoneID());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u", option);
if (csid == 0x0040) then
if (hasStrAppDocStatus(player) == false) then
local docStatus = 1; -- Assistant
if ( option == strAppPass(player)) then -- Good password
docStatus = 0; -- Doctor
giveStrAppDocStatus(player);
end
player:updateEvent(docStatus, 0, INFINITY_CORE, 0, 0, 0, 0, 0);
end
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0042) then
local drop = player:getLocalVar("strAppDrop");
local dropQty = player:getLocalVar("strAppDropQty");
if (drop ~= 0) then
if ( dropQty == 0) then
dropQty = 1;
end
player:addItem(drop, dropQty);
player:setLocalVar("strAppDrop", 0);
player:setLocalVar("strAppDropQty", 0);
end
end
end; | gpl-3.0 |
vlinhd11/vlinhd11-android-scripting | lua/luasocket/samples/lpr.lua | 59 | 1574 | local lp = require("socket.lp")
local function usage()
print('\nUsage: lua lpr.lua [filename] [keyword=val...]\n')
print('Valid keywords are :')
print(
' host=remote host or IP address (default "localhost")\n' ..
' queue=remote queue or printer name (default "printer")\n' ..
' port=remote port number (default 515)\n' ..
' user=sending user name\n' ..
' format=["binary" | "text" | "ps" | "pr" | "fortran"] (default "binary")\n' ..
' banner=true|false\n' ..
' indent=number of columns to indent\n' ..
' mail=email of address to notify when print is complete\n' ..
' title=title to use for "pr" format\n' ..
' width=width for "text" or "pr" formats\n' ..
' class=\n' ..
' job=\n' ..
' name=\n' ..
' localbind=true|false\n'
)
return nil
end
if not arg or not arg[1] then
return usage()
end
do
local opt = {}
local pat = "[%s%c%p]*([%w]*)=([\"]?[%w%s_!@#$%%^&*()<>:;]+[\"]\?\.?)"
for i = 2, table.getn(arg), 1 do
string.gsub(arg[i], pat, function(name, value) opt[name] = value end)
end
if not arg[2] then
return usage()
end
if arg[1] ~= "query" then
opt.file = arg[1]
r,e=lp.send(opt)
io.stdout:write(tostring(r or e),'\n')
else
r,e=lp.query(opt)
io.stdout:write(tostring(r or e), '\n')
end
end
-- trivial tests
--lua lp.lua lp.lua queue=default host=localhost
--lua lp.lua lp.lua queue=default host=localhost format=binary localbind=1
--lua lp.lua query queue=default host=localhost
| apache-2.0 |
DarkstarProject/darkstar | scripts/zones/Apollyon/mobs/Apollyon_Cleaner.lua | 9 | 1201 | -----------------------------------
-- Area: Apollyon NE
-- Mob: Apollyon Cleaner
-----------------------------------
require("scripts/globals/limbus");
-----------------------------------
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();
if (mobID ==16933082) then -- item
GetNPCByID(16932864+140):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+140):setStatus(dsp.status.NORMAL);
elseif (mobID ==16933085) then -- timer T1
GetNPCByID(16932864+139):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+139):setStatus(dsp.status.NORMAL);
elseif (mobID ==16933087) then -- timer T2
GetNPCByID(16932864+85):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+85):setStatus(dsp.status.NORMAL);
elseif (mobID ==16933092) then -- timer T3
GetNPCByID(16932864+94):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+94):setStatus(dsp.status.NORMAL);
elseif (mobID ==16933095) then -- recover
GetNPCByID(16932864+141):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+141):setStatus(dsp.status.NORMAL);
end
end; | gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Yuhtunga_Jungle/IDs.lua | 8 | 4606 | -----------------------------------
-- Area: Yuhtunga_Jungle
-----------------------------------
require("scripts/globals/zone")
-----------------------------------
zones = zones or {}
zones[dsp.zone.YUHTUNGA_JUNGLE] =
{
text =
{
NOTHING_HAPPENS = 119, -- Nothing happens...
ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory.
ITEM_OBTAINED = 6388, -- Obtained: <item>.
GIL_OBTAINED = 6389, -- Obtained <number> gil.
KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>.
KEYITEM_LOST = 6392, -- Lost key item: <keyitem>.
NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here.
CONQUEST_BASE = 7049, -- Tallying conquest results...
BEASTMEN_BANNER = 7130, -- There is a beastmen's banner.
CONQUEST = 7217, -- You've earned conquest points!
FISHING_MESSAGE_OFFSET = 7550, -- You can't fish here.
DIG_THROW_AWAY = 7563, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away.
FIND_NOTHING = 7565, -- You dig and you dig, but find nothing.
FLOWER_BLOOMING = 7656, -- A large flower is blooming.
FOUND_NOTHING_IN_FLOWER = 7659, -- You find nothing inside the flower.
FEEL_DIZZY = 7660, -- You feel slightly dizzy. You must have breathed in too much of the pollen.
SOMETHING_BETTER = 7673, -- Don't you have something better to do right now?
CANNOT_REMOVE_FRAG = 7676, -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed...
ALREADY_OBTAINED_FRAG = 7677, -- You have already obtained this monument's <keyitem>. Try searching for another.
ALREADY_HAVE_ALL_FRAGS = 7678, -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine!
FOUND_ALL_FRAGS = 7679, -- You have obtained <keyitem>! You now have all 8 fragments of light!
ZILART_MONUMENT = 7680, -- It is an ancient Zilart monument.
LOGGING_IS_POSSIBLE_HERE = 7697, -- Logging is possible here if you have <item>.
HARVESTING_IS_POSSIBLE_HERE = 7704, -- Harvesting is possible here if you have <item>.
SOMETHING_IS_BURIED_HERE = 7747, -- It looks like something is buried here. If you had <item> you could dig it up.
PLAYER_OBTAINS_ITEM = 7860, -- <name> obtains <item>!
UNABLE_TO_OBTAIN_ITEM = 7861, -- You were unable to obtain the item.
PLAYER_OBTAINS_TEMP_ITEM = 7862, -- <name> obtains the temporary item: <item>!
ALREADY_POSSESS_TEMP = 7863, -- You already possess that temporary item.
NO_COMBINATION = 7868, -- You were unable to enter a combination.
REGIME_REGISTERED = 10046, -- New training regime registered!
COMMON_SENSE_SURVIVAL = 12040, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world.
},
mob =
{
MISCHIEVOUS_MICHOLAS_PH =
{
[17281148] = 17281149, -- -265.616 -0.5 -24.389
},
TIPHA = 17281030,
CARTHI = 17281031,
ROSE_GARDEN_PH = 17281356,
ROSE_GARDEN = 17281357,
VOLUPTUOUS_VILMA = 17281358,
},
npc =
{
CASKET_BASE = 17281559,
BLUE_RAFFLESIA_OFFSET = 17281586,
OVERSEER_BASE = 17281600,
CERMET_HEADSTONE = 17281625,
PEDDLESTOX = 17281640,
BEASTMEN_TREASURE =
{
17281643, -- qm3
17281644, -- qm4
17281645, -- qm5
17281646, -- qm6
17281647, -- qm7
17281648, -- qm8
17281649, -- qm9
17281650, -- qm10
},
HARVESTING =
{
17281636,
17281637,
17281638,
},
LOGGING =
{
17281630,
17281631,
17281632,
17281633,
17281634,
17281635,
},
},
}
return zones[dsp.zone.YUHTUNGA_JUNGLE]
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Sanraku.lua | 9 | 9782 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Sanraku
-- Type: Zeni NM pop item and trophy management.
-- !pos -125.724 0.999 22.136 50
-----------------------------------
require("scripts/globals/keyitems")
require("scripts/globals/besieged")
local ID = require("scripts/zones/Aht_Urhgan_Whitegate/IDs")
-----------------------------------
function onTrade(player,npc,trade)
--[[
local trophies =
{
2616, 2617, 2618, 2613, 2614, 2615, 2610, 2611, 2612,
2609, 2626, 2627, 2628, 2623, 2624, 2625, 2620, 2621,
2622, 2619, 2636, 2637, 2638, 2633, 2634, 2635, 2630,
2631, 2632, 2629
}
local seals =
{
dsp.ki.MAROON_SEAL, dsp.ki.MAROON_SEAL, dsp.ki.MAROON_SEAL,
dsp.ki.APPLE_GREEN_SEAL,dsp.ki.APPLE_GREEN_SEAL,dsp.ki.APPLE_GREEN_SEAL,
dsp.ki.CHARCOAL_GREY_SEAL, dsp.ki.DEEP_PURPLE_SEAL, dsp.ki.CHESTNUT_COLORED_SEAL,
dsp.ki.LILAC_COLORED_SEAL,
dsp.ki.CERISE_SEAL,dsp.ki.CERISE_SEAL,dsp.ki.CERISE_SEAL,
dsp.ki.SALMON_COLORED_SEAL,dsp.ki.SALMON_COLORED_SEAL,dsp.ki.SALMON_COLORED_SEAL,
dsp.ki.PURPLISH_GREY_SEAL, dsp.ki.GOLD_COLORED_SEAL, dsp.ki.COPPER_COLORED_SEAL,
dsp.ki.BRIGHT_BLUE_SEAL,
dsp.ki.PINE_GREEN_SEAL,dsp.ki.PINE_GREEN_SEAL,dsp.ki.PINE_GREEN_SEAL,
dsp.ki.AMBER_COLORED_SEAL,dsp.ki.AMBER_COLORED_SEAL,dsp.ki.AMBER_COLORED_SEAL,
dsp.ki.FALLOW_COLORED_SEAL,dsp.ki.TAUPE_COLORED_SEAL,dsp.ki.SIENNA_COLORED_SEAL,
dsp.ki.LAVENDER_COLORED_SEAL
}
if trade:getItemCount() == 1 then
if trade:hasItemQty(2477,1) then -- Trade Soul Plate
zeni = math.random(1,200) -- random value since soul plates aren't implemented yet.
player:tradeComplete()
player:addCurrency("zeni_point", zeni)
player:startEvent(910,zeni)
else
znm = -1
found = false
while znm <= 30 and not(found) do
znm = znm + 1
found = trade:hasItemQty(trophies[znm + 1],1)
end
if (found) then
znm = znm + 1
if player:hasKeyItem(seals[znm]) == false then
player:tradeComplete()
player:addKeyItem(seals[znm])
player:startEvent(912,0,0,0,seals[znm])
else
player:messageSpecial(ID.text.SANCTION + 8,seals[znm]) -- You already possess .. (not sure this is authentic)
end
end
end
end
]]
end
function onTrigger(player,npc)
--[[
if player:getCharVar("ZeniStatus") == 0 then
player:startEvent(908)
else
local param = 2140136440 -- Defaut bitmask, Tier 1 ZNM Menu + don't ask option
-- Tinnin Path
if player:hasKeyItem(dsp.ki.MAROON_SEAL) then
param = param - 0x38 -- unlocks Tinnin path tier 2 ZNMs.
end
if player:hasKeyItem(dsp.ki.APPLE_GREEN_SEAL) then
param = param - 0x1C0 -- unlocks Tinnin path tier 3 ZNMs.
end
if player:hasKeyItem(dsp.ki.CHARCOAL_GREY_SEAL) and player:hasKeyItem(dsp.ki.DEEP_PURPLE_SEAL) and player:hasKeyItem(dsp.ki.CHESTNUT_COLORED_SEAL) then
param = param - 0x200 -- unlocks Tinnin.
end
-- Sarameya Path
if player:hasKeyItem(dsp.ki.CERISE_SEAL) then
param = param - 0xE000 -- unlocks Sarameya path tier 2 ZNMs.
end
if player:hasKeyItem(dsp.ki.SALMON_COLORED_SEAL) then
param = param - 0x70000 -- unlocks Sarameya path tier 3 ZNMs.
end
if player:hasKeyItem(dsp.ki.PURPLISH_GREY_SEAL) and player:hasKeyItem(dsp.ki.GOLD_COLORED_SEAL) and player:hasKeyItem(dsp.ki.COPPER_COLORED_SEAL) then
param = param - 0x80000 -- unlocks Sarameya.
end
-- Tyger Path
if player:hasKeyItem(dsp.ki.PINE_GREEN_SEAL) then
param = param - 0x3800000 -- unlocks Tyger path tier 2 ZNMs.
end
if player:hasKeyItem(dsp.ki.AMBER_COLORED_SEAL) then
param = param - 0x1C000000 -- unlocks Tyger path tier 3 ZNMs.
end
if player:hasKeyItem(dsp.ki.TAUPE_COLORED_SEAL) and player:hasKeyItem(dsp.ki.FALLOW_COLORED_SEAL) and player:hasKeyItem(dsp.ki.SIENNA_COLORED_SEAL) then
param = param - 0x20000000 -- unlocks Tyger.
end
if player:hasKeyItem(dsp.ki.LILAC_COLORED_SEAL) and player:hasKeyItem(dsp.ki.BRIGHT_BLUE_SEAL) and player:hasKeyItem(dsp.ki.LAVENDER_COLORED_SEAL) then
param = param - 0x40000000 -- unlocks Pandemonium Warden.
end
player:startEvent(909,param)
end
]]
end
function onEventUpdate(player,csid,option)
-- printf("updateRESULT: %u",option)
--[[
local lures =
{
2580, 2581, 2582, 2577, 2578, 2579, 2574, 2575, 2576,
2573, 2590, 2591, 2592, 2587, 2588, 2589, 2584, 2585,
2586, 2583, 2600, 2601, 2602, 2597, 2598, 2599, 2594,
2595, 2596, 2593, 2572
}
local seals =
{
dsp.ki.MAROON_SEAL, dsp.ki.MAROON_SEAL, dsp.ki.MAROON_SEAL,
dsp.ki.APPLE_GREEN_SEAL,dsp.ki.APPLE_GREEN_SEAL,dsp.ki.APPLE_GREEN_SEAL,
dsp.ki.CHARCOAL_GREY_SEAL, dsp.ki.DEEP_PURPLE_SEAL, dsp.ki.CHESTNUT_COLORED_SEAL,
dsp.ki.LILAC_COLORED_SEAL,
dsp.ki.CERISE_SEAL,dsp.ki.CERISE_SEAL,dsp.ki.CERISE_SEAL,
dsp.ki.SALMON_COLORED_SEAL,dsp.ki.SALMON_COLORED_SEAL,dsp.ki.SALMON_COLORED_SEAL,
dsp.ki.PURPLISH_GREY_SEAL, dsp.ki.GOLD_COLORED_SEAL, dsp.ki.COPPER_COLORED_SEAL,
dsp.ki.BRIGHT_BLUE_SEAL,
dsp.ki.PINE_GREEN_SEAL,dsp.ki.PINE_GREEN_SEAL,dsp.ki.PINE_GREEN_SEAL,
dsp.ki.AMBER_COLORED_SEAL,dsp.ki.AMBER_COLORED_SEAL,dsp.ki.AMBER_COLORED_SEAL,
dsp.ki.FALLOW_COLORED_SEAL,dsp.ki.TAUPE_COLORED_SEAL,dsp.ki.SIENNA_COLORED_SEAL,
dsp.ki.LAVENDER_COLORED_SEAL
}
if csid == 909 then
local zeni = player:getCurrency("zeni_point")
if option >= 300 and option <= 302 then
if option == 300 then
salt = dsp.ki.SICKLEMOON_SALT
elseif option == 301 then
salt = dsp.ki.SILVER_SEA_SALT
elseif option == 302 then
salt = dsp.ki.CYAN_DEEP_SALT
end
if zeni < 500 then
player:updateEvent(2,500) -- not enough zeni
elseif player:hasKeyItem(salt) then
player:updateEvent(3,500) -- has salt already
else
player:updateEvent(1,500,0,salt)
player:addKeyItem(salt)
player:delCurrency("zeni_point", 500)
end
else -- player is interested in buying a pop item.
n = option % 10
if n <= 2 then
if option == 130 or option == 440 then
tier = 5
else
tier = 1
end
elseif n >= 3 and n <= 5 then
tier = 2
elseif n >= 6 and n <= 8 then
tier = 3
else
tier = 4
end
cost = tier * 1000 -- static pricing for now.
if option >= 100 and option <= 130 then
player:updateEvent(0,0,0,0,0,0,cost)
elseif option >= 400 and option <=440 then
if option == 440 then
option = 430
end
item = lures[option-399]
if option == 430 then -- Pandemonium Warden
keyitem1 = dsp.ki.LILAC_COLORED_SEAL keyitem2 = dsp.ki.BRIGHT_BLUE_SEAL keyitem3 = dsp.ki.LAVENDER_COLORED_SEAL
elseif option == 409 then -- Tinnin
keyitem1 = dsp.ki.CHARCOAL_GREY_SEAL keyitem2 = dsp.ki.DEEP_PURPLE_SEAL keyitem3 = dsp.ki.CHESTNUT_COLORED_SEAL
elseif option == 419 then -- Sarameya
keyitem1 = dsp.ki.PURPLISH_GREY_SEAL keyitem2 = dsp.ki.GOLD_COLORED_SEAL keyitem3 = dsp.ki.COPPER_COLORED_SEAL
elseif option == 429 then -- Tyger
keyitem1 = dsp.ki.TAUPE_COLORED_SEAL keyitem2 = dsp.ki.FALLOW_COLORED_SEAL keyitem3 = dsp.ki.SIENNA_COLORED_SEAL
else
keyitem1 = seals[option - 402] keyitem2 = nil keyitem3 = nil
end
if cost > zeni then
player:updateEvent(2, cost, item, keyitem1,keyitem2,keyitem3) -- you don't have enough zeni.
elseif player:addItem(item) then
if keyitem1 ~= nil then
player:delKeyItem(keyitem1)
end
if keyitem2 ~= nil then
player:delKeyItem(keyitem2)
end
if keyitem3 ~= nil then
player:delKeyItem(keyitem3)
end
player:updateEvent(1, cost, item, keyitem1,keyitem2,keyitem3)
player:delCurrency("zeni_point", cost)
else
player:updateEvent(4, cost, item, keyitem1,keyitem2,keyitem3) -- Cannot obtain.
end
elseif option == 500 then -- player has declined to buy a pop item
player:updateEvent(1,1) -- restore the "Gaining access to the islets" option.
else
-- print("onEventSelection - CSID:",csid)
-- print("onEventSelection - option ===",option)
end
end
end
]]
end
function onEventFinish(player,csid,option)
-- printf("finishRESULT: %u",option)
--[[
if csid == 908 then
player:setCharVar("ZeniStatus",1)
player:addCurrency("zeni_point", 2000)
end
]]
end | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Southern_San_dOria_[S]/npcs/_6eo.lua | 31 | 1367 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Door:House
-- @zone 80
-- @pos 148 0 27
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR, KNOT_QUITE_THERE) == QUEST_ACCEPTED and player:getVar("KnotQuiteThere") == 3) then
player:startEvent(0x003F);
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 == 0x003F) then
player:completeQuest(CRYSTAL_WAR, KNOT_QUITE_THERE);
player:addItem(751);
player:messageSpecial(ITEM_OBTAINED,751); --Platinum Beastcoin
player:setVar("KnotQuiteThere",0);
end
end; | gpl-3.0 |
exhu/miod | notes/expr_model.lua | 1 | 3546 | --[[
Modelling compile-time expression evaluation.
--]]
local pp = require 'pp'
local M = {}
-- utils --
local function enum(t)
local newt = {}
for i = 1, #t do
newt[t[i]] = i
end
return newt
end
-- === ---
-- constant folding phase, compile-time evaluation of expressions
-- 'value' means known constant or literal
-- 'unknown' means undefined variable for 1st pass or error for 2nd pass
M.node_value_kind = enum { 'unknown', 'runtime', 'value', 'generic' }
M.symitem_kind = enum { 'unit', 'alias', 'struct', 'interface',
'class', 'proc', 'method', 'var', 'const', 'enum' }
pp(M.node_value_kind)
function M.new_node_result(kind, v_type)
assert(M.node_value_kind[kind])
return { value_kind = kind, value_type = v_type }
end
--[[
function M.create_ast_node(name)
return { name = name, result = M.create_node_result('unknown', nil) }
end
local sample_ast = { {'plus', nodes = { {value_kind = 'value', value = 3 },
{value_kind = 'value', value = 4}} } }
--]]
local numeric_ops = enum { 'neg', 'bnot', 'mul', 'div', 'mod', 'plus', 'minus',
'bor', 'band', 'xor', 'shl', 'shr', 'gt', 'lt', 'ge', 'le', 'eq', 'ne' }
local function is_string(a,b)
return a.value_type == b.value_type and a.value_type == 'string'
end
local numeric_types = enum { 'cardinal', 'int32', 'uint32', 'int64', 'float', 'double' }
local function is_numeric(a,b)
return numeric_types[a.value_type] and numeric_types[b.value_type]
end
local function calc_values(op, a,b)
if a.value_type == 'unknown' or b.value_type == 'unknown' then
return M.create_node_result('unknown', nil)
end
if is_string(a,b) then
if op == 'eq' or op == 'ne' or op == 'plus' then
if a.value_kind == 'value' and b.value_kind == 'value' then
if op == 'plus' then
-- concatenate strings
return M.create_node_result('value', 'string')
else
return "unsupported operation"
end
end
return M.create_node_result('runtime', 'string')
end
else
if is_numeric(a,b) then
if numeric_ops[op] == nil then
return "unsupported operation"
end
if is_comparable(a,b) then
local new_type = promote(a,b)
local res = M.create_node_result('value', new_type)
-- do operation
res.value = "new value"
return res
else
return "incompatible numeric types"
end
else
if is_bool(a,b) then
-- todo validate op
else
return "unsupported operation for the types given"
end
end
end
return M.create_node_result('unknown', nil)
end
local type_id = enum { 'int32', 'cardinal', 'struct', 'struct_ref' }
local function int_type(type_id, bits)
local t = {}
t.type_id = type_id
t.bits = bits
return t
end
-- struct_decl_item = decl_struct from symbol table
local function struct_type(struct_decl_item)
local t = {}
t.type_id = 'struct'
t.struct = struct_decl
return t
end
local function struct_ref(struct_decl_item)
local t = {}
t.type_id = 'struct_ref'
t.struct = struct_decl
return t
end
local symtable = {}
local function decl_struct(name, fields)
local t = {kind = 'struct', fields = fields}
symtable[name] = t
return t
end
----------------
return M
| mit |
Fenix-XI/Fenix | scripts/zones/Windurst_Woods/Zone.lua | 26 | 2352 | -----------------------------------
--
-- Zone: Windurst_Woods (241)
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/events/harvest_festivals");
require("scripts/globals/zone");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
applyHalloweenNpcCostumes(zone:getID())
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
-- FIRST LOGIN (START CS)
if (player:getPlaytime(false) == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x016F;
end
player:setPos(0,0,-50,0);
player:setHomePoint();
end
-- MOG HOUSE EXIT
if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
position = math.random(1,5) + 37;
player:setPos(-138,-10,position,0);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
return cs;
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x016F) then
player:messageSpecial(ITEM_OBTAINED,0x218);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end; | gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Al_Zahbi/npcs/Mihli_Aliapoh.lua | 13 | 1049 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Mihli Aliapoh
-- Type: Waterserpent General
-- @zone: 48
-- @pos -22.615 -7 78.907
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x010b);
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 |
grmss214/shg | plugins/inrealm.lua | 850 | 25085 | -- 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 |
sina021/bottg | plugins/inrealm.lua | 850 | 25085 | -- 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 |
aqasaeed/w | plugins/inrealm.lua | 850 | 25085 | -- 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 |
Fenix-XI/Fenix | scripts/zones/Port_Windurst/npcs/Pichichi.lua | 13 | 2775 | -----------------------------------
-- Area: Port Windurst
-- NPC: Pichichi
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY);
KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS);
InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET);
OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS);
CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS);
ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE);
if (ThePromise == QUEST_COMPLETED) then
Message = math.random(0,1)
if (Message == 1) then
player:startEvent(0x0212);
else
player:startEvent(0x0218);
end
elseif (CryingOverOnions == QUEST_COMPLETED) then
player:startEvent(0x01ff);
elseif (CryingOverOnions == QUEST_ACCEPTED) then
player:startEvent(0x01f7);
elseif (OnionRings == QUEST_COMPLETED) then
player:startEvent(0x01bd);
elseif (OnionRings == QUEST_ACCEPTED ) then
player:startEvent(0x01b6);
elseif (InspectorsGadget == QUEST_COMPLETED) then
player:startEvent(0x01a7);
elseif (InspectorsGadget == QUEST_ACCEPTED) then
player:startEvent(0x019f);
elseif (KnowOnesOnions == QUEST_COMPLETED) then
player:startEvent(0x019b);
elseif (KnowOnesOnions == QUEST_ACCEPTED) then
KnowOnesOnionsVar = player:getVar("KnowOnesOnions");
if (KnowOnesOnionsVar == 2) then
player:startEvent(0x019a);
else
player:startEvent(0x018b);
end
elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then
player:startEvent(0x0181);
elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then
player:startEvent(0x0176);
else
player:startEvent(0x016c);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
dualface/killpests | src/framework/cocos2dx.lua | 18 | 1999 | --[[
Copyright (c) 2011-2014 chukong-inc.com
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.
]]
--------------------------------
-- @module cocos2dx
--[[--
针对 cocos2d-x 的一些封装和扩展
预定义的节点事件:
- cc.NODE_EVENT - enter, exit 等事件
- cc.NODE_ENTER_FRAME_EVENT - 帧事件
- cc.NODE_TOUCH_EVENT - 触摸事件
- cc.NODE_TOUCH_CAPTURE_EVENT - 捕获触摸事件
预定义的层事件:
- cc.ACCELERATE_EVENT - 重力感应事件
- cc.KEYPAD_EVENT - 硬件按键事件
预定义的触摸模式:
- cc.TOUCH_MODE_ALL_AT_ONCE - 多点触摸
- cc.TOUCH_MODE_ONE_BY_ONE - 单点触摸
]]
local p = cc.PACKAGE_NAME .. ".cocos2dx."
if not cc.p then
-- cc.p exist, so the cocos.init have loaded
require(p .. "Cocos2dConstants")
require(p .. "OpenglConstants")
require(p .. "Cocos2d")
require(p .. "StudioConstants")
end
require(p .. "Event")
require(p .. "ActionEx")
require(p .. "NodeEx")
require(p .. "SceneEx")
require(p .. "SpriteEx")
require(p .. "DrawNodeEx")
| mit |
Fenix-XI/Fenix | scripts/globals/weaponskills/tachi_jinpu.lua | 11 | 1398 | -----------------------------------
-- Tachi Jinpu
-- Great Katana weapon skill
-- Skill level: 150
-- Two-hit attack. Deals Physical and wind elemental damage to enemy. Additonal Effect Damage varies with TP.
-- Will stack with Sneak Attack and Souleater.
-- Aligned with the Breeze Gorget & Shadow Gorget.
-- Aligned with the Breeze Belt & Shadow Belt.
-- Element: Wind
-- Modifiers: STR:30%
-- 100%TP 200%TP 300%TP
-- .5 .75 1.00
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_WIND;
params.skill = SKILL_GKT;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.ftp100 = 0.5; params.ftp200 = 0.75; params.ftp300 = 1;
params.str_wsc = 0.3;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, wsID, params, tp, primary);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Norg/npcs/Magephaud.lua | 17 | 2210 | -----------------------------------
-- Area: Norg
-- NPC: Magephaud
-- Standard Info NPC
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
EveryonesGrudge = player:getQuestStatus(OUTLANDS,EVERYONES_GRUDGE);
if (EveryonesGrudge == QUEST_ACCEPTED) then
if (trade:hasItemQty(748,3) and trade:getItemCount() == 3) then
player:startEvent(0x0076,748);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
nFame = player:getFameLevel(NORG);
if (player:getQuestStatus(OUTLANDS,EVERYONES_GRUDGE) == QUEST_AVAILABLE and player:getVar("EVERYONES_GRUDGE_KILLS") >= 1 and nFame >= 2) then
player:startEvent(0x0074,748); -- Quest start - you have tonberry kills?! I got yo back ^.-
elseif (player:getVar("EveryonesGrudgeStarted") == 1) then
player:startEvent(0x0075,748);
elseif (player:getQuestStatus(OUTLANDS,EVERYONES_GRUDGE) == QUEST_COMPLETED) then
player:startEvent(0x0077); -- After completion cs
else
player:startEvent(0x0073);
end
printf("CSID: %u",nFame);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
if (csid == 0x0074) then
player:addQuest(OUTLANDS,EVERYONES_GRUDGE);
player:setVar("EveryonesGrudgeStarted",1);
elseif (csid == 0x0076) then
player:completeQuest(OUTLANDS,EVERYONES_GRUDGE);
player:tradeComplete();
player:addFame(OUTLANDS,80);
player:addKeyItem(291); -- Permanent Tonberry key
player:messageSpecial(KEYITEM_OBTAINED,291);
player:setVar("EveryonesGrudgeStarted",0);
player:addTitle(HONORARY_DOCTORATE_MAJORING_IN_TONBERRIES);
end
end;
| gpl-3.0 |
DarkstarProject/darkstar | scripts/globals/items/bowl_of_cursed_soup.lua | 11 | 1308 | -----------------------------------------
-- ID: 4235
-- Item: Bowl of Cursed Soup
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Strength -7
-- Dexterity -7
-- Agility -7
-- Vitality -7
-- Intelligence -7
-- Mind -7
-- Charisma -7
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,14400,4235)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.STR, -7)
target:addMod(dsp.mod.DEX, -7)
target:addMod(dsp.mod.AGI, -7)
target:addMod(dsp.mod.VIT, -7)
target:addMod(dsp.mod.INT, -7)
target:addMod(dsp.mod.MND, -7)
target:addMod(dsp.mod.CHR, -7)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, -7)
target:delMod(dsp.mod.DEX, -7)
target:delMod(dsp.mod.AGI, -7)
target:delMod(dsp.mod.VIT, -7)
target:delMod(dsp.mod.INT, -7)
target:delMod(dsp.mod.MND, -7)
target:delMod(dsp.mod.CHR, -7)
end
| gpl-3.0 |
Fenix-XI/Fenix | scripts/zones/Dynamis-Tavnazia/Zone.lua | 13 | 2401 | -----------------------------------
--
-- Zone: Dynamis-Tavnazia
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Dynamis-Tavnazia/TextIDs"] = nil;
require("scripts/zones/Dynamis-Tavnazia/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaTavnazia]UniqueID")) then
if (player:isBcnmsFull() == 1) then
if (player:hasStatusEffect(EFFECT_DYNAMIS, 0) == false) then
inst = player:addPlayerToDynamis(1289);
if (inst == 1) then
player:bcnmEnter(1289);
else
cs = 0x0065;
end
else
player:bcnmEnter(1289);
end
else
inst = player:bcnmRegister(1289);
if (inst == 1) then
player:bcnmEnter(1289);
else
cs = 0x0065;
end
end
else
cs = 0x0065;
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 == 0x0065) then
player:setPos(0.0,-7,-23,195,26);
end
end;
| gpl-3.0 |
Fenix-XI/Fenix | scripts/globals/mobskills/Glacier_Splitter.lua | 33 | 1074 | ---------------------------------------------
-- Glacier Splitter
--
-- Description: Cleaves into targets in a fan-shaped area. Additional effect: Paralyze
-- Type: Physical
-- Utsusemi/Blink absorb: 1-3 shadows
-- Range: Unknown cone
-- Notes: Only used the Aern wielding a sword (RDM, DRK, and PLD).
---------------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/monstertpmoves");
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
return 0;
end;
function onMobWeaponSkill(target, mob, skill)
local numhits = math.random(1,3);
local accmod = 1;
local dmgmod = 1;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded);
local typeEffect = EFFECT_PARALYSIS;
MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 15, 0, 120);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
asdofindia/prosody-modules | mod_http_index/mod_http_index.lua | 31 | 3606 | local st = require "util.stanza";
local url = require"socket.url";
module:depends"http";
-- local dump = require"util.serialization".new"dump".serialize;
local function template(data)
--[[ DOC
Like util.template, but deals with plain text
Returns a closure that is called with a table of values
{name} is substituted for values["name"] and is XML escaped
{name!} is substituted without XML escaping
{name?} is optional and is replaced with an empty string if no value exists
]]
return function(values)
return (data:gsub("{([^}]-)(%p?)}", function (name, opt)
local value = values[name];
if value then
if opt ~= "!" then
return st.xml_escape(value);
end
return value;
elseif opt == "?" then
return "";
end
end));
end
end
-- TODO Move templates into files
local base = template(template[[
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="generator" value="prosody/{prosody_version} mod_{mod_name}">
<link rel="canonical" href="{canonical}">
<title>{title}</title>
<style>
body{background-color:#eeeeec;margin:1ex 0;padding-bottom:3em;font-family:Arial,Helvetica,sans-serif;}
header,footer{margin:1ex 1em;}
footer{font-size:smaller;color:#babdb6;}
.content{background-color:white;padding:1em;list-style-position:inside;}
nav{font-size:large;margin:1ex 1ex;clear:both;line-height:1.5em;}
nav a{padding: 1ex;text-decoration:none;}
nav a[rel="up"]{font-size:smaller;}
nav a[rel="prev"]{float:left;}
nav a[rel="next"]{float:right;}
nav a[rel="next::after"]{content:" →";}
nav a[rel="prev::before"]{content:"← ";}
nav a:empty::after,nav a:empty::before{content:""}
@media screen and (min-width: 460px) {
nav{font-size:x-large;margin:1ex 1em;}
}
a:link,a:visited{color:#2e3436;text-decoration:none;}
a:link:hover,a:visited:hover{color:#3465a4;}
ul,ol{padding:0;}
li{list-style:none;}
hr{visibility:hidden;clear:both;}
br{clear:both;}
li time{float:right;font-size:small;opacity:0.2;}
li:hover time{opacity:1;}
.room-list .description{font-size:smaller;}
q.body::before,q.body::after{content:"";}
.presence .verb{font-style:normal;color:#30c030;}
.presence.unavailable .verb{color:#c03030;}
</style>
</head>
<body>
<header>
<h1>{title}</h1>
{header!}
</header>
<hr>
<div class="content">
{body!}
</div>
<hr>
<footer>
{footer!}
<br>
<div class="powered-by">Prosody {prosody_version?}</div>
</footer>
</body>
</html>
]] { prosody_version = prosody.version, mod_name = module.name });
local canonical = module:http_url(nil, "/");
local page_template = template(base{
canonical = canonical;
title = "HTTP stuff";
header = "";
body = [[
<nav>
<ul>
{lines!}
</ul>
</nav>
]];
footer = "";
});
local line_template = template[[
<li><a href="{url}" title="{module}">{name}</a></li>
]];
local function relative(base, link)
base = url.parse(base);
link = url.parse(link);
for k,v in pairs(base) do
if link[k] == v then
link[k] = nil;
end
end
return url.build(link);
end
local function handler(event)
local items = module:get_host_items("http-provider");
local item;
for i = 1, #items do
item = items[i];
if module.name ~= item._provided_by then
items[i] = line_template{
name = item.name;
module = "mod_" .. item._provided_by;
url = relative(canonical, module:http_url(item.name, item.default_path));
};
else
items[i] = "";
end
end
event.response.headers.content_type = "text/html";
return page_template{
lines = table.concat(items);
};
end
module:provides("http", {
route = {
["GET /"] = handler;
};
default_path = "/";
});
| mit |
tcatm/luci | applications/luci-app-multiwan/luasrc/controller/multiwan.lua | 62 | 1929 | module("luci.controller.multiwan", package.seeall)
function index()
local fs = require "nixio.fs"
if not fs.access("/etc/config/multiwan") then
return
end
local page
page = entry({"admin", "network", "multiwan"}, cbi("multiwan/multiwan"), _("Multi-WAN"))
page.dependent = true
entry({"admin", "network", "multiwan", "status"}, call("multiwan_status"))
page = entry({"mini", "network", "multiwan"}, cbi("multiwan/multiwanmini", {autoapply=true}), _("Multi-WAN"))
page.dependent = true
end
function multiwan_status()
local nfs = require "nixio.fs"
local cachefile = "/tmp/.mwan/cache"
local rv = { }
cachefile = nfs.readfile(cachefile)
if cachefile then
local ntm = require "luci.model.network".init()
_, _, wan_if_map = string.find(cachefile, "wan_if_map=\"([^\"]*)\"")
_, _, wan_fail_map = string.find(cachefile, "wan_fail_map=\"([^\"]*)\"")
_, _, wan_recovery_map = string.find(cachefile, "wan_recovery_map=\"([^\"]*)\"")
rv.wans = { }
wansid = {}
for wanname, wanifname in string.gfind(wan_if_map, "([^%[]+)%[([^%]]+)%]") do
local wanlink = ntm:get_interface(wanifname)
wanlink = wanlink and wanlink:get_network()
wanlink = wanlink and wanlink:adminlink() or "#"
wansid[wanname] = #rv.wans + 1
rv.wans[wansid[wanname]] = { name = wanname, link = wanlink, ifname = wanifname, status = "ok", count = 0 }
end
for wanname, failcount in string.gfind(wan_fail_map, "([^%[]+)%[([^%]]+)%]") do
if failcount == "x" then
rv.wans[wansid[wanname]].status = "ko"
else
rv.wans[wansid[wanname]].status = "failing"
rv.wans[wansid[wanname]].count = failcount
end
end
for wanname, recoverycount in string.gfind(wan_recovery_map, "([^%[]+)%[([^%]]+)%]") do
rv.wans[wansid[wanname]].status = "recovering"
rv.wans[wansid[wanname]].count = recoverycount
end
end
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
end
| apache-2.0 |
emender/emender | src/writers/messageWriter.lua | 1 | 2817 | -- messageWriter.lua - a writer for the very simple summary plain text file format
-- Copyright (C) 2014 - 2017 Pavel Tisnovsky
-- This file is part of Emender.
-- 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, version 3 of the License.
--
-- This program is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTA-
-- BILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public
-- License for more details.
--
-- You should have received a copy of the GNU General Public License along
-- with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Data structure that holds all exported variables and functions
--
local messageWriter = {
}
--
-- Do nothing:
--
function messageWriter.writeHeader(fout, results)
return
end
--
-- Write the report footer to the file:
--
function messageWriter.writeFooter(fout, results)
local passed = results.passedTests
local failed = results.failedTests
local total = passed + failed
fout:write("Total: " .. total .. " Passed: " .. passed .. " Failed: " .. failed)
end
--
-- Do nothing:
--
function messageWriter.writeSuiteStart(fout, testSuite)
return
end
--
-- Do nothing:
--
function messageWriter.writeSuiteEnd(fout, testSuite)
return
end
--
-- Do nothing:
--
function messageWriter.writeCaseStart(fout, testCase)
return
end
--
-- Do nothing:
--
function messageWriter.writeCaseEnd(fout, testCaseInfo)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestPass(fout, testName, message)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestFail(fout, testName, message)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestFailLink(fout, testName, message, url)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestInfo(fout, testName, message)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestInfoLink(fout, testName, message, url)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestDebug(fout, testName, message)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestError(fout, testName, message)
return
end
--
-- Do nothing:
--
function messageWriter.writeTestLink(fout, testName, message, url)
return
end
--
-- Setup color output or no color output.
--
function messageWriter.setColorOutput(colorOutput)
end
--
-- Called to initialize the writer.
--
function messageWriter.initialize(outdir)
end
--
-- Called to finalize the writer.
--
function messageWriter.finalize(outdir)
end
--
-- Export the module API
--
return messageWriter
| gpl-3.0 |
DarkstarProject/darkstar | scripts/zones/Waughroon_Shrine/bcnms/operation_desert_swarm.lua | 9 | 1077 | -----------------------------------
-- Operation Desert Storm
-- Waughroon Shrine KSNM30, Lachesis Orb
-- !additem 1178
-----------------------------------
require("scripts/globals/battlefield")
-----------------------------------
function onBattlefieldInitialise(battlefield)
battlefield:setLocalVar("loot", 1)
end
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), 0)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
| gpl-3.0 |
soheildiscover/soheil | plugins/media.lua | 376 | 1679 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
Fenix-XI/Fenix | scripts/zones/Windurst_Waters/npcs/Cochal-Monchal.lua | 13 | 1597 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Cochal-Monchal
-- Involved in Quest: Dark Legacy
-- @zone 238
-- @pos -52 -6 110
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getVar("darkLegacyCS") == 2) then
player:startEvent(0x02b9,0,DARKSTEEL_FORMULA);
elseif (player:getVar("darkLegacyCS") == 3) then
player:startEvent(0x02ba,0,DARKSTEEL_FORMULA);
elseif (player:hasKeyItem(DARKSTEEL_FORMULA)) then
player:startEvent(0x02bb,0,DARKSTEEL_FORMULA);
else
player:startEvent(0x2b8);
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 == 0x02b9) then
player:setVar("darkLegacyCS",3);
player:delKeyItem(LETTER_FROM_THE_DARKSTEEL_FORGE);
end
end; | gpl-3.0 |
marcel-sch/luci | libs/luci-lib-nixio/docsrc/nixio.File.lua | 173 | 4457 | --- Large File Object.
-- Large file operations are supported up to 52 bits if the Lua number type is
-- double (default).
-- @cstyle instance
module "nixio.File"
--- Write to the file descriptor.
-- @class function
-- @name File.write
-- @usage <strong>Warning:</strong> It is not guaranteed that all data
-- in the buffer is written at once especially when dealing with pipes.
-- 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
--- Read from a file descriptor.
-- @class function
-- @name File.read
-- @usage <strong>Warning:</strong> It is not guaranteed that all requested data
-- is read at once especially when dealing with pipes.
-- 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
--- Reposition read / write offset of the file descriptor.
-- The seek will be done either from the beginning of the file or relative
-- to the current position or relative to the end.
-- @class function
-- @name File.seek
-- @usage This function calls lseek().
-- @param offset File Offset
-- @param whence Starting point [<strong>"set"</strong>, "cur", "end"]
-- @return new (absolute) offset position
--- Return the current read / write offset of the file descriptor.
-- @class function
-- @name File.tell
-- @usage This function calls lseek() with offset 0 from the current position.
-- @return offset position
--- Synchronizes the file with the storage device.
-- Returns when the file is successfully written to the disk.
-- @class function
-- @name File.sync
-- @usage This function calls fsync() when data_only equals false
-- otherwise fdatasync(), on Windows _commit() is used instead.
-- @usage fdatasync() is only supported by Linux and Solaris. For other systems
-- the <em>data_only</em> parameter is ignored and fsync() is always called.
-- @param data_only Do not synchronize the metadata. (optional, boolean)
-- @return true
--- Apply or test a lock on the file.
-- @class function
-- @name File.lock
-- @usage This function calls lockf() on POSIX and _locking() on Windows.
-- @usage The "lock" command is blocking, "tlock" is non-blocking,
-- "ulock" unlocks and "test" only tests for the lock.
-- @usage The "test" command is not available on Windows.
-- @usage Locks are by default advisory on POSIX, but mandatory on Windows.
-- @param command Locking Command ["lock", "tlock", "ulock", "test"]
-- @param length Amount of Bytes to lock from current offset (optional)
-- @return true
--- Get file status and attributes.
-- @class function
-- @name File.stat
-- @param field Only return a specific field, not the whole table (optional)
-- @usage This function calls fstat().
-- @return Table containing: <ul>
-- <li>atime = Last access timestamp</li>
-- <li>blksize = Blocksize (POSIX only)</li>
-- <li>blocks = Blocks used (POSIX only)</li>
-- <li>ctime = Creation timestamp</li>
-- <li>dev = Device ID</li>
-- <li>gid = Group ID</li>
-- <li>ino = Inode</li>
-- <li>modedec = Mode converted into a decimal number</li>
-- <li>modestr = Mode as string as returned by `ls -l`</li>
-- <li>mtime = Last modification timestamp</li>
-- <li>nlink = Number of links</li>
-- <li>rdev = Device ID (if special file)</li>
-- <li>size = Size in bytes</li>
-- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li>
-- <li>uid = User ID</li>
-- </ul>
--- Close the file descriptor.
-- @class function
-- @name File.close
-- @return true
--- Get the number of the filedescriptor.
-- @class function
-- @name File.fileno
-- @return file descriptor number
--- (POSIX) Set the blocking mode of the file descriptor.
-- @class function
-- @name File.setblocking
-- @param blocking (boolean)
-- @return true | apache-2.0 |
jeiboor/nod32bot | plugins/plugins.lua | 1 | 6390 | do
-- Returns the key (index) in the config.enabled_plugins table
local function plugin_enabled( name )
for k,v in pairs(_config.enabled_plugins) do
if name == v then
return k
end
end
-- If not found
return false
end
-- Returns true if file exists in plugins folder
local function plugin_exists( name )
for k,v in pairs(plugins_names()) do
if name..'.lua' == v then
return true
end
end
return false
end
local function list_all_plugins(only_enabled)
local tmp = ''
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '/Disable➣'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '/Enable➣'
end
nact = nact+1
end
if not only_enabled or status == '/Enable➣' then
-- get the name
v = string.match (v, "(.*)%.lua")
text = text..nsum..'.'..status..' '..v..' \n'
end
end
local text = text..'\n\n'..nsum..' plugins installed\n\n'..nact..' plugins enabled\n\n'..nsum-nact..' plugins disabled'..tmp
return text
end
local function list_plugins(only_enabled)
local text = ''
local nsum = 0
for k, v in pairs( plugins_names( )) do
-- ✔ enabled, ❌ disabled
local status = '/Disable➣'
nsum = nsum+1
nact = 0
-- Check if is enabled
for k2, v2 in pairs(_config.enabled_plugins) do
if v == v2..'.lua' then
status = '/Enable➣'
end
nact = nact+1
end
if not only_enabled or status == '/Enable➣' then
-- get the name
v = string.match (v, "(.*)%.lua")
-- text = text..v..' '..status..'\n'
end
end
local text = text..'\nPlugins Reloaded !\n\n'..nact..' plugins enabled\n'..nsum..' plugins installed\n\n@BeyondTeam'
return text
end
local function reload_plugins( )
plugins = {}
load_plugins()
return list_plugins(true)
end
local function enable_plugin( plugin_name )
print('checking if '..plugin_name..' exists')
-- Check if plugin is enabled
if plugin_enabled(plugin_name) then
return ''..plugin_name..' is enabled'
end
-- Checks if plugin exists
if plugin_exists(plugin_name) then
-- Add to the config table
table.insert(_config.enabled_plugins, plugin_name)
print(plugin_name..' added to _config table')
save_config()
-- Reload the plugins
return reload_plugins( )
else
return ''..plugin_name..' does not exists'
end
end
local function disable_plugin( name, chat )
-- Check if plugins exists
if not plugin_exists(name) then
return ' '..name..' does not exists'
end
local k = plugin_enabled(name)
-- Check if plugin is enabled
if not k then
return ' '..name..' not enabled'
end
-- Disable and reload
table.remove(_config.enabled_plugins, k)
save_config( )
return reload_plugins(true)
end
local function disable_plugin_on_chat(receiver, plugin)
if not plugin_exists(plugin) then
return "Plugin doesn't exists"
end
if not _config.disabled_plugin_on_chat then
_config.disabled_plugin_on_chat = {}
end
if not _config.disabled_plugin_on_chat[receiver] then
_config.disabled_plugin_on_chat[receiver] = {}
end
_config.disabled_plugin_on_chat[receiver][plugin] = true
save_config()
return ' '..plugin..' disabled on this chat'
end
local function reenable_plugin_on_chat(receiver, plugin)
if not _config.disabled_plugin_on_chat then
return 'There aren\'t any disabled plugins'
end
if not _config.disabled_plugin_on_chat[receiver] then
return 'There aren\'t any disabled plugins for this chat'
end
if not _config.disabled_plugin_on_chat[receiver][plugin] then
return 'This plugin is not disabled'
end
_config.disabled_plugin_on_chat[receiver][plugin] = false
save_config()
return ' '..plugin..' is enabled again'
end
local function run(msg, matches)
-- Show the available plugins
if matches[1]:lower() == '!plist' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return list_all_plugins()
end
-- Re-enable a plugin for this chat
if matches[1] == '+' and matches[3] == 'chat' then
if is_momod(msg) then
local receiver = get_receiver(msg)
local plugin = matches[2]
print("enable "..plugin..' on this chat')
return reenable_plugin_on_chat(receiver, plugin)
end
end
-- Enable a plugin
if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if is_momod(msg) then
local plugin_name = matches[2]
print("enable: "..matches[2])
return enable_plugin(plugin_name)
end
end
-- Disable a plugin on a chat
if matches[1] == '-' and matches[3] == 'chat' then
if is_momod(msg) then
local plugin = matches[2]
local receiver = get_receiver(msg)
print("disable "..plugin..' on this chat')
return disable_plugin_on_chat(receiver, plugin)
end
end
-- Disable a plugin
if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo
if matches[2] == 'plug' then
return 'This plugin can\'t be disabled'
end
print("disable: "..matches[2])
return disable_plugin(matches[2])
end
-- Reload all the plugins!
if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
if matches[1]:lower() == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo
return reload_plugins(true)
end
end
return {
description = "Plugin to manage other plugins. Enable, disable or reload.",
usage = {
moderator = {
"!plug disable [plugin] chat : disable plugin only this chat.",
"!plug enable [plugin] chat : enable plugin only this chat.",
},
sudo = {
"!plist : list all plugins.",
"!pl + [plugin] : enable plugin.",
"!pl - [plugin] : disable plugin.",
"!pl * : reloads all plugins." },
},
patterns = {
"^!plist$",
"^!pl? (+) ([%w_%.%-]+)$",
"^!pl? (-) ([%w_%.%-]+)$",
"^!pl? (+) ([%w_%.%-]+) (chat)",
"^!pl? (-) ([%w_%.%-]+) (chat)",
"^!pl? (*)$",
"^[!/](reload)$"
},
run = run,
moderated = true, -- set to moderator mode
--privileged = true
}
end
| gpl-2.0 |
Fenix-XI/Fenix | scripts/globals/weaponskills/armor_break.lua | 10 | 1754 | -----------------------------------
-- Armor Break
-- Great Axe weapon skill
-- Skill level: 100
-- Lowers enemy's defense. Duration of effect varies with TP.
-- Lowers defense by as much as 25% if unresisted.
-- Strong against: Antica, Bats, Cockatrice, Dhalmel, Lizards, Mandragora, Worms.
-- Immune: Ahriman.
-- Will stack with Sneak Attack.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: Wind
-- Modifiers: STR:20% ; VIT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID, tp, primary)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.2; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0;
params.canCrit = false;
params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0;
params.atkmulti = 1;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.6; params.vit_wsc = 0.6;
end
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary);
if (damage > 0) then
local duration = (tp/1000 * 70) + 60;
if (target:hasStatusEffect(EFFECT_DEFENSE_DOWN) == false) then
target:addStatusEffect(EFFECT_DEFENSE_DOWN, 25, 0, duration);
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.