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 |
|---|---|---|---|---|---|
FilthyPeasantDEV/PokeBot | BizHawk-1.11.6/Lua/NES/Faxandu.lua | 7 | 2650 | ------------------------------
--Faxandu collision box viewer
--Author: Pasky
------------------------------
local HP = true -- toggle to false to turn off hitpoint display on enemies
function findbit(p)
return 2 ^ (p - 1)
end
function hasbit(x, p)
return x % (p + p) >= p
end
local function hex(val)
val = string.format("%X",val)
return val
end
memory.usememorydomain("System Bus")
local function player()
local x = memory.read_u8(0x9E)
local y = memory.read_u8(0xA1) + 0x1F
local hp = memory.read_u8(0x431)
-- vuln box
gui.drawBox(x,y,x+0xB,y+0x1B,0xFF0000FF,0x300000FF)
--attack box
local xrad = memory.read_u8(0xD2)
local yrad = memory.read_u8(0xD3)
local atk = memory.read_u8(0xA4)
local x2 = memory.read_u8(0xCE)
local y2 = memory.read_u8(0xD0) + 0x1F
if hasbit(atk,findbit(8)) then
gui.drawBox(x2,y2,x2+xrad,y2+yrad)
end
--Magic
local mag = memory.read_u8(0x02B3)
if mag ~= 0xFF then
local addr = 0x8B73 + mag
local magx = memory.read_u8(0x2B6)
local magy = memory.read_u8(0x2B8) + 0x1F
xrad = memory.read_u8(addr)
yrad = memory.read_u8(addr + 5)
gui.drawBox(magx,magy,magx+xrad,magy+yrad)
end
end
local function enemies()
local base = 0xBA
for i = 0,7,1 do
local etype = memory.read_u8(0x2CC + i)
if etype ~= 0xFF then
local x = memory.read_u8(base + i)
local y = memory.read_u8(base + 8 + i) + 0x1F
local hp = memory.read_u8(0x344 + i)
local atk = memory.read_u8(0x2E4 + i)
local atk2 = false
local facing = memory.read_u8(0x2DC + i)
local addr
if etype == 0x1F or etype == 0x21 then -- Check if dwarf or ???
if atk == 0x02 then
addr = 0x8A71
atk2 = true
else
addr = 0xB200 + (etype * 4) + 0x73
end
elseif etype == 0x20 then
if atk == 0x04 then
addr = 0x8A75
atk2 = true
else
addr = 0xB200 + (etype * 4) + 0x73
end
else
addr = 0xB200 + (etype * 4) + 0x73
end
local xoff = memory.read_s8(addr)
local yoff = memory.read_s8(addr + 1)
local xrad = memory.read_s8(addr + 2)
local yrad = memory.read_s8(addr + 3)
if not hasbit(facing,findbit(1)) and atk2 == true then
xoff = xoff * -1
xrad = xrad * -1
end
--Attack box
gui.drawBox(x,y+yoff,x+xoff+xrad,y+yoff+yrad,0xFFFF0000,0x70FF0000)
if HP == true then
gui.text(x,y-10,"HP: " .. hp)
end
--Vuln box
if memory.read_u8(etype + 0xB544) == 0 then
addr = 0xB407 + (etype * 2)
xrad = memory.read_u8(addr)
yrad = memory.read_u8(addr + 1)
gui.drawBox(x,y,x+xrad,y+yrad,0xFFFFFF00,0x30FFFF00)
end
end
end
end
while true do
player()
enemies()
emu.frameadvance()
end | mit |
woesdo/XY | plugins/boobs.lua | 90 | 1731 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
Samanstar/Assasin | plugins/boobs.lua | 90 | 1731 | do
-- Recursive function
local function getRandomButts(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.obutts.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt <= 3 then
print('Cannot get that butts, trying another one...')
return getRandomButts(attempt)
end
return 'http://media.obutts.ru/' .. data.preview
end
local function getRandomBoobs(attempt)
attempt = attempt or 0
attempt = attempt + 1
local res,status = http.request("http://api.oboobs.ru/noise/1")
if status ~= 200 then return nil end
local data = json:decode(res)[1]
-- The OpenBoobs API sometimes returns an empty array
if not data and attempt < 10 then
print('Cannot get that boobs, trying another one...')
return getRandomBoobs(attempt)
end
return 'http://media.oboobs.ru/' .. data.preview
end
local function run(msg, matches)
local url = nil
if matches[1] == "!boobs" then
url = getRandomBoobs()
end
if matches[1] == "!butts" then
url = getRandomButts()
end
if url ~= nil then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, url)
else
return 'Error getting boobs/butts for you, please try again later.'
end
end
return {
description = "Gets a random boobs or butts pic",
usage = {
"!boobs: Get a boobs NSFW image. 🔞",
"!butts: Get a butts NSFW image. 🔞"
},
patterns = {
"^!boobs$",
"^!butts$"
},
run = run
}
end
--Copyright; @behroozyaghi
--Persian Translate; @behroozyaghi
--ch : @nod32team
--کپی بدون ذکر منبع حرام است
| gpl-2.0 |
jiang42/Algorithm-Implementations | Rabin_Karp/Lua/Yonaba/rabin_karp.lua | 26 | 1376 | -- Rabin-Karp string searching algorithm implementation
-- See: http://en.wikipedia.org/wiki/Rabin%E2%80%93Karp_string_search_algorithm
-- Note: This implementation is based on the Python implementation of Shivam Bansal
-- See : https://github.com/kennyledet/Algorithm-Implementations/blob/master/Rabin_Karp/Python/shivam5992/rabin_karp.py
-- Rabin-Karp string searching function
-- needle : the pattern to search
-- haystack : the string in which the pattern will be searched
-- q : an optional prime number (internally used for hashing)
-- returns : an array of positions of all matches found, otherwise nil
return function(needle, haystack, q)
q = q or 19
local found = {}
local d, h, flag = 256, 1, 0
local M, N = #needle, #haystack
for i = 1, M - 1 do h = (h * d) % q end
local p, t = 0, 0
for i = 1, M do
p = (d * p + needle:sub(i, i):byte()) % q
t = (d * t + haystack:sub(i, i):byte()) % q
end
for i = 1, N - M + 1 do
if p == t then
local k = M
for j = 1, M do
if haystack:sub(i + j - 1, i + j - 1) ~= needle:sub(j, j) then break end
end
if k == M then table.insert(found, i) end
end
if i - 1 < N - M then
t = (d * (t - haystack:sub(i, i):byte() * h) + haystack:sub(i + M,i + M):byte()) % q
if t < 0 then t = t + q end
end
end
if #f > 0 then return f end
end
| mit |
ccxvii/mio | proxy.lua | 1 | 4067 | local table_unpack = table.unpack
local table_insert = table.insert
local meshlist = {}
local lamplist = {}
entities = {}
actions = {}
function playonce(skel, anim)
local frame = 0
local n = anim_len(anim)
while frame < n do
skel:animate(anim, frame, 1)
coroutine.yield()
frame = frame + 1
end
end
mixer = 0
function playmix2(skel, a, b)
local a_i, a_n = 0, anim_len(a)
local b_i, b_n = 0, anim_len(b)
local a_step = a_n / b_n
while true do
skel:animate(a, a_i, 1)
skel:animate(b, b_i, mixer)
coroutine.yield()
a_i = a_i + a_step
b_i = b_i + 1
if a_i >= a_n then a_i = a_i - a_n end
if b_i >= b_n then b_i = b_i - b_n end
end
end
function playmix(skel, a, b, duration)
local a_i, a_n = 0, anim_len(a)
local b_i, b_n = 0, anim_len(b)
local a_step = a_n / b_n
local i = 0
print("mix", a_n, b_n, a_step)
for i = 0, duration-1 do
skel:animate(a, a_i, 1)
skel:animate(b, b_i, (i / duration))
coroutine.yield()
a_i = a_i + a_step
b_i = b_i + 1
if a_i >= a_n then a_i = a_i - a_n end
if b_i >= b_n then b_i = b_i - b_n end
i = i + 1
end
while true do
skel:animate(b, b_i, 1)
coroutine.yield()
b_i = b_i + 1
if b_i >= b_n then b_i = b_i - b_n end
end
end
function playseq(skel, list)
while true do
for i, anim in ipairs(list) do
playonce(skel, anim)
end
end
end
function playloop(skel, anim, frame)
local n = anim_len(anim)
while true do
skel:animate(anim, frame, 1)
coroutine.yield()
frame = frame + 1
if frame >= n then
frame = frame - n
end
end
end
function run(f)
table.insert(actions, coroutine.wrap(f))
end
function update()
for k, action in pairs(actions) do
action()
end
for k, ent in pairs(meshlist) do
if ent.transform then
if ent.parent then
if ent.parentbone then
update_transform_parent_skel(ent.transform, ent.parent.transform, ent.parent.skel, ent.parentbone)
else
update_transform_parent(ent.transform, ent.parent.transform)
end
else
update_transform(ent.transform)
end
end
end
end
function draw_geometry()
for k, ent in pairs(meshlist) do
if ent.skel then
if ent.mesh then
draw_mesh_skel(ent.transform, ent.mesh, ent.skel)
end
if ent.meshlist then
for i, mesh in pairs(ent.meshlist) do
draw_mesh_skel(ent.transform, mesh, ent.skel)
end
end
else
if ent.mesh then
draw_mesh(ent.transform, ent.mesh)
end
if ent.meshlist then
for i, mesh in pairs(ent.meshlist) do
draw_mesh(ent.transform, mesh)
end
end
end
end
end
function draw_light()
for k, ent in pairs(lamplist) do
if ent.lamp then
draw_lamp(ent.transform, ent.lamp)
end
end
end
function new_transform(t)
local tra = new_transform_imp()
if t then
if t.position then tra:set_position(table_unpack(t.position)) end
if t.rotation then tra:set_rotation(table_unpack(t.rotation)) end
if t.scale then tra:set_scale(table_unpack(t.scale)) end
end
return tra
end
function new_lamp(t)
local lamp = new_lamp_imp()
if t then
if t.type then lamp:set_type(t.type) end
if t.energy then lamp:set_energy(t.energy) end
if t.color then lamp:set_color(table_unpack(t.color)) end
if t.distance then lamp:set_distance(t.distance) end
if t.spot_angle then lamp:set_spot_angle(t.spot_angle) end
if t.spot_blend then lamp:set_spot_blend(t.spot_blend) end
if type(t.use_sphere) == 'boolean' then lamp:set_use_sphere(t.use_sphere) end
if type(t.use_shadow) == 'boolean' then lamp:set_use_shadow(t.use_shadow) end
end
return lamp
end
function new_meshlist(list)
for k, filename in pairs(list) do
list[k] = new_mesh(filename)
end
return list
end
function entity(t)
if t.name then
entities[t.name] = t
end
t.transform = new_transform(t.transform)
if t.lamp then t.lamp = new_lamp(t.lamp) end
if t.skel then t.skel = new_skel(t.skel) end
if t.mesh then t.mesh = new_mesh(t.mesh) end
if t.meshlist then t.meshlist = new_meshlist(t.meshlist) end
if t.mesh or t.meshlist then table_insert(meshlist, t) end
if t.lamp then table_insert(lamplist, t) end
return t
end
| isc |
actionless/awesome | tests/examples/awful/placement/closest_mouse.lua | 5 | 2826 | --DOC_GEN_OUTPUT --DOC_GEN_IMAGE --DOC_HIDE
local awful = {placement = require("awful.placement")} --DOC_HIDE
local c = client.gen_fake {x = 20, y = 20, width= 280, height=200, screen =screen[1]} --DOC_HIDE
local bw = c.border_width --DOC_HIDE
-- Left --DOC_HIDE
mouse.coords {x=100,y=100} --DOC_HIDE
-- Move the mouse to the closest corner of the focused client
awful.placement.closest_corner(mouse, {include_sides=true, parent=c})
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x) --DOC_HIDE
assert(mouse.coords().y == (c.y) + (c.height)/2+bw) --DOC_HIDE
-- Top left --DOC_HIDE
mouse.coords {x=60,y=40} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x and mouse.coords().y == c.y) --DOC_HIDE
-- Top right --DOC_HIDE
mouse.coords {x=230,y=50} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x+c.width+2*bw and mouse.coords().y == c.y) --DOC_HIDE
-- Right --DOC_HIDE
mouse.coords {x=240,y=140} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x+c.width+2*bw and mouse.coords().y == c.y+c.height/2+bw) --DOC_HIDE
-- Bottom right --DOC_HIDE
mouse.coords {x=210,y=190} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x+c.width+2*bw and mouse.coords().y == c.y+c.height+2*bw) --DOC_HIDE
-- Bottom --DOC_HIDE
mouse.coords {x=130,y=190} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x+c.width/2+bw and mouse.coords().y == c.y + c.height + 2*bw) --DOC_HIDE
-- Top --DOC_HIDE
mouse.coords {x=130,y=30} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x + c.width/2+bw and mouse.coords().y == c.y) --DOC_HIDE
-- Bottom left + outside of "c" --DOC_HIDE
mouse.coords {x=0,y=230} --DOC_HIDE
awful.placement.closest_corner(mouse, {include_sides=true, parent=c}) --DOC_HIDE
mouse.push_history() --DOC_HIDE
assert(mouse.coords().x == c.x and mouse.coords().y == c.y+c.height+2*bw) --DOC_HIDE
-- It is possible to emulate the mouse API to get the closest corner of
-- random area
local _, corner = awful.placement.closest_corner(
{coords=function() return {x = 100, y=100} end},
{include_sides = true, bounding_rect = {x=0, y=0, width=200, height=200}}
)
print("Closest corner:", corner)
--DOC_HIDE vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
nenau/naev | dat/factions/equip/zalek.lua | 3 | 6476 | -- Generic equipping routines, helper functions and outfit definitions.
include("dat/factions/equip/generic.lua")
--[[
-- @brief Does zalek pilot equipping
--
-- @param p Pilot to equip
--]]
function equip( p )
-- Start with an empty ship
p:rmOutfit("all")
p:rmOutfit("cores")
-- Get ship info
local shiptype, shipsize = equip_getShipBroad( p:ship():class() )
-- Split by type
if shiptype == "military" then
equip_empireMilitary( p, shipsize )
elseif
shiptype == "robotic" then
equip_empireMilitary( p, shipsize )
else
equip_generic( p )
end
end
-- CANNONS
function equip_forwardZlkLow ()
return { "Particle Lance" }
end
function equip_forwardZlkMedLow ()
return { "Orion Lance" }
end
function equip_forwardZlkMed ()
return { "Laser Cannon MK3", "Orion Lance", "Grave Lance", "Heavy Ripper Cannon" }
end
-- TURRETS
function equip_turretZlkLow ()
return { "Laser Turret MK2" }
end
function equip_turretZlkMed ()
return { "Pulse Beam", "Laser Turret MK3" }
end
function equip_turretZlkHig ()
return { "Grave Beam", "Ragnarok Beam" }
end
-- RANGED
function equip_rangedZlk ()
return { "Electron Burst Cannon" }
end
function equip_secondaryZlk ()
return { "Shattershield Lance", "Unicorp Headhunter Launcher" }
end
-- NON-COMBAT
--[[
-- Utility slots
--]]
function equip_mediumZlkLow ()
return { "Reactor Class I", "Unicorp Scrambler", "Small Shield Booster" }
end
function equip_mediumZlkMed ()
return { "Reactor Class II", "Milspec Scrambler", "Medium Shield Booster" }
end
function equip_mediumZlkHig ()
return { "Reactor Class III", "Milspec Scrambler", "Large Shield Booster" }
end
--[[
-- Structure slots
--]]
function equip_lowZlkLow ()
return { "Battery", "Shield Capacitor", "Engine Reroute" }
end
function equip_lowZlkMed ()
return { "Shield Capacitor II", "Shield Capacitor III", "Engine Reroute", "Battery II" }
end
function equip_lowZlkHig ()
return { "Shield Capacitor III", "Shield Capacitor IV", "Battery III" }
end
--[[
-- @brief Equips a zalek military type ship.
--]]
function equip_empireMilitary( p, shipsize )
local medium, low
local use_primary, use_secondary, use_medium, use_low
local use_forward, use_turrets, use_medturrets
local nhigh, nmedium, nlow = p:ship():slots()
local scramble
-- Defaults
medium = { "Unicorp Scrambler" }
weapons = {}
scramble = false
-- Equip by size and type
if shipsize == "small" then
local class = p:ship():class()
cores = {
{"Tricon Zephyr Engine", "Milspec Orion 2301 Core System", "S&K Ultralight Combat Plating"},
{"Tricon Zephyr II Engine", "Milspec Orion 3701 Core System", "S&K Light Combat Plating"}
}
equip_cores(p, equip_getCores(p, shipsize, cores))
-- Scout
if class == "Scout" then
equip_cores(p, "Tricon Zephyr Engine", "Milspec Orion 2301 Core System", "S&K Ultralight Stealth Plating")
use_primary = rnd.rnd(1,nhigh)
addWeapons( equip_forwardLow(), use_primary )
medium = { "Generic Afterburner", "Milspec Scrambler" }
use_medium = 2
low = { "Solar Panel" }
-- Drone
elseif class == "Drone" then
-- equip_cores(p, "Tricon Zephyr Engine", "Milspec Orion 2301 Core System", "S&K Light Stealth Plating")
use_primary = nhigh
addWeapons( equip_forwardZlkLow(), use_primary )
medium = equip_mediumZlkLow()
low = equip_lowZlkLow()
-- Heavy Drone
elseif class == "Heavy Drone" then
use_primary = nhigh
addWeapons( equip_forwardZlkLow(), 2 )
addWeapons( equip_forwardZlkMedLow(), 1 )
addWeapons( equip_rangedZlk(), 1 )
medium = equip_mediumZlkLow()
low = equip_lowZlkLow()
-- Bomber
elseif class == "Bomber" then
use_primary = rnd.rnd(1,2)
use_secondary = nhigh - use_primary
addWeapons( equip_forwardZlkLow(), use_primary )
addWeapons( equip_rangedZlk(), use_secondary )
medium = equip_mediumZlkLow()
low = equip_lowZlkLow()
end
elseif shipsize == "medium" then
local class = p:ship():class()
cores = {
{"Tricon Cyclone Engine", "Milspec Orion 4801 Core System", "S&K Medium Combat Plating"},
{"Tricon Cyclone II Engine", "Milspec Orion 5501 Core System", "S&K Medium-Heavy Combat Plating"}
}
equip_cores(p, equip_getCores(p, shipsize, cores))
-- Corvette
if class == "Corvette" then
use_secondary = rnd.rnd(1,2)
use_primary = nhigh - use_secondary
addWeapons( equip_forwardZlkMed(), use_primary )
addWeapons( equip_secondaryZlk(), use_secondary )
medium = equip_mediumZlkMed()
low = equip_lowZlkMed()
end
-- Destroyer
if class == "Destroyer" then
use_secondary = rnd.rnd(1,2)
use_turrets = nhigh - use_secondary - rnd.rnd(1,2)
use_forward = nhigh - use_secondary - use_turrets
addWeapons( equip_secondaryZlk(), use_secondary )
addWeapons( equip_turretZlkMed(), use_turrets )
addWeapons( equip_forwardZlkMed(), use_forward )
medium = equip_mediumZlkMed()
low = equip_lowZlkMed()
end
else -- "large"
-- TODO: Divide into carrier and cruiser classes.
cores = {
{"Tricon Typhoon Engine", "Milspec Orion 9901 Core System", "S&K Heavy Combat Plating"},
{"Tricon Typhoon II Engine", "Milspec Orion 9901 Core System", "S&K Superheavy Combat Plating"}
}
equip_cores(p, equip_getCores(p, shipsize, cores))
use_secondary = 2
if rnd.rnd() > 0.4 then -- Anti-fighter variant.
use_turrets = nhigh - use_secondary - rnd.rnd(2,3)
use_medturrets = nhigh - use_secondary - use_turrets
addWeapons( equip_turretZlkMed(), use_medturrets )
else -- Anti-capital variant.
use_turrets = nhigh - use_secondary
end
addWeapons( equip_turretZlkHig(), use_turrets )
addWeapons( equip_secondaryZlk(), use_secondary )
medium = equip_mediumZlkHig()
low = equip_lowZlkHig()
end
equip_ship( p, scramble, weapons, medium, low,
use_medium, use_low )
end
| gpl-3.0 |
hcorg/thrift | test/lua/test_basic_client.lua | 30 | 5926 | -- Licensed to the Apache Software Foundation (ASF) under one
-- or more contributor license agreements. See the NOTICE file
-- distributed with this work for additional information
-- regarding copyright ownership. The ASF licenses this file
-- to you under the Apache License, Version 2.0 (the
-- "License"); you may not use this file except in compliance
-- with the License. You may obtain a copy of the License at
-- http://www.apache.org/licenses/LICENSE-2.0
-- Unless required by applicable law or agreed to in writing,
-- software distributed under the License is distributed on an
-- "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
-- KIND, either express or implied. See the License for the
-- specific language governing permissions and limitations
-- under the License.
require('TSocket')
require('TBufferedTransport')
require('TFramedTransport')
require('THttpTransport')
require('TCompactProtocol')
require('TJsonProtocol')
require('TBinaryProtocol')
require('ThriftTest_ThriftTest')
require('liblualongnumber')
local client
function teardown()
if client then
-- close the connection
client:close()
end
end
function parseArgs(rawArgs)
local opt = {
protocol='binary',
transport='buffered',
port='9090',
}
for i, str in pairs(rawArgs) do
if i > 0 then
k, v = string.match(str, '--(%w+)=(%w+)')
assert(opt[k] ~= nil, 'Unknown argument')
opt[k] = v
end
end
return opt
end
function assertEqual(val1, val2, msg)
assert(val1 == val2, msg)
end
function testBasicClient(rawArgs)
local opt = parseArgs(rawArgs)
local socket = TSocket:new{
port = tonumber(opt.port)
}
assert(socket, 'Failed to create client socket')
socket:setTimeout(5000)
local transports = {
buffered = TBufferedTransport,
framed = TFramedTransport,
http = THttpTransport,
}
assert(transports[opt.transport] ~= nil)
local transport = transports[opt.transport]:new{
trans = socket,
isServer = false
}
local protocols = {
binary = TBinaryProtocol,
compact = TCompactProtocol,
json = TJSONProtocol,
}
assert(protocols[opt.protocol] ~= nil)
local protocol = protocols[opt.protocol]:new{
trans = transport
}
assert(protocol, 'Failed to create binary protocol')
client = ThriftTestClient:new{
protocol = protocol
}
assert(client, 'Failed to create client')
-- Open the transport
local status, _ = pcall(transport.open, transport)
assert(status, 'Failed to connect to server')
-- String
assertEqual(client:testString('lala'), 'lala', 'Failed testString')
assertEqual(client:testString('wahoo'), 'wahoo', 'Failed testString')
-- Bool
assertEqual(client:testBool(true), true, 'Failed testBool true')
assertEqual(client:testBool(false), false, 'Failed testBool false')
-- Byte
assertEqual(client:testByte(0x01), 1, 'Failed testByte 1')
assertEqual(client:testByte(0x40), 64, 'Failed testByte 2')
assertEqual(client:testByte(0x7f), 127, 'Failed testByte 3')
assertEqual(client:testByte(0x80), -128, 'Failed testByte 4')
assertEqual(client:testByte(0xbf), -65, 'Failed testByte 5')
assertEqual(client:testByte(0xff), -1, 'Failed testByte 6')
assertEqual(client:testByte(128), -128, 'Failed testByte 7')
assertEqual(client:testByte(255), -1, 'Failed testByte 8')
-- I32
assertEqual(client:testI32(0x00000001), 1, 'Failed testI32 1')
assertEqual(client:testI32(0x40000000), 1073741824, 'Failed testI32 2')
assertEqual(client:testI32(0x7fffffff), 2147483647, 'Failed testI32 3')
assertEqual(client:testI32(0x80000000), -2147483648, 'Failed testI32 4')
assertEqual(client:testI32(0xbfffffff), -1073741825, 'Failed testI32 5')
assertEqual(client:testI32(0xffffffff), -1, 'Failed testI32 6')
assertEqual(client:testI32(2147483648), -2147483648, 'Failed testI32 7')
assertEqual(client:testI32(4294967295), -1, 'Failed testI32 8')
-- I64 (lua only supports 16 decimal precision so larger numbers are
-- initialized by their string value)
local long = liblualongnumber.new
assertEqual(client:testI64(long(0x0000000000000001)),
long(1),
'Failed testI64 1')
assertEqual(client:testI64(long(0x4000000000000000)),
long(4611686018427387904),
'Failed testI64 2')
assertEqual(client:testI64(long('0x7fffffffffffffff')),
long('9223372036854775807'),
'Failed testI64 3')
assertEqual(client:testI64(long(0x8000000000000000)),
long(-9223372036854775808),
'Failed testI64 4')
assertEqual(client:testI64(long('0xbfffffffffffffff')),
long('-4611686018427387905'),
'Failed testI64 5')
assertEqual(client:testI64(long('0xffffffffffffffff')),
long(-1),
'Failed testI64 6')
-- Double
assertEqual(
client:testDouble(1.23456789), 1.23456789, 'Failed testDouble 1')
assertEqual(
client:testDouble(0.123456789), 0.123456789, 'Failed testDouble 2')
assertEqual(
client:testDouble(0.123456789), 0.123456789, 'Failed testDouble 3')
-- TODO testBinary() ...
-- Accuracy of 16 decimal digits (rounds)
local a, b = 1.12345678906666663, 1.12345678906666661
assertEqual(a, b)
assertEqual(client:testDouble(a), b, 'Failed testDouble 5')
-- Struct
local o = Xtruct:new{
string_thing = 'Zero',
byte_thing = 1,
i32_thing = -3,
i64_thing = long(-5)
}
local r = client:testStruct(o)
assertEqual(o.string_thing, r.string_thing, 'Failed testStruct 1')
assertEqual(o.byte_thing, r.byte_thing, 'Failed testStruct 2')
assertEqual(o.i32_thing, r.i32_thing, 'Failed testStruct 3')
assertEqual(o.i64_thing, r.i64_thing, 'Failed testStruct 4')
-- TODO add list map set exception etc etc
end
testBasicClient(arg)
teardown()
| apache-2.0 |
kidaa/FFXIOrgins | scripts/zones/Sealions_Den/mobs/Omega.lua | 1 | 1240 | -----------------------------------
-- Area: Sealions Den
-- NPC: Omega
-----------------------------------
require("scripts/globals/titles");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
killer:addTitle(OMEGA_OSTRACIZER);
killer:startEvent(0x000b);
end;
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x000b) then
local instance = player:getVar("bcnm_instanceid")
--Players are healed in between the fights, but their TP is set to 0
player:setHP(player:getMaxHP());
player:setMP(player:getMaxMP());
player:setTP(0);
if(instance == 1) then
player:setPos(-779, -103, -80);
SpawnMob(16908295); --ultima1
elseif(instance == 2) then
player:setPos(-140, -23, -440);
SpawnMob(16908302); --ultima2
else
player:setPos(499, 56, -802);
SpawnMob(16908309); --ultima3
end
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/weaponskills/spirits_within.lua | 1 | 1117 | -----------------------------------
-- Spirits Within
-- Sword weapon skill
-- Spirits Within Sword Weapon Skill
-- TrolandAdded by Troland
-- Skill Level: 175
-- Delivers an unavoidable attack. Damage varies with HP and TP.
-- Not aligned with any "elemental gorgets" or "elemental belts" due to it's absence of Skillchain properties.
-- Element: None
-- Modifiers: HP:
-- 100%TP 200%TP 300%TP
-- 1/8 3/16 15/32
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
require("scripts/globals/utils");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local D = player:getWeaponDmg();
local HP = player:getHP();
local TP = player:getTP();
local WSC = 0;
if (TP == 300) then
WSC = HP * 0.46875;
elseif (TP >= 200) then
WSC = HP * ((TP - 200) / (100 / (0.46875 - 0.1875)));
elseif (TP >= 100) then
WSC = HP * ((TP - 100) / (100 / (0.1875 - 0.125)));
end
local damage = target:breathDmgTaken(math.floor(D + WSC));
return 1, 0, false, damage;
end
| gpl-3.0 |
diezombies/MCGC | MCGC/utility.lua | 1 | 54503 | Auxiliary = { }
aux = Auxiliary
function Auxiliary.Stringid(code, id)
-- 计算数据库所存的字符串ID
return code * 16 + id
end
function Auxiliary.Next(g)
-- 返回(返回g中下一张卡片的)函数
local first = true
return function()
if first then
first = false return g:GetFirst()
else
return g:GetNext()
end
end
end
function Auxiliary.NULL()
-- 返回NULL
end
function Auxiliary.TRUE()
-- 返回True
return true
end
function Auxiliary.FALSE()
-- 返回False
return false
end
function Auxiliary.AND(f1, f2)
-- 将两个函数按逻辑与组合
return function(a, b, c)
return f1(a, b, c) and f2(a, b, c)
end
end
function Auxiliary.OR(f1, f2)
-- 将两个函数按逻辑或组合
return function(a, b, c)
return f1(a, b, c) or f2(a, b, c)
end
end
function Auxiliary.NOT(f)
-- 返回(函数f的非的)函数
return function(a, b, c)
return not f(a, b, c)
end
end
function Auxiliary.IsDualState(effect)
local c = effect:GetHandler()
return not c:IsDisabled() and c:IsDualState()
end
function Auxiliary.IsNotDualState(effect)
local c = effect:GetHandle()
return c:IsDisabled() or not c:IsDualState()
end
function Auxiliary.DualNormalCondition(effect)
local c = effect:GetHandler()
return c:IsFaceup() and not c:IsDualState()
end
function Auxiliary.BeginPuzzle(effect)
local e1 = Effect.GlobalEffect()
e1:SetType(EFFECT_TYPE_FIELD + EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_TURN_END)
e1:SetCountLimit(1)
e1:SetOperation(Auxiliary.PuzzleOp)
Duel.RegisterEffect(e1, 0)
local e2 = Effect.GlobalEffect()
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e2:SetCode(EFFECT_SKIP_DP)
e2:SetTargetRange(1, 0)
Duel.RegisterEffect(e2, 0)
local e3 = Effect.GlobalEffect()
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e3:SetCode(EFFECT_SKIP_SP)
e3:SetTargetRange(1, 0)
Duel.RegisterEffect(e3, 0)
end
function Auxiliary.PuzzleOp(e, tp)
Duel.SetLP(0, 0)
end
function Auxiliary.EnableDualAttribute(c)
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DUAL_SUMMONABLE)
c:RegisterEffect(e1)
local e2 = Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_ADD_TYPE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE + LOCATION_GRAVE)
e2:SetCondition(aux.DualNormalCondition)
e2:SetValue(TYPE_NORMAL)
c:RegisterEffect(e2)
local e3 = e2:Clone()
e3:SetCode(EFFECT_REMOVE_TYPE)
e3:SetValue(TYPE_EFFECT)
c:RegisterEffect(e3)
end
function Auxiliary.TargetEqualFunction(f, value, a, b, c)
return function(effect, target)
return f(target, a, b, c) == value
end
end
function Auxiliary.TargetBoolFunction(f, a, b, c)
return function(effect, target)
return f(target, a, b, c)
end
end
function Auxiliary.FilterEqualFunction(f, value, a, b, c)
return function(target)
return f(target, a, b, c) == value
end
end
function Auxiliary.FilterBoolFunction(f, a, b, c)
return function(target)
return f(target, a, b, c)
end
end
function Auxiliary.NonTuner(f, a, b, c)
return function(target)
return target:IsNotTuner() and(not f or f(target, a, b, c))
end
end
function Auxiliary.AddSynchroProcedure(c, f1, f2, ct)
-- Synchro monster, 1 tuner + n or more monsters
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE + EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetRange(LOCATION_EXTRA)
e1:SetCondition(Auxiliary.SynCondition(f1, f2, ct, 99))
e1:SetTarget(Auxiliary.SynTarget(f1, f2, ct, 99))
e1:SetOperation(Auxiliary.SynOperation(f1, f2, ct, 99))
e1:SetValue(SUMMON_TYPE_SYNCHRO)
c:RegisterEffect(e1)
end
function Auxiliary.SynCondition(f1, f2, minct, maxc)
return function(e, c, smat, mg)
if c == nil then return true end
if c:IsType(TYPE_PENDULUM) and c:IsFaceup() then return false end
local ft = Duel.GetLocationCount(c:GetControler(), LOCATION_MZONE)
local ct = - ft
local minc = minct
if minc < ct then minc = ct end
if maxc < minc then return false end
if smat and smat:IsType(TYPE_TUNER) and(not f1 or f1(smat)) then
return Duel.CheckTunerMaterial(c, smat, f1, f2, minc, maxc, mg)
end
return Duel.CheckSynchroMaterial(c, f1, f2, minc, maxc, smat, mg)
end
end
function Auxiliary.SynTarget(f1, f2, minct, maxc)
return function(e, tp, eg, ep, ev, re, r, rp, chk, c, smat, mg)
local g = nil
local ft = Duel.GetLocationCount(c:GetControler(), LOCATION_MZONE)
local ct = - ft
local minc = minct
if minc < ct then minc = ct end
if smat and smat:IsType(TYPE_TUNER) and(not f1 or f1(smat)) then
g = Duel.SelectTunerMaterial(c:GetControler(), c, smat, f1, f2, minc, maxc, mg)
else
g = Duel.SelectSynchroMaterial(c:GetControler(), c, f1, f2, minc, maxc, smat, mg)
end
if g then
g:KeepAlive()
e:SetLabelObject(g)
return true
else
return false
end
end
end
function Auxiliary.SynOperation(f1, f2, minct, maxc)
return function(e, tp, eg, ep, ev, re, r, rp, c, smat, mg)
local g = e:GetLabelObject()
c:SetMaterial(g)
Duel.SendtoGrave(g, REASON_MATERIAL + REASON_SYNCHRO)
g:DeleteGroup()
end
end
function Auxiliary.AddSynchroProcedure2(c, f1, f2)
-- Synchro monster, 1 tuner + 1 monster
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE + EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetRange(LOCATION_EXTRA)
e1:SetCondition(Auxiliary.SynCondition(f1, f2, 1, 1))
e1:SetTarget(Auxiliary.SynTarget(f1, f2, 1, 1))
e1:SetOperation(Auxiliary.SynOperation(f1, f2, 1, 1))
e1:SetValue(SUMMON_TYPE_SYNCHRO)
c:RegisterEffect(e1)
end
function Auxiliary.XyzAlterFilter(c, alterf, xyzc)
return alterf(c) and c:IsCanBeXyzMaterial(xyzc)
end
function Auxiliary.AddXyzProcedure(c, f, lv, ct, alterf, desc, maxct, op)
-- Xyz monster, lv k*n
-- set c.xyz_filter, c.xyz_count
if c.xyz_filter == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
if f then
mt.xyz_filter = function(mc) return f(mc) and mc:IsXyzLevel(c, lv) end
else
mt.xyz_filter = function(mc) return mc:IsXyzLevel(c, lv) end
end
mt.xyz_count = ct
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_EXTRA)
if not maxct then maxct = ct end
if alterf then
e1:SetCondition(Auxiliary.XyzCondition2(f, lv, ct, maxct, alterf, desc, op))
e1:SetTarget(Auxiliary.XyzTarget2(f, lv, ct, maxct, alterf, desc, op))
e1:SetOperation(Auxiliary.XyzOperation2(f, lv, ct, maxct, alterf, desc, op))
else
e1:SetCondition(Auxiliary.XyzCondition(f, lv, ct, maxct))
e1:SetTarget(Auxiliary.XyzTarget(f, lv, ct, maxct))
e1:SetOperation(Auxiliary.XyzOperation(f, lv, ct, maxct))
end
e1:SetValue(SUMMON_TYPE_XYZ)
c:RegisterEffect(e1)
end
function Auxiliary.XyzCondition(f, lv, minc, maxc)
-- Xyz Summon(normnal)
-- og: use special material
return function(e, c, og)
if c == nil then return true end
if c:IsType(TYPE_PENDULUM) and c:IsFaceup() then return false end
local ft = Duel.GetLocationCount(c:GetControler(), LOCATION_MZONE)
local ct = - ft
if minc <= ct then return false end
return Duel.CheckXyzMaterial(c, f, lv, minc, maxc, og)
end
end
function Auxiliary.XyzTarget(f, lv, minc, maxc)
return function(e, tp, eg, ep, ev, re, r, rp, chk, c, og)
if og then
return true
else
local g = Duel.SelectXyzMaterial(tp, c, f, lv, minc, maxc)
if g then
g:KeepAlive()
e:SetLabelObject(g)
return true
else
return false
end
end
end
end
function Auxiliary.XyzOperation(f, lv, minc, maxc)
return function(e, tp, eg, ep, ev, re, r, rp, c, og)
if og then
local sg = Group.CreateGroup()
local tc = og:GetFirst()
while tc do
local sg1 = tc:GetOverlayGroup()
sg:Merge(sg1)
tc = og:GetNext()
end
Duel.SendtoGrave(sg, REASON_RULE)
c:SetMaterial(og)
Duel.Overlay(c, og)
else
local mg = e:GetLabelObject()
local sg = Group.CreateGroup()
local tc = mg:GetFirst()
while tc do
local sg1 = tc:GetOverlayGroup()
sg:Merge(sg1)
tc = mg:GetNext()
end
Duel.SendtoGrave(sg, REASON_RULE)
c:SetMaterial(mg)
Duel.Overlay(c, mg)
mg:DeleteGroup()
end
end
end
function Auxiliary.XyzCondition2(f, lv, minc, maxc, alterf, desc, op)
-- Xyz summon(alterf)
return function(e, c, og)
if c == nil then return true end
if c:IsType(TYPE_PENDULUM) and c:IsFaceup() then return false end
local tp = c:GetControler()
local ft = Duel.GetLocationCount(tp, LOCATION_MZONE)
local ct = - ft
if minc <= ct then return false end
if ct < 1 and not og and Duel.IsExistingMatchingCard(Auxiliary.XyzAlterFilter, tp, LOCATION_MZONE, 0, 1, nil, alterf, c)
and(not op or op(e, tp, 0)) then
return true
end
return Duel.CheckXyzMaterial(c, f, lv, minc, maxc, og)
end
end
function Auxiliary.XyzTarget2(f, lv, minc, maxc, alterf, desc, op)
return function(e, tp, eg, ep, ev, re, r, rp, chk, c, og)
if og then
return true
else
local ft = Duel.GetLocationCount(tp, LOCATION_MZONE)
local ct = - ft
local b1 = Duel.CheckXyzMaterial(c, f, lv, minc, maxc, og)
local b2 = ct < 1 and Duel.IsExistingMatchingCard(Auxiliary.XyzAlterFilter, tp, LOCATION_MZONE, 0, 1, nil, alterf, c)
and(not op or op(e, tp, 0))
if b2 and(not b1 or Duel.SelectYesNo(tp, desc)) then
e:SetLabel(1)
return true
else
e:SetLabel(0)
local g = Duel.SelectXyzMaterial(tp, c, f, lv, minc, maxc)
if g then
g:KeepAlive()
e:SetLabelObject(g)
return true
else
return false
end
end
end
end
end
function Auxiliary.XyzOperation2(f, lv, minc, maxc, alterf, desc, op)
return function(e, tp, eg, ep, ev, re, r, rp, c, og)
if og then
local sg = Group.CreateGroup()
local tc = og:GetFirst()
while tc do
local sg1 = tc:GetOverlayGroup()
sg:Merge(sg1)
tc = og:GetNext()
end
Duel.SendtoGrave(sg, REASON_RULE)
c:SetMaterial(og)
Duel.Overlay(c, og)
else
if e:GetLabel() == 1 then
if op then op(e, tp, 1) end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_XMATERIAL)
local mg = Duel.SelectMatchingCard(tp, Auxiliary.XyzAlterFilter, tp, LOCATION_MZONE, 0, 1, 1, nil, alterf, c)
local mg2 = mg:GetFirst():GetOverlayGroup()
if mg2:GetCount() ~= 0 then
Duel.Overlay(c, mg2)
end
c:SetMaterial(mg)
Duel.Overlay(c, mg)
else
local mg = e:GetLabelObject()
local sg = Group.CreateGroup()
local tc = mg:GetFirst()
while tc do
local sg1 = tc:GetOverlayGroup()
sg:Merge(sg1)
tc = mg:GetNext()
end
Duel.SendtoGrave(sg, REASON_RULE)
c:SetMaterial(mg)
Duel.Overlay(c, mg)
mg:DeleteGroup()
end
end
end
end
function Auxiliary.FConditionCheckF(c, chkf)
return c:IsOnField() and c:IsControler(chkf)
end
function Auxiliary.AddFusionProcCode2(c, code1, code2, sub, insf)
-- Fusion monster, name + name
-- material_count: number of different names in material list
-- material: names in material list
if c.material_count == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
mt.material_count = 2
mt.material = { code1, code2 }
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionCode2(code1, code2, sub, insf))
e1:SetOperation(Auxiliary.FOperationCode2(code1, code2, sub, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilter21(c, code1, code2)
local code = c:GetCode()
return code == code1 or code == code2
end
function Auxiliary.FConditionFilter22(c, code1, code2, sub)
local code = c:GetCode()
return code == code1 or code == code2 or(sub and c:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
end
function Auxiliary.FConditionCode2(code1, code2, sub, insf)
-- g:Material group(nil for Instant Fusion)
-- gc:Material already used
-- chkf: check field, default:PLAYER_NONE
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then
if gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
return g:IsExists(Auxiliary.FConditionFilter21, 1, gc, code1, code2)
elseif gc:IsCode(code1) then
return g:IsExists(Card.IsCode, 1, gc, code2)
elseif gc:IsCode(code2) then
return g:IsExists(Card.IsCode, 1, gc, code1)
else
return false
end
end
local b1 = 0 local b2 = 0 local bs = 0
local fs = false
local tc = g:GetFirst()
while tc do
local code = tc:GetCode()
if code == code1 then
b1 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code2 then
b2 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
bs = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
end
tc = g:GetNext()
end
return b1 + b2 + bs >= 2 and(fs or chkf == PLAYER_NONE)
end
end
function Auxiliary.FOperationCode2(code1, code2, sub, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
g1 = eg:FilterSelect(tp, Auxiliary.FConditionFilter21, 1, 1, gc, code1, code2)
elseif gc:IsCode(code1) then
g1 = eg:FilterSelect(tp, Card.IsCode, 1, 1, gc, code2)
else
g1 = eg:FilterSelect(tp, Card.IsCode, 1, 1, gc, code1)
end
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(Auxiliary.FConditionFilter22, nil, code1, code2, sub)
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if chkf ~= PLAYER_NONE then
g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
else
g1 = sg:Select(tp, 1, 1, nil)
end
if g1:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g1:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
end
end
function Auxiliary.AddFusionProcCode3(c, code1, code2, code3, sub, insf)
-- Fusion monster, name + name + name
if c.material_count == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
mt.material_count = 3
mt.material = { code1, code2, code3 }
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionCode3(code1, code2, code3, sub, insf))
e1:SetOperation(Auxiliary.FOperationCode3(code1, code2, code3, sub, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilter31(c, code1, code2, code3)
local code = c:GetCode()
return code == code1 or code == code2 or code == code3
end
function Auxiliary.FConditionFilter32(c, code1, code2, code3, sub)
local code = c:GetCode()
return code == code1 or code == code2 or code == code3 or(sub and c:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
end
function Auxiliary.FConditionCode3(code1, code2, code3, sub, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then
local b1 = 0 local b2 = 0 local b3 = 0
local tc = g:GetFirst()
while tc do
local code = tc:GetCode()
if code == code1 then
b1 = 1
elseif code == code2 then
b2 = 1
elseif code == code3 then
b3 = 1
end
tc = g:GetNext()
end
if gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
return b1 + b2 + b3 > 1
else
local code = gc:GetCode()
if code == code1 then
b1 = 1
elseif code == code2 then
b2 = 1
elseif code == code3 then
b3 = 1
else
return false
end
return b1 + b2 + b3 > 2
end
end
local b1 = 0 local b2 = 0 local b3 = 0 local bs = 0
local fs = false
local tc = g:GetFirst()
while tc do
local code = tc:GetCode()
if code == code1 then
b1 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code2 then
b2 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code3 then
b3 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
bs = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
end
tc = g:GetNext()
end
return b1 + b2 + b3 + bs >= 3 and(fs or chkf == PLAYER_NONE)
end
end
function Auxiliary.FOperationCode3(code1, code2, code3, sub, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
local sg = eg:Filter(Auxiliary.FConditionFilter31, gc, code1, code2, code3)
if not gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsCode, nil, gc:GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg:Select(tp, 1, 1, nil)
sg:Remove(Card.IsCode, nil, g1:GetFirst():GetCode())
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(Auxiliary.FConditionFilter32, nil, code1, code2, code3, sub)
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if chkf ~= PLAYER_NONE then
g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
else
g1 = sg:Select(tp, 1, 1, nil)
end
if g1:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g1:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
if g2:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g2:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g3 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
g1:Merge(g3)
Duel.SetFusionMaterial(g1)
end
end
function Auxiliary.AddFusionProcCode4(c, code1, code2, code3, code4, sub, insf)
-- Fusion monster, name + name + name + name
if c.material_count == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
mt.material_count = 4
mt.material = { code1, code2, code3, code4 }
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionCode4(code1, code2, code3, code4, sub, insf))
e1:SetOperation(Auxiliary.FOperationCode4(code1, code2, code3, code4, sub, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilter41(c, code1, code2, code3, code4)
local code = c:GetCode()
return code == code1 or code == code2 or code == code3 or code == code4
end
function Auxiliary.FConditionFilter42(c, code1, code2, code3, code4, sub)
local code = c:GetCode()
return code == code1 or code == code2 or code == code3 or code == code4 or(sub and c:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
end
function Auxiliary.FConditionCode4(code1, code2, code3, code4, sub, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then
local b1 = 0 local b2 = 0 local b3 = 0 local b4 = 0
local tc = g:GetFirst()
while tc do
local code = tc:GetCode()
if code == code1 then
b1 = 1
elseif code == code2 then
b2 = 1
elseif code == code3 then
b3 = 1
elseif code == code4 then
b4 = 1
else
return false
end
tc = g:GetNext()
end
if gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
return b1 + b2 + b3 + b4 > 2
else
local code = gc:GetCode()
if code == code1 then
b1 = 1
elseif code == code2 then
b2 = 1
elseif code == code3 then
b3 = 1
elseif code == code4 then
b4 = 1
end
return b1 + b2 + b3 + b4 > 3
end
end
local b1 = 0 local b2 = 0 local b3 = 0 local b4 = 0 local bs = 0
local fs = false
local tc = g:GetFirst()
while tc do
local code = tc:GetCode()
if code == code1 then
b1 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code2 then
b2 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code3 then
b3 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif code == code4 then
b4 = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
elseif sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
bs = 1
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
end
tc = g:GetNext()
end
return b1 + b2 + b3 + b4 + bs >= 4 and(fs or chkf == PLAYER_NONE)
end
end
function Auxiliary.FOperationCode4(code1, code2, code3, code4, sub, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
local sg = eg:Filter(Auxiliary.FConditionFilter41, gc, code1, code2, code3, code4)
if not gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsCode, nil, gc:GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg:Select(tp, 1, 1, nil)
sg:Remove(Card.IsCode, nil, g1:GetFirst():GetCode())
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
sg:Remove(Card.IsCode, nil, g2:GetFirst():GetCode())
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g3 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
g1:Merge(g3)
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(Auxiliary.FConditionFilter42, nil, code1, code2, code3, code4, sub)
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if chkf ~= PLAYER_NONE then
g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
else
g1 = sg:Select(tp, 1, 1, nil)
end
if g1:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g1:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
if g2:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g2:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g3 = sg:Select(tp, 1, 1, nil)
if g3:GetFirst():IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:Remove(Card.IsCode, nil, g3:GetFirst():GetCode())
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g4 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
g1:Merge(g3)
g1:Merge(g4)
Duel.SetFusionMaterial(g1)
end
end
-- Fusion monster, name + condition
function Auxiliary.AddFusionProcCodeFun(c, code1, f, cc, sub, insf)
if c.material_count == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
mt.material_count = 1
mt.material = { code1 }
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionCodeFun(code1, f, cc, sub, insf))
e1:SetOperation(Auxiliary.FOperationCodeFun(code1, f, cc, sub, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilterCF(c, g2, cc)
return g2:IsExists(aux.TRUE, cc, c)
end
function Auxiliary.FConditionCodeFun(code, f, cc, sub, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then
if (gc:IsCode(code) or(sub and gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))) and g:IsExists(f, cc, gc) then
return true
elseif f(gc) then
local g1 = Group.CreateGroup() local g2 = Group.CreateGroup()
local tc = g:GetFirst()
while tc do
if tc:IsCode(code) or(sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
then
g1:AddCard(tc)
end
if f(tc) then g2:AddCard(tc) end
tc = g:GetNext()
end
if cc > 1 then
g2:RemoveCard(gc)
return g1:IsExists(Auxiliary.FConditionFilterCF, 1, gc, g2, cc - 1)
else
g1:RemoveCard(gc)
return g1:GetCount() > 0
end
else
return false
end
end
local b1 = 0 local b2 = 0 local bw = 0
local fs = false
local tc = g:GetFirst()
while tc do
local c1 = tc:IsCode(code) or(sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
local c2 = f(tc)
if c1 or c2 then
if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end
if c1 and c2 then
bw = bw + 1
elseif c1 then
b1 = 1
else
b2 = b2 + 1
end
end
tc = g:GetNext()
end
if b2 > cc then b2 = cc end
return b1 + b2 + bw >= 1 + cc and(fs or chkf == PLAYER_NONE)
end
end
function Auxiliary.FOperationCodeFun(code, f, cc, sub, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
if (gc:IsCode(code) or(sub and gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))) and eg:IsExists(f, cc, gc) then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = eg:FilterSelect(tp, f, cc, cc, gc)
Duel.SetFusionMaterial(g1)
else
local sg1 = Group.CreateGroup() local sg2 = Group.CreateGroup()
local tc = eg:GetFirst()
while tc do
if tc:IsCode(code) or(sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE)) then sg1:AddCard(tc) end
if f(tc) then sg2:AddCard(tc) end
tc = eg:GetNext()
end
if cc > 1 then
sg2:RemoveCard(gc)
if sg2:GetCount() == cc - 1 then
sg1:Sub(sg2)
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg1:Select(tp, 1, 1, gc)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg2:Select(tp, cc - 1, cc - 1, g1:GetFirst())
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
else
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg1:Select(tp, 1, 1, gc)
Duel.SetFusionMaterial(g1)
end
end
return
end
local sg1 = Group.CreateGroup() local sg2 = Group.CreateGroup() local fs = false
local tc = eg:GetFirst()
while tc do
if tc:IsCode(code) or(sub and tc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE)) then sg1:AddCard(tc) end
if f(tc) then sg2:AddCard(tc) if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end end
tc = eg:GetNext()
end
if chkf ~= PLAYER_NONE then
if sg2:GetCount() == cc then
sg1:Sub(sg2)
end
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if fs then
g1 = sg1:Select(tp, 1, 1, nil)
else
g1 = sg1:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
end
local tc1 = g1:GetFirst()
sg2:RemoveCard(tc1)
if Auxiliary.FConditionCheckF(tc1, chkf) or sg2:GetCount() == cc then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg2:Select(tp, cc, cc, tc1)
g1:Merge(g2)
else
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg2:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, tc1, chkf)
g1:Merge(g2)
if cc > 1 then
sg2:RemoveCard(g2:GetFirst())
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
g2 = sg2:Select(tp, cc - 1, cc - 1, tc1)
g1:Merge(g2)
end
end
Duel.SetFusionMaterial(g1)
else
if sg2:GetCount() == cc then
sg1:Sub(sg2)
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg1:Select(tp, 1, 1, nil)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
g1:Merge(sg2:Select(tp, cc, cc, g1:GetFirst()))
Duel.SetFusionMaterial(g1)
end
end
end
function Auxiliary.AddFusionProcFun2(c, f1, f2, insf)
-- Fusion monster, condition + condition
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionFun2(f1, f2, insf))
e1:SetOperation(Auxiliary.FOperationFun2(f1, f2, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilterF2(c, g2)
return g2:IsExists(aux.TRUE, 1, c)
end
function Auxiliary.FConditionFilterF2c(c, f1, f2)
return f1(c) or f2(c)
end
function Auxiliary.FConditionFilterF2r(c, f1, f2)
return f1(c) and not f2(c)
end
function Auxiliary.FConditionFun2(f1, f2, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then
return(f1(gc) and g:IsExists(f2, 1, gc))
or(f2(gc) and g:IsExists(f1, 1, gc))
end
local g1 = Group.CreateGroup() local g2 = Group.CreateGroup() local fs = false
local tc = g:GetFirst()
while tc do
if f1(tc) then g1:AddCard(tc) if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end end
if f2(tc) then g2:AddCard(tc) if Auxiliary.FConditionCheckF(tc, chkf) then fs = true end end
tc = g:GetNext()
end
if chkf ~= PLAYER_NONE then
return fs and g1:IsExists(Auxiliary.FConditionFilterF2, 1, nil, g2)
else
return g1:IsExists(Auxiliary.FConditionFilterF2, 1, nil, g2)
end
end
end
function Auxiliary.FOperationFun2(f1, f2, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
local sg = Group.CreateGroup()
if f1(gc) then sg:Merge(eg:Filter(f2, gc)) end
if f2(gc) then sg:Merge(eg:Filter(f1, gc)) end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg:Select(tp, 1, 1, nil)
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(Auxiliary.FConditionFilterF2c, nil, f1, f2)
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if chkf ~= PLAYER_NONE then
g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
else
g1 = sg:Select(tp, 1, 1, nil)
end
local tc1 = g1:GetFirst()
sg:RemoveCard(tc1)
local b1 = f1(tc1)
local b2 = f2(tc1)
if b1 and not b2 then sg:Remove(Auxiliary.FConditionFilterF2r, nil, f1, f2) end
if b2 and not b1 then sg:Remove(Auxiliary.FConditionFilterF2r, nil, f2, f1) end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
g1:Merge(g2)
Duel.SetFusionMaterial(g1)
end
end
-- Fusion monster, name * n
function Auxiliary.AddFusionProcCodeRep(c, code1, cc, sub, insf)
if c.material_count == nil then
local code = c:GetOriginalCode()
local mt = _G["c" .. code]
mt.material_count = 1
mt.material = { code1 }
end
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionCodeRep(code1, cc, sub, insf))
e1:SetOperation(Auxiliary.FOperationCodeRep(code1, cc, sub, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFilterCR(c, code, sub)
return c:IsCode(code) or(sub and c:IsHasEffect(EFFECT_FUSION_SUBSTITUTE))
end
function Auxiliary.FConditionCodeRep(code, cc, sub, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then return(gc:IsCode(code) or gc:IsHasEffect(EFFECT_FUSION_SUBSTITUTE)) and g:IsExists(Card.IsCode, cc - 1, gc, code) end
local g1 = g:Filter(Card.IsCode, nil, code)
if not sub then
if chkf ~= PLAYER_NONE then
return g1:GetCount() >= cc and g1:FilterCount(Card.IsOnField, nil) ~= 0
else
return g1:GetCount() >= cc
end
end
local g2 = g:Filter(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
if chkf ~= PLAYER_NONE then
return(g1:FilterCount(Card.IsOnField, nil) ~= 0 or g2:FilterCount(Card.IsOnField, nil) ~= 0)
and g1:GetCount() >= cc - 1 and g1:GetCount() + g2:GetCount() >= cc
else
return g1:GetCount() >= cc - 1 and g1:GetCount() + g2:GetCount() >= cc
end
end
end
function Auxiliary.FOperationCodeRep(code, cc, sub, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = eg:FilterSelect(tp, Card.IsCode, cc - 1, cc - 1, gc, code)
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(Auxiliary.FConditionFilterCR, nil, code, sub)
local g1 = nil
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
if chkf ~= PLAYER_NONE then
g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
else
g1 = sg:Select(tp, 1, 1, nil)
end
local tc1 = g1:GetFirst()
for i = 1, cc - 1 do
if tc1:IsHasEffect(EFFECT_FUSION_SUBSTITUTE) then
sg:Remove(Card.IsHasEffect, nil, EFFECT_FUSION_SUBSTITUTE)
else
sg:RemoveCard(tc1)
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, 1, 1, nil)
tc1 = g2:GetFirst()
g1:Merge(g2)
end
Duel.SetFusionMaterial(g1)
end
end
function Auxiliary.AddFusionProcFunRep(c, f, cc, insf)
-- Fusion monster, condition * n
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_FUSION_MATERIAL)
e1:SetCondition(Auxiliary.FConditionFunRep(f, cc, insf))
e1:SetOperation(Auxiliary.FOperationFunRep(f, cc, insf))
c:RegisterEffect(e1)
end
function Auxiliary.FConditionFunRep(f, cc, insf)
return function(e, g, gc, chkf)
if g == nil then return insf end
if gc then return f(gc) and g:IsExists(f, cc - 1, gc) end
local g1 = g:Filter(f, nil)
if chkf ~= PLAYER_NONE then
return g1:FilterCount(Card.IsOnField, nil) ~= 0 and g1:GetCount() >= cc
else
return g1:GetCount() >= cc
end
end
end
function Auxiliary.FOperationFunRep(f, cc, insf)
return function(e, tp, eg, ep, ev, re, r, rp, gc, chkf)
if gc then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = eg:FilterSelect(tp, f, cc - 1, cc - 1, gc)
Duel.SetFusionMaterial(g1)
return
end
local sg = eg:Filter(f, nil)
if chkf == PLAYER_NONE or sg:GetCount() == cc then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg:Select(tp, cc, cc, nil)
Duel.SetFusionMaterial(g1)
return
end
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g1 = sg:FilterSelect(tp, Auxiliary.FConditionCheckF, 1, 1, nil, chkf)
if cc > 1 then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_FMATERIAL)
local g2 = sg:Select(tp, cc - 1, cc - 1, g1:GetFirst())
g1:Merge(g2)
end
Duel.SetFusionMaterial(g1)
end
end
function Auxiliary.AddRitualProcGreater(c, filter)
-- Ritual Summon, geq fixed lv
local e1 = Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(Auxiliary.RPGTarget(filter))
e1:SetOperation(Auxiliary.RPGOperation(filter))
c:RegisterEffect(e1)
end
function Auxiliary.RPGFilter(c, filter, e, tp, m)
if (filter and not filter(c)) or not c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_RITUAL, tp, false, true) then return false end
local mg = m:Filter(Card.IsCanBeRitualMaterial, c, c)
return mg:CheckWithSumGreater(Card.GetRitualLevel, c:GetOriginalLevel(), c)
end
function Auxiliary.RPGTarget(filter)
return function(e, tp, eg, ep, ev, re, r, rp, chk)
if chk == 0 then
local mg = Duel.GetRitualMaterial(tp)
return Duel.IsExistingMatchingCard(Auxiliary.RPGFilter, tp, LOCATION_HAND, 0, 1, nil, filter, e, tp, mg)
end
Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, nil, 1, tp, LOCATION_HAND)
end
end
function Auxiliary.RPGOperation(filter)
return function(e, tp, eg, ep, ev, re, r, rp)
local mg = Duel.GetRitualMaterial(tp)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local tg = Duel.SelectMatchingCard(tp, Auxiliary.RPGFilter, tp, LOCATION_HAND, 0, 1, 1, nil, filter, e, tp, mg)
local tc = tg:GetFirst()
if tc then
mg = mg:Filter(Card.IsCanBeRitualMaterial, tc, tc)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_RELEASE)
local mat = mg:SelectWithSumGreater(tp, Card.GetRitualLevel, tc:GetOriginalLevel(), tc)
tc:SetMaterial(mat)
Duel.ReleaseRitualMaterial(mat)
Duel.BreakEffect()
Duel.SpecialSummon(tc, SUMMON_TYPE_RITUAL, tp, tp, false, true, POS_FACEUP)
tc:CompleteProcedure()
end
end
end
function Auxiliary.AddRitualProcEqual(c, filter)
-- Ritual Summon, equal to fixed lv
local e1 = Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(Auxiliary.RPETarget(filter))
e1:SetOperation(Auxiliary.RPEOperation(filter))
c:RegisterEffect(e1)
end
function Auxiliary.RPEFilter(c, filter, e, tp, m)
if (filter and not filter(c)) or not c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_RITUAL, tp, false, true) then return false end
local mg = m:Filter(Card.IsCanBeRitualMaterial, c, c)
return mg:CheckWithSumEqual(Card.GetRitualLevel, c:GetOriginalLevel(), 1, 99, c)
end
function Auxiliary.RPETarget(filter)
return function(e, tp, eg, ep, ev, re, r, rp, chk)
if chk == 0 then
local mg = Duel.GetRitualMaterial(tp)
return Duel.IsExistingMatchingCard(Auxiliary.RPEFilter, tp, LOCATION_HAND, 0, 1, nil, filter, e, tp, mg)
end
Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, nil, 1, tp, LOCATION_HAND)
end
end
function Auxiliary.RPEOperation(filter)
return function(e, tp, eg, ep, ev, re, r, rp)
local mg = Duel.GetRitualMaterial(tp)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local tg = Duel.SelectMatchingCard(tp, Auxiliary.RPEFilter, tp, LOCATION_HAND, 0, 1, 1, nil, filter, e, tp, mg)
local tc = tg:GetFirst()
if tc then
mg = mg:Filter(Card.IsCanBeRitualMaterial, tc, tc)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_RELEASE)
local mat = mg:SelectWithSumEqual(tp, Card.GetRitualLevel, tc:GetOriginalLevel(), 1, 99, tc)
tc:SetMaterial(mat)
Duel.ReleaseRitualMaterial(mat)
Duel.BreakEffect()
Duel.SpecialSummon(tc, SUMMON_TYPE_RITUAL, tp, tp, false, true, POS_FACEUP)
tc:CompleteProcedure()
end
end
end
function Auxiliary.AddRitualProcEqual2(c, filter)
-- Ritual Summon, equal to monster lv
local e1 = Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(Auxiliary.RPETarget2(filter))
e1:SetOperation(Auxiliary.RPEOperation2(filter))
c:RegisterEffect(e1)
end
function Auxiliary.RPEFilter2(c, filter, e, tp, m)
if (filter and not filter(c)) or not c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_RITUAL, tp, false, true) then return false end
local mg = m:Filter(Card.IsCanBeRitualMaterial, c, c)
return mg:CheckWithSumEqual(Card.GetRitualLevel, c:GetLevel(), 1, 99, c)
end
function Auxiliary.RPETarget2(filter)
return function(e, tp, eg, ep, ev, re, r, rp, chk)
if chk == 0 then
local mg = Duel.GetRitualMaterial(tp)
return Duel.IsExistingMatchingCard(Auxiliary.RPEFilter2, tp, LOCATION_HAND, 0, 1, nil, filter, e, tp, mg)
end
Duel.SetOperationInfo(0, CATEGORY_SPECIAL_SUMMON, nil, 1, tp, LOCATION_HAND)
end
end
function Auxiliary.RPEOperation2(filter)
return function(e, tp, eg, ep, ev, re, r, rp)
local mg = Duel.GetRitualMaterial(tp)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local tg = Duel.SelectMatchingCard(tp, Auxiliary.RPEFilter2, tp, LOCATION_HAND, 0, 1, 1, nil, filter, e, tp, mg)
local tc = tg:GetFirst()
if tc then
mg = mg:Filter(Card.IsCanBeRitualMaterial, tc, tc)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_RELEASE)
local mat = mg:SelectWithSumEqual(tp, Card.GetRitualLevel, tc:GetLevel(), 1, 99, tc)
tc:SetMaterial(mat)
Duel.ReleaseRitualMaterial(mat)
Duel.BreakEffect()
Duel.SpecialSummon(tc, SUMMON_TYPE_RITUAL, tp, tp, false, true, POS_FACEUP)
tc:CompleteProcedure()
end
end
end
function Auxiliary.AddPendulumProcedure(c)
-- add procedure to Pendulum monster
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC_G)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE + EFFECT_FLAG_CANNOT_DISABLE)
e1:SetRange(LOCATION_PZONE)
e1:SetCountLimit(1, 10000000)
e1:SetCondition(Auxiliary.PendCondition())
e1:SetOperation(Auxiliary.PendOperation())
e1:SetValue(SUMMON_TYPE_PENDULUM)
c:RegisterEffect(e1)
end
function Auxiliary.PConditionFilter(c, e, tp, lscale, rscale)
local lv = 0
if c.pendulum_level then
lv = c.pendulum_level
else
lv = c:GetLevel()
end
return(c:IsLocation(LOCATION_HAND) or(c:IsFaceup() and c:IsType(TYPE_PENDULUM)))
and lv > lscale and lv < rscale and c:IsCanBeSpecialSummoned(e, SUMMON_TYPE_PENDULUM, tp, false, false)
and not c:IsForbidden()
end
function Auxiliary.PendCondition()
return function(e, c, og)
if c == nil then return true end
local tp = c:GetControler()
if c:GetSequence() ~= 6 then return false end
local rpz = Duel.GetFieldCard(tp, LOCATION_SZONE, 7)
if rpz == nil then return false end
local lscale = c:GetLeftScale()
local rscale = rpz:GetRightScale()
if lscale > rscale then lscale, rscale = rscale, lscale end
local ft = Duel.GetLocationCount(tp, LOCATION_MZONE)
if ft <= 0 then return false end
if og then
return og:IsExists(Auxiliary.PConditionFilter, 1, nil, e, tp, lscale, rscale)
else
return Duel.IsExistingMatchingCard(Auxiliary.PConditionFilter, tp, LOCATION_HAND + LOCATION_EXTRA, 0, 1, nil, e, tp, lscale, rscale)
end
end
end
function Auxiliary.PendOperation()
return function(e, tp, eg, ep, ev, re, r, rp, c, sg, og)
local rpz = Duel.GetFieldCard(tp, LOCATION_SZONE, 7)
local lscale = c:GetLeftScale()
local rscale = rpz:GetRightScale()
if lscale > rscale then lscale, rscale = rscale, lscale end
local ft = Duel.GetLocationCount(tp, LOCATION_MZONE)
if og then
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local g = og:FilterSelect(tp, Auxiliary.PConditionFilter, 1, ft, nil, e, tp, lscale, rscale)
sg:Merge(g)
else
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_SPSUMMON)
local g = Duel.SelectMatchingCard(tp, Auxiliary.PConditionFilter, tp, LOCATION_HAND + LOCATION_EXTRA, 0, 1, ft, nil, e, tp, lscale, rscale)
sg:Merge(g)
end
Duel.HintSelection(Group.FromCards(c))
Duel.HintSelection(Group.FromCards(rpz))
end
end
function Auxiliary.disfilter1(c)
-- card effect disable filter(target)
return c:IsFaceup() and not c:IsDisabled() and(not c:IsType(TYPE_NORMAL) or bit.band(c:GetOriginalType(), TYPE_EFFECT) ~= 0)
end
function Auxiliary.bdcon(e, tp, eg, ep, ev, re, r, rp)
-- condition of EVENT_BATTLE_DESTROYING
local c = e:GetHandler()
return c:IsRelateToBattle()
end
function Auxiliary.bdocon(e, tp, eg, ep, ev, re, r, rp)
-- condition of EVENT_BATTLE_DESTROYING + opponent monster
local c = e:GetHandler()
return c:IsRelateToBattle() and c:IsStatus(STATUS_OPPO_BATTLE)
end
function Auxiliary.bdgcon(e, tp, eg, ep, ev, re, r, rp)
-- condition of EVENT_BATTLE_DESTROYING + to_grave
local c = e:GetHandler()
local bc = c:GetBattleTarget()
return c:IsRelateToBattle() and bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER)
end
function Auxiliary.bdogcon(e, tp, eg, ep, ev, re, r, rp)
-- condition of EVENT_BATTLE_DESTROYING + opponent monster + to_grave
local c = e:GetHandler()
local bc = c:GetBattleTarget()
return c:IsRelateToBattle() and c:IsStatus(STATUS_OPPO_BATTLE) and bc:IsLocation(LOCATION_GRAVE) and bc:IsType(TYPE_MONSTER)
end
function Auxiliary.chainreg(e, tp, eg, ep, ev, re, r, rp)
-- flag effect for spell counter
if e:GetHandler():GetFlagEffect(1) == 0 then
e:GetHandler():RegisterFlagEffect(1, RESET_EVENT + 0x1fc0000 + RESET_CHAIN, 0, 1)
end
end
function Auxiliary.imval1(e, c)
-- default filter for EFFECT_CANNOT_BE_BATTLE_TARGET/EFFECT_MUST_BE_ATTACKED
return not c:IsImmuneToEffect(e)
end
function Auxiliary.tgval(e, re, rp)
-- default filter for EFFECT_CANNOT_BE_EFFECT_TARGET
return not re:GetHandler():IsImmuneToEffect(e)
end
function Auxiliary.tgoval(e, re, rp)
-- filter for EFFECT_CANNOT_BE_EFFECT_TARGET + opponent
return rp ~= e:GetHandlerPlayer() and not re:GetHandler():IsImmuneToEffect(e)
end
function Auxiliary.nzatk(c)
-- filter for non-zero ATK
return c:IsFaceup() and c:GetAttack() > 0
end
function Auxiliary.nzdef(c)
-- filter for non-zero DEF
return c:IsFaceup() and c:GetDefence() > 0
end
function Auxiliary.sumreg(e, tp, eg, ep, ev, re, r, rp)
-- flag effect for summon/sp_summon turn
local tc = eg:GetFirst()
local code = e:GetLabel()
while tc do
if tc:GetOriginalCode() == code then
tc:RegisterFlagEffect(code, RESET_EVENT + 0x1ec0000 + RESET_PHASE + PHASE_END, 0, 1)
end
tc = eg:GetNext()
end
end
function Auxiliary.fuslimit(e, se, sp, st)
-- sp_summon condition for fusion monster
return bit.band(st, SUMMON_TYPE_FUSION) == SUMMON_TYPE_FUSION
end
function Auxiliary.ritlimit(e, se, sp, st)
-- sp_summon condition for ritual monster
return bit.band(st, SUMMON_TYPE_RITUAL) == SUMMON_TYPE_RITUAL
end
function Auxiliary.synlimit(e, se, sp, st)
-- sp_summon condition for synchro monster
return bit.band(st, SUMMON_TYPE_SYNCHRO) == SUMMON_TYPE_SYNCHRO
end
function Auxiliary.xyzlimit(e, se, sp, st)
-- sp_summon condition for xyz monster
return bit.band(st, SUMMON_TYPE_XYZ) == SUMMON_TYPE_XYZ
end
function Auxiliary.penlimit(e, se, sp, st)
-- sp_summon condition for pendulum monster
return bit.band(st, SUMMON_TYPE_PENDULUM) == SUMMON_TYPE_PENDULUM
end
function Auxiliary.damcon1(e, tp, eg, ep, ev, re, r, rp)
-- effects inflicting damage to tp
local e1 = Duel.IsPlayerAffectedByEffect(tp, EFFECT_REVERSE_DAMAGE)
local e2 = Duel.IsPlayerAffectedByEffect(tp, EFFECT_REVERSE_RECOVER)
local rd = e1 and not e2
local rr = not e1 and e2
local ex, cg, ct, cp, cv = Duel.GetOperationInfo(ev, CATEGORY_DAMAGE)
if ex and(cp == tp or cp == PLAYER_ALL) and not rd and not Duel.IsPlayerAffectedByEffect(tp, EFFECT_NO_EFFECT_DAMAGE) then
return true
end
ex, cg, ct, cp, cv = Duel.GetOperationInfo(ev, CATEGORY_RECOVER)
return ex and(cp == tp or cp == PLAYER_ALL) and rr and not Duel.IsPlayerAffectedByEffect(tp, EFFECT_NO_EFFECT_DAMAGE)
end
function Auxiliary.qlifilter(e, te)
-- filter for the immune effetc of qli monsters
if te:IsActiveType(TYPE_MONSTER)
and(te:IsHasType(0x7e0) or(te:IsHasProperty(EFFECT_FLAG_FIELD_ONLY) and not te:IsHasProperty(EFFECT_FLAG_CONTINUOUS))
or te:IsHasProperty(EFFECT_FLAG_OWNER_RELATE)) then
local lv = e:GetHandler():GetLevel()
local ec = te:GetOwner()
if ec:IsType(TYPE_XYZ) then
return ec:GetOriginalRank() < lv
else
return ec:GetOriginalLevel() < lv
end
else
return false
end
end
function Auxiliary.nvfilter(c)
-- filter for necro_valley test
return not c:IsHasEffect(EFFECT_NECRO_VALLEY)
end | mit |
BTAxis/naev | dat/missions/empire/longdistanceshipping/emp_longdistancecargo5.lua | 2 | 2812 | --[[
Fifth diplomatic mission to Sirius space that opens up the Empire long-distance cargo missions.
Author: micahmumper
]]--
include "dat/scripts/numstring.lua"
include "dat/scripts/jumpdist.lua"
bar_desc = _("Lieutenant Czesc from the Empire Aramda Shipping Division is sitting at the bar.")
misn_title = _("Sirius Long Distance Recruitment")
misn_reward = _("500,000 credits")
misn_desc = _("Deliver a shipping diplomat for the Empire to Madria in the Esker system.")
title = {}
title[1] = _("Spaceport Bar")
title[2] = _("Sirius Long Distance Recruitment")
title[3] = _("Mission Accomplished")
text = {}
text[1] = _([[Lieutenant Czesc approaches as you enter the bar. "If it isn't my favorite Empire Armada employee. We're on track to establish a deal with House Sirius. This should be the last contract to be negotiated. Ready to go?"]])
text[2] = _([["You know how this goes by now." says Lieutenant Czesc, "Drop the bureaucrat off at Madria in the Esker system. Sirius space is quite a distance, so be prepared for anything. Afterwards, come find me one more time and we'll finalize the paperwork to get you all set up for these missions."]])
text[3] = _([[You drop the diplomat off on Madria, and she hands you a credit chip. Lieutenant Czesc said to look for him in an Empire bar for some paperwork. Bureaucracy at its finest.]])
function create ()
-- Note: this mission does not make any system claims.
-- Get the planet and system at which we currently are.
startworld, startworld_sys = planet.cur()
-- Set our target system and planet.
targetworld_sys = system.get("Esker")
targetworld = planet.get("Madria")
misn.setNPC( _("Lieutenant"), "empire/unique/czesc" )
misn.setDesc( bar_desc )
end
function accept ()
-- Set marker to a system, visible in any mission computer and the onboard computer.
misn.markerAdd( targetworld_sys, "low")
---Intro Text
if not tk.yesno( title[1], text[1] ) then
misn.finish()
end
-- Flavour text and mini-briefing
tk.msg( title[2], text[2] )
---Accept the mission
misn.accept()
-- Description is visible in OSD and the onboard computer, it shouldn't be too long either.
reward = 500000
misn.setTitle(misn_title)
misn.setReward(misn_reward)
misn.setDesc( string.format( misn_desc, targetworld:name(), targetworld_sys:name() ) )
misn.osdCreate(title[2], {misn_desc})
-- Set up the goal
hook.land("land")
person = misn.cargoAdd( "Person" , 0 )
end
function land()
if planet.cur() == targetworld then
misn.cargoRm( person )
player.pay( reward )
-- More flavour text
tk.msg( title[3], text[3] )
faction.modPlayerSingle( "Empire",3 );
misn.finish(true)
end
end
function abort()
misn.finish(false)
end
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Metalworks/npcs/Vicious_Eye.lua | 4 | 1064 | -----------------------------------
-- Area: Metalworks
-- NPC: Vicious Eye
-- Guild Merchant NPC: Blacksmithing Guild
-- @zone: 237
-- @pos: -106.132 0.999 -28.757
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:sendGuild(528,8,23,2)) then
player:showText(npc, VICIOUS_EYE_SHOP_DIALOG);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Davoi/npcs/Zantaviat.lua | 19 | 2238 | -----------------------------------
-- Area: Davoi
-- NPC: Zantaviat
-- Involved in Mission: The Davoi Report
-- @pos 215 0.1 -10 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(SANDORIA);
local infiltrateDavoi = player:hasCompletedMission(SANDORIA,INFILTRATE_DAVOI);
if(CurrentMission == THE_DAVOI_REPORT and player:getVar("MissionStatus") == 0) then
player:startEvent(0x0064);
elseif(CurrentMission == THE_DAVOI_REPORT and player:hasKeyItem(LOST_DOCUMENT)) then
player:startEvent(0x0068);
elseif(CurrentMission == INFILTRATE_DAVOI and infiltrateDavoi and player:getVar("MissionStatus") == 0) then
player:startEvent(0x0066);
elseif(CurrentMission == INFILTRATE_DAVOI and player:getVar("MissionStatus") == 9) then
player:startEvent(0x0069);
else
player:startEvent(0x0065);
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 == 0x0064) then
player:setVar("MissionStatus",1);
elseif(csid == 0x0068) then
player:setVar("MissionStatus",3);
player:delKeyItem(LOST_DOCUMENT);
player:addKeyItem(TEMPLE_KNIGHTS_DAVOI_REPORT);
player:messageSpecial(KEYITEM_OBTAINED,TEMPLE_KNIGHTS_DAVOI_REPORT);
elseif(csid == 0x0066) then
player:setVar("MissionStatus",6);
elseif(csid == 0x0069) then
player:setVar("MissionStatus",10);
player:delKeyItem(EAST_BLOCK_CODE);
player:delKeyItem(SOUTH_BLOCK_CODE);
player:delKeyItem(NORTH_BLOCK_CODE);
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Windurst_Waters/npcs/Akkeke.lua | 36 | 1418 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Akkeke
-- Involved in Quest: Making the Grade
-- Working 100%
-- @zone = 238
-- @pos = 135 -6 165
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
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:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then
player:startEvent(0x01c5); -- During Making the GRADE
else
player:startEvent(0x01ab); -- Standard conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Temenos/mobs/Dark_Elemental.lua | 2 | 1235 | -----------------------------------
-- Area: Temenos E T
-- NPC: Dark Elemental
-----------------------------------
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)
local mobID = mob:getID();
local mobX = mob:getXPos();
local mobY = mob:getYPos();
local mobZ = mob:getZPos();
switch (mobID): caseof {
-- 100 a 106 inclut (Temenos -Northern Tower )
[16928892] = function (x)
GetNPCByID(16928768+70):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+70):setStatus(STATUS_NORMAL);
end ,
[16928893] = function (x)
GetNPCByID(16928768+123):setPos(mobX,mobY,mobZ);
GetNPCByID(16928768+123):setStatus(STATUS_NORMAL);
end ,
}
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Quicksand_Caves/npcs/HomePoint#1.lua | 1 | 1654 | -----------------------------------
-- Area: Quicksand_Caves
-- NPC: HomePoint#1
-- @pos -984 17 -289 208
-----------------------------------
package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Quicksand_Caves/TextIDs");
require("scripts/globals/homepoint");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
if(HOMEPOINT_TELEPORT == 1)then
-- ?/1-Ru'lude5 /Lude-Ru'Aun/Tav-end/ ?/Gil /Expantion level/Registered
player:startEvent(0x21fc,0,player:getVar("hpmask1"),player:getVar("hpmask2"),player:getVar("hpmask3"),player:getVar("hpmask4"),player:getGil(),4095,56 + addtohps(player,2,24));
else
player:startEvent(0x21fc)
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 == 0x21fc) then
if (option == 1) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
else
hpteleport(player,option);
end
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Metalworks/npcs/Cloud_Walker.lua | 2 | 1073 | -----------------------------------
-- Area: Metalworks
-- NPC: Cloud Walker
-- Type: Marriage NPC
-- @zone: 237
-- @pos: 89, -20, -12
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Metalworks/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/titles");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x07D1);
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 |
flyzjhz/openwrt-bb | feeds/routing/alfred/files/bat-hosts.lua | 17 | 2889 | #!/usr/bin/lua
local type_id = 64 -- bat-hosts
function get_hostname()
local hostfile = io.open("/proc/sys/kernel/hostname", "r")
local ret_string = hostfile:read()
hostfile:close()
return ret_string
end
function get_interfaces_names()
local ret = {}
for name in io.popen("ls -1 /sys/class/net/"):lines() do
table.insert(ret, name)
end
return ret
end
function get_interface_address(name)
local addressfile = io.open("/sys/class/net/"..name.."/address", "r")
local ret_string = addressfile:read()
addressfile:close()
return ret_string
end
local function generate_bat_hosts()
-- get hostname and interface macs/names
-- then return a table containing valid bat-hosts lines
local n, i
local ifaces, ret = {}, {}
local hostname = get_hostname()
for n, i in ipairs(get_interfaces_names()) do
local address = get_interface_address(i)
if not ifaces[address] then ifaces[address] = i end
end
for mac, iname in pairs(ifaces) do
if mac:match("^%x%x:%x%x:%x%x:%x%x:%x%x:%x%x$") and not mac:match("00:00:00:00:00:00") then
table.insert(ret, mac.." "..hostname.."_"..iname.."\n")
end
end
return ret
end
local function publish_bat_hosts()
-- pass a raw chunk of data to alfred
local fd = io.popen("alfred -s " .. type_id, "w")
if fd then
local ret = generate_bat_hosts()
if ret then
fd:write(table.concat(ret))
end
fd:close()
end
end
local function write_bat_hosts(rows)
local content = { "### /tmp/bat-hosts generated by alfred-bat-hosts\n",
"### /!\\ This file is overwritten every 5 minutes /!\\\n",
"### (To keep manual changes, replace /etc/bat-hosts symlink with a static file)\n" }
-- merge the chunks from all nodes, de-escaping newlines
for _, row in ipairs(rows) do
local node, value = unpack(row)
table.insert(content, "# Node ".. node .. "\n")
table.insert(content, value:gsub("\x0a", "\n") .. "\n")
end
-- write parsed content down to disk
local fd = io.open("/tmp/bat-hosts", "w")
if fd then
fd:write(table.concat(content))
fd:close()
end
-- try to make a symlink in /etc pointing to /tmp,
-- if it exists, ln will do nothing.
os.execute("ln -ns /tmp/bat-hosts /etc/bat-hosts 2>/dev/null")
end
local function receive_bat_hosts()
-- read raw chunks from alfred, convert them to a nested table and call write_bat_hosts
local fd = io.popen("alfred -r " .. type_id)
--[[ this command returns something like
{ "54:e6:fc:b9:cb:37", "00:11:22:33:44:55 ham_wlan0\x0a00:22:33:22:33:22 ham_eth0\x0a" },
{ "90:f6:52:bb:ec:57", "00:22:33:22:33:23 spam\x0a" },
]]--
if fd then
local output = fd:read("*a")
if output then
assert(loadstring("rows = {" .. output .. "}"))()
write_bat_hosts(rows)
end
fd:close()
end
end
publish_bat_hosts()
receive_bat_hosts()
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Batallia_Downs/npcs/Stone_Monument.lua | 4 | 1249 | -----------------------------------
-- Area: Batallia Downs
-- NPC: Stone Monument
-- Involved in quest "An Explorer's Footsteps"
-----------------------------------
package.loaded["scripts/zones/Batallia_Downs/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Batallia_Downs/TextIDs");
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0384);
end;
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1 and trade:hasItemQty(571,1)) then
player:tradeComplete();
player:addItem(570);
player:specialMessage(ITEM_OBTAINED,570);
player:setVar("anExplorer-CurrentTablet",0x10000);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Norg/npcs/Jaucribaix.lua | 4 | 9487 | -----------------------------------
-- Area: Norg
-- NPC: Jaucribaix
-- Starts and Finishes Quest: Forge Your Destiny, The Sacred Katana, Yomi Okuri, A Thief in Norg!?
-- @pos 91 -7 -8 252
-----------------------------------
package.loaded["scripts/zones/Norg/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Norg/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local count = trade:getItemCount();
if(player:getQuestStatus(OUTLANDS,FORGE_YOUR_DESTINY) == QUEST_ACCEPTED) then
if(trade:hasItemQty(1153,1) and trade:hasItemQty(1152,1) and count == 2) then -- Trade Sacred branch and Bomb Steel
player:startEvent(0x001b);
end
end
if(player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA) == QUEST_ACCEPTED) then
if(player:hasKeyItem(HANDFUL_OF_CRYSTAL_SCALES) and trade:hasItemQty(17809,1) and count == 1) then -- Trade Mumeito
player:startEvent(0x008d);
end
end
if(player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG) == QUEST_ACCEPTED) then
if(player:hasKeyItem(CHARRED_HELM) and trade:hasItemQty(823,1) and count == 1) then -- Trade Gold Thread
player:startEvent(0x00a2);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ForgeYourDestiny = player:getQuestStatus(OUTLANDS, FORGE_YOUR_DESTINY);
local theSacredKatana = player:getQuestStatus(OUTLANDS,THE_SACRED_KATANA);
local yomiOkuri = player:getQuestStatus(OUTLANDS,YOMI_OKURI);
local aThiefinNorg = player:getQuestStatus(OUTLANDS,A_THIEF_IN_NORG);
local mLvl = player:getMainLvl();
local mJob = player:getMainJob();
if(mLvl >= ADVANCED_JOB_LEVEL and ForgeYourDestiny == QUEST_AVAILABLE) then
player:startEvent(0x0019,1153,1152); -- Sacred branch, Bomb Steel
elseif(ForgeYourDestiny == QUEST_ACCEPTED) then
local swordTimer = player:getVar("ForgeYourDestiny_timer");
if(swordTimer > os.time()) then
player:startEvent(0x001c,(swordTimer - os.time())/144);
elseif(swordTimer < os.time() and swordTimer ~= 0) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(CARRYING_TOO_MUCH_ALREADY);
else
player:startEvent(0x001d, 17809); -- Finish Quest "Forge Your Destiny"
end
else
player:startEvent(0x001a);
end
elseif(theSacredKatana == QUEST_AVAILABLE and mJob == 12 and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x008b); -- Start Quest "The Sacred Katana"
elseif(theSacredKatana == QUEST_ACCEPTED) then
if(player:hasItem(17809) == false) then
player:startEvent(0x008f); -- CS without Mumeito
else
player:startEvent(0x008c); -- CS with Mumeito
end
elseif(theSacredKatana == QUEST_COMPLETED and yomiOkuri == QUEST_AVAILABLE and mJob == 12 and mLvl >= AF2_QUEST_LEVEL) then
if(player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForYomiOkuri_date")) then
player:startEvent(0x008e); -- Need to zone and wait midnight after "The Sacred Katana"
else
player:startEvent(0x0092); -- Start Quest "Yomi Okuri"
end
elseif(yomiOkuri == QUEST_ACCEPTED) then
local yomiOkuriCS = player:getVar("yomiOkuriCS");
local yomotsuFeather = player:hasKeyItem(YOMOTSU_FEATHER);
if(yomiOkuriCS <= 3 and yomotsuFeather == false) then
player:startEvent(0x0093);
elseif(yomotsuFeather) then
player:startEvent(0x0098);
elseif(yomiOkuriCS == 4 and (tonumber(os.date("%j")) == player:getVar("Wait1DayForYomiOkuri2_date") or player:needToZone())) then
player:startEvent(0x0099);
elseif(yomiOkuriCS == 4) then
player:startEvent(0x009a);
elseif(yomiOkuriCS == 5 and player:hasKeyItem(YOMOTSU_HIRASAKA)) then
player:startEvent(0x009b);
elseif(player:hasKeyItem(FADED_YOMOTSU_HIRASAKA)) then
player:startEvent(0x009c); -- Finish Quest "Yomi Okuri"
end
elseif(yomiOkuri == QUEST_COMPLETED and aThiefinNorg == QUEST_AVAILABLE and mJob == 12 and mLvl >= 50) then
if(player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForAThiefinNorg_date")) then
player:startEvent(0x009d); -- Need to zone and wait midnight after "Yomi Okuri"
else
player:startEvent(0x009e); -- Start Quest "A Thief in Norg!?"
end
elseif(aThiefinNorg == QUEST_ACCEPTED) then
local aThiefinNorgCS = player:getVar("aThiefinNorgCS");
if(aThiefinNorgCS < 5) then
player:startEvent(0x009f);
elseif(aThiefinNorgCS == 5) then
player:startEvent(0x00a6);
elseif(aThiefinNorgCS == 6 and player:hasItem(1166)) then -- Banishing Charm
player:startEvent(0x00a7); -- Go to the battlefield
elseif(aThiefinNorgCS == 6) then
player:startEvent(0x00a8); -- If you delete the item
elseif(aThiefinNorgCS == 7) then
player:startEvent(0x00a0);
elseif(aThiefinNorgCS == 8) then
player:startEvent(0x00a1);
elseif(aThiefinNorgCS == 9 and (player:needToZone() or tonumber(os.date("%j")) == player:getVar("Wait1DayForAThiefinNorg2_date"))) then
player:startEvent(0x00a3);
elseif(aThiefinNorgCS == 9) then
player:startEvent(0x00a4); -- Finish Quest "A Thief in Norg!?"
end
elseif(aThiefinNorg == QUEST_COMPLETED) then
player:startEvent(0x00a5); -- New Standard dialog
else
player:startEvent(0x0047); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0019 and option == 1) then
player:addQuest(OUTLANDS,FORGE_YOUR_DESTINY);
elseif(csid == 0x001b) then
player:tradeComplete();
player:setVar("ForgeYourDestiny_timer", os.time() + 10368); --Add 3 game days
elseif(csid == 0x001d) then
player:tradeComplete();
player:addTitle(BUSHIDO_BLADE);
player:addItem(17809);
player:messageSpecial(YOU_CAN_NOW_BECOME_A_SAMURAI, 17809); -- You can now become a samurai
player:unlockJob(12); -- Samurai Job Unlocked
player:setVar("ForgeYourDestiny_timer",0);
player:setVar("ForgeYourDestiny_Event",0);
player:addFame(OUTLANDS, NORG_FAME*30);
player:completeQuest(OUTLANDS, FORGE_YOUR_DESTINY);
elseif(csid == 0x008b and option == 1) then
player:addQuest(OUTLANDS,THE_SACRED_KATANA);
elseif(csid == 0x008d) then
player:tradeComplete();
player:delKeyItem(HANDFUL_OF_CRYSTAL_SCALES);
player:needToZone(true);
player:setVar("Wait1DayForYomiOkuri_date", os.date("%j")); -- %M for next minute, %j for next day
player:setVar("Wait1DayForYomiOkuri",VanadielDayOfTheYear());
player:addItem(17812);
player:messageSpecial(ITEM_OBTAINED,17812); -- Magoroku
player:addFame(OUTLANDS,NORG_FAME*AF1_FAME);
player:completeQuest(OUTLANDS,THE_SACRED_KATANA);
elseif(csid == 0x0092 and option == 1) then
player:addQuest(OUTLANDS,YOMI_OKURI);
player:setVar("Wait1DayForYomiOkuri_date",0);
player:setVar("yomiOkuriCS",1);
elseif(csid == 0x0098) then
player:delKeyItem(YOMOTSU_FEATHER);
player:setVar("yomiOkuriCS",4);
player:needToZone(true);
player:setVar("Wait1DayForYomiOkuri2_date", os.date("%j")); -- %M for next minute, %j for next day
elseif(csid == 0x009a) then
player:setVar("yomiOkuriCS",5);
player:setVar("Wait1DayForYomiOkuri2_date",0);
player:addKeyItem(YOMOTSU_HIRASAKA);
player:messageSpecial(KEYITEM_OBTAINED,YOMOTSU_HIRASAKA);
elseif(csid == 0x009c) then
if(player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14100);
else
player:delKeyItem(FADED_YOMOTSU_HIRASAKA);
player:addItem(14100);
player:messageSpecial(ITEM_OBTAINED,14100); -- Myochin Sune-Ate
player:setVar("yomiOkuriCS",0);
player:needToZone(true);
player:setVar("Wait1DayForAThiefinNorg_date", os.date("%j")); -- %M for next minute, %j for next day
player:addFame(OUTLANDS,NORG_FAME*AF2_FAME);
player:completeQuest(OUTLANDS,YOMI_OKURI);
end
elseif(csid == 0x009e and option == 1) then
player:addQuest(OUTLANDS,A_THIEF_IN_NORG);
player:setVar("Wait1DayForAThiefinNorg_date",0);
player:setVar("aThiefinNorgCS",1);
elseif(csid == 0x00a6 or csid == 0x00a8) then
if(player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1166);
else
player:addItem(1166);
player:messageSpecial(ITEM_OBTAINED,1166); -- Banishing Charm
player:setVar("aThiefinNorgCS",6);
end
elseif(csid == 0x00a0) then
player:setVar("aThiefinNorgCS",8);
elseif(csid == 0x00a2) then
player:tradeComplete();
player:delKeyItem(CHARRED_HELM);
player:setVar("aThiefinNorgCS",9);
player:needToZone(true);
player:setVar("Wait1DayForAThiefinNorg2_date", os.date("%j")); -- %M for next minute, %j for next day
elseif(csid == 0x00a4) then
if(player:getFreeSlotsCount() < 1) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13868);
else
player:addItem(13868);
player:messageSpecial(ITEM_OBTAINED,13868); -- Myochin Kabuto
player:addTitle(PARAGON_OF_SAMURAI_EXCELLENCE);
player:setVar("aThiefinNorgCS",0);
player:setVar("Wait1DayForAThiefinNorg2_date",0);
player:addFame(OUTLANDS,NORG_FAME*AF3_FAME);
player:completeQuest(OUTLANDS,A_THIEF_IN_NORG);
end
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/weaponskills/trueflight.lua | 2 | 4541 | -----------------------------------
-- Skill Level: N/A
-- Description: Deals light elemental damage. Damage varies with TP. Gastraphetes: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Ranger) quest.
-- Does not work with Flashy Shot.
-- Does not work with Stealth Shot.
-- Aligned with the Breeze Gorget, Thunder Gorget & Soil Gorget.
-- Aligned with the Breeze Belt, Thunder Belt & Soil Belt.
-- Properties
-- Element: Light
-- Skillchain Properties: Fragmentation/Scission
-- Modifiers: AGI:30%
-- Damage Multipliers by TP:
-- 100%TP 200%TP 300%TP
-- 4.0 4.25 4.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0;
params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0;
params.chr_wsc = 0.0;
params.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;
-- needs ignore defense. param
local damage, tpHits, extraHits = doRangedWeaponskill(player, target, params);
if((player:getEquipID(SLOT_RANGED) == 19001) and (player:getMainJob() == JOB_RNG)) then
if(damage > 0) then
-- AFTERMATH LV1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 3);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 3);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 3);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 3);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 3);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 3);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 3);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 3);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 3);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 3);
-- AFTERMATH LV2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 4);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 4);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 4);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 4);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 4);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 4);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 4);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 4);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 4);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 4);
-- AFTERMATH LV3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 2);
end
end
end
local criticalHit = false;
return tpHits, extraHits, criticalHit, damage;
end;
| gpl-3.0 |
meshr-net/meshr_win32 | usr/lib/lua/luci/model/cbi/siitwizard.lua | 11 | 10095 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
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: siitwizard.lua 3966 2008-12-29 17:39:48Z jow $
]]--
local uci = require "luci.model.uci".cursor()
-------------------- Init --------------------
--
-- Find link-local address
--
LL_PREFIX = luci.ip.IPv6("fe80::/64")
function find_ll()
for _, r in ipairs(luci.sys.net.routes6()) do
if LL_PREFIX:contains(r.dest) and r.dest:higher(LL_PREFIX) then
return r.dest:sub(LL_PREFIX)
end
end
return luci.ip.IPv6("::")
end
--
-- Determine defaults
--
local ula_prefix = uci:get("siit", "ipv6", "ula_prefix") or "fd00::"
local ula_global = uci:get("siit", "ipv6", "ula_global") or "00ca:ffee:babe::" -- = Freifunk
local ula_subnet = uci:get("siit", "ipv6", "ula_subnet") or "0000:0000:0000:4223::" -- = Berlin
local siit_prefix = uci:get("siit", "ipv6", "siit_prefix") or "::ffff:0000:0000"
local ipv4_pool = uci:get("siit", "ipv4", "pool") or "172.16.0.0/12"
local ipv4_netsz = uci:get("siit", "ipv4", "netsize") or "24"
--
-- Find IPv4 allocation pool
--
local gv4_net = luci.ip.IPv4(ipv4_pool)
--
-- Generate ULA
--
local ula = luci.ip.IPv6("::/64")
for _, prefix in ipairs({ ula_prefix, ula_global, ula_subnet }) do
ula = ula:add(luci.ip.IPv6(prefix))
end
ula = ula:add(find_ll())
-------------------- View --------------------
f = SimpleForm("siitwizward", "SIIT-Wizzard",
"This wizzard helps to setup SIIT (IPv4-over-IPv6) translation according to RFC2765.")
f:field(DummyValue, "info_ula", "Mesh ULA address").value = ula:string()
f:field(DummyValue, "ipv4_pool", "IPv4 allocation pool").value =
"%s (%i hosts)" %{ gv4_net:string(), 2 ^ ( 32 - gv4_net:prefix() ) - 2 }
f:field(DummyValue, "ipv4_size", "IPv4 LAN network prefix").value =
"%i bit (%i hosts)" %{ ipv4_netsz, 2 ^ ( 32 - ipv4_netsz ) - 2 }
mode = f:field(ListValue, "mode", "Operation mode")
mode:value("client", "Client")
mode:value("gateway", "Gateway")
dev = f:field(ListValue, "device", "Wireless device")
uci:foreach("wireless", "wifi-device",
function(section)
dev:value(section[".name"])
end)
lanip = f:field(Value, "ipaddr", "LAN IPv4 subnet")
function lanip.formvalue(self, section)
local val = self.map:formvalue(self:cbid(section))
local net = luci.ip.IPv4("%s/%i" %{ val, ipv4_netsz })
if net then
if gv4_net:contains(net) then
if not net:minhost():equal(net:host()) then
self.error = { [section] = true }
f.errmessage = "IPv4 address is not the first host of " ..
"subnet, expected " .. net:minhost():string()
end
else
self.error = { [section] = true }
f.errmessage = "IPv4 address is not within the allocation pool"
end
else
self.error = { [section] = true }
f.errmessage = "Invalid IPv4 address given"
end
return val
end
dns = f:field(Value, "dns", "DNS server for LAN clients")
dns.value = "141.1.1.1"
-------------------- Control --------------------
function f.handle(self, state, data)
if state == FORM_VALID then
luci.http.redirect(luci.dispatcher.build_url("admin", "uci", "changes"))
return false
end
return true
end
function mode.write(self, section, value)
--
-- Find LAN IPv4 range
--
local lan_net = luci.ip.IPv4(
( lanip:formvalue(section) or "172.16.0.1" ) .. "/" .. ipv4_netsz
)
if not lan_net then return end
--
-- Find wifi interface, dns server and hostname
--
local device = dev:formvalue(section)
local dns_server = dns:formvalue(section) or "141.1.1.1"
local hostname = "siit-" .. lan_net:host():string():gsub("%.","-")
--
-- Configure wifi device
--
local wifi_device = dev:formvalue(section)
local wifi_essid = uci:get("siit", "wifi", "essid") or "6mesh.freifunk.net"
local wifi_bssid = uci:get("siit", "wifi", "bssid") or "02:ca:ff:ee:ba:be"
local wifi_channel = uci:get("siit", "wifi", "channel") or "1"
-- nuke old device definition
uci:delete_all("wireless", "wifi-iface",
function(s) return s.device == wifi_device end )
uci:delete_all("network", "interface",
function(s) return s['.name'] == wifi_device end )
-- create wifi device definition
uci:tset("wireless", wifi_device, {
disabled = 0,
channel = wifi_channel,
-- txantenna = 1,
-- rxantenna = 1,
-- diversity = 0
})
uci:section("wireless", "wifi-iface", nil, {
encryption = "none",
mode = "adhoc",
txpower = 10,
sw_merge = 1,
network = wifi_device,
device = wifi_device,
ssid = wifi_essid,
bssid = wifi_bssid,
})
--
-- Gateway mode
--
-- * wan port is dhcp, lan port is 172.23.1.1/24
-- * siit0 gets a dummy address: 169.254.42.42
-- * wl0 gets an ipv6 address, in this case the fdca:ffee:babe::1:1/64
-- * we do a ::ffff:ffff:0/96 route into siit0, so everything from 6mesh goes into translation.
-- * an HNA6 of ::ffff:ffff:0:0/96 announces the mapped 0.0.0.0/0 ipv4 space.
-- * MTU on WAN, LAN down to 1400, ipv6 headers are slighly larger.
if value == "gateway" then
-- wan mtu
uci:set("network", "wan", "mtu", 1240)
-- lan settings
uci:tset("network", "lan", {
mtu = 1240,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string(),
proto = "static"
})
-- use full siit subnet
siit_route = luci.ip.IPv6(siit_prefix .. "/96")
-- v4 <-> siit route
uci:delete_all("network", "route",
function(s) return s.interface == "siit0" end)
uci:section("network", "route", nil, {
interface = "siit0",
target = gv4_net:network():string(),
netmask = gv4_net:mask():string()
})
--
-- Client mode
--
-- * 172.23.2.1/24 on its lan, fdca:ffee:babe::1:2 on wl0 and the usual dummy address on siit0.
-- * we do a ::ffff:ffff:172.13.2.0/120 to siit0, because in this case, only traffic directed to clients needs to go into translation.
-- * same route as HNA6 announcement to catch the traffic out of the mesh.
-- * Also, MTU on LAN reduced to 1400.
else
-- lan settings
uci:tset("network", "lan", {
mtu = 1240,
ipaddr = lan_net:host():string(),
netmask = lan_net:mask():string()
})
-- derive siit subnet from lan config
siit_route = luci.ip.IPv6(
siit_prefix .. "/" .. (96 + lan_net:prefix())
):add(lan_net[2])
-- ipv4 <-> siit route
uci:delete_all("network", "route",
function(s) return s.interface == "siit0" end)
-- XXX: kind of a catch all, gv4_net would be better
-- but does not cover non-local v4 space
uci:section("network", "route", nil, {
interface = "siit0",
target = "0.0.0.0",
netmask = "0.0.0.0"
})
end
-- setup the firewall
uci:delete_all("firewall", "zone",
function(s) return (
s['.name'] == "siit0" or s.name == "siit0" or
s.network == "siit0" or s['.name'] == wifi_device or
s.name == wifi_device or s.network == wifi_device
) end)
uci:delete_all("firewall", "forwarding",
function(s) return (
s.src == wifi_device and s.dest == "siit0" or
s.dest == wifi_device and s.src == "siit0" or
s.src == "lan" and s.dest == "siit0" or
s.dest == "lan" and s.src == "siit0"
) end)
uci:section("firewall", "zone", "siit0", {
name = "siit0",
network = "siit0",
input = "ACCEPT",
output = "ACCEPT",
forward = "ACCEPT"
})
uci:section("firewall", "zone", wifi_device, {
name = wifi_device,
network = wifi_device,
input = "ACCEPT",
output = "ACCEPT",
forward = "ACCEPT"
})
uci:section("firewall", "forwarding", nil, {
src = wifi_device,
dest = "siit0"
})
uci:section("firewall", "forwarding", nil, {
src = "siit0",
dest = wifi_device
})
uci:section("firewall", "forwarding", nil, {
src = "lan",
dest = "siit0"
})
uci:section("firewall", "forwarding", nil, {
src = "siit0",
dest = "lan"
})
-- firewall include
uci:delete_all("firewall", "include",
function(s) return s.path == "/etc/firewall.user" end)
uci:section("firewall", "include", nil, {
path = "/etc/firewall.user"
})
-- siit0 interface
uci:delete_all("network", "interface",
function(s) return ( s.ifname == "siit0" ) end)
uci:section("network", "interface", "siit0", {
ifname = "siit0",
proto = "none"
})
-- siit0 route
uci:delete_all("network", "route6",
function(s) return siit_route:contains(luci.ip.IPv6(s.target)) end)
uci:section("network", "route6", nil, {
interface = "siit0",
target = siit_route:string()
})
-- create wifi network interface
uci:section("network", "interface", wifi_device, {
proto = "static",
mtu = 1400,
ip6addr = ula:string()
})
-- nuke old olsrd interfaces
uci:delete_all("olsrd", "Interface",
function(s) return s.interface == wifi_device end)
-- configure olsrd interface
uci:foreach("olsrd", "olsrd",
function(s) uci:set("olsrd", s['.name'], "IpVersion", 6) end)
uci:section("olsrd", "Interface", nil, {
ignore = 0,
interface = wifi_device,
Ip6AddrType = "unique-local"
})
-- hna6
uci:delete_all("olsrd", "Hna6",
function(s) return true end)
uci:section("olsrd", "Hna6", nil, {
netaddr = siit_route:host():string(),
prefix = siit_route:prefix()
})
-- txtinfo v6 & olsrd nameservice
uci:foreach("olsrd", "LoadPlugin",
function(s)
if s.library == "olsrd_txtinfo.so.0.1" then
uci:set("olsrd", s['.name'], "accept", "::1")
elseif s.library == "olsrd_nameservice.so.0.3" then
uci:set("olsrd", s['.name'], "name", hostname)
end
end)
-- lan dns
uci:tset("dhcp", "lan", {
dhcp_option = "6," .. dns_server,
start = bit.band(lan_net:minhost():add(1)[2][2], 0xFF),
limit = ( 2 ^ ( 32 - lan_net:prefix() ) ) - 3
})
-- hostname
uci:foreach("system", "system",
function(s)
uci:set("system", s['.name'], "hostname", hostname)
end)
uci:save("wireless")
uci:save("firewall")
uci:save("network")
uci:save("system")
uci:save("olsrd")
uci:save("dhcp")
end
return f
| apache-2.0 |
kidaa/FFXIOrgins | scripts/globals/abilities/addendum_black.lua | 4 | 1051 | -----------------------------------
-- Ability: Addendum: Black
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
if player:hasStatusEffect(EFFECT_ADDENDUM_BLACK) then
return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0;
end
return 0,0;
end;
function OnUseAbility(player, target, ability)
player:delStatusEffectSilent(EFFECT_LIGHT_ARTS);
player:delStatusEffectSilent(EFFECT_ADDENDUM_WHITE);
player:delStatusEffectSilent(EFFECT_DARK_ARTS);
local skillbonus = player:getMod(MOD_DARK_ARTS_SKILL);
local effectbonus = player:getMod(MOD_DARK_ARTS_EFFECT);
local helixbonus = 0;
if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then
helixbonus = math.floor(player:getMainLvl() / 4);
end
player:addStatusEffectEx(EFFECT_ADDENDUM_BLACK,EFFECT_ADDENDUM_BLACK,effectbonus,0,7200,0,helixbonus,true);
return EFFECT_ADDENDUM_BLACK;
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/items/cup_of_chai_+1.lua | 2 | 1153 | -----------------------------------------
-- ID: 5594
-- Item: cup_of_chai_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Vitality -3
-- Charisma 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5594);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -3);
target:addMod(MOD_CHR, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -3);
target:delMod(MOD_CHR, 3);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Aht_Urhgan_Whitegate/npcs/Tehf_Kimasnahya.lua | 4 | 2986 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Tehf Kimasnahya
-- Type: Standard NPC
-- @zone: 50
-- @pos: -89.897 -1 6.199
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local gotitall = player:getQuestStatus(AHT_URHGAN,GOT_IT_ALL);
local gotItAllProg = player:getVar("gotitallCS");
local threeMenProg = player:getVar("threemenandaclosetCS");
if(gotitall == QUEST_AVAILABLE) then
player:startEvent(0x0208);
elseif(gotItAllProg == 4) then
player:startEvent(0x020d);
elseif(gotItAllProg == 6) then
player:startEvent(0x020f);
elseif(gotItAllProg >= 7 and player:getVar("Wait1DayForgotitallCS_date") < os.time() and player:needToZone() == false) then
player:startEvent(0x0210);
elseif(gotItAllProg >= 7) then
player:startEvent(0x021b);
elseif(gotItAllProg >= 1 and gotItAllProg <= 3) then
player:startEvent(0x0209);
elseif(threeMenProg == 5) then
player:startEvent(0x034b);
elseif(threeMenProg == 6) then
player:startEvent(0x034c);
else
player:startEvent(0x0211);
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 == 0x0208)then
player:addQuest(AHT_URHGAN,GOT_IT_ALL);
player:setVar("gotitallCS",1);
elseif(csid == 0x020d and option == 0)then
player:setVar("gotitallCS",5);
player:delKeyItem(VIAL_OF_LUMINOUS_WATER);
elseif(csid == 0x020f)then
player:setVar("gotitallCS",7);
player:setVar("Wait1DayForgotitallCS_date", getMidnight());
player:needToZone(true);
elseif(csid == 0x021b)then
player:setVar("gotitallCS",8);
elseif(csid == 0x0210)then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,18257);
else
player:setVar("Wait1DayForgotitallCS_date",0);
player:setVar("gotitallCS",0);
player:addItem(18257); -- Bibiki Seashell
player:messageSpecial(ITEM_OBTAINED,18257);
player:completeQuest(AHT_URHGAN,GOT_IT_ALL);
end
elseif(csid == 0x034b and option == 1)then
player:setVar("threemenandaclosetCS",6);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/West_Ronfaure/npcs/Palcomondau.lua | 35 | 12378 | -----------------------------------
-- Area: West Ronfaure
-- NPC: Palcomondau
-- Type: Patrol
-- @pos -349.796 -45.345 344.733 100
-----------------------------------
package.loaded["scripts/zones/West_Ronfaure/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/pathfind");
-----------------------------------
local path = {
-373.096863, -45.742077, 340.182159,
-361.441864, -46.052444, 340.367371,
-360.358276, -46.063702, 340.457428,
-359.297211, -46.093231, 340.693817,
-358.264465, -46.285988, 341.032928,
-357.301941, -45.966343, 341.412994,
-356.365295, -45.641331, 341.804657,
-353.933533, -45.161453, 342.873901,
-346.744659, -45.006634, 346.113251,
-345.843506, -44.973419, 346.716309,
-345.138519, -44.939915, 347.540436,
-344.564056, -44.925575, 348.463470,
-344.069366, -44.945713, 349.431824,
-343.621704, -45.004826, 350.421936,
-343.194946, -45.062874, 351.421173,
-342.118958, -45.391632, 354.047485,
-334.448578, -44.964996, 373.198242,
-333.936615, -45.028484, 374.152283,
-333.189636, -45.068111, 374.939209,
-332.252838, -45.073158, 375.488129,
-331.241516, -45.065205, 375.888031,
-330.207855, -45.043056, 376.226532,
-329.165100, -45.022049, 376.536011,
-328.118622, -45.000935, 376.832428,
-323.437805, -45.726982, 378.101166,
-305.333038, -49.030193, 382.936646,
-304.308228, -49.435581, 383.130188,
-303.259979, -49.765697, 383.194305,
-302.209290, -50.104950, 383.175659,
-301.161774, -50.446033, 383.117767,
-300.114624, -50.787590, 383.041473,
-298.422943, -51.390713, 382.898590,
-281.798126, -56.178822, 381.370544,
-280.718414, -56.161697, 381.241425,
-279.641785, -56.142433, 381.087341,
-278.567627, -56.121262, 380.917938,
-261.485809, -55.875919, 378.010284,
-260.404205, -55.893314, 377.898254,
-259.317078, -55.908813, 377.861389,
-258.229248, -55.923473, 377.879669,
-257.142151, -55.938625, 377.919037,
-254.834976, -55.888081, 378.032623,
-224.857941, -56.603645, 379.721832,
-194.892044, -59.911034, 381.416382,
-178.437729, -61.500011, 382.347656,-- report?
-179.524124, -61.500011, 382.285919,
-209.530518, -58.837189, 380.588806,
-239.543137, -56.145073, 378.891602,
-257.769012, -55.930656, 377.861328,
-258.856445, -55.915405, 377.839905,
-259.943420, -55.900009, 377.884918,
-261.025116, -55.882565, 377.999329,
-262.102173, -55.864536, 378.151794,
-263.193237, -55.845242, 378.320587,
-279.088043, -56.134182, 381.021332,
-280.165344, -56.153133, 381.172882,
-281.246033, -56.168983, 381.299683,
-282.302917, -56.181866, 381.408691,
-301.977173, -50.175457, 383.230652,
-302.993134, -49.847698, 383.246735,
-303.998260, -49.580284, 383.147003,
-305.083649, -49.109840, 382.933411,
-306.061432, -48.755005, 382.706818,
-307.152679, -48.355675, 382.435608,
-327.497711, -45.027401, 377.016663,
-328.548553, -45.009663, 376.735291,
-331.569672, -45.071396, 375.927429,
-332.566711, -45.084835, 375.500153,
-333.347351, -45.055779, 374.749634,
-333.952423, -44.990082, 373.848999,
-334.454071, -44.958176, 372.884399,
-334.909607, -44.930862, 371.896698,
-335.338989, -44.939476, 370.897034,
-336.319305, -45.033978, 368.508484,
-344.092773, -44.934128, 349.103394,
-344.599304, -44.920494, 348.142578,
-345.289124, -44.948330, 347.305328,
-346.152740, -44.981884, 346.646881,
-347.087494, -45.014847, 346.091278,
-348.052368, -45.047348, 345.589172,
-349.030975, -45.039383, 345.114044,
-350.016052, -45.036438, 344.652252,
-357.274414, -45.947830, 341.359833,
-358.277222, -46.126381, 340.958984,
-359.326965, -46.091412, 340.679291,
-360.404205, -46.072746, 340.529785,
-361.488525, -46.061684, 340.441284,
-362.575226, -46.055046, 340.388184,
-363.662323, -46.050694, 340.353088,
-367.288086, -45.562141, 340.276978,
-397.408386, -46.031933, 339.796722,
-427.522491, -45.366581, 339.319641,
-457.651947, -45.910805, 338.841827,
-463.498932, -45.831551, 338.757111,
-464.580750, -45.752060, 338.776215,
-465.656433, -45.603558, 338.822693,
-467.953491, -45.463387, 338.967407,
-494.403381, -45.661190, 340.958710,
-495.442017, -45.667831, 341.254303,
-496.256042, -45.713417, 341.966400,
-496.865723, -45.720673, 342.866852,
-497.385132, -45.755371, 343.821838,
-498.376312, -45.856812, 345.908539,
-498.820007, -45.996841, 346.899353,
-499.174530, -46.197227, 347.923767,
-499.352539, -46.093906, 348.989563,
-499.416016, -46.074814, 350.073944,
-499.423279, -46.070366, 351.161072,
-499.397400, -46.084679, 352.248505,
-499.358795, -46.133957, 353.335815,
-498.771545, -46.025249, 365.000885,
-498.687347, -45.804886, 366.615082,
-498.166779, -45.846115, 376.640106,
-498.109924, -45.862961, 377.726410,
-497.697968, -45.951462, 385.738007,
-497.694122, -46.004673, 386.825317,
-497.737915, -46.056293, 387.912231,
-497.809082, -46.020039, 388.997162,
-498.192322, -46.074364, 393.595886,
-499.513733, -47.018887, 408.449036,
-499.682556, -47.223618, 409.509949,
-499.959503, -47.415245, 410.549194,
-500.307434, -47.595810, 411.566589,
-500.686859, -48.017868, 412.545349,
-501.077026, -48.478256, 413.506836,
-501.873901, -49.394321, 415.425659,
-502.207245, -49.737534, 416.425812,
-502.382660, -50.058594, 417.464630,
-502.406891, -50.394829, 418.516327,
-502.342438, -50.724243, 419.565948,
-502.251190, -51.088074, 420.607056,
-502.139435, -51.460213, 421.645935,
-501.954468, -52.022106, 423.198792,
-500.171021, -55.784023, 437.153931,
-500.033447, -56.010731, 438.356873,
-499.879120, -56.021641, 439.981689,
-499.679840, -55.963177, 442.392639,
-499.790558, -55.536102, 443.497894,
-500.205383, -55.237358, 444.453308,
-500.785736, -55.148598, 445.369598,
-501.427277, -55.099243, 446.246521,
-502.103760, -55.051254, 447.097015,
-502.791046, -55.003696, 447.939423,
-503.574524, -55.015862, 448.879730,
-510.872284, -55.089428, 457.484222,
-511.691742, -55.159729, 458.188812,
-512.678040, -55.280975, 458.628448,
-513.720825, -55.419674, 458.910309,
-514.785461, -55.554832, 459.097260,
-515.851929, -55.741619, 459.240265,
-516.923096, -55.906597, 459.366913,
-517.998413, -56.087105, 459.482513,
-521.921387, -56.035919, 459.879913,
-522.965271, -55.886223, 460.131927,
-523.947327, -55.785652, 460.568665,
-524.886719, -55.581245, 461.082581,
-525.805237, -55.438984, 461.645203,
-526.824829, -55.279068, 462.300720,
-531.560181, -54.945484, 465.464722,
-532.406555, -54.961479, 466.143524,
-533.060120, -54.995003, 467.010559,
-533.618408, -55.030079, 467.943695,
-534.158691, -55.026203, 468.887848,
-538.343323, -55.609158, 476.336639,
-538.852539, -55.920918, 477.273773,
-539.335510, -56.089600, 478.277985,
-539.767029, -56.035652, 479.274902,
-540.283997, -56.042004, 480.532135,
-544.975769, -55.047729, 492.510040,
-545.471375, -55.034317, 493.475891,
-546.206604, -55.009632, 494.270599,
-547.121643, -54.949020, 494.853882,
-548.100342, -54.921333, 495.329163,
-549.105103, -54.930302, 495.747131,
-550.121033, -54.979893, 496.133270,
-551.140991, -55.035213, 496.507385,
-556.089600, -55.924522, 498.256134,
-557.125793, -56.028824, 498.568329,
-558.182983, -56.208153, 498.806641,
-559.256592, -56.133862, 498.981354,
-560.335327, -56.116646, 499.118896,
-562.091736, -56.104050, 499.314911,
-574.530396, -56.559124, 500.553680,
-575.606262, -56.603722, 500.706024,
-576.649963, -56.813107, 500.963989,
-577.670288, -57.037365, 501.291138,
-578.679321, -57.266209, 501.647278,
-579.683105, -57.510010, 502.019379,
-581.321777, -57.800549, 502.643463,
-608.199463, -60.061394, 513.086548, -- turn around
-607.195618, -59.956524, 512.696411,
-579.141602, -57.367210, 501.788940,
-578.157959, -57.136345, 501.407318,
-577.150146, -56.915344, 501.086304,
-576.116089, -56.711021, 500.848358,
-575.049622, -56.572414, 500.676178,
-573.971497, -56.540531, 500.535004,
-572.891418, -56.511803, 500.410767,
-571.541260, -56.454227, 500.267334,
-559.917480, -56.117676, 499.110870,
-558.841248, -56.137356, 498.953400,
-557.782593, -56.166878, 498.714447,
-556.750061, -55.982758, 498.415985,
-555.608704, -55.807209, 498.053894,
-553.104614, -55.239231, 497.204651,
-547.725464, -54.925472, 495.326019,
-546.765625, -54.984024, 494.821899,
-546.022339, -55.011047, 494.032928,
-545.445923, -55.024132, 493.110931,
-544.951660, -55.061985, 492.142212,
-544.503357, -55.055382, 491.151031,
-544.083557, -55.041119, 490.147827,
-543.675354, -55.021049, 489.139801,
-540.065735, -56.014805, 479.933258,
-539.634155, -56.052246, 478.935516,
-539.166565, -56.161896, 477.960266,
-538.697327, -55.847233, 477.044403,
-538.208557, -55.557598, 476.136658,
-537.436646, -55.298710, 474.733032,
-533.392761, -55.013466, 467.513885,
-532.726868, -54.979912, 466.657013,
-531.930054, -54.948929, 465.917389,
-531.075134, -54.949390, 465.244354,
-530.197693, -54.950920, 464.600464,
-529.308838, -54.990524, 463.974792,
-525.172791, -55.543240, 461.159485,
-524.214478, -55.720425, 460.668243,
-523.196838, -55.850220, 460.304413,
-522.141357, -56.015007, 460.066986,
-521.068726, -56.020702, 459.886475,
-519.991577, -56.039570, 459.735687,
-518.911011, -56.055336, 459.609558,
-517.433777, -55.982838, 459.449738,
-513.966614, -55.460213, 459.099396,
-512.921997, -55.323360, 458.849701,
-512.001587, -55.181244, 458.291351,
-511.179230, -55.105251, 457.583893,
-510.412476, -55.032543, 456.816132,
-509.680267, -54.958725, 456.014191,
-508.602783, -54.942749, 454.788452,
-500.669189, -55.143158, 445.473999,
-500.128296, -55.247131, 444.541412,
-499.898651, -55.518276, 443.507935,
-499.821869, -55.910942, 442.468292,
-499.832764, -56.027439, 441.384308,
-499.881256, -56.021374, 440.297485,
-499.962463, -56.011227, 439.212982,
-500.072205, -56.031265, 438.133789,
-500.329163, -55.395157, 435.970062,
-502.441742, -50.690495, 419.476440,
-502.485474, -50.371307, 418.460999,
-502.368835, -50.054039, 417.447144,
-502.131531, -49.750740, 416.450317,
-501.775696, -49.393009, 415.406342,
-501.394318, -48.913757, 414.410278,
-500.999023, -48.445408, 413.431396,
-500.303253, -47.637516, 411.756561,
-499.980103, -47.454823, 410.747284,
-499.763947, -47.256901, 409.705627,
-499.603699, -47.051754, 408.654358,
-499.474274, -46.886150, 407.591583,
-499.360931, -46.714558, 406.528320,
-497.842590, -45.999271, 389.667542,
-497.735077, -46.047218, 388.312012,
-497.702972, -46.022728, 387.226166,
-497.717407, -45.968018, 386.140686,
-497.752014, -45.910450, 385.054596,
-498.532532, -45.704178, 369.587616,
-498.589294, -45.753151, 368.501129,
-499.547089, -46.040310, 350.040375,
-499.412354, -46.078503, 348.964417,
-499.099609, -46.221172, 347.926239,
-498.741913, -46.030338, 346.926208,
-498.351959, -45.860306, 345.923828,
-497.941467, -45.805256, 344.918884,
-497.518524, -45.751751, 343.918427,
-497.074768, -45.707314, 342.926636,
-496.434631, -45.690395, 342.056549,
-495.518555, -45.685642, 341.481903,
-494.478638, -45.677624, 341.169525,
-493.406281, -45.681431, 340.990509,
-492.333801, -46.148170, 340.858154,
-491.272858, -45.972626, 340.751801,
-490.196564, -45.903652, 340.655212,
-466.653748, -45.466057, 338.859863,
-465.575256, -45.615093, 338.803314,
-464.496521, -45.763508, 338.779785,
-463.410126, -45.832458, 338.774506,
-433.375122, -45.735828, 339.226624,
-403.243805, -46.015915, 339.704468,
};
-----------------------------------
-- onSpawn Action
-----------------------------------
function onSpawn(npc)
npc:initNpcAi();
npc:setPos(pathfind.first(path));
onPath(npc);
end;
-----------------------------------
-- onPath Action
-----------------------------------
function onPath(npc)
if (npc:atPoint(pathfind.get(path, 45))) then
local Gachemage = GetNPCByID(npc:getID() + 3);
Gachemage:showText(npc, PALCOMONDAU_REPORT);
-- small delay after path finish
npc:wait(8000);
end
pathfind.patrol(npc, path);
end;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, PALCOMONDAU_DIALOG);
--npc:wait(1500);
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 |
kidaa/FFXIOrgins | scripts/zones/Upper_Jeuno/npcs/Constance.lua | 4 | 1754 | -----------------------------------
-- Area: Upper Jeuno
-- NPC: Constance
-- Involved in Quests: Save the Clock Tower
-- @zone 244
-- @pos -48 0 4
-----------------------------------
package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Upper_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(555,1) == true and trade:getItemCount() == 1) then
a = player:getVar("saveTheClockTowerNPCz1"); -- NPC Part1
if(a == 0 or (a ~= 8 and a ~= 9 and a ~= 10 and a ~= 12 and a ~= 24 and a ~= 11 and a ~= 28 and a ~= 13 and
a ~= 26 and a ~= 14 and a ~= 25 and a ~= 15 and a ~= 27 and a ~= 29 and a ~= 30 and a ~= 31)) then
player:startEvent(0x00b4,10 - player:getVar("saveTheClockTowerVar")); -- "Save the Clock Tower" Quest
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x005a);
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 == 0x00b4) then
player:setVar("saveTheClockTowerVar",player:getVar("saveTheClockTowerVar") + 1);
player:setVar("saveTheClockTowerNPCz1",player:getVar("saveTheClockTowerNPCz1") + 8);
end
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Temenos/mobs/Orichalcum_Quadav.lua | 2 | 1618 | -----------------------------------
-- Area: Temenos
-- NPC: Orichalcum Quadav
-----------------------------------
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)
if (IsMobDead(16929017)==true and IsMobDead(16929018)==true and IsMobDead(16929019)==true and
IsMobDead(16929020)==true and IsMobDead(16929021)==true and IsMobDead(16929022)==true
)then
mob:setMod(MOD_SLASHRES,1400);
mob:setMod(MOD_PIERCERES,1400);
mob:setMod(MOD_IMPACTRES,1400);
mob:setMod(MOD_HTHRES,1400);
else
mob:setMod(MOD_SLASHRES,300);
mob:setMod(MOD_PIERCERES,300);
mob:setMod(MOD_IMPACTRES,300);
mob:setMod(MOD_HTHRES,300);
end
GetMobByID(16929005):updateEnmity(target);
GetMobByID(16929007):updateEnmity(target);
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
if(IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true)then
GetNPCByID(16928768+78):setPos(-280,-161,-440);
GetNPCByID(16928768+78):setStatus(STATUS_NORMAL);
GetNPCByID(16928768+473):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
SlySven/Mudlet | src/mudlet-lua/lua/GUIUtils.lua | 2 | 90896 | ----------------------------------------------------------------------------------
--- Mudlet GUI Utils
----------------------------------------------------------------------------------
--- The <i>gaugesTable table</i>. First we need to make this table which will be
--- used later to store important data in.
---
--- @class function
--- @name gaugesTable
gaugesTable = {}
--- The <i>color_table table</i> holds definition of color names. These are intended to be
-- used in conjunction with fg() and bg() colorizer functions.
-- Mudlet's original table - going back a few years - differs from the
-- "standard" which can be found at https://www.w3.org/TR/SVG11/types.html#ColorKeywords
-- Mudlet has additional colours not in the standard:
-- "light_goldenrod", "light_slate_blue", "navy_blue" and "violet_red"
-- Mudlet is missing some colours:
-- "aqua", "fuchsia", "dark_blue", "dark_cyan", "dark_gray"/"dark_grey",
-- "dark_magenta", "dark_red", "indigo", "light_green", "olive", "silver",
-- "teal", "violet_red"
-- Also Mudlet redefines:
-- "gray"/"grey", "green", "maroon" and "purple"
-- All of the above also implies the Camel Case equivalents; in summary:
-- Colour Mudlet Web Standard
-- aqua 0, 255, 255
-- fuchsia 255, 0, 255
-- dark_blue 0, 0, 139
-- dark_gray/dark_grey 169, 169, 169
-- dark_magenta 139, 0, 139
-- dark_red 139, 0, 0
-- gray/grey 190, 190, 190 128, 128, 128
-- green 0, 255, 0 0, 128, 0
-- indigo 75, 0, 130
-- light_goldrod 238, 221, 130
-- light_slate_blue 132, 112, 255
-- light_green 144, 238, 144
-- maroon 176, 48, 96 128, 0, 0
-- navy_blue 0, 0, 128
-- olive 128, 128, 0
-- purple 160, 32, 240 128, 0, 128
-- silver 192, 192, 192
-- teal 0, 128, 128
-- violet_red 208, 32, 240
-- @see showColors
-- @see bg
-- @see fg
-- @class function
-- @name color_table
color_table = color_table or {}
color_table["alice_blue"] = { 240, 248, 255 }
color_table["AliceBlue"] = { 240, 248, 255 }
color_table["antique_white"] = { 250, 235, 215 }
color_table["AntiqueWhite"] = { 250, 235, 215 }
color_table["aquamarine"] = { 127, 255, 212 }
color_table["azure"] = { 240, 255, 255 }
color_table["beige"] = { 245, 245, 220 }
color_table["bisque"] = { 255, 228, 196 }
color_table["black"] = { 0, 0, 0 }
color_table["blanched_almond"] = { 255, 235, 205 }
color_table["BlanchedAlmond"] = { 255, 235, 205 }
color_table["blue"] = { 0, 0, 255 }
color_table["blue_violet"] = { 138, 43, 226 }
color_table["BlueViolet"] = { 138, 43, 226 }
color_table["brown"] = { 165, 42, 42 }
color_table["burlywood"] = { 222, 184, 135 }
color_table["cadet_blue"] = { 95, 158, 160 }
color_table["CadetBlue"] = { 95, 158, 160 }
color_table["chartreuse"] = { 127, 255, 0 }
color_table["chocolate"] = { 210, 105, 30 }
color_table["coral"] = { 255, 127, 80 }
color_table["cornflower_blue"] = { 100, 149, 237 }
color_table["CornflowerBlue"] = { 100, 149, 237 }
color_table["cornsilk"] = { 255, 248, 220 }
color_table["cyan"] = { 0, 255, 255 }
color_table["dark_goldenrod"] = { 184, 134, 11 }
color_table["DarkGoldenrod"] = { 184, 134, 11 }
color_table["dark_green"] = { 0, 100, 0 }
color_table["DarkGreen"] = { 0, 100, 0 }
color_table["dark_khaki"] = { 189, 183, 107 }
color_table["DarkKhaki"] = { 189, 183, 107 }
color_table["dark_olive_green"] = { 85, 107, 47 }
color_table["DarkOliveGreen"] = { 85, 107, 47 }
color_table["dark_orange"] = { 255, 140, 0 }
color_table["DarkOrange"] = { 255, 140, 0 }
color_table["dark_orchid"] = { 153, 50, 204 }
color_table["DarkOrchid"] = { 153, 50, 204 }
color_table["dark_salmon"] = { 233, 150, 122 }
color_table["DarkSalmon"] = { 233, 150, 122 }
color_table["dark_slate_blue"] = { 72, 61, 139 }
color_table["dark_sea_green"] = { 143, 188, 143 }
color_table["DarkSeaGreen"] = { 143, 188, 143 }
color_table["DarkSlateBlue"] = { 72, 61, 139 }
color_table["dark_slate_gray"] = { 47, 79, 79 }
color_table["DarkSlateGray"] = { 47, 79, 79 }
color_table["dark_slate_grey"] = { 47, 79, 79 }
color_table["DarkSlateGrey"] = { 47, 79, 79 }
color_table["dark_turquoise"] = { 0, 206, 209 }
color_table["DarkTurquoise"] = { 0, 206, 209 }
color_table["dark_violet"] = { 148, 0, 211 }
color_table["DarkViolet"] = { 148, 0, 211 }
color_table["deep_pink"] = { 255, 20, 147 }
color_table["DeepPink"] = { 255, 20, 147 }
color_table["deep_sky_blue"] = { 0, 191, 255 }
color_table["DeepSkyBlue"] = { 0, 191, 255 }
color_table["dodger_blue"] = { 30, 144, 255 }
color_table["DodgerBlue"] = { 30, 144, 255 }
color_table["dim_gray"] = { 105, 105, 105 }
color_table["DimGray"] = { 105, 105, 105 }
color_table["dim_grey"] = { 105, 105, 105 }
color_table["DimGrey"] = { 105, 105, 105 }
color_table["firebrick"] = { 178, 34, 34 }
color_table["floral_white"] = { 255, 250, 240 }
color_table["FloralWhite"] = { 255, 250, 240 }
color_table["forest_green"] = { 34, 139, 34 }
color_table["ForestGreen"] = { 34, 139, 34 }
color_table["gainsboro"] = { 220, 220, 220 }
color_table["ghost_white"] = { 248, 248, 255 }
color_table["GhostWhite"] = { 248, 248, 255 }
color_table["gold"] = { 255, 215, 0 }
color_table["goldenrod"] = { 218, 165, 32 }
color_table["gray"] = { 190, 190, 190 }
color_table["grey"] = { 190, 190, 190 }
color_table["green"] = { 0, 255, 0 }
color_table["green_yellow"] = { 173, 255, 47 }
color_table["GreenYellow"] = { 173, 255, 47 }
color_table["honeydew"] = { 240, 255, 240 }
color_table["hot_pink"] = { 255, 105, 180 }
color_table["HotPink"] = { 255, 105, 180 }
color_table["indian_red"] = { 205, 92, 92 }
color_table["IndianRed"] = { 205, 92, 92 }
color_table["khaki"] = { 240, 230, 140 }
color_table["ivory"] = { 255, 255, 240 }
color_table["lavender"] = { 230, 230, 250 }
color_table["lavender_blush"] = { 255, 240, 245 }
color_table["LavenderBlush"] = { 255, 240, 245 }
color_table["lawn_green"] = { 124, 252, 0 }
color_table["LawnGreen"] = { 124, 252, 0 }
color_table["lemon_chiffon"] = { 255, 250, 205 }
color_table["LemonChiffon"] = { 255, 250, 205 }
color_table["light_blue"] = { 173, 216, 230 }
color_table["LightBlue"] = { 173, 216, 230 }
color_table["light_coral"] = { 240, 128, 128 }
color_table["LightCoral"] = { 240, 128, 128 }
color_table["light_cyan"] = { 224, 255, 255 }
color_table["LightCyan"] = { 224, 255, 255 }
color_table["light_goldenrod"] = { 238, 221, 130 }
color_table["LightGoldenrod"] = { 238, 221, 130 }
color_table["light_goldenrod_yellow"] = { 250, 250, 210 }
color_table["LightGoldenrodYellow"] = { 250, 250, 210 }
color_table["light_gray"] = { 211, 211, 211 }
color_table["LightGray"] = { 211, 211, 211 }
color_table["light_grey"] = { 211, 211, 211 }
color_table["LightGrey"] = { 211, 211, 211 }
color_table["light_pink"] = { 255, 182, 193 }
color_table["LightPink"] = { 255, 182, 193 }
color_table["light_salmon"] = { 255, 160, 122 }
color_table["LightSalmon"] = { 255, 160, 122 }
color_table["light_sea_green"] = { 32, 178, 170 }
color_table["LightSeaGreen"] = { 32, 178, 170 }
color_table["light_sky_blue"] = { 135, 206, 250 }
color_table["LightSkyBlue"] = { 135, 206, 250 }
color_table["light_slate_blue"] = { 132, 112, 255 }
color_table["LightSlateBlue"] = { 132, 112, 255 }
color_table["light_slate_gray"] = { 119, 136, 153 }
color_table["LightSlateGray"] = { 119, 136, 153 }
color_table["light_slate_grey"] = { 119, 136, 153 }
color_table["LightSlateGrey"] = { 119, 136, 153 }
color_table["light_steel_blue"] = { 176, 196, 222 }
color_table["LightSteelBlue"] = { 176, 196, 222 }
color_table["light_yellow"] = { 255, 255, 224 }
color_table["LightYellow"] = { 255, 255, 224 }
color_table["lime_green"] = { 50, 205, 50 }
color_table["LimeGreen"] = { 50, 205, 50 }
color_table["linen"] = { 250, 240, 230 }
color_table["magenta"] = { 255, 0, 255 }
color_table["maroon"] = { 176, 48, 96 }
color_table["medium_aquamarine"] = { 102, 205, 170 }
color_table["MediumAquamarine"] = { 102, 205, 170 }
color_table["medium_blue"] = { 0, 0, 205 }
color_table["MediumBlue"] = { 0, 0, 205 }
color_table["medium_orchid"] = { 186, 85, 211 }
color_table["MediumOrchid"] = { 186, 85, 211 }
color_table["medium_purple"] = { 147, 112, 219 }
color_table["MediumPurple"] = { 147, 112, 219 }
color_table["medium_sea_green"] = { 60, 179, 113 }
color_table["MediumSeaGreen"] = { 60, 179, 113 }
color_table["medium_slate_blue"] = { 123, 104, 238 }
color_table["MediumSlateBlue"] = { 123, 104, 238 }
color_table["medium_spring_green"] = { 0, 250, 154 }
color_table["MediumSpringGreen"] = { 0, 250, 154 }
color_table["medium_turquoise"] = { 72, 209, 204 }
color_table["MediumTurquoise"] = { 72, 209, 204 }
color_table["medium_violet_red"] = { 199, 21, 133 }
color_table["MediumVioletRed"] = { 199, 21, 133 }
color_table["midnight_blue"] = { 25, 25, 112 }
color_table["MidnightBlue"] = { 25, 25, 112 }
color_table["mint_cream"] = { 245, 255, 250 }
color_table["MintCream"] = { 245, 255, 250 }
color_table["misty_rose"] = { 255, 228, 225 }
color_table["MistyRose"] = { 255, 228, 225 }
color_table["moccasin"] = { 255, 228, 181 }
color_table["navajo_white"] = { 255, 222, 173 }
color_table["NavajoWhite"] = { 255, 222, 173 }
color_table["navy"] = { 0, 0, 128 }
color_table["navy_blue"] = { 0, 0, 128 }
color_table["NavyBlue"] = { 0, 0, 128 }
color_table["old_lace"] = { 253, 245, 230 }
color_table["OldLace"] = { 253, 245, 230 }
color_table["olive_drab"] = { 107, 142, 35 }
color_table["OliveDrab"] = { 107, 142, 35 }
color_table["orange"] = { 255, 165, 0 }
color_table["orange_red"] = { 255, 69, 0 }
color_table["OrangeRed"] = { 255, 69, 0 }
color_table["orchid"] = { 218, 112, 214 }
color_table["pale_goldenrod"] = { 238, 232, 170 }
color_table["PaleGoldenrod"] = { 238, 232, 170 }
color_table["pale_green"] = { 152, 251, 152 }
color_table["PaleGreen"] = { 152, 251, 152 }
color_table["pale_turquoise"] = { 175, 238, 238 }
color_table["PaleTurquoise"] = { 175, 238, 238 }
color_table["pale_violet_red"] = { 219, 112, 147 }
color_table["PaleVioletRed"] = { 219, 112, 147 }
color_table["papaya_whip"] = { 255, 239, 213 }
color_table["PapayaWhip"] = { 255, 239, 213 }
color_table["peach_puff"] = { 255, 218, 185 }
color_table["PeachPuff"] = { 255, 218, 185 }
color_table["peru"] = { 205, 133, 63 }
color_table["pink"] = { 255, 192, 203 }
color_table["plum"] = { 221, 160, 221 }
color_table["powder_blue"] = { 176, 224, 230 }
color_table["PowderBlue"] = { 176, 224, 230 }
color_table["purple"] = { 160, 32, 240 }
color_table["royal_blue"] = { 65, 105, 225 }
color_table["RoyalBlue"] = { 65, 105, 225 }
color_table["red"] = { 255, 0, 0 }
color_table["rosy_brown"] = { 188, 143, 143 }
color_table["RosyBrown"] = { 188, 143, 143 }
color_table["saddle_brown"] = { 139, 69, 19 }
color_table["SaddleBrown"] = { 139, 69, 19 }
color_table["salmon"] = { 250, 128, 114 }
color_table["sandy_brown"] = { 244, 164, 96 }
color_table["SandyBrown"] = { 244, 164, 96 }
color_table["sea_green"] = { 46, 139, 87 }
color_table["SeaGreen"] = { 46, 139, 87 }
color_table["seashell"] = { 255, 245, 238 }
color_table["sienna"] = { 160, 82, 45 }
color_table["sky_blue"] = { 135, 206, 235 }
color_table["SkyBlue"] = { 135, 206, 235 }
color_table["slate_blue"] = { 106, 90, 205 }
color_table["SlateBlue"] = { 106, 90, 205 }
color_table["slate_gray"] = { 112, 128, 144 }
color_table["SlateGray"] = { 112, 128, 144 }
color_table["slate_grey"] = { 112, 128, 144 }
color_table["SlateGrey"] = { 112, 128, 144 }
color_table["snow"] = { 255, 250, 250 }
color_table["steel_blue"] = { 70, 130, 180 }
color_table["SteelBlue"] = { 70, 130, 180 }
color_table["spring_green"] = { 0, 255, 127 }
color_table["SpringGreen"] = { 0, 255, 127 }
color_table["tan"] = { 210, 180, 140 }
color_table["thistle"] = { 216, 191, 216 }
color_table["tomato"] = { 255, 99, 71 }
color_table["transparent"] = { 255, 255, 255, 0}
color_table["turquoise"] = { 64, 224, 208 }
color_table["violet_red"] = { 208, 32, 144 }
color_table["VioletRed"] = { 208, 32, 144 }
color_table["violet"] = { 238, 130, 238 }
color_table["wheat"] = { 245, 222, 179 }
color_table["white"] = { 255, 255, 255 }
color_table["white_smoke"] = { 245, 245, 245 }
color_table["WhiteSmoke"] = { 245, 245, 245 }
color_table["yellow"] = { 255, 255, 0 }
color_table["yellow_green"] = { 154, 205, 50 }
color_table["YellowGreen"] = { 154, 205, 50 }
--- Move a custom gauge.
---
--- @usage This would move the health bar gauge to the location 1200, 400.
--- <pre>
--- moveGauge("healthBar", 1200, 400)
--- </pre>
---
--- @see createGauge
function moveGauge(gaugeName, x, y)
assert(gaugesTable[gaugeName], "moveGauge: no such gauge exists.")
assert(x and y, "moveGauge: need to have both X and Y dimensions.")
moveWindow(gaugeName .. "_back", x, y)
moveWindow(gaugeName .. "_text", x, y)
-- save new values in table
gaugesTable[gaugeName].x, gaugesTable[gaugeName].y = x, y
setGauge(gaugeName, gaugesTable[gaugeName].value, 1)
end
--- Hide a custom gauge.
---
--- @usage This should hide the given gauge.
--- <pre>
--- hideGauge("healthBar")
--- </pre>
---
--- @see createGauge, moveGauge, showGauge
function hideGauge(gaugeName)
assert(gaugesTable[gaugeName], "hideGauge: no such gauge exists.")
hideWindow(gaugeName .. "_back")
hideWindow(gaugeName .. "_front")
hideWindow(gaugeName .. "_text")
end
--- Show a custom gauge.
---
--- @usage This should show the given gauge.
--- <pre>
--- showGauge("healthBar")
--- </pre>
---
--- @see createGauge, moveGauge, hideGauge
function showGauge(gaugeName)
assert(gaugesTable[gaugeName], "showGauge: no such gauge exists.")
showWindow(gaugeName .. "_back")
showWindow(gaugeName .. "_front")
showWindow(gaugeName .. "_text")
end
--- @see createGauge
function setGaugeWindow(windowName, gaugeName, x, y, show)
windowName = windowName or "main"
x = x or 0
y = y or 0
show = show or true
assert(gaugesTable[gaugeName], "setGaugeWindow: no such gauge exists.")
setWindow(windowName, gaugeName .. "_back", x, y, show)
setWindow(windowName, gaugeName .. "_front", x, y, show)
setWindow(windowName, gaugeName .. "_text", x, y, show)
-- save new values in table
gaugesTable[gaugeName].x, gaugesTable[gaugeName].y = x, y
setGauge(gaugeName, gaugesTable[gaugeName].value, 1)
end
--- Set the text on a custom gauge.
---
--- @usage
--- <pre>
--- setGaugeText("healthBar", "HP: 100%", 40, 40, 40)
--- </pre>
--- @usage
--- <pre>
--- setGaugeText("healthBar", "HP: 100%", "red")
--- </pre>
---
--- @param gaugeName
--- @param gaugeText An empty gaugeText will clear the text entirely.
--- @param color1 Colors are optional and will default to 0,0,0(black) if not passed as args.
--- @param color2
--- @param color3
---
--- @see createGauge
function setGaugeText(gaugeName, gaugeText, r, g, b)
assert(gaugesTable[gaugeName], "setGaugeText: no such gauge exists.")
if r ~= nil then
if g == nil then
r, g, b = getRGB(r)
end
else
r, g, b = 0, 0, 0
end
gaugeText = gaugeText or ""
local echoString = [[<font color="#]] .. RGB2Hex(r, g, b) .. [[">]] .. gaugeText .. [[</font>]]
echo(gaugeName .. "_text", echoString)
-- save new values in table
gaugesTable[gaugeName].text = echoString
end
--- Set gauge to no longer intercept mouse events
--- @param gaugeName
function enableGaugeClickthrough(gaugeName)
assert(gaugesTable[gaugeName], "enableGaugeClickthrough: no such gauge exists.")
enableClickthrough(gaugeName .. "_back")
enableClickthrough(gaugeName .. "_front")
enableClickthrough(gaugeName .. "_text")
end
--- Set gauge to once again intercept mouse events
--- @param gaugeName
function disableGaugeClickthrough(gaugeName)
assert(gaugesTable[gaugeName], "disableGaugeClickthrough: no such gauge exists.")
disableClickthrough(gaugeName .. "_back")
disableClickthrough(gaugeName .. "_front")
disableClickthrough(gaugeName .. "_text")
end
--- Set gauge to have a tooltip
--- @param gaugeName
--- @param text the tooltip text
--- @param duration tooltip duration
function setGaugeToolTip(gaugeName, text, duration)
duration = duration or 0
assert(gaugesTable[gaugeName], "setGaugeToolTip: no such gauge exists.")
setLabelToolTip(gaugeName .. "_text", text, duration)
end
--- Reset gauge tooltip
--- @param gaugeName
function resetGaugeToolTip(gaugeName)
assert(gaugesTable[gaugeName], "resetGaugeToolTip: no such gauge exists.")
resetLabelToolTip(gaugeName .. "_text")
end
--- Pads a hex number to ensure a minimum of 2 digits.
---
--- @usage Following command will returns "F0".
--- <pre>
--- PadHexNum("F")
--- </pre>
function PadHexNum(incString)
local l_Return = incString
if tonumber(incString, 16) < 16 then
if tonumber(incString, 16) < 10 then
l_Return = "0" .. l_Return
elseif tonumber(incString, 16) > 10 then
l_Return = l_Return .. "0"
end
end
return l_Return
end
--- Converts an RGB value into an HTML compliant(label usable) HEX number.
--- This function is colorNames aware and can take any defined global color as its first argument.
---
--- @usage Both following commands will returns "FFFFFF".
--- <pre>
--- RGB2Hex(255,255,255)
--- RGB2Hex("white")
--- </pre>
---
--- @see showColor
function RGB2Hex(red, green, blue)
local l_Red, l_Green, l_Blue = 0, 0, 0
if green == nil then
-- Not an RGB but a "color" instead!
l_Red, l_Green, l_Blue = getRGB(red)
else -- Nope, true color here
l_Red, l_Green, l_Blue = red, green, blue
end
return PadHexNum(string.format("%X", l_Red)) ..
PadHexNum(string.format("%X", l_Green)) ..
PadHexNum(string.format("%X", l_Blue))
end
--- Get RGB component from color name.
---
--- @usage Following will display "0.255.0" on your screen.
--- <pre>
--- local red, green, blue = getRGB("green")
--- echo(red .. "." .. green .. "." .. blue )
--- </pre>
function getRGB(colorName)
local red = color_table[colorName][1]
local green = color_table[colorName][2]
local blue = color_table[colorName][3]
return red, green, blue
end
--- Make your very own customized gauge with this function.
---
--- @usage This would make a gauge at that's 300px width, 20px in height, located at Xpos and Ypos and is green.
--- <pre>
--- createGauge("healthBar", 300, 20, 30, 300, nil, 0, 255, 0)
--- </pre>
--- @usage The second example is using the same names you'd use for something like fg() or bg().
--- <pre>
--- createGauge("healthBar", 300, 20, 30, 300, nil, "green")
--- </pre>
--- @usage Finally we'll add some text to our gauge.
--- <pre>
--- createGauge("healthBar", 300, 20, 30, 300, "Now with some text", "green")
--- </pre>
--- @usage You can add an orientation argument as well now:
--- <pre>
--- createGauge("healthBar", 300, 20, 30, 300, "Now with some text", "green", "horizontal, vertical, goofy, or batty")
--- </pre>
function createGauge(windowname, gaugeName, width, height, x, y, gaugeText, r, g, b, orientation)
--Make windowname optional
if type(gaugeName) == "number" then
orientation = b
b = g
g = r
r = gaugeText
gaugeText = y
y = x
x = height
height = width
width = gaugeName
gaugeName = windowname
windowname= nil
end
windowname = windowname or "main"
gaugeText = gaugeText or ""
if type(r) == "string" then
orientation = g
r, g, b = getRGB(r)
elseif r == nil then
orientation = orientation or g
-- default colors
r, g, b = 128, 128, 128
end
orientation = orientation or "horizontal"
assert(table.contains({ "horizontal", "vertical", "goofy", "batty" }, orientation), "createGauge: orientation must be horizontal, vertical, goofy, or batty")
local tbl = { width = width, height = height, x = x, y = y, text = gaugeText, r = r, g = g, b = b, orientation = orientation, value = 1 }
createLabel(windowname, gaugeName .. "_back", 0, 0, 0, 0, 1)
setBackgroundColor(gaugeName .. "_back", r, g, b, 100)
createLabel(windowname, gaugeName .. "_front", 0, 0, 0, 0, 1)
setBackgroundColor(gaugeName .. "_front", r, g, b, 255)
createLabel(windowname, gaugeName .. "_text", 0, 0, 0, 0, 1)
setBackgroundColor(gaugeName .. "_text", 0, 0, 0, 0)
-- save new values in table
gaugesTable[gaugeName] = tbl
resizeGauge(gaugeName, tbl.width, tbl.height)
moveGauge(gaugeName, tbl.x, tbl.y)
setGaugeText(gaugeName, gaugeText, "black")
showGauge(gaugeName)
end
--- Use this function when you want to change the gauges look according to your values.
--- Typical usage would be in a prompt with your current health or whatever value, and throw
--- in some variables instead of the numbers.
---
--- @usage In that example, we'd change the looks of the gauge named healthBar and make it fill
--- to half of its capacity. The height is always remembered.
--- <pre>
--- setGauge("healthBar", 200, 400)
--- </pre>
--- @usage Change the text on your gauge.
--- <pre>
--- setGauge("healthBar", 200, 400, "some text")
--- </pre>
function setGauge(gaugeName, currentValue, maxValue, gaugeText)
assert(gaugesTable[gaugeName], "setGauge: no such gauge exists.")
assert(currentValue and maxValue, "setGauge: need to have both current and max values.")
local value = currentValue / maxValue
-- save new values in table
gaugesTable[gaugeName].value = value
local info = gaugesTable[gaugeName]
local x, y, w, h = info.x, info.y, info.width, info.height
if info.orientation == "horizontal" then
resizeWindow(gaugeName .. "_front", w * value, h)
moveWindow(gaugeName .. "_front", x, y)
elseif info.orientation == "vertical" then
resizeWindow(gaugeName .. "_front", w, h * value)
moveWindow(gaugeName .. "_front", x, y + h * (1 - value))
elseif info.orientation == "goofy" then
resizeWindow(gaugeName .. "_front", w * value, h)
moveWindow(gaugeName .. "_front", x + w * (1 - value), y)
elseif info.orientation == "batty" then
resizeWindow(gaugeName .. "_front", w, h * value)
moveWindow(gaugeName .. "_front", x, y)
end
if gaugeText then
setGaugeText(gaugeName, gaugeText)
end
end
--- Make a new console window with ease. The default background is black and text color white.
--- If you wish to change the color you can easily do this when updating your text or manually somewhere, using
--- setFgColor() and setBackgroundColor().
---
--- @usage This will create a miniconsole window that has a font size of 8pt, will display 80 characters in width,
--- hold a maximum of 20 lines and be place at 200x400 of your Mudlet window.
--- <pre>
--- createConsole("myConsoleWindow", 8, 80, 20, 200, 400)
--- </pre>
function createConsole(windowname, consoleName, fontSize, charsPerLine, numberOfLines, Xpos, Ypos)
if Ypos == nil then
Ypos = Xpos
Xpos = numberOfLines
numberOfLines = charsPerLine
charsPerLine = fontSize
fontSize = consoleName
consoleName = windowname
windowname = "main"
end
createMiniConsole(windowname, consoleName, 0, 0, 1, 1)
setMiniConsoleFontSize(consoleName, fontSize)
local x, y = calcFontSize( fontSize )
resizeWindow(consoleName, x * charsPerLine, y * numberOfLines)
setWindowWrap(consoleName, charsPerLine)
moveWindow(consoleName, Xpos, Ypos)
setBackgroundColor(consoleName, 0, 0, 0, 0)
setFgColor(consoleName, 255, 255, 255)
end
--- Function will gag the whole line. <b>Use deleteLine() instead.</b>
function gagLine()
deleteLine()
end
--- Replaces all occurrences of what in the current line with <i>with</i>.
---
--- @usage This will replace all occurrences of John with the word Doe.
--- <pre>
--- replaceAll("John", "Doe")
---
--- -- also handles recursive matches:
--- replaceAll("you", "you and me")
--- </pre>
function replaceAll(word, what, keepColor)
local getCurrentLine, selectSection, replace = getCurrentLine, selectSection, replace
local startp, endp = 1, 1
while true do
startp, endp = getCurrentLine():find(word, endp)
if not startp then
break
end
selectSection(startp - 1, endp - startp + 1)
replace(what, keepColor)
endp = endp + (#what - #word) + 1 -- recalculate the new word ending to start search from there
end
end
--- Replace an entire line with a string you'd like.
---
--- @see deleteLine
function replaceLine(window, text)
if not text then
selectCurrentLine()
text = window
else
selectCurrentLine(window)
end
replace("")
insertText(text)
end
--- Default resizeEvent handler function. Overwrite this function to make a custom event handler
--- if the main window is being resized. <br/><br/>
---
--- The standard implementation of this function does nothing. However, this function gets called whenever
--- the main window is being manually resized. You can overwrite this function in your own scripts to handle window
--- resize events yourself and e.g. adjust the screen position and size of your mini console windows, labels or
--- other relevant GUI elements in your scripts that depend on the size of the main Window. To override this
--- function you can simply put a function with the same name in one of your scripts thus overwriting the
--- original empty implementation of this function.
--- <pre>
--- function handleWindowResizeEvent()
--- -- determine the size of your screen
--- WindowWidth=0;
--- WindowHeight=0;
--- WindowWidth, WindowHeight = getMainWindowSize();
--- -- move mini console "sys" to the far right side of the screen whenever the screen gets resized
--- moveWindow("sys",WindowWidth-300,0)
--- end
--- </pre>
function handleWindowResizeEvent()
end
--- Sets current background color to a named color.
---
--- @usage Set background color to magenta.
--- <pre>
--- bg("magenta")
---
--- bg("my miniconsole", "blue")
--- </pre>
---
--- @see fg
--- @see showColors
function bg(console, colorName)
local colorName = colorName or console
if colorName == nil then
error("bg: bad argument #1 type (color name as string expected, got nil)!")
end
if not color_table[colorName] then
error(string.format("bg: '%s' color doesn't exist - see showColors()", colorName))
end
local alpha = color_table[colorName][4] or 255
if console == colorName or console == "main" then
setBgColor(color_table[colorName][1], color_table[colorName][2], color_table[colorName][3], alpha)
else
setBgColor(console, color_table[colorName][1], color_table[colorName][2], color_table[colorName][3], alpha)
end
end
--- Sets current foreground color to a named color.
---
--- @usage Set foreground color to black.
--- <pre>
--- fg("black")
--- </pre>
---
--- @see bg
--- @see showColors
function fg(console, colorName)
local colorName = colorName or console
if colorName == nil then
error("fg: bad argument #1 type (color name as string expected, got nil)!")
end
if not color_table[colorName] then
error(string.format("fg: '%s' color doesn't exist - see showColors()", colorName))
end
if console == colorName or console == "main" then
setFgColor(color_table[colorName][1], color_table[colorName][2], color_table[colorName][3])
else
setFgColor(console, color_table[colorName][1], color_table[colorName][2], color_table[colorName][3])
end
end
--- Replaces the given wildcard (as a number) with the given text.
---
--- @usage Replace "goodbye" with "hello" on a trigger of "^You wave (goodbye)\.$"
--- <pre>
--- replaceWildcard(2, "hello")
--- </pre>
--- Is equivalent to doing:
--- <pre>
--- selectString(matches[2], 1)
--- replace("hello")
--- </pre>
function replaceWildcard(what, replacement, keepColor)
if replacement == nil or what == nil then
return
end
selectCaptureGroup(what)
replace(replacement, keepColor)
end
-- internal sorting function, sorts first by hue, then luminosity, then value
local sortColorsByHue = function(lhs,rhs)
local lh,ll,lv = unpack(lhs.sort)
local rh,rl,rv = unpack(rhs.sort)
if lh < rh then
return true
elseif lh > rh then
return false
elseif ll < rl then
return true
elseif ll > rl then
return false
else
return lv < rv
end
end
-- internal sorting function, removes _ from snake_case and compares to camelCase
local sortColorsByName = function(a,b)
local aname = string.gsub(string.lower(a.name), "_", "")
local bname = string.gsub(string.lower(b.name), "_", "")
return aname < bname
end
-- internal function, converts rgb to hsv
-- found at https://github.com/EmmanuelOga/columns/blob/master/utils/color.lua#L89
local rgbToHsv = function(r, g, b)
r, g, b = r / 255, g / 255, b / 255
local max, min = math.max(r, g, b), math.min(r, g, b)
local h, s, v
v = max
local d = max - min
if max == 0 then
s = 0
else
s = d / max
end
if max == min then
h = 0 -- achromatic
else
if max == r then
h = (g - b) / d
if g < b then h = h + 6 end
elseif max == g then
h = (b - r) / d + 2
elseif max == b then
h = (r - g) / d + 4
end
h = h / 6
end
return h, s, v
end
-- internal stepping function, removes some of the noise for a more pleasing sort
-- cribbed from the python on https://www.alanzucconi.com/2015/09/30/colour-sorting/
local step = function(r,g,b)
local lum = math.sqrt( .241 * r + .691 * g + .068 * b )
local reps = 8
local h, s, v = rgbToHsv(r,g,b)
local h2 = math.floor(h * reps)
local v2 = math.floor(v * reps)
if h2 % 2 == 1 then
v2 = reps - v2
lum = reps - lum
end
return h2, lum, v2
end
local function calc_luminosity(r,g,b)
r = r < 11 and r / (255 * 12.92) or ((0.055 + r / 255) / 1.055) ^ 2.4
g = g < 11 and g / (255 * 12.92) or ((0.055 + g / 255) / 1.055) ^ 2.4
b = b < 11 and b / (255 * 12.92) or ((0.055 + b / 255) / 1.055) ^ 2.4
return (0.2126 * r) + (0.7152 * g) + (0.0722 * b)
end
--- Prints out a formatted list of all available named colors (EXCEPT FOR
--- the 256 colors with names of form "ansi_###" where ### is 000 to 255),
--- optional args specifies:
--- * (number) number of columns to print in, defaults to 4;
--- * (string) substring required to match to include in output, defaults to
--- showing all if not supplied;
--- * (boolean) whether to sort the output, defaults to false.
--- @usage Print list in 4 columns by default.
--- <pre>
--- showColors()
--- </pre>
--- @usage Print list in 2 columns.
--- <pre>
--- showColors(2)
--- </pre>
---
--- @see color_table
function showColors(...)
local cols, search, sort = 4, "", false
for _, val in ipairs(arg) do
if type(val) == "string" then
search = val:lower()
elseif type(val) == "number" then
cols = val
elseif type(val) == "boolean" then
sort = val
end
end
local colors = {}
for k, v in pairs(color_table) do
local color = {}
color.rgb = v
color.name = k
color.sort = {step(unpack(v))}
if not string.find(k, "ansi_%d%d%d") then
table.insert(colors,color)
end
end
if sort then
table.sort(colors, sortColorsByName)
else
table.sort(colors,sortColorsByHue)
end
local i = 1
for _, k in ipairs(colors) do
if k.name:lower():find(search) then
local v = k.rgb
local fgc = "white"
if calc_luminosity(v[1],v[2],v[3]) > 0.5 then
fgc = "black"
end
cechoLink(string.format('<%s:%s> %-23s<reset> ',fgc,k.name,k.name), [[appendCmdLine("]] .. k.name .. [[")]], table.concat(v, ", "), true)
if i == cols then
echo("\n")
i = 1
else
i = i + 1
end
end
end
if i ~= 1 then echo("\n") end
end
--- Prints out a sorted, formatted list of the 256 colors with names of form
--- "ansi_###" where ### is 000 to 255), optional arg specifies:
--- * (number) number of columns to print in, defaults to 4;
--- @usage Print list in 4 columns by default.
--- <pre>
--- showAnsiColors()
--- </pre>
--- @usage Print list in 2 columns.
--- <pre>
--- showAnsiColors(2)
--- </pre>
---
--- @see color_table
function showAnsiColors(...)
local cols = 8
for _, val in ipairs(arg) do
if type(val) == "number" then
cols = val
end
end
local colors = {}
for k, v in pairs(color_table) do
-- Only use the ansi_### 256 colors entries
if string.find(k, "ansi_%d%d%d") then
table.insert(colors,k)
end
end
table.sort(colors)
local i = 1
for _, k in ipairs(colors) do
local v = color_table[k]
local fgc = "white"
if calc_luminosity(v[1],v[2],v[3]) > 0.5 then
fgc = "black"
end
cechoLink(string.format('<%s:%s> %8s <reset> ',fgc,k,k), [[printCmdLine("]] .. k .. [[")]], table.concat(v, ", "), true)
if i == cols then
echo("\n")
i = 1
else
i = i + 1
end
end
if i ~= 1 then echo("\n") end
end
--- <b><u>TODO</u></b> resizeGauge(gaugeName, width, height)
function resizeGauge(gaugeName, width, height)
assert(gaugesTable[gaugeName], "resizeGauge: no such gauge exists.")
assert(width and height, "resizeGauge: need to have both width and height.")
resizeWindow(gaugeName .. "_back", width, height)
resizeWindow(gaugeName .. "_text", width, height)
-- save new values in table
gaugesTable[gaugeName].width, gaugesTable[gaugeName].height = width, height
setGauge(gaugeName, gaugesTable[gaugeName].value, 1)
end
--- <b><u>TODO</u></b> setGaugeStyleSheet(gaugeName, css, cssback)
function setGaugeStyleSheet(gaugeName, css, cssback, csstext)
if not setLabelStyleSheet then
return
end -- mudlet 1.0.5 and lower compatibility
assert(gaugesTable[gaugeName], "setGaugeStyleSheet: no such gauge exists.")
setLabelStyleSheet(gaugeName .. "_back", cssback or css)
setLabelStyleSheet(gaugeName .. "_front", css)
setLabelStyleSheet(gaugeName .. "_text", csstext or "")
end
-- https://wiki.mudlet.org/w/Manual:Lua_Functions#getHTMLformat
-- used by xEcho for creating formatting span tags for labels
-- fmt is a table of format options as returned by getTextFormat
function getHTMLformat(fmt)
-- next two lines effectively invert the colors if fmt.reverse is true
local type = type
local sfmt = string.format
local fore = fmt.foreground
local back = fmt.background
if fmt.reverse then
if type(back) ~= "table" then
if back:find("Q.-Gradient") then
-- we can't gradient the foreground, so we'll make the background the foreground, and the foreground the inverse of that
if type(fore) == "table" then
back = table.deepcopy(fore)
else
local r,g,b = fore:match("rgb%((%d+),%s*(%d+),%s*(%d+))")
if b then
back = { r, g, b, 255 }
else
local hexstring = fore:match("(#......)")
if hexstring then
r,g,b = Geyser.Color.parse(hexstring)
else
back = { 255, 255, 255, 255 } -- can't parse the foreground, default to black on white
end
end
end
for index,value in ipairs(back) do
fore[index] = 255 - value
end
elseif back:find("rgba") then
local r,g,b = back:match("rgba%((%d+),%s*(%d+),%s*(%d+),%s*%d+%)")
fore = { r, g, b }
back = fmt.foreground
else
-- back should work as-is as a foreground
fore = fmt.background
back = fmt.foreground
end
else
fore = fmt.background
back = fmt.foreground
end
end
local color,background
if type(fore) == "table" then
color = sfmt("color: rgb(%d, %d, %d);", unpack(fore))
else
color = sfmt("color: %s;", fore)
end
if type(back) == "table" then
back[4] = back[4] or 255 -- if alpha isn't specified, assume 255
background = sfmt("background-color: rgba(%d, %d, %d, %d);", unpack(back))
else
background = sfmt("background-color: %s;", back)
end
local bold = fmt.bold and " font-weight: bold;" or " font-weight: normal;"
local italic = fmt.italic and " font-style: italic;" or " font-style: normal;"
local textDecoration
if not (fmt.underline or fmt.overline or fmt.strikeout) then
textDecoration = " text-decoration: none;"
else
textDecoration = sfmt(" text-decoration:%s%s%s;", fmt.overline and " overline" or "", fmt.underline and " underline" or "", fmt.strikeout and " line-through" or "")
end
local result = sfmt([[<span style="%s%s%s%s%s">]], color, background, bold, italic, textDecoration)
return result
end
-- https://wiki.mudlet.org/w/Manual:Lua_Functions#getLabelFormat
-- used by xEcho for getting the default format for a label, taking into account
-- the background color setting and stylesheet
function getLabelFormat(win)
local r,g,b = 192, 192, 192
local reset = {
foreground = { r, g, b },
background = "rgba(0, 0, 0, 0)",
bold = false,
italic = false,
overline = false,
reverse = false,
strikeout = false,
underline = false,
}
local stylesheet = getLabelStyleSheet(win)
if stylesheet ~= "" then
if stylesheet:find(";") then
local styleTable = {}
stylesheet = stylesheet:gsub("[\r\n]", "")
for _,element in ipairs(stylesheet:split(";")) do
element = element:trim()
local attr, val = element:match("^(.-):(.+)$")
if attr and val then
styleTable[attr:trim()] = val:trim()
end
end
if styleTable.color then
reset.foreground = styleTable.color
end
if styleTable["text-decoration"] then
local td = styleTable["text-decoration"]
if td:match("underline") then
reset.underline = true
end
if td:match("overline") then
reset.overline = true
end
if td:match("line%-through") then
reset.strikeout = true
end
end
if styleTable.font then
reset.bold = styleTable.font:match("bold") and true or false
reset.italic = styleTable.font:match("italic") and true or false
end
if styleTable["font-weight"] and styleTable["font-weight"]:match("bold") then
reset.bold = true
end
if styleTable["font-style"] and styleTable["font-style"]:match("italic") then
reset.italic = true
end
end
end
return reset
end
if rex then
_Echos = {
Patterns = {
Hex = {
[[(\x5c?(?:#|\|c)?(?:[0-9a-fA-F]{6}|(?:#,|\|c,)[0-9a-fA-F]{6,8})(?:,[0-9a-fA-F]{6,8})?)|(?:\||#)(\/?[biruso])]],
rex.new [[(?:#|\|c)(?:([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2}))?(?:,([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})([0-9a-fA-F]{2})?)?]],
},
Decimal = {
[[(<[0-9,:]+>)|<(/?[biruso])>]],
rex.new [[<(?:([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}))?(?::(?=>))?(?::([0-9]{1,3}),([0-9]{1,3}),([0-9]{1,3}),?([0-9]{1,3})?)?>]],
},
Color = {
[[(</?[a-zA-Z0-9_,:]+>)]],
rex.new [[<([a-zA-Z0-9_]+)?(?:[:,](?=>))?(?:[:,]([a-zA-Z0-9_]+))?>]],
},
Ansi = {
[[(<[0-9,:]+>)]],
rex.new [[<([0-9]{1,2})?(?::([0-9]{1,2}))?>]],
},
},
Process = function(str, style)
local t = {}
local tonumber, _Echos, color_table = tonumber, _Echos, color_table
-- s: A subject section (can be an empty string)
-- c: colour code
-- r: reset code
for s, c, r in rex.split(str, _Echos.Patterns[style][1]) do
if c and (c:byte(1) == 92) then
c = c:sub(2)
if s then
s = s .. c else s = c
end
c = nil
end
if s then
t[#t + 1] = s
end
if r == 'r' then
t[#t + 1] = "\27reset"
elseif r == "b" then
t[#t + 1] = "\27bold"
elseif r == "/b" then
t[#t + 1] = "\27boldoff"
elseif r == "i" then
t[#t + 1] = "\27italics"
elseif r == "/i" then
t[#t + 1] = "\27italicsoff"
elseif r == "u" then
t[#t + 1] = "\27underline"
elseif r == "/u" then
t[#t + 1] = "\27underlineoff"
elseif r == "s" then
t[#t + 1] = "\27strikethrough"
elseif r == "/s" then
t[#t + 1] = "\27strikethroughoff"
elseif r == "o" then
t[#t + 1] = "\27overline"
elseif r == "/o" then
t[#t + 1] = "\27overlineoff"
end
if c then
if style == 'Hex' or style == 'Decimal' then
local fr, fg, fb, br, bg, bb, ba = _Echos.Patterns[style][2]:match(c)
local color = {}
if style == 'Hex' then
-- hex has alpha value in front
if ba then
local temp = ba
ba = br
br = bg
bg = bb
bb = temp
else
ba = "ff"
end
if fr and fg and fb then
fr, fg, fb = tonumber(fr, 16), tonumber(fg, 16), tonumber(fb, 16)
end
if br and bg and bb and ba then
ba, br, bg, bb = tonumber(ba, 16), tonumber(br, 16), tonumber(bg, 16), tonumber(bb, 16)
end
end
if fr and fg and fb then
color.fg = { fr, fg, fb }
end
ba = ba or 255
if br and bg and bb and ba then
color.bg = { br, bg, bb, ba }
end
-- if the colour failed to match anything, then what we captured in <> wasn't a colour -
-- pass it into the text stream then
t[#t + 1] = ((fr or br) and color or c)
elseif style == 'Color' then
if c == "<reset>" or c == "<r>" then
t[#t + 1] = "\27reset"
elseif c == "<b>" then
t[#t + 1] = "\27bold"
elseif c == "</b>" then
t[#t + 1] = "\27boldoff"
elseif c == "<i>" then
t[#t + 1] = "\27italics"
elseif c == "</i>" then
t[#t + 1] = "\27italicsoff"
elseif c == "<u>" then
t[#t + 1] = "\27underline"
elseif c == "</u>" then
t[#t + 1] = "\27underlineoff"
elseif c == "<s>" then
t[#t + 1] = "\27strikethrough"
elseif c == "</s>" then
t[#t + 1] = "\27strikethroughoff"
elseif c == "<o>" then
t[#t + 1] = "\27overline"
elseif c == "</o>" then
t[#t + 1] = "\27overlineoff"
else
local fcolor, bcolor = _Echos.Patterns[style][2]:match(c)
local color = {}
if fcolor and color_table[fcolor] then
color.fg = color_table[fcolor]
end
if bcolor and color_table[bcolor] then
color.bg = color_table[bcolor]
end
if color.fg or color.bg then
t[#t + 1] = color
else
t[#t + 1] = c
end
end
end
end
end
return t
end,
}
--- Generic color echo and insert function (allowing hecho, decho, cecho, hinsertText, dinsertText and cinsertText).
---
--- @param style Hex, Decimal or Color
--- @param insert boolean flag to determine echo/insert behaviour
--- @param win windowName optional
--- @param str text with embedded color information
---
--- @see cecho
--- @see decho
--- @see hecho
--- @see cinsertText
--- @see dinsertText
--- @see hinsertText
function xEcho(style, func, ...)
local win, str, cmd, hint, fmt
local out
local args = { ... }
local n = #args
assert(type(args[1]) == 'string', style:sub(1,1):lower() .. func .. ': bad argument #1, string expected, got '..type(args[1])..'!)')
if string.find(func, "Link") then
if n < 3 then
error 'Insufficient arguments, usage: ([window, ] string, command, hint)'
elseif n == 3 then
str, cmd, hint = ...
elseif n == 4 and type(args[4]) == 'boolean' then
str, cmd, hint, fmt = ...
elseif n >= 4 and type(args[4]) == 'string' then
win, str, cmd, hint, fmt = ...
else
error 'Improper arguments, usage: ([window, ] string, command, hint)'
end
elseif string.find(func, "Popup") then
if n < 3 then
error 'Insufficient arguments, usage: ([window, ] string, {commands}, {hints})'
elseif n == 3 then
str, cmd, hint = ...
elseif n == 4 and type(args[4]) == 'boolean' then
str, cmd, hint, fmt = ...
elseif n >= 4 and type(args[4]) == 'table' then
win, str, cmd, hint, fmt = ...
else
error 'Improper arguments, usage: ([window, ] string, {commands}, {hints})'
end
else
if args[1] and args[2] and args[1] ~= "main" then
win, str = args[1], args[2]
elseif args[1] and args[2] and args[1] == "main" then
str = args[2]
else
str = args[1]
end
end
win = win or "main"
out = function(...)
_G[func](...)
end
if windowType(win) == "label" and win ~= "main" then
str = str:gsub("\n", "<br>")
local t = _Echos.Process(str, style)
if func ~= "echo" then
return nil, "you cannot use echoLink, echoPopup, or insertText with Labels"
end
local result = ""
local reset = getLabelFormat(win)
local format = table.deepcopy(reset)
if format.bold or format.italic or format.overline or format.strikeout or format.underline then
result = getHTMLformat(format)
end
for _,v in ipairs(t) do
local formatChanged = false
if type(v) == "table" then
if v.fg then
format.foreground = {v.fg[1], v.fg[2], v.fg[3]}
formatChanged = true
end
if v.bg then
format.background = {v.bg[1], v.bg[2], v.bg[3]}
formatChanged = true
end
elseif v == "\27bold" then
format.bold = true
formatChanged = true
elseif v == "\27boldoff" then
format.bold = false
formatChanged = true
elseif v == "\27italics" then
format.italic = true
formatChanged = true
elseif v == "\27italicsoff" then
format.italic = false
formatChanged = true
elseif v == "\27underline" then
format.underline = true
formatChanged = true
elseif v == "\27underlineoff" then
format.underline = false
formatChanged = true
elseif v == "\27strikethrough" then
format.strikeout = true
formatChanged = true
elseif v == "\27strikethroughoff" then
format.strikeout = false
formatChanged = true
elseif v == "\27overline" then
format.overline = true
formatChanged = true
elseif v == "\27overlineoff" then
format.overline = false
formatChanged = true
elseif v == "\27reset" then
format = table.deepcopy(reset)
formatChanged = true
end
v = formatChanged and getHTMLformat(format) or v
result = result .. v
end
echo(win, result)
else
local t = _Echos.Process(str, style)
deselect(win)
resetFormat(win)
for _, v in ipairs(t) do
if type(v) == 'table' then
if v.fg then
local fr, fg, fb = unpack(v.fg)
setFgColor(win, fr, fg, fb)
end
if v.bg then
local br, bg, bb, ba = unpack(v.bg)
ba = ba or 255
setBgColor(win, br, bg, bb, ba)
end
elseif v == "\27bold" then
setBold(win, true)
elseif v == "\27boldoff" then
setBold(win, false)
elseif v == "\27italics" then
setItalics(win, true)
elseif v == "\27italicsoff" then
setItalics(win, false)
elseif v == "\27underline" then
setUnderline(win, true)
elseif v == "\27underlineoff" then
setUnderline(win, false)
elseif v == "\27strikethrough" then
setStrikeOut(win, true)
elseif v == "\27strikethroughoff" then
setStrikeOut(win, false)
elseif v == "\27overline" then
setOverline(win, true)
elseif v == "\27overlineoff" then
setOverline(win, false)
elseif v == "\27reset" then
resetFormat(win)
else
if func == 'echo' or func == 'insertText' then
out(win, v)
if func == 'insertText' then
moveCursor(win, getColumnNumber(win) + string.len(v), getLineNumber(win))
end
else
-- if fmt then setUnderline(win, true) end -- not sure if underline is necessary unless asked for
out(win, v, cmd, hint, (fmt == true and true or false))
end
end
end
resetFormat(win)
end
end
--- Echo string with embedded hex color information. <br/><br/>
---
--- Color changes can be made within the string using the format |cFRFGFB,BRBGBB where FR is the foreground red value,
--- FG is the foreground green value, FB is the foreground blue value, BR is the background red value, etc., BRBGBB is optional.
--- |r can be used within the string to reset the colors to default.
---
--- @usage Print red test on green background.
--- <pre>
--- hecho("|cff0000,00ff00test")
--- </pre>
---
--- @see xEcho
--- @see hinsertText
function hecho(...)
xEcho("Hex", "echo", ...)
end
--- Echo string with embedded decimal color information. <br/><br/>
---
--- Color changes can be made using the format <FR,FG,FB:BR,BG,BB> where each field is a number from 0 to 255.
--- The background portion can be omitted using <FR,FG,FB> or the foreground portion can be omitted using <:BR,BG,BB>.
---
--- @usage Print red test on green background.
--- <pre>
--- decho("<255,0,0:0,255,0>test")
--- </pre>
---
--- @see xEcho
--- @see dinsertText
function decho(...)
xEcho("Decimal", "echo", ...)
end
--- Echo string with embedded color name information.
---
--- @usage Consider following example:
--- <pre>
--- cecho("<green>green text <blue>blue text <red>red text")
--- </pre>
---
--- @see xEcho
--- @see cinsertText
function cecho(...)
xEcho("Color", "echo", ...)
end
--- Inserts string with embedded hex color information.
---
--- @see xEcho
--- @see hecho
function hinsertText(...)
xEcho("Hex", "insertText", ...)
end
--- Inserts string with embedded decimal color information.
---
--- @see xEcho
--- @see decho
function dinsertText(...)
xEcho("Decimal", "insertText", ...)
end
--- Inserts string with embedded color name information.
---
--- @see xEcho
--- @see cecho
function cinsertText(...)
xEcho("Color", "insertText", ...)
end
--- Echos a link with embedded hex color information.
---
--- @usage hechoLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see hecho
function hechoLink(...)
xEcho("Hex", "echoLink", ...)
end
--- Echos a link with embedded decimal color information.
---
--- @usage dechoLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see decho
function dechoLink(...)
xEcho("Decimal", "echoLink", ...)
end
--- Echos a link with embedded color name information.
---
--- @usage cechoLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see cecho
function cechoLink(...)
xEcho("Color", "echoLink", ...)
end
--- Inserts a link with embedded color name information at the current position
---
--- @usage cinsertLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see cecho
function cinsertLink(...)
xEcho("Color", "insertLink", ...)
end
--- Inserts a link with embedded decimal color information at the current position
---
--- @usage dinsertLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see decho
function dinsertLink(...)
xEcho("Decimal", "insertLink", ...)
end
--- Inserts a link with embedded hex color information at the current position
---
--- @usage hinsertLink([window, ] string, command, hint)
---
--- @see xEcho
--- @see hecho
function hinsertLink(...)
xEcho("Hex", "insertLink", ...)
end
--- Echos a popup with embedded color name information.
---
--- @usage cechoPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see cecho
function cechoPopup(...)
xEcho("Color", "echoPopup", ...)
end
--- Echos a popup with embedded color name information.
---
--- @usage dechoPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see decho
function dechoPopup(...)
xEcho("Decimal", "echoPopup", ...)
end
--- Echos a popup with embedded hex color information.
---
--- @usage hechoPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see hecho
function hechoPopup(...)
xEcho("Hex", "echoPopup", ...)
end
--- Echos a popup with embedded color name information.
---
--- @usage cinsertPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see cecho
function cinsertPopup(...)
xEcho("Color", "insertPopup", ...)
end
--- Echos a popup with embedded decimal color information.
---
--- @usage dinsertPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see decho
function dinsertPopup(...)
xEcho("Decimal", "insertPopup", ...)
end
--- Echos a popup with embedded hex color information.
---
--- @usage hinsertPopup([window, ] string, {commands}, {hints})
---
--- @see xEcho
--- @see hecho
function hinsertPopup(...)
xEcho("Hex", "insertPopup", ...)
end
-- Backwards compatibility
checho = cecho
-- table to facilitate converting color names to ansi escapes
local ctable =
{
black = "0",
red = "1",
green = "2",
yellow = "3",
blue = "4",
magenta = "5",
cyan = "6",
white = "7",
light_black = "8",
light_red = "9",
light_green = "10",
light_yellow = "11",
light_blue = "12",
light_magenta = "13",
light_cyan = "14",
light_white = "15",
lightBlack = "8",
lightRed = "9",
lightGreen = "10",
lightYellow = "11",
lightBlue = "12",
lightMagenta = "13",
lightCyan = "14",
lightWhite = "15",
}
for i = 0, 255 do
local key = tostring(i)
ctable[key] = key
ctable["ansi_" .. key] = key
end
-- local lookup table to find ansi escapes for to ansi conversions
local resets = {
["r"] = "\27[0m",
["reset"] = "\27[0m",
["i"] = "\27[3m",
["/i"] = "\27[23m",
["b"] = "\27[1m",
["/b"] = "\27[22m",
["u"] = "\27[4m",
["/u"] = "\27[24m",
["s"] = "\27[9m",
["/s"] = "\27[29m",
["o"] = "\27[53m",
["/o"] = "\27[55m"
}
-- take a color name and turn it into an ANSI escape string
local function colorToAnsi(colorName)
local result = ""
local cols = colorName:split(":")
local fore = cols[1]
local back = cols[2]
if fore ~= "" then
local res = resets[fore]
if res then
result = result .. res
else
local colorNumber = ctable[fore]
if colorNumber then
result = string.format("%s\27[38:5:%sm", result, colorNumber)
elseif color_table[fore] then
local rgb = color_table[fore]
result = string.format("%s\27[38:2::%s:%s:%sm", result, rgb[1], rgb[2], rgb[3])
end
end
end
if back then
local colorNumber = ctable[back]
if colorNumber then
result = string.format("%s\27[48:5:%sm", result, colorNumber)
elseif color_table[back] then
local rgb = color_table[back]
result = string.format("%s\27[48:2::%s:%s:%sm", result, rgb[1], rgb[2], rgb[3])
end
end
return result
end
-- converts decho color information to ansi escape sequences
local function rgbToAnsi(rgb)
local result = ""
local cols = rgb:split(":")
local fore = cols[1]
local back = cols[2]
if fore ~= "" then
local components = fore:split(",")
result = string.format("%s\27[38:2::%s:%s:%sm", result, components[1] or "0", components[2] or "0", components[3] or "0")
end
if back then
local components = back:split(",")
result = string.format("%s\27[48:2::%s:%s:%sm", result, components[1] or "0", components[2] or "0", components[3] or "0")
end
return result
end
-- converts a 6 digit hex color code to ansi escape sequence
local function hexToAnsi(hexcode)
local result = ""
local cols = hexcode:split(",")
local fore = cols[1]
local back = cols[2]
if fore ~= "" then
local components = {
tonumber(fore:sub(1,2),16),
tonumber(fore:sub(3,4),16),
tonumber(fore:sub(5,6),16)
}
result = string.format("%s\27[38:2::%s:%s:%sm", result, components[1] or "0", components[2] or "0", components[3] or "0")
end
if back then
local components = {
tonumber(back:sub(1,2),16),
tonumber(back:sub(3,4),16),
tonumber(back:sub(5,6),16)
}
result = string.format("%s\27[48:2::%s:%s:%sm", result, components[1] or "0", components[2] or "0", components[3] or "0")
end
return result
end
function cecho2ansi(text)
local colorPattern = _Echos.Patterns.Color[1]
local result = ""
for str, color in rex.split(text, colorPattern) do
result = result .. str
if color then
result = result .. colorToAnsi(color:match("<(.+)>"))
end
end
return result
end
--- feedTriggers with cecho style color information.
-- Valid colors are black,red,green,yellow,blue,magenta,cyan,white and light_* versions of same
-- Can also pass in a number between 0 and 255 to use the expanded ansi 255 colors. IE <124> will set foreground to the color ANSI124
-- Will also take ansi colors as ansi_#, IE <ansi_124>
-- Reset using <r> or <reset>
--@param text the text to pump into feedTriggers
--@see cecho
--@see cinsertText
function cfeedTriggers(text)
feedTriggers(cecho2ansi(text) .. "\n")
echo("")
end
--- Returns a string with decho style color codes converted to ANSI color
-- IE <128,0,0> for red, <0,128,0> for green, <0,128,0:128,0,0> for green on red background.
-- <r> to reset
--@param text the text to convert to ansi colors
--@see decho
--@see dinsertText
function decho2ansi(text)
local colorPattern = _Echos.Patterns.Decimal[1]
local result = ""
for str, color, res in rex.split(text, colorPattern) do
result = result .. str
if color then
result = result .. rgbToAnsi(color:match("<(.+)>"))
end
if res then
result = result .. resets[res]
end
end
return result
end
--- feedTriggers with decho style color information.
-- IE <128,0,0> for red, <0,128,0> for green, <0,128,0:128,0,0> for green on red background.
-- <r> to reset
--@param text the text to pump into feedTriggers
--@see decho
--@see dinsertText
function dfeedTriggers(text)
feedTriggers(decho2ansi(text) .. "\n")
echo("")
end
--- turn hecho style color information into an ANSI color string
-- IE #800000 for red, #008000 for green, #008000,800000 for green on red background
-- #r to reset
--@param text the text convert to ansi colors
--@see hecho
--@see hinsertText
function hecho2ansi(text)
local colorPattern = _Echos.Patterns.Hex[1]
local result = ""
for str, color, res in rex.split(text, colorPattern) do
result = result .. str
if color then
if color:sub(1,1) == "|" then color = color:gsub("|c", "#") end
result = result .. hexToAnsi(color:sub(2,-1))
end
if res then
result = result .. resets[res]
end
end
return result
end
--- feedTriggers with hecho style color information.
-- IE #800000 for red, #008000 for green, #008000,800000 for green on red background
-- #r to reset
--@param text the text to pump into feedTriggers
--@see hecho
--@see hinsertText
function hfeedTriggers(text)
feedTriggers(hecho2ansi(text) .. "\n")
echo("")
end
else
-- NOT using rex module:
-- NOT LUADOC
-- See xEcho/another cecho for description.
function cecho(window, text)
local win = text and window
local s = text or window
if win == "main" then
win = nil
end
if win then
resetFormat(win)
else
resetFormat()
end
for color, text in string.gmatch("<white>" .. s, "<([a-z_0-9, :]+)>([^<>]+)") do
local colist = string.split(color .. ":", "%s*:%s*")
local fgcol = colist[1] ~= "" and colist[1] or "white"
local bgcol = colist[2] ~= "" and colist[2] or "black"
local FGrgb = color_table[fgcol] or string.split(fgcol, ",")
local BGrgb = color_table[bgcol] or string.split(bgcol, ",")
local alpha = BGrgb[4] or 255
if win then
setFgColor(win, FGrgb[1], FGrgb[2], FGrgb[3])
setBgColor(win, BGrgb[1], BGrgb[2], BGrgb[3], alpha)
echo(win, text)
else
setFgColor(FGrgb[1], FGrgb[2], FGrgb[3])
setBgColor(BGrgb[1], BGrgb[2], BGrgb[3], alpha)
echo(text)
end
end
if win then
resetFormat(win)
else
resetFormat()
end
end
-- NOT LUADOC
-- See xEcho/another decho for description.
function decho(window, text)
local win = text and window
local s = text or window
if win == "main" then
win = nil
end
local reset
if win then
reset = function()
resetFormat(win)
end
else
reset = function()
resetFormat()
end
end
reset()
for color, text in s:gmatch("<([0-9,:]+)>([^<>]+)") do
if color == "reset" then
reset()
if win then
echo(win, text) else echo(text)
end
else
local colist = string.split(color .. ":", "%s*:%s*")
local fgcol = colist[1] ~= "" and colist[1] or "white"
local bgcol = colist[2] ~= "" and colist[2] or "black"
local FGrgb = color_table[fgcol] or string.split(fgcol, ",")
local BGrgb = color_table[bgcol] or string.split(bgcol, ",")
local alpha = BGrgb[4] or 255
if win then
setFgColor(win, FGrgb[1], FGrgb[2], FGrgb[3])
setBgColor(win, BGrgb[1], BGrgb[2], BGrgb[3], alpha)
echo(win, text)
else
setFgColor(FGrgb[1], FGrgb[2], FGrgb[3])
setBgColor(BGrgb[1], BGrgb[2], BGrgb[3], alpha)
echo(text)
end
end
end
reset()
end
end
-- improve replace to have a third argument, keepcolor
do
local oldreplace = replace
function replace(arg1, arg2, arg3)
local windowname, text, keepcolor
if arg1 and arg2 and arg3 ~= nil then
windowname, text, keepcolor = arg1, arg2, arg3
elseif arg1 and type(arg2) == "string" then
windowname, text = arg1, arg2
elseif arg1 and type(arg2) == "boolean" then
text, keepcolor = arg1, arg2
else
text = arg1
end
local selection = {getSelection()}
if _comp(selection, {"", 0, 0}) then
return nil, "replace: nothing is selected to be replaced. Did selectString return -1?"
end
text = text or ""
if keepcolor then
if not windowname then
setBgColor(getBgColor())
setFgColor(getFgColor())
else
setBgColor(windowname, getBgColor(windowname))
setFgColor(windowname, getFgColor(windowname))
end
end
if windowname then
oldreplace(windowname, text)
else
oldreplace(text)
end
end
end
-- function for converting a color formatted string to 'plaintext' string
local function x2string(text, style)
local ttbl = _Echos.Process(text, style)
local result = ""
for _, val in ipairs(ttbl) do
if type(val) == "string" and not val:starts("\27") then
result = result .. val
end
end
return result
end
-- function to convert a cecho formatted string to a nonformatted string
function cecho2string(text)
return x2string(text, "Color")
end
-- function to convert a decho formatted string to a nonformatted string
function decho2string(text)
return x2string(text, "Decimal")
end
-- function to convert a hecho formatted string to a nonformatted string
function hecho2string(text)
return x2string(text, "Hex")
end
local ansiPattern = rex.new("\\e\\[([0-9:;]*?)m")
-- function for converting a raw ANSI string into plain strings
function ansi2string(text)
assert(type(text) == 'string', 'ansi2string: bad argument #1 type (expected string, got '..type(text)..'!)')
local result = rex.gsub(text, ansiPattern, "")
return result
end
-- function for converting a raw ANSI string into something decho can process
-- italics and underline not currently supported since decho doesn't support them
-- bold is emulated so it is supported, up to an extent
function ansi2decho(text, ansi_default_color)
assert(type(text) == 'string', 'ansi2decho: bad argument #1 type (expected string, got '..type(text)..'!)')
local lastColour = ansi_default_color
local coloursToUse = nil
-- match each set of ansi tags, ie [0;36;40m and convert to decho equivalent.
-- this works since both ansi colours and echo don't need closing tags and map to each other
local result = rex.gsub(text, ansiPattern, function(s)
local output = {} -- assemble the output into this table
local delim = ";"
if s:find(":") then delim = ":" end
local t = string.split(s, delim) -- split the codes into an indexed table
-- given an xterm256 index, returns an rgb string for decho use
local function convertindex(tag)
local ansi = string.format("ansi_%03d", tag)
return color_table[ansi] or false
end
local colours = {}
for i = 0, 7 do
colours[i] = convertindex(i)
end
local lightColours = {}
for i = 0, 7 do
lightColours[i] = convertindex(i+8)
end
coloursToUse = coloursToUse or colours
-- since fg/bg can come in different order and we need them as fg:bg for decho, collect
-- the data first, then assemble it in the order we need at the end
local fg, bg
local i = 1
local floor = math.floor
while i <= #t do
local code = t[i]
local formatCodeHandled = false
if code == '0' or code == '00' or code == '' then
-- reset attributes
output[#output + 1] = "<r>"
fg, bg = nil, nil
coloursToUse = colours
lastColour = ansi_default_color
elseif code == "1" then
-- light or bold
coloursToUse = lightColours
elseif code == "22" then
-- not light or bold
coloursToUse = colours
elseif code == "3" then
formatCodeHandled = true
output[#output+1] = "<i>"
elseif code == "23" then
-- turn off italics
formatCodeHandled = true
output[#output+1] = "</i>"
elseif code == "4" then
-- underline
formatCodeHandled = true
output[#output+1] = "<u>"
elseif code == "24" then
-- turn off underline
formatCodeHandled = true
output[#output+1] = "</u>"
elseif code == "9" then
-- strikethrough
formatCodeHandled = true
output[#output+1] = "<s>"
elseif code == "29" then
-- turn off strikethrough
formatCodeHandled = true
output[#output+1] = "</s>"
elseif code == "53" then
-- turn on overline
formatCodeHandled = true
output[#output+1] = "<o>"
elseif code == "55" then
-- turn off overline
formatCodeHandled = true
output[#output+1] = "</o>"
else
formatCodeHandled = true
local layerCode = floor(code / 10) -- extract the "layer": 3 is fore
-- 4 is back
local cmd = code - (layerCode * 10) -- extract the actual "command"
-- 0-7 is a colour, 8 is xterm256
local colour = nil
if cmd == 8 and t[i + 1] == '5' then
-- xterm256, colour indexed
colour = convertindex(tonumber(t[i + 2]))
i = i + 2
elseif cmd == 8 and t[i + 1] == '2' then
-- xterm256, rgb
if delim == ";" then
colour = { t[i + 2] or '0', t[i + 3] or '0', t[i + 4] or '0' }
i = i + 4
elseif delim == ":" then
colour = { t[i + 3] or '0', t[i + 4] or '0', t[i + 5] or '0' }
i = i + 5
end
elseif layerCode == 9 or layerCode == 10 then
--light colours
colour = lightColours[cmd]
elseif layerCode == 4 then
-- background colours know no "bright" for
colour = colours[cmd] -- mudlet
else -- usual ANSI colour index
colour = coloursToUse[cmd]
end
if layerCode == 3 or layerCode == 9 then
fg = colour
lastColour = cmd
elseif layerCode == 4 or layerCode == 10 then
bg = colour
end
end
-- If formatCodeHandled is false it means that we've encountered a SGBR
-- code such as 'bold' or 'dim'.
-- In those cases, if there's a previous color, we are supposed to
-- modify it
if not formatCodeHandled and lastColour then
fg = coloursToUse[lastColour]
end
i = i + 1
end
-- assemble and return the data
if fg or bg then
output[#output + 1] = '<'
if fg then
output[#output + 1] = table.concat(fg, ",")
end
if bg then
output[#output + 1] = ':'
output[#output + 1] = table.concat(bg, ",")
end
output[#output + 1] = '>'
end
return table.concat(output)
end)
return result, lastColour
end
--- Form of setFgColor that accepts a hex color string instead of decimal values
--- @param windowName Optional name of the window to use the function on
--- @param colorString hex string for the color to use
function setHexFgColor(windowName, colorString)
local win = colorString and windowName
local col = colorString or windowName
if win == "main" then
win = nil
end
if #col ~= 6 then
error("setHexFgColor needs a 6 digit hex color code.")
end
local colTable = {
r = tonumber(col:sub(1, 2), 16),
g = tonumber(col:sub(3, 4), 16),
b = tonumber(col:sub(5, 6), 16)
}
if win then
setFgColor(win, colTable.r, colTable.g, colTable.b)
else
setFgColor(colTable.r, colTable.g, colTable.b)
end
end
--- Form of setBgColor that accepts a hex color string instead of decimal values
--- @param windowName Optional name of the window to use the function on
--- @param colorString hex string for the color to use
function setHexBgColor(windowName, colorString)
local win = colorString and windowName
local col = colorString or windowName
if win == "main" then
win = nil
end
if #col ~= 6 then
error("setHexBgColor needs a 6 digit hex color code.")
end
local colTable = {
r = tonumber(col:sub(1, 2), 16),
g = tonumber(col:sub(3, 4), 16),
b = tonumber(col:sub(5, 6), 16)
}
if win then
setBgColor(win, colTable.r, colTable.g, colTable.b)
else
setBgColor(colTable.r, colTable.g, colTable.b)
end
end
local insertFuncs = {[echo] = insertText, [cecho] = cinsertText, [decho] = dinsertText, [hecho] = hinsertText}
--- Suffixes text at the end of the current line when used in a trigger.
---
--- @see prefix
function suffix(what, func, fgc, bgc, window)
window = window or "main"
func = insertFuncs[func] or func or insertText
local length = utf8.len(getCurrentLine(window))
moveCursor(window, length - 1, getLineNumber(window))
if fgc then fg(window,fgc) end
if bgc then bg(window,bgc) end
func(window,what)
resetFormat(window)
end
--- Prefixes text at the beginning of the current line when used in a trigger.
---
--- @usage Prefix the hours, minutes and seconds onto our prompt even though Mudlet has a button for that.
--- <pre>
--- prefix(os.date("%H:%M:%S "))
--- </pre>
---
--- @see suffix
function prefix(what, func, fgc, bgc, window)
window = window or "main"
func = insertFuncs[func] or func or insertText
moveCursor(window, 0, getLineNumber(window))
if fgc then fg(window,fgc) end
if bgc then bg(window,bgc) end
func(window,what)
resetFormat(window)
end
--- Moves the cursor in the given window up a specified number of lines
--- @param windowName Optional name of the window to use the function on
--- @param lines Number of lines to move cursor
--- @param keep_horizontal Optional boolean to specify if horizontal position should be retained
function moveCursorUp(window, lines, keep_horizontal)
if type(window) ~= "string" then lines, window, keep_horizontal = window, "main", lines end
lines = tonumber(lines) or 1
if not type(keep_horizontal) == "boolean" then keep_horizontal = false end
local curLine = getLineNumber(window)
if not curLine then return nil, "window does not exist" end
local x = 0
if keep_horizontal then x = getColumnNumber(window) end
moveCursor(window, x, math.max(curLine - lines, 0))
end
--- Moves the cursor in the given window down a specified number of lines
--- @param windowName Optional name of the window to use the function on
--- @param lines Number of lines to move cursor
--- @param keep_horizontal Optional boolean to specify if horizontal position should be retained
function moveCursorDown(window, lines, keep_horizontal)
if type(window) ~= "string" then lines, window, keep_horizontal = window, "main", lines end
lines = tonumber(lines) or 1
if not type(keep_horizontal) == "boolean" then keep_horizontal = false end
local curLine = getLineNumber(window)
if not curLine then return nil, "window does not exist" end
local x = 0
if keep_horizontal then x = getColumnNumber(window) end
moveCursor(window, x, math.min(curLine + lines, getLastLineNumber(window)))
end
-- internal function that handles coloured replace variants
function xReplace(window, text, type)
if not text then
text = window
window = "main"
end
local str, start, stop = getSelection(window)
if window ~= "main" then
replace(window, "")
moveCursor(window, start, getLineNumber(window))
else
replace("")
moveCursor(start, getLineNumber())
end
if type == 'c' then
cinsertText(window, text)
elseif type == 'd' then
dinsertText(window, text)
elseif type == 'h' then
hinsertText(window, text)
else
insertText(window, text)
end
end
--- version of replace function that allows for color, by way of cinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function creplace(window, text)
xReplace(window, text, 'c')
end
--- version of replaceLine function that allows for color, by way of cinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function creplaceLine(window, text)
if not text then
selectCurrentLine()
else
selectCurrentLine(window)
end
creplace(window, text)
end
--- version of replace function that allows for color, by way of dinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function dreplace(window, text)
xReplace(window, text, 'd')
end
--- version of replaceLine function that allows for color, by way of dinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function dreplaceLine(window, text)
if not text then
selectCurrentLine()
else
selectCurrentLine(window)
end
dreplace(window, text)
end
--- version of replace function that allows for color, by way of hinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function hreplace(window, text)
xReplace(window, text, 'h')
end
--- version of replaceLine function that allows for color, by way of hinsertText
--- @param windowName Optional name of the window to replace on
--- @param text The text to replace the selection with.
function hreplaceLine(window, text)
if not text then
selectCurrentLine()
else
selectCurrentLine(window)
end
hreplace(window, text)
end
function resetLabelToolTip(label)
return setLabelToolTip(label, "")
end
-- functions to move and resize Map Widget
-- be aware that moving or resizing Map Widget puts the Map Widget in floating state
function moveMapWidget(x, y)
assert(type(x) == 'number', 'moveMapWidget: bad argument #1 type (x-coordinate as number expected, got '..type(x)..'!)')
assert(type(y) == 'number', 'moveMapWidget: bad argument #2 type (y-coordinate as number expected, got '..type(y)..'!)')
openMapWidget(x, y)
end
function resizeMapWidget(width, height)
assert(type(width) == 'number', 'resizeMapWidget: bad argument #1 type (width as number expected, got '..type(width)..'!)')
assert(type(height) == 'number', 'resizeMapWidget: bad argument #2 type (height as number expected, got '..type(height)..'!)')
openMapWidget(-1, -1, width, height)
end
--
-- functions to manipulate room label display and offsets
--
-- get offset of room's label (x,y)
-- @param room Room ID
function getRoomNameOffset(room)
assert(type(room) == 'number', 'getRoomNameOffset: bad argument #1 type (room ID as number expected, got '..type(room)..'!)')
local d = getRoomUserData(room, "room.ui_nameOffset")
if d == nil or d == "" then return 0,0 end
local split = {}
for w in string.gfind(d, '[%.%d]+') do split[#split+1] = tonumber(w) end
if #split == 1 then return 0,split[1] end
if #split >= 2 then return split[1],split[2] end
return 0,0
end
-- set offset of room's label (x,y)
-- @param room Room ID
-- @param room X shift (positive = to the right)
-- @param room Y shift (positive = down)
function setRoomNameOffset(room, x, y)
assert(type(room) == 'number', 'setRoomNameOffset: bad argument #1 type (room ID as number expected, got '..type(room)..'!)')
assert(type(x) == 'number', 'setRoomNameOffset: bad argument #2 type (X shift as number expected, got '..type(x)..'!)')
assert(type(y) == 'number', 'setRoomNameOffset: bad argument #3 type (y shift as number expected, got '..type(y)..'!)')
if x == 0 then
setRoomUserData(room, "room.ui_nameOffset", y)
else
setRoomUserData(room, "room.ui_nameOffset", x .. " " .. y)
end
end
-- show or hide a room's name
-- @param room Room ID
-- @param flag (bool)
function setRoomNameVisible(room, flag)
assert(type(room) == 'number', 'setRoomNameVisible: bad argument #1 type (room ID as number expected, got '..type(room)..'!)')
assert(type(flag) == 'boolean', 'setRoomNameVisible: bad argument #2 type (flag as boolean expected, got '..type(flag)..'!)')
setRoomUserData(room, "room.ui_showName", flag and "1" or "0")
end
--wrapper for createButton
-- createButton is deprecated better use createLabel instead
createButton = createLabel
-- Internal function used by copy2html and copy2decho
local function copy2color(name,win,str,inst)
local line,err = getCurrentLine(win or "main")
if err ~= nil then
win, str, inst = "main", win, str
line,err = getCurrentLine(win)
if err ~= nil then
error(err)
end
end
win = win or "main"
str = str or line
inst = inst or 1
if str == "" then
-- happens when you try to use copy2decho() on an empty line
return ""
end
local start, len = selectString(win, str, inst), utf8.len(str)
if not start then
error(name..": string not found",3)
end
local style, endspan, result, r, g, b, rb, gb, bb, cr, cg, cb, crb, cgb, cbb
local selectSection, getFgColor, getBgColor = selectSection, getFgColor, getBgColor
if name == "copy2html" then
style = "%s<span style=\'color: rgb(%d,%d,%d);background: rgb(%d,%d,%d);'>%s"
endspan = "</span>"
elseif name == "copy2decho" then
style = "%s<%d,%d,%d:%d,%d,%d>%s"
endspan = "<r>"
end
for index = start + 1, start + len do
if win ~= "main" then
selectSection(win, index - 1, 1)
r,g,b = getFgColor(win)
rb,gb,bb = getBgColor(win)
else
selectSection(index - 1, 1)
r,g,b = getFgColor()
rb,gb,bb = getBgColor()
end
if r ~= cr or g ~= cg or b ~= cb or rb ~= crb or gb ~= cgb or bb ~= cbb then
cr,cg,cb,crb,cgb,cbb = r,g,b,rb,gb,bb
result = string.format(style, result and (result..endspan) or "", r, g, b, rb, gb, bb, utf8.sub(line, index, index))
else
result = result .. utf8.sub(line, index, index)
end
end
result = result .. endspan
if name == "copy2html" then
local conversions = {["¦"] = "¦", ["×"] = "×", ["«"] = "«", ["»"] = "»"}
for from, to in pairs(conversions) do
result = string.gsub(result, from, to)
end
end
return result
end
--- copies text with color information in decho format
--- @param win optional, the window to copy from. Defaults to the main window
--- @param str optional, the string to copy. Defaults to copying the entire line
--- @param inst optional, the instance of the string to copy. Defaults to the first instance.
--- @usage to copy matches[2] with color information and echo it to miniconsole "test"
--- <pre>
--- decho("test", copy2decho(matches[2]))
--- </pre>
---
--- @usage to copy the entire line with color information, then echo it to miniconsole "test"
--- <pre>
--- decho("test", copy2decho())
--- </pre>
function copy2decho(win, str, inst)
return copy2color("copy2decho", win, str, inst)
end
--- copies text with color information in html format, for echoing to a label for instance
--- @param win optional, the window to copy from. Defaults to the main window
--- @param str optional, the string to copy. Defaults to copying the entire line
--- @param inst optional, the instance of the string to copy. Defaults to the first instance.
--- @usage to copy matches[2] with color information and echo it to label "test"
--- <pre>
--- echo("test", copy2html(matches[2]))
--- </pre>
---
--- @usage to copy the entire line with color information, then echo it to label "test"
--- <pre>
--- echo("test", copy2html())
--- </pre>
function copy2html(win, str, inst)
return copy2color("copy2html", win, str, inst)
end
function resetLabelCursor(name)
assert(type(name) == 'string', 'resetLabelCursor: bad argument #1 type (name as string expected, got '..type(name)..'!)')
return setLabelCursor(name, -1)
end
local setLabelCursorLayer = setLabelCursor
function setLabelCursor(labelname, cursorShape)
if type(cursorShape) == "string" then
cursorShape = mudlet.cursor[cursorShape]
end
return setLabelCursorLayer(labelname, cursorShape)
end
mudlet.BgImageMode ={
["border"] = 1,
["center"] = 2,
["tile"] = 3,
["style"] = 4,
}
local setConsoleBackgroundImageLayer = setBackgroundImage
function setBackgroundImage(...)
local mode = arg[arg.n]
if type(mode) == "string" then
mode = mudlet.BgImageMode[mode] or mode
end
arg[arg.n] = mode
return setConsoleBackgroundImageLayer(unpack(arg))
end
--These functions ensure backward compatibility for the setActionCallback functions
--unpack function which also returns the nil values
-- the arg_table (arg) saves the number of arguments in n -> arg_table.n (arg.n)
function unpack_w_nil (arg_table, counter)
counter = counter or 1
if counter >= arg_table.n then
return arg_table[counter]
end
return arg_table[counter], unpack_w_nil(arg_table, counter + 1)
end
-- This wrapper gives callback functions the possibility to be used like
-- setCallBackFunction (name,function as string,args)
-- it is used by setLabelCallBack functions and setCmdLineAction
local function setActionCallback(callbackFunc, funcName, name, func, ...)
local nr = arg.n + 1
arg.n = arg.n + 1
if type(func) == "string" then
func = loadstring("return "..func.."(...)")
end
assert(type(func) == 'function', string.format('<%s: bad argument #2 type (function expected, got %s!)>', funcName, type(func)))
if nr > 1 then
return callbackFunc(name,
function(event)
if not event then
arg.n = nr - 1
end
arg[nr] = event
func(unpack_w_nil(arg))
end )
end
return callbackFunc(name, func)
end
local callBackFunc = {"setLabelClickCallback", "setLabelDoubleClickCallback", "setLabelReleaseCallback", "setLabelMoveCallback", "setLabelWheelCallback", "setLabelOnEnter", "setLabelOnLeave", "setCmdLineAction"}
for i = 1, #callBackFunc do
local funcName = callBackFunc[i]
local callBackFunction = _G[funcName]
_G[funcName] = function(...) return setActionCallback(callBackFunction, funcName, ...) end
end
function resetUserWindowTitle(windowname)
return setUserWindowTitle(windowname, "")
end
function resetMapWindowTitle()
return setMapWindowTitle("")
end
--- This function takes in a color and returns the closest color from color_table. The following all return "ansi_001"
--- closestColor({127,0,0})
--- closestColor(127,0,0)
--- closestColor("#7f0000")
--- closestColor("|c7f0000")
--- closestColor("<127,0,0>")
function closestColor(r,g,b)
local rtype = type(r)
local rgb
if rtype == "table" then
rgb = {}
local tmp = r
local err = f"Could not parse {table.concat(tmp, ',')} into RGB coordinates to look for.\n"
if #tmp ~= 3 then
return nil, err
end
for index,coord in ipairs(tmp) do
local num = tonumber(coord)
if not num or num < 0 or num > 255 then
return nil, err
end
rgb[index] = num
end
elseif rtype == "string" and not tonumber(r) then
if color_table[r] then
return r
end
rgb = {Geyser.Color.parse(r)}
if rgb[1] == nil then
return nil, f"Could not parse {r} into a set of RGB coordinates to look for.\n"
end
elseif rtype == "number" or tonumber(r) then
local nr = tonumber(r)
local ng = tonumber(g)
local nb = tonumber(b)
if not nr or not ng or not nb or (nr < 0 or nr > 255) or (ng < 0 or ng > 255) or (nb < 0 or nb > 255) then
return nil, f"Could not parse {r},{g},{b} into a set of RGB coordinates to look for.\n"
end
rgb = {nr,ng,nb}
else
return nil, f"Could not parse your parameters into RGB coordinates.\n"
end
local least_distance = math.huge
local cname = ""
for name, color in pairs(color_table) do
local color_distance = math.sqrt((color[1] - rgb[1]) ^ 2 + (color[2] - rgb[2]) ^ 2 + (color[3] - rgb[3]) ^ 2)
if color_distance < least_distance then
least_distance = color_distance
cname = name
end
end
return cname
end
--- Scrolls the given window up a specified number of lines
--- @param windowName Optional name of the window to use the function on
--- @param lines Number of lines to scroll
function scrollUp(window, lines)
if type(window) ~= "string" then window, lines = "main", window end
lines = tonumber(lines) or 1
local numLines = getLastLineNumber(window)
if not numLines then return nil, "window does not exist" end
local curScroll = getScroll(window)
scrollTo(window, math.max(curScroll - lines, 0))
end
--- Scrolls the given window down a specified number of lines
--- @param windowName Optional name of the window to use the function on
--- @param lines Number of lines to scroll
function scrollDown(window, lines)
if type(window) ~= "string" then window, lines = "main", window end
lines = tonumber(lines) or 1
local numLines = getLastLineNumber(window)
if not numLines then return nil, "window does not exist" end
local curScroll = getScroll(window)
scrollTo(window, math.min(curScroll + lines, numLines))
end
| gpl-2.0 |
ceason/epgp-tfatf | libs/AceGUI-3.0/widgets/AceGUIWidget-EditBox.lua | 30 | 7163 | --[[-----------------------------------------------------------------------------
EditBox Widget
-------------------------------------------------------------------------------]]
local Type, Version = "EditBox", 25
local AceGUI = LibStub and LibStub("AceGUI-3.0", true)
if not AceGUI or (AceGUI:GetWidgetVersion(Type) or 0) >= Version then return end
-- Lua APIs
local tostring, pairs = tostring, pairs
-- WoW APIs
local PlaySound = PlaySound
local GetCursorInfo, ClearCursor, GetSpellInfo = GetCursorInfo, ClearCursor, GetSpellInfo
local CreateFrame, UIParent = CreateFrame, UIParent
local _G = _G
-- Global vars/functions that we don't upvalue since they might get hooked, or upgraded
-- List them here for Mikk's FindGlobals script
-- GLOBALS: AceGUIEditBoxInsertLink, ChatFontNormal, OKAY
--[[-----------------------------------------------------------------------------
Support functions
-------------------------------------------------------------------------------]]
if not AceGUIEditBoxInsertLink then
-- upgradeable hook
hooksecurefunc("ChatEdit_InsertLink", function(...) return _G.AceGUIEditBoxInsertLink(...) end)
end
function _G.AceGUIEditBoxInsertLink(text)
for i = 1, AceGUI:GetWidgetCount(Type) do
local editbox = _G["AceGUI-3.0EditBox"..i]
if editbox and editbox:IsVisible() and editbox:HasFocus() then
editbox:Insert(text)
return true
end
end
end
local function ShowButton(self)
if not self.disablebutton then
self.button:Show()
self.editbox:SetTextInsets(0, 20, 3, 3)
end
end
local function HideButton(self)
self.button:Hide()
self.editbox:SetTextInsets(0, 0, 3, 3)
end
--[[-----------------------------------------------------------------------------
Scripts
-------------------------------------------------------------------------------]]
local function Control_OnEnter(frame)
frame.obj:Fire("OnEnter")
end
local function Control_OnLeave(frame)
frame.obj:Fire("OnLeave")
end
local function Frame_OnShowFocus(frame)
frame.obj.editbox:SetFocus()
frame:SetScript("OnShow", nil)
end
local function EditBox_OnEscapePressed(frame)
AceGUI:ClearFocus()
end
local function EditBox_OnEnterPressed(frame)
local self = frame.obj
local value = frame:GetText()
local cancel = self:Fire("OnEnterPressed", value)
if not cancel then
PlaySound("igMainMenuOptionCheckBoxOn")
HideButton(self)
end
end
local function EditBox_OnReceiveDrag(frame)
local self = frame.obj
local type, id, info = GetCursorInfo()
if type == "item" then
self:SetText(info)
self:Fire("OnEnterPressed", info)
ClearCursor()
elseif type == "spell" then
local name = GetSpellInfo(id, info)
self:SetText(name)
self:Fire("OnEnterPressed", name)
ClearCursor()
elseif type == "macro" then
local name = GetMacroInfo(id)
self:SetText(name)
self:Fire("OnEnterPressed", name)
ClearCursor()
end
HideButton(self)
AceGUI:ClearFocus()
end
local function EditBox_OnTextChanged(frame)
local self = frame.obj
local value = frame:GetText()
if tostring(value) ~= tostring(self.lasttext) then
self:Fire("OnTextChanged", value)
self.lasttext = value
ShowButton(self)
end
end
local function EditBox_OnFocusGained(frame)
AceGUI:SetFocus(frame.obj)
end
local function Button_OnClick(frame)
local editbox = frame.obj.editbox
editbox:ClearFocus()
EditBox_OnEnterPressed(editbox)
end
--[[-----------------------------------------------------------------------------
Methods
-------------------------------------------------------------------------------]]
local methods = {
["OnAcquire"] = function(self)
-- height is controlled by SetLabel
self:SetWidth(200)
self:SetDisabled(false)
self:SetLabel()
self:SetText()
self:DisableButton(false)
self:SetMaxLetters(0)
end,
["OnRelease"] = function(self)
self:ClearFocus()
end,
["SetDisabled"] = function(self, disabled)
self.disabled = disabled
if disabled then
self.editbox:EnableMouse(false)
self.editbox:ClearFocus()
self.editbox:SetTextColor(0.5,0.5,0.5)
self.label:SetTextColor(0.5,0.5,0.5)
else
self.editbox:EnableMouse(true)
self.editbox:SetTextColor(1,1,1)
self.label:SetTextColor(1,.82,0)
end
end,
["SetText"] = function(self, text)
self.lasttext = text or ""
self.editbox:SetText(text or "")
self.editbox:SetCursorPosition(0)
HideButton(self)
end,
["GetText"] = function(self, text)
return self.editbox:GetText()
end,
["SetLabel"] = function(self, text)
if text and text ~= "" then
self.label:SetText(text)
self.label:Show()
self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,-18)
self:SetHeight(44)
self.alignoffset = 30
else
self.label:SetText("")
self.label:Hide()
self.editbox:SetPoint("TOPLEFT",self.frame,"TOPLEFT",7,0)
self:SetHeight(26)
self.alignoffset = 12
end
end,
["DisableButton"] = function(self, disabled)
self.disablebutton = disabled
if disabled then
HideButton(self)
end
end,
["SetMaxLetters"] = function (self, num)
self.editbox:SetMaxLetters(num or 0)
end,
["ClearFocus"] = function(self)
self.editbox:ClearFocus()
self.frame:SetScript("OnShow", nil)
end,
["SetFocus"] = function(self)
self.editbox:SetFocus()
if not self.frame:IsShown() then
self.frame:SetScript("OnShow", Frame_OnShowFocus)
end
end
}
--[[-----------------------------------------------------------------------------
Constructor
-------------------------------------------------------------------------------]]
local function Constructor()
local num = AceGUI:GetNextWidgetNum(Type)
local frame = CreateFrame("Frame", nil, UIParent)
frame:Hide()
local editbox = CreateFrame("EditBox", "AceGUI-3.0EditBox"..num, frame, "InputBoxTemplate")
editbox:SetAutoFocus(false)
editbox:SetFontObject(ChatFontNormal)
editbox:SetScript("OnEnter", Control_OnEnter)
editbox:SetScript("OnLeave", Control_OnLeave)
editbox:SetScript("OnEscapePressed", EditBox_OnEscapePressed)
editbox:SetScript("OnEnterPressed", EditBox_OnEnterPressed)
editbox:SetScript("OnTextChanged", EditBox_OnTextChanged)
editbox:SetScript("OnReceiveDrag", EditBox_OnReceiveDrag)
editbox:SetScript("OnMouseDown", EditBox_OnReceiveDrag)
editbox:SetScript("OnEditFocusGained", EditBox_OnFocusGained)
editbox:SetTextInsets(0, 0, 3, 3)
editbox:SetMaxLetters(256)
editbox:SetPoint("BOTTOMLEFT", 6, 0)
editbox:SetPoint("BOTTOMRIGHT")
editbox:SetHeight(19)
local label = frame:CreateFontString(nil, "OVERLAY", "GameFontNormalSmall")
label:SetPoint("TOPLEFT", 0, -2)
label:SetPoint("TOPRIGHT", 0, -2)
label:SetJustifyH("LEFT")
label:SetHeight(18)
local button = CreateFrame("Button", nil, editbox, "UIPanelButtonTemplate")
button:SetWidth(40)
button:SetHeight(20)
button:SetPoint("RIGHT", -2, 0)
button:SetText(OKAY)
button:SetScript("OnClick", Button_OnClick)
button:Hide()
local widget = {
alignoffset = 30,
editbox = editbox,
label = label,
button = button,
frame = frame,
type = Type
}
for method, func in pairs(methods) do
widget[method] = func
end
editbox.obj, button.obj = widget, widget
return AceGUI:RegisterAsWidget(widget)
end
AceGUI:RegisterWidgetType(Type, Constructor, Version)
| bsd-3-clause |
Fatalerror66/ffxi-a | scripts/zones/Port_Jeuno/npcs/Moulloie.lua | 5 | 1029 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Moulloie
-- Type: Standard NPC
-- @zone: 246
-- @pos: -77.724 7.003 59.044
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x002e);
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 |
actionless/awesome | lib/wibox/container/constraint.lua | 1 | 5098 | ---------------------------------------------------------------------------
-- Restrict a widget size using one of multiple available strategies.
--
--@DOC_wibox_container_defaults_constraint_EXAMPLE@
-- @author Lukáš Hrázký
-- @copyright 2012 Lukáš Hrázký
-- @containermod wibox.container.constraint
-- @supermodule wibox.widget.base
---------------------------------------------------------------------------
local setmetatable = setmetatable
local base = require("wibox.widget.base")
local gtable = require("gears.table")
local math = math
local constraint = { mt = {} }
-- Layout a constraint layout
function constraint:layout(_, width, height)
if self._private.widget then
return { base.place_widget_at(self._private.widget, 0, 0, width, height) }
end
end
-- Fit a constraint layout into the given space
function constraint:fit(context, width, height)
local w, h
if self._private.widget then
w = self._private.strategy(width, self._private.width)
h = self._private.strategy(height, self._private.height)
w, h = base.fit_widget(self, context, self._private.widget, w, h)
else
w, h = 0, 0
end
w = self._private.strategy(w, self._private.width)
h = self._private.strategy(h, self._private.height)
return w, h
end
--- The widget to be constrained.
--
-- @property widget
-- @tparam widget widget The widget
-- @interface container
constraint.set_widget = base.set_widget_common
function constraint:get_widget()
return self._private.widget
end
function constraint:get_children()
return {self._private.widget}
end
function constraint:set_children(children)
self:set_widget(children[1])
end
--- Set the strategy to use for the constraining.
-- Valid values are:
--
-- * **max**: Never allow the size to be larger than the limit.
-- * **min**: Never allow the size to tbe below the limit.
-- * **exact**: Force the widget size.
--
-- @property strategy
-- @tparam string strategy Either 'max', 'min' or 'exact'.
-- @propemits true false
function constraint:set_strategy(val)
local func = {
min = function(real_size, limit)
return limit and math.max(limit, real_size) or real_size
end,
max = function(real_size, limit)
return limit and math.min(limit, real_size) or real_size
end,
exact = function(real_size, limit)
return limit or real_size
end
}
if not func[val] then
error("Invalid strategy for constraint layout: " .. tostring(val))
end
self._private.strategy = func[val]
self:emit_signal("widget::layout_changed")
self:emit_signal("property::strategy", val)
end
function constraint:get_strategy()
return self._private.strategy
end
--- Set the maximum width to val. nil for no width limit.
--
-- @property height
-- @tparam number height
-- @propemits true false
function constraint:set_width(val)
self._private.width = val
self:emit_signal("widget::layout_changed")
self:emit_signal("property::width", val)
end
function constraint:get_width()
return self._private.width
end
--- Set the maximum height to val. nil for no height limit.
--
-- @property width
-- @tparam number width
-- @propemits true false
function constraint:set_height(val)
self._private.height = val
self:emit_signal("widget::layout_changed")
self:emit_signal("property::height", val)
end
function constraint:get_height()
return self._private.height
end
--- Reset this layout.
--
--The widget will be unreferenced, strategy set to "max"
-- and the constraints set to nil.
--
-- @method reset
-- @interface container
function constraint:reset()
self._private.width = nil
self._private.height = nil
self:set_strategy("max")
self:set_widget(nil)
end
--- Returns a new constraint container.
--
-- This container will constraint the size of a
-- widget according to the strategy. Note that this will only work for layouts
-- that respect the widget's size, eg. fixed layout. In layouts that don't
-- (fully) respect widget's requested size, the inner widget still might get
-- drawn with a size that does not fit the constraint, eg. in flex layout.
-- @param[opt] widget A widget to use.
-- @param[opt] strategy How to constraint the size. 'max' (default), 'min' or
-- 'exact'.
-- @param[opt] width The maximum width of the widget. nil for no limit.
-- @param[opt] height The maximum height of the widget. nil for no limit.
-- @treturn table A new constraint container
-- @constructorfct wibox.container.constraint
local function new(widget, strategy, width, height)
local ret = base.make_widget(nil, nil, {enable_properties = true})
gtable.crush(ret, constraint, true)
ret:set_strategy(strategy or "max")
ret:set_width(width)
ret:set_height(height)
if widget then
ret:set_widget(widget)
end
return ret
end
function constraint.mt:__call(...)
return new(...)
end
return setmetatable(constraint, constraint.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
githubmereza/rezajack | bot/utils.lua | 646 | 23489 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end
--Check if this chat is realm or not
function is_realm(msg)
local var = false
local realms = 'realms'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(realms)] then
if data[tostring(realms)][tostring(msg.to.id)] then
var = true
end
return var
end
end
--Check if this chat is a group or not
function is_group(msg)
local var = false
local groups = 'groups'
local data = load_data(_config.moderation.data)
local chat = msg.to.id
if data[tostring(groups)] then
if data[tostring(groups)][tostring(msg.to.id)] then
var = true
end
return var
end
end
function savelog(group, logtxt)
local text = (os.date("[ %c ]=> "..logtxt.."\n \n"))
local file = io.open("./groups/logs/"..group.."log.txt", "a")
file:write(text)
file:close()
end
function user_print_name(user)
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
--Check if user is the owner of that group or not
function is_owner(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_owner2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is admin or not
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_admin2(user_id)
local var = false
local data = load_data(_config.moderation.data)
local user = user_id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == user_id then
var = true
end
end
return var
end
--Check if user is the mod of that group or not
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['set_owner'] then
if data[tostring(msg.to.id)]['set_owner'] == tostring(user) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
function is_momod2(user_id, group_id)
local var = false
local data = load_data(_config.moderation.data)
local usert = user_id
if data[tostring(group_id)] then
if data[tostring(group_id)]['moderators'] then
if data[tostring(group_id)]['moderators'][tostring(usert)] then
var = true
end
end
end
if data[tostring(group_id)] then
if data[tostring(group_id)]['set_owner'] then
if data[tostring(group_id)]['set_owner'] == tostring(user_id) then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user_id)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == usert then
var = true
end
end
return var
end
-- Returns the name of the sender
function kick_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_owner2(user_id, chat_id) then -- Ignore admins
return
end
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, ok_cb, true)
end
-- Ban
function ban_user(user_id, chat_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'banned:'..chat_id
redis:sadd(hash, user_id)
-- Kick from chat
kick_user(user_id, chat_id)
end
-- Global ban
function banall_user(user_id)
if tonumber(user_id) == tonumber(our_id) then -- Ignore bot
return
end
if is_admin2(user_id) then -- Ignore admins
return
end
-- Save to redis
local hash = 'gbanned'
redis:sadd(hash, user_id)
end
-- Global unban
function unbanall_user(user_id)
--Save on redis
local hash = 'gbanned'
redis:srem(hash, user_id)
end
-- Check if user_id is banned in chat_id or not
function is_banned(user_id, chat_id)
--Save on redis
local hash = 'banned:'..chat_id
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Check if user_id is globally banned or not
function is_gbanned(user_id)
--Save on redis
local hash = 'gbanned'
local banned = redis:sismember(hash, user_id)
return banned or false
end
-- Returns chat_id ban list
function ban_list(chat_id)
local hash = 'banned:'..chat_id
local list = redis:smembers(hash)
local text = "Ban list !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- Returns globally ban list
function banall_list()
local hash = 'gbanned'
local list = redis:smembers(hash)
local text = "global bans !\n\n"
for k,v in pairs(list) do
text = text..k.." - "..v.." \n"
end
return text
end
-- /id by reply
function get_message_callback_id(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
send_large_msg(chat, result.from.id)
else
return 'Use This in Your Groups'
end
end
-- kick by reply for mods and owner
function Kick_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
-- Kick by reply for admins
function Kick_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't kick myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
else
return 'Use This in Your Groups'
end
end
--Ban by reply for admins
function ban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_momod2(result.from.id, result.to.id) then -- Ignore mods,owner,admin
return "you can't kick mods,owner and admins"
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Ban by reply for admins
function ban_by_reply_admins(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't ban myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
ban_user(result.from.id, result.to.id)
send_large_msg(chat, "User "..result.from.id.." Banned")
else
return 'Use This in Your Groups'
end
end
-- Unban by reply
function unban_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't unban myself"
end
send_large_msg(chat, "User "..result.from.id.." Unbanned")
-- Save on redis
local hash = 'banned:'..result.to.id
redis:srem(hash, result.from.id)
else
return 'Use This in Your Groups'
end
end
function banall_by_reply(extra, success, result)
if result.to.type == 'chat' then
local chat = 'chat#id'..result.to.id
if tonumber(result.from.id) == tonumber(our_id) then -- Ignore bot
return "I won't banall myself"
end
if is_admin2(result.from.id) then -- Ignore admins
return
end
local name = user_print_name(result.from)
banall_user(result.from.id)
chat_del_user(chat, 'user#id'..result.from.id, ok_cb, false)
send_large_msg(chat, "User "..name.."["..result.from.id.."] hammered")
else
return 'Use This in Your Groups'
end
end
| gpl-2.0 |
kidaa/FFXIOrgins | scripts/zones/Davoi/npcs/qm1.lua | 2 | 1365 | -----------------------------------
-- Area: Davoi
-- NPC: ??? (qm1)
-- Involved in Quest: To Cure a Cough
-- @pos -115.830 -0.427 -184.289 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local toCureaCough = player:getQuestStatus(SANDORIA,TO_CURE_A_COUGH);
if(toCureaCough == QUEST_ACCEPTED and player:hasKeyItem(THYME_MOSS) == false) then
player:addKeyItem(THYME_MOSS);
player:messageSpecial(KEYITEM_OBTAINED,THYME_MOSS);
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 |
kidaa/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Ashene.lua | 4 | 1977 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Ashene
-- Standard Merchant NPC
-- @zone 230
-- @pos 70 0 61
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,ASH_THADI_ENE_SHOP_DIALOG);
local stock = {0x4047,4309,1, --Baselard
0x4094,16934,1, --Gladius
0x40a1,21067,1, --Broadsword
0x40c0,35769,1, --Hunting Sword
0x408c,13406,1, --Fleuret
0x4001,129,2, --Cesti
0x4042,1827,2, --Dagger
0x4098,7128,2, --Iron Sword
0x40b6,8294,2, --Longsword
0x4040,140,3, --Bronze Dagger
0x4041,837,3, --Brass Dagger
0x4093,3523,3, --Brass Xiphos
0x4097,241,3, --Bronze Sword
0x40b5,1674,3} --Spatha
showNationShop(player, SANDORIA, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Puccio7/bot-telegram | plugins/twitter_send.lua | 627 | 1555 | do
local OAuth = require "OAuth"
local consumer_key = ""
local consumer_secret = ""
local access_token = ""
local access_token_secret = ""
local client = OAuth.new(consumer_key, consumer_secret, {
RequestToken = "https://api.twitter.com/oauth/request_token",
AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"},
AccessToken = "https://api.twitter.com/oauth/access_token"
}, {
OAuthToken = access_token,
OAuthTokenSecret = access_token_secret
})
function run(msg, matches)
if consumer_key:isempty() then
return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua"
end
if consumer_secret:isempty() then
return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua"
end
if access_token:isempty() then
return "Twitter Access Token is empty, write it in plugins/twitter_send.lua"
end
if access_token_secret:isempty() then
return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua"
end
if not is_sudo(msg) then
return "You aren't allowed to send tweets"
end
local response_code, response_headers, response_status_line, response_body =
client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", {
status = matches[1]
})
if response_code ~= 200 then
return "Error: "..response_code
end
return "Tweet sent"
end
return {
description = "Sends a tweet",
usage = "!tw [text]: Sends the Tweet with the configured account.",
patterns = {"^!tw (.+)"},
run = run
}
end
| apache-2.0 |
lzpfmh/MonaServer | FunctionalTests/www/FunctionalTests/LUATests/Serializers/main.lua | 7 | 2010 | local _dateTime = {__time=1412082917000}
local _bytes = {__raw="\xFF\x00\x14"}
local _array = {2.7,true,{__type="test",key="val"}}
local _map = { map="map", __size=1 }
setmetatable(_map,{__mode="v"})
local _mixed = { prop="prop", "elt1" }
local _notmixed = { { prop="prop" }, "elt1" }
local Object = { -- object
key1 = "value1", -- string
key2 = 2.7, -- number
key3 = true, -- boolean
key4 = _dateTime, -- date
key5 = _bytes, -- bytes
key6 = _array, -- array
key7 = _map, -- map
key8 = { "value", _dateTime, _bytes, _array, _map } -- repeated
}
function Values(cyclic,mixed)
if cyclic then
Object.cyclic = Object
else
Object.cyclic = nil
end
if mixed then
Object.mixed = _mixed
Object.notmixed = nil
else
Object.mixed = nil
Object.notmixed = _mixed
end
return 3.7, Object, nil, "hello"
end
function check(...)
local args = table.pack(...)
if #args~=4 then error(#args.." different of 4") end
if args[1]~=3.7 then error(args[1].." different of 3.7") end
compareTable(Object,args[2],_notmixed)
if args[3]~=nil then error(args[3].." is not nil") end
if args[4]~="hello" then error(args[4].." different of 'hello'") end
end
function AMF()
check(mona:fromAMF(mona:toAMF(Values(true,true))))
end
function AMF0()
check(mona:fromAMF(mona:toAMF0(Values(true,true))))
end
function JSON()
local json = mona:toJSON()
assert(json=="[]")
assert(mona:fromJSON(json)==nil)
json = mona:toJSON({})
assert(json=="[[]]")
compareTable(mona:fromJSON(json),{})
json = mona:toJSON({{}})
assert(json=="[[[]]]")
compareTable(mona:fromJSON(json),{{}})
check(mona:fromJSON( mona:toJSON(Values(false,false))))
end
function XMLRPC()
local xml = mona:toXMLRPC()
assert(xml=="<?xml version=\"1.0\"?><methodResponse><params></params></methodResponse>")
assert(mona:fromXMLRPC(xml)==nil)
check(mona:fromXMLRPC(mona:toXMLRPC(Values(false,false))))
end
function run()
return AMF,AMF0,JSON,XMLRPC
end | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Cape_Teriggan/npcs/Salimardi_RK.lua | 2 | 2967 | -----------------------------------
-- Area: Cape Teriggan
-- NPC: Bright Moon
-- 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");
guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno
guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border
region = VOLLBOW;
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
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
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
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
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 |
kidaa/FFXIOrgins | scripts/zones/The_Eldieme_Necropolis/npcs/_5fd.lua | 4 | 1062 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: Shiva's Gate
-- @pos 110 -34 -60 195
-----------------------------------
package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/The_Eldieme_Necropolis/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
player:messageSpecial(SOLID_STONE);
end
return 0;
end;
--
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Northern_San_dOria/npcs/Chapal-Afal_WW.lua | 2 | 5312 | -----------------------------------
-- Area: Northern Sand Oria
-- NPC: Chapal-Afal, W.W.
-- Type: Conquest NPC
-- @zone 231
-- @pos -59.555, -2.000, 28.178
-- X Grant Signet
-- X Recharge Emperor Band, Empress Band, or Chariot Band
-- X Accepts traded Crystals to fill up the Rank bar to open new Missions.
-- X Sells items in exchange for Conquest Points
-- X Start Supply Run Missions and offers a list of already-delivered supplies.
-- Start an Expeditionary Force by giving an E.F. region insignia to you.
-------------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/conquest");
require("scripts/globals/common");
require("scripts/zones/Northern_San_dOria/TextIDs");
guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, JEUNO
guardtype = 2; -- 1: city, 2: foreign, 3: outpost, 4: border
size = table.getn(WindInv);
inventory = WindInv;
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
tradeConquestGuard(player,npc,trade,guardnation,guardtype);
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then
player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies."
region = player:getVar("supplyQuest_region");
player:delKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region));
player:setVar("supplyQuest_started",0);
player:setVar("supplyQuest_region",0);
player:setVar("supplyQuest_fresh",0);
else
Menu1 = getArg1(guardnation,player);
Menu2 = getExForceAvailable(guardnation,player);
Menu3 = conquestRanking();
Menu4 = getSupplyAvailable(guardnation,player);
Menu5 = player:getNationTeleport(guardnation);
Menu6 = getArg6(player);
Menu7 = player:getCP();
Menu8 = getRewardExForce(guardnation,player);
player:startEvent(0x7ff7,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdateCSID: %u",csid);
--printf("onUpdateOPTION: %u",option);
if(option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if(option == inventory[Item]) then
CPVerify = 1;
if(player:getCP() >= inventory[Item + 1]) then
CPVerify = 0;
end;
player:updateEvent(2,CPVerify,inventory[Item + 2]);
break;
end;
end;
end;
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinishCSID: %u",csid);
--printf("onFinishOPTION: %u",option);
if(option == 1) then
duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600;
player:delStatusEffect(EFFECT_SIGNET);
player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet
elseif(option >= 32768 and option <= 32944) then
for Item = 1,size,3 do
if(option == inventory[Item]) then
if(player:hasItem(inventory[Item + 2]) == 1) then
if(inventory[Item + 2] == 0x3D91) then -- Chariot Band
cannotObtain = 1;
elseif(inventory[Item + 2] == 0x3D92) then -- Empress Band
cannotObtain = 1;
elseif(inventory[Item + 2] == 0x3D93) then -- Emperor Band
cannotObtain = 1;
end
else
cannotObtain = 0;
end
if(player:getFreeSlotsCount() >= 1 and cannotObtain == 0) then
-- Logic to impose limits on exp bands
if (option >= 32933 and option <= 32935) then
if (checkConquestRing(player) > 0) then
player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]);
break;
else
player:setVar("CONQUEST_RING_TIMER",getConquestTally());
end
end
if(player:getNation() == guardnation) then
itemCP = inventory[Item + 1];
else
if(inventory[Item + 1] <= 8000) then
itemCP = inventory[Item + 1] * 2;
else
itemCP = inventory[Item + 1] + 8000;
end;
end;
if(player:hasItem(inventory[Item + 2]) == false) then
player:delCP(itemCP);
player:addItem(inventory[Item + 2],1);
player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]);
end;
break;
end;
end;
elseif(option >= 65541 and option <= 65565) then -- player chose supply quest.
region = option - 65541;
player:addKeyItem(getSupplyKey(region));
player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region));
player:setVar("supplyQuest_started",vanaDay());
player:setVar("supplyQuest_region",region);
player:setVar("supplyQuest_fresh",getConquestTally());
end;
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Western_Altepa_Desert/Zone.lua | 1 | 2276 | -----------------------------------
--
-- Zone: Western_Altepa_Desert (125)
--
-----------------------------------
package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil;
require("scripts/zones/Western_Altepa_Desert/TextIDs");
require("scripts/globals/icanheararainbow");
require("scripts/globals/weather");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn( player, prevZone)
cs = -1;
if( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then
player:setPos( -19.901, 13.607, 440.058, 78);
end
if( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow
cs = 0x0002;
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);
if( csid == 0x0002) then
lightCutsceneUpdate( player); -- Quest: I Can Hear A Rainbow
end
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish( player, csid, option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x0002) then
lightCutsceneFinish( player); -- Quest: I Can Hear A Rainbow
end
end;
function OnZoneWeatherChange(weather)
if(GetMobAction(17289575) == 24 and (weather == WEATHER_DUST_STORM or weather == WEATHER_SAND_STORM)) then
SpawnMob(17289575); -- King Vinegarroon
elseif(GetMobAction(17289575) == 16 and (weather ~= WEATHER_DUST_STORM and weather ~= WEATHER_SAND_STORM)) then
DespawnMob(17289575);
end
end; | gpl-3.0 |
Inorizushi/DDR-EXTREME-JP-SM5 | BGAnimations/ScreenEvaluationOni decorations/stats.lua | 1 | 1765 | local t= Def.ActorFrame{};
local xPosPlayer = {
P1 = SCREEN_CENTER_X-228,
P2 = SCREEN_CENTER_X+228
}
for _, pn in pairs(GAMESTATE:GetEnabledPlayers()) do
local pss = STATSMAN:GetCurStageStats():GetPlayerStageStats(pn)
local function FindText(pss)
return string.format("%02d",pss:GetSongsPassed())
end
t[#t+1] = Def.ActorFrame{
InitCommand=function(self)
local short = ToEnumShortString(pn)
self:x(xPosPlayer[short]):y(SCREEN_CENTER_Y+10):draworder(100)
end;
OnCommand=function(self)
if pn == PLAYER_1 then
self:addx(-172):sleep(0.250):decelerate(0.150):addx(172)
else
self:addx(172):sleep(0.250):decelerate(0.150):addx(-172)
end
end,
OffCommand=function(self)
if pn == PLAYER_1 then
self:sleep(0.6):accelerate(0.150):addx(-172)
else
self:sleep(0.6):accelerate(0.150):addx(172)
end
end,
LoadActor("frame "..ToEnumShortString(pn));
Def.BitmapText{
Font="ScreenEvaluation stage";
InitCommand=function(self) self:xy(8,-16) end,
OnCommand=function(self)
self:settext(FindText(pss))
end
};
Def.Sprite{
InitCommand=function(s) s:xy(pn=='PlayerNumber_P2' and 55 or -55, -6) end,
OnCommand=function(self)
local course = GAMESTATE:GetCurrentCourse()
local stages = course:GetCourseEntries()
if pn == PLAYER_1 then
self:Load(THEME:GetPathB("","ScreenEvaluationOni decorations/bar p1"))
else
self:Load(THEME:GetPathB("","ScreenEvaluationOni decorations/bar p2"))
end;
self:croptop(math.max(0,1-pss:GetPercentDancePoints()))
end;
};
};
end
return t; | mit |
Fatalerror66/ffxi-a | scripts/globals/items/marinara_pizza.lua | 2 | 1691 | -----------------------------------------
-- ID: 5743
-- Item: marinara_pizza
-- Food Effect: 3hours, All Races
-----------------------------------------
-- Health Points 20
-- Attack +20% (cap 50 @ 250 base attack)
-- Accuracy +10% (cap 40+ @ 400+ base accuracy) *Wiki doesnt know for sure, its uncorfirmed on how hight the accuracy caps at, so i just put at 40 for now
-- Undead Killer
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,5743);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_FOOD_ATTP, 20);
target:addMod(MOD_FOOD_ATT_CAP, 50);
target:addMod(MOD_FOOD_ACCP, 10);
target:addMod(MOD_FOOD_ACC_CAP, 40);
target:addMod(MOD_UNDEAD_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_FOOD_ATTP, 20);
target:delMod(MOD_FOOD_ATT_CAP, 50);
target:delMod(MOD_FOOD_ACCP, 10);
target:delMod(MOD_FOOD_ACC_CAP, 40);
target:delMod(MOD_UNDEAD_KILLER, 5);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Katharina.lua | 6 | 1054 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Katharina
-- General Info NPC
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
require("scripts/globals/settings");
function onTrigger(player,npc)
player:startEvent(0x377);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("RESULT:",option);
end; | gpl-3.0 |
mys007/nn | FlattenTable.lua | 18 | 3118 | local FlattenTable, parent = torch.class('nn.FlattenTable', 'nn.Module')
function FlattenTable:__init()
parent.__init(self)
self.output = {}
self.input_map = {}
self.gradInput = {}
end
-- Recursive function to flatten a table (output is a table)
local function flatten(output, input)
local input_map -- has the same structure as input, but stores the
-- indices to the corresponding output
if type(input) == 'table' then
input_map = {}
-- forward DFS order
for i = 1, #input do
input_map[#input_map+1] = flatten(output, input[i])
end
else
input_map = #output + 1
output[input_map] = input -- append the tensor
end
return input_map
end
-- Recursive function to check if we need to rebuild the output table
local function checkMapping(output, input, input_map)
if input_map == nil or output == nil or input == nil then
return false
end
if type(input) == 'table' then
if type(input_map) ~= 'table' then
return false
end
if #input ~= #input_map then
return false
end
-- forward DFS order
for i = 1, #input do
local ok = checkMapping(output, input[i], input_map[i])
if not ok then
return false
end
end
return true
else
if type(input_map) ~= 'number' then
return false
end
return output[input_map] == input
end
end
-- During BPROP we have to build a gradInput with the same shape as the
-- input. This is a recursive function to build up a gradInput
local function inverseFlatten(gradOutput, input_map)
if type(input_map) == 'table' then
local gradInput = {}
for i = 1, #input_map do
gradInput[#gradInput + 1] = inverseFlatten(gradOutput, input_map[i])
end
return gradInput
else
return gradOutput[input_map]
end
end
function FlattenTable:updateOutput(input)
assert(type(input) == 'table', 'input must be a table')
-- to avoid updating rebuilding the flattened table every updateOutput call
-- we will do a DFS pass over the existing output table and the inputs to
-- see if it needs to be rebuilt.
if not checkMapping(self.output, input, self.input_map) then
self.output = {}
self.input_map = flatten(self.output, input)
end
return self.output
end
function FlattenTable:updateGradInput(input, gradOutput)
assert(type(input) == 'table', 'input must be a table')
assert(type(input) == 'table', 'gradOutput must be a table')
-- If the input changes between the updateOutput and updateGradInput call,
-- then we may have to rebuild the input_map! However, let's assume that
-- the input_map is valid and that forward has already been called.
-- However, we should check that the gradInput is valid:
if not checkMapping(gradOutput, self.gradInput, self.input_map) then
self.gradInput = inverseFlatten(gradOutput, self.input_map)
end
return self.gradInput
end
function FlattenTable:type(type)
-- This function just stores references so we don't need to do any type
-- conversions. Just force the tables to be empty.
self.output = {}
self.input_map = {}
end
| bsd-3-clause |
Fatalerror66/ffxi-a | scripts/zones/Port_Jeuno/npcs/Kindlix.lua | 2 | 1446 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Kindlix
-- Standard Merchant NPC
-- @zone 246
-- @pos -18.82, 4, 23.302
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/shop");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x015C);
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 == 0x015C) then
stock = {4167,25, -- Cracker
4168,25, -- Twinkle Shower
4169,25, -- Little Comet
4217,25, -- Sparkling Hand
4215,50, -- Popstar
4216,50, -- Brilliant Snow
4186,100, -- Airborne
4218,100, -- Air Rider
4257,300, -- Papillion
5441,300} -- Angelwing
showShop(player, STATIC, stock);
end
end; | gpl-3.0 |
nenau/naev | dat/scripts/jumpdist.lua | 16 | 2247 | --[[
-- @brief Fetches an array of systems from min to max jumps away from the given
-- system sys.
--
-- The following example gets a random Sirius M class planet between 1 to 6 jumps away.
--
-- @code
-- local planets = {}
-- getsysatdistance( system.cur(), 1, 6,
-- function(s)
-- for i, v in ipairs(s:planets()) do
-- if v:faction() == faction.get("Sirius") and v:class() == "M" then
-- return true
-- end
-- end
-- return false
-- end )
--
-- if #planets == 0 then abort() end -- Sanity in case no suitable planets are in range.
--
-- local index = rnd.rnd(1, #planets)
-- destplanet = planets[index][1]
-- destsys = planets[index][2]
-- @endcode
--
-- @param sys System to calculate distance from or nil to use current system
-- @param min Min distance to check for.
-- @param max Maximum distance to check for.
-- @param filter Optional filter function to use for more details.
-- @param data Data to pass to filter
-- @param hidden Whether or not to consider hidden jumps (off by default)
-- @return The table of systems n jumps away from sys
--]]
function getsysatdistance( sys, min, max, filter, data, hidden )
-- Get default parameters
if sys == nil then
sys = system.cur()
end
if max == nil then
max = min
end
open = { sys }
close = { [sys:name()]=sys }
dist = { [sys:name()]=0 }
-- Run max times
for i=1,max do
nopen = {}
-- Get all the adjacent system of the current set
for _,s in ipairs(open) do
adjsys = s:adjacentSystems( hidden ) -- Get them all
for _,a in ipairs(adjsys) do
-- Must not have been explored previously
if close[ a:name() ] == nil then
nopen[ #nopen+1 ] = a
close[ a:name() ] = a
dist[ a:name() ] = i
end
end
end
open = nopen -- New table becomes the old
end
-- Now we filter the solutions
finalset = {}
for i,s in pairs(close) do
if dist[i] >= min and dist[i] <= max and
(filter == nil or filter(s,data)) then
finalset[ #finalset+1 ] = s
end
end
return finalset
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/spells/diaga_iii.lua | 2 | 1811 | -----------------------------------------
-- Spell: Diaga III
-- Lowers an enemy's defense and gradually deals light elemental damage.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 3;
local dmg = calculateMagicDamage(basedmg,5,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false);
dmg = utils.clamp(dmg, 1, 60);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg,spell:getElement());
--add in final adjustments including the actual damage dealt
local final = finalMagicAdjustments(caster,target,spell,dmg);
-- Calculate duration.
local duration = 120;
-- Check for Bio.
local bio = target:getStatusEffect(EFFECT_BIO);
-- Do it!
if(bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 3) or (DIA_OVERWRITE == 1 and bio:getPower() < 3)) then
target:addStatusEffect(EFFECT_DIA,3,3,duration,FLAG_ERASABLE, 0, 15);
spell:setMsg(2);
else
spell:setMsg(75);
end
-- Try to kill same tier Bio
if(BIO_OVERWRITE == 1 and bio ~= nil) then
if(bio:getPower() <= 3) then
target:delStatusEffect(EFFECT_BIO);
end
end
return final;
end; | gpl-3.0 |
njligames/Engine | cmake.in/ldoc.in/Node.lua | 4 | 21588 |
----
-- @file Node
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:calculateSerializeBufferSize()
end
---- Brief description.
-- @author James Folk, 16-02-11 15:02:45
-- <#Description#>
-- @param dataBuffer <#dataBuffer description#>
-- @param btSerializer <#btSerializer description#>
-- @return
function Node:serialize(dataBuffer, btSerializer)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getClassName()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getType()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getWorldTransform()
end
---- Brief description.
-- The transformation is the combination of the node’s rotation, position, and scale properties. The default transformation is SCNMatrix4Identity.
-- When you set the value of this property, the node’s rotation, orientation, eulerAngles, position, and scale properties automatically change to match the new transform, and vice versa. JLIEngine can perform this conversion only if the transform you provide is a combination of rotation, translation, and scale operations. If you set the value of this property to a skew transformation or to a nonaffine transformation, the values of these properties become undefined. Setting a new value for any of these properties causes JLIEngine to compute a new transformation, discarding any skew or nonaffine operations in the original transformation.
-- @return The Transform for this instance.
function Node:getTransform()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:36
-- <#Description#>
-- @param transform <#transform description#>
-- @return
function Node:setTransform(transform)
end
---- Brief description.
-- The node’s position locates it within the coordinate system of its parent, as modified by the node’s pivot property. The default position is the zero vector, indicating that the node is placed at the origin of the parent node’s coordinate system.
-- @return The Origin for this instance.
function Node:getOrigin()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:56
-- <#Description#>
-- @param origin <#origin description#>
-- @return
function Node:setOrigin(origin)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:02
-- <#Description#>
-- @param origin <#origin description#>
-- @return
function Node:setOrigin(origin)
end
---- Brief description.
-- The four-component rotation vector specifies the direction of the rotation axis in the first three components and the angle of rotation (in radians) in the fourth. The default rotation is the zero vector, specifying no rotation. Rotation is applied relative to the node’s pivot property.
-- The rotation, eulerAngles, and orientation properties all affect the rotational aspect of its transform property. Any change to one of these properties is reflected in the others.
-- @return the Rotation for this instance.
function Node:getRotation()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:22
-- <#Description#>
-- @param rotation <#rotation description#>
-- @return
function Node:setRotation(rotation)
end
---- Brief description.
-- Roll is the rotation about the node’s z-axis, yaw is the rotation about the node’s y-axis, and pitch is the rotation about the node’s x-axis. Rotation is applied relative to the node’s pivot property.
-- @return The Euler Angles for this instance.
function Node:getEulerAngles()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:44
-- <#Description#>
-- @param angles <#angles description#>
-- @return
function Node:setEulerAngles(angles)
end
---- Brief description.
-- The rotation, eulerAngles, and orientation properties all affect the rotational aspect of its transform property. Any change to one of these properties is reflected in the others.
-- @return The Orientation for this instance.
function Node:getOrientation()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:04
-- <#Description#>
-- @param orientation <#orientation description#>
-- @return
function Node:setOrientation(orientation)
end
---- Brief description.
-- Each component of the scale vector multiplies the corresponding dimension of the node’s geometry. The default scale is 1.0 in all three dimensions. For example, applying a scale of (2.0, 0.5, 2.0) to a node containing a cube geometry reduces its height and increases its width and depth. Scaling is applied relative to the node’s pivot property.
-- @return The scale for this instance.
function Node:getScale()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:21
-- <#Description#>
-- @param scale <#scale description#>
-- @return
function Node:setScale(scale)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:30
-- <#Description#>
-- @param scale <#scale description#>
-- @return
function Node:setScale(scale)
end
---- Brief description.
-- A node’s pivot is the transformation between its coordinate space and that used by its position, rotation, and scale properties. The default pivot is SCNMatrix4Identity, specifying that the node’s position locates the origin of its coordinate system, its rotation is about an axis through its center, and its scale is also relative to that center point.
-- Changing the pivot transform alters these behaviors in many useful ways. You can:
-- Offset the node’s contents relative to its position. For example, by setting the pivot to a translation transform you can position a node containing a sphere geometry relative to where the sphere would rest on a floor instead of relative to its center.
-- Move the node’s axis of rotation. For example, with a translation transform you can cause a node to revolve around a faraway point instead of rotating around its center, and with a rotation transform you can tilt the axis of rotation.
-- Adjust the center point and direction for scaling the node. For example, with a translation transform you can cause a node to grow or shrink relative to a corner instead of to its center.
-- @return The Pivot for this instance.
function Node:getPivot()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:55
-- <#Description#>
-- @param pivot <#pivot description#>
-- @return
function Node:setPivot(pivot)
end
---- Brief description.
-- <#Description#>
-- @param emitter <#emitter description#>
-- @return <#return value description#>
function Node:addParticleEmitter(emitter)
end
---- Brief description.
-- <#Description#>
-- @param emitter <#emitter description#>
-- @return <#return value description#>
function Node:removeParticleEmitter(emitter)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:09
-- <#Description#>
-- @return
function Node:removeAllParticleEmitters()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:numberOfParticleEmitters()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:19
-- <#Description#>
-- @param particleEmitters <#particleEmitters description#>
-- @return
function Node:getParticleEmitters(particleEmitters)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function Node:getParticleEmitterIndex(object)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getParticleEmitter(index)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getParticleEmitter(index)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:34
-- <#Description#>
-- @param body <#body description#>
-- @return
function Node:addPhysicsBody(body)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:38
-- <#Description#>
-- @return
function Node:removePhysicsBody()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getPhysicsBody()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getPhysicsBody()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:56
-- <#Description#>
-- @param body <#body description#>
-- @return
function Node:addLight(body)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:03
-- <#Description#>
-- @return
function Node:removeLight()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getLight()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getLight()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:17
-- <#Description#>
-- @param body <#body description#>
-- @return
function Node:addCamera(body)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:21
-- <#Description#>
-- @return
function Node:removeCamera()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getCamera()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getCamera()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:33
-- <#Description#>
-- @param body <#body description#>
-- @return
function Node:addGeometry(body)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:36
-- <#Description#>
-- @return
function Node:removeGeometry()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getGeometry()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getGeometry()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:48
-- <#Description#>
-- @param body <#body description#>
-- @return
function Node:addPhysicsField(body)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:52
-- <#Description#>
-- @return
function Node:removePhysicsField()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getPhysicsField()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getPhysicsField()
end
---- Brief description.
-- <#Description#>
-- @param sound <#sound description#>
-- @return <#return value description#>
function Node:addSound(sound)
end
---- Brief description.
-- <#Description#>
-- @param sound <#sound description#>
-- @return <#return value description#>
function Node:removeSound(sound)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:13
-- <#Description#>
-- @return
function Node:removeAllSounds()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:17
-- <#Description#>
-- @param sounds <#sounds description#>
-- @return
function Node:getSounds(sounds)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function Node:getSoundIndex(object)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getSound(index)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getSound(index)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:36
-- <#Description#>
-- @param opacity <#opacity description#>
-- @return
function Node:setOpacity(opacity)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:54
-- <#Description#>
-- @param transfrom <#transfrom description#>
-- @return
function Node:transformVertices(transfrom)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:57
-- <#Description#>
-- @param transform <#transform description#>
-- @return
function Node:transformVertexColors(transform)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:03
-- <#Description#>
-- @param transform <#transform description#>
-- @return
function Node:transformTextureCoordinates(transform)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getOpacity()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:hasOpacity()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:17
-- <#Description#>
-- @param camera <#camera description#>
-- @return
function Node:hide(camera)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:11
-- <#Description#>
-- @param camera <#camera description#>
-- @return
function Node:show(camera)
end
---- Brief description.
-- <#Description#>
-- @param camera <#camera description#>
-- @return <#return value description#>
function Node:isHidden(camera)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:17
-- <#Description#>
-- @param node <#node description#>
-- @return
function Node:setRenderCategory(node)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getStateMachine()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getStateMachine()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:27
-- <#Description#>
-- @return
function Node:removeStateMachine()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:isTouched()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:34
-- <#Description#>
-- @param enable <#enable description#>
-- @return
function Node:enableTouched(enable)
end
---- Brief description.
-- <#Description#>
-- @param from <#from description#>
-- @param to <#to description#>
-- @param rayContact <#rayContact description#>
-- @param collisionGroup <#collisionGroup description#>
-- @param collisionMask <#collisionMask description#>
-- @return <#return value description#>
function Node:rayTestClosest(from, to, rayContact, collisionGroup, collisionMask)
end
---- Brief description.
-- <#Description#>
-- @param from <#from description#>
-- @param to <#to description#>
-- @param rayContacts <#rayContacts description#>
-- @param numContacts <#numContacts description#>
-- @param collisionGroup <#collisionGroup description#>
-- @param collisionMask <#collisionMask description#>
-- @return <#return value description#>
function Node:rayTestAll(from, to, rayContacts, numContacts, collisionGroup, collisionMask)
end
---- Brief description.
-- <#Description#>
-- @param screenPosition <#screenPosition description#>
-- @param rayContact <#rayContact description#>
-- @param collisionGroup <#collisionGroup description#>
-- @param collisionMask <#collisionMask description#>
-- @return <#return value description#>
function Node:rayTestClosest(screenPosition, rayContact, collisionGroup, collisionMask)
end
---- Brief description.
-- <#Description#>
-- @param screenPosition <#screenPosition description#>
-- @param rayContacts <#rayContacts description#>
-- @param numContacts <#numContacts description#>
-- @param collisionGroup <#collisionGroup description#>
-- @param collisionMask <#collisionMask description#>
-- @return <#return value description#>
function Node:rayTestAll(screenPosition, rayContacts, numContacts, collisionGroup, collisionMask)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:57
-- <#Description#>
-- @param action <#action description#>
-- @param callCompletionFunction <#callCompletionFunction description#>
-- @return
function Node:runAction(action, callCompletionFunction)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:02
-- <#Description#>
-- @param action <#action description#>
-- @param key <#key description#>
-- @param callCompletionFunction <#callCompletionFunction description#>
-- @return
function Node:runAction(action, key, callCompletionFunction)
end
---- Brief description.
-- <#Description#>
-- @param key <#key description#>
-- @return <#return value description#>
function Node:removeAction(key)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:08
-- <#Description#>
-- @return
function Node:removeAllActions()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:12
-- <#Description#>
-- @param aabbMin <#aabbMin description#>
-- @param aabbMax <#aabbMax description#>
-- @return
function Node:getAabb(aabbMin, aabbMax)
end
---- Brief description.
-- <#Description#>
-- <#Description#>
-- <#Description#>
-- <#Description#>
-- <#Description#>
-- @return <#return value description#>
function Node:getParentNode()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:getParentNode()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:hasParentNode()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:30
-- <#Description#>
-- @param parent <#parent description#>
-- @return
function Node:setParentNode(parent)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:40
-- <#Description#>
-- @return
function Node:removeParentNode()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:removeFromParentNode()
end
---- Brief description.
-- <#Description#>
-- @param name <#name description#>
-- @return <#return value description#>
function Node:findChildNode(name)
end
---- Brief description.
-- <#Description#>
-- @param name <#name description#>
-- @return <#return value description#>
function Node:findChildNode(name)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getChildNode(index)
end
---- Brief description.
-- <#Description#>
-- @param index <#index description#>
-- @return <#return value description#>
function Node:getChildNode(index)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:08
-- <#Description#>
-- @param children <#children description#>
-- @return
function Node:getChildrenNodes(children)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function Node:getChildNodeIndex(object)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function Node:hasChildNode(object)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:hasChildrenNodes()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:29
-- <#Description#>
-- @param object <#object description#>
-- @return
function Node:addChildNode(object)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:34
-- <#Description#>
-- @param index <#index description#>
-- @return
function Node:removeChildNode(index)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:38
-- <#Description#>
-- @param object <#object description#>
-- @return
function Node:removeChildNode(object)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:43
-- <#Description#>
-- @return
function Node:removeChildrenNodes()
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function Node:numberOfChildrenNodes()
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:50
-- <#Description#>
-- @param oldChild <#oldChild description#>
-- @param newChild <#newChild description#>
-- @return
function Node:replaceChildNode(oldChild, newChild)
end
---- Brief description.
-- <#Description#>
-- @param size <#size description#>
-- @return <#return value description#>
function NJLI.Node.createArray(size)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:13
-- <#Description#>
-- @param array <#array description#>
-- @param size <#size description#>
-- @return
function NJLI.Node.destroyArray(array, size)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function NJLI.Node.create()
end
---- Brief description.
-- <#Description#>
-- @param builder <#builder description#>
-- @return <#return value description#>
function NJLI.Node.create(builder)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function NJLI.Node.clone(object)
end
---- Brief description.
-- <#Description#>
-- @param object <#object description#>
-- @return <#return value description#>
function NJLI.Node.copy(object)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:41
-- <#Description#>
-- @param object <#object description#>
-- @param destroyChildrenNodes <#destroyChildrenNodes description#>
-- @return
function NJLI.Node.destroy(object, destroyChildrenNodes)
end
---- Brief description.
-- @author James Folk, 16-02-10 21:02:46
-- <#Description#>
-- @param object <#object description#>
-- @param L <#L description#>
-- @param stack_index <#stack_index description#>
-- @return
function NJLI.Node.load(object, L, stack_index)
end
---- Brief description.
-- <#Description#>
-- @return <#return value description#>
function NJLI.Node.type()
end
---- Brief description.
-- @return <#return value description#>
function NJLI.Node.updateActions()
end
| mit |
kidaa/FFXIOrgins | scripts/globals/weaponskills/steel_cyclone.lua | 4 | 1353 | -----------------------------------
-- Steel Cyclone
-- Great Axe weapon skill
-- Skill level: 240
-- Delivers a single-hit attack. Damage varies with TP.
-- In order to obtain Steel Cyclone, the quest The Weight of Your Limits must be completed.
-- Will stack with Sneak Attack.
-- Aligned with the Breeze Gorget, Aqua Gorget & Snow Gorget.
-- Aligned with the Breeze Belt, Aqua Belt & Snow Belt.
-- Element: None
-- Modifiers: STR:50% ; VIT:50%
-- 100%TP 200%TP 300%TP
-- 1.50 1.75 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 3;
params.str_wsc = 0.5; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
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.66;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/The_Shrine_of_RuAvitau/mobs/Seiryu.lua | 2 | 1126 | -----------------------------------
-- Area: Ru'Aun Gardens
-- NPC: Seiryu
-----------------------------------
-----------------------------------
require("scripts/globals/status");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function OnMobSpawn(mob)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob, killer)
end;
-----------------------------------
-- onMonsterMagicPrepare
-----------------------------------
function onMonsterMagicPrepare(mob,target)
-- For some reason, this returns false even when Hundred Fists is active, so... yeah.
-- Core does this:
-- m_PMob->StatusEffectContainer->AddStatusEffect(new CStatusEffect(EFFECT_HUNDRED_FISTS,0,1,0,45));
if (mob:hasStatusEffect(EFFECT_HUNDRED_FISTS,0) == false) then
local rnd = math.random();
if (rnd < 0.5) then
return 186; -- aeroga 3
elseif (rnd < 0.7) then
return 157; -- aero 4
elseif (rnd < 0.9) then
return 208; -- tornado
else
return 237; -- choke
end
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Northern_San_dOria/npcs/Castilchat.lua | 2 | 3230 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Castilchat
-- Starts Quest: Trial Size Trial by Ice
-- @pos -186 0 107 231
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/teleports");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
local count = trade:getItemCount();
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED and trade:hasItemQty(532,1) and count == 1) then
player:messageSpecial(FLYER_REFUSED);
elseif(trade:hasItemQty(1545,1) and player:getQuestStatus(SANDORIA,TRIAL_SIZE_TRIAL_BY_ICE) == QUEST_ACCEPTED and player:getMainJob() == JOB_SMN and count == 1) then -- Trade mini fork of ice
player:startEvent(0x02de,0,1545,4,20);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local TrialSizeByIce = player:getQuestStatus(SANDORIA,TRIAL_SIZE_TRIAL_BY_ICE);
if(player:getMainLvl() >= 20 and player:getMainJob() == JOB_SMN and TrialSizeByIce == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then -- Requires player to be Summoner at least lvl 20
player:startEvent(0x02dd,0,1545,4,20); --mini tuning fork of ice, zone, level
elseif(TrialSizeByIce == QUEST_ACCEPTED) then
local IceFork = player:hasItem(1545);
if(IceFork) then
player:startEvent(0x02c4); --Dialogue given to remind player to be prepared
elseif(IceFork == false and tonumber(os.date("%j")) ~= player:getVar("TrialSizeIce_date")) then
player:startEvent(0x02e1,0,1545,4,20); -- Need another mini tuning fork
else
player:startEvent(0x02f6); -- Standard dialog when you loose, and you don't wait 1 real day
end
elseif(TrialSizeByIce == QUEST_COMPLETED) then
player:startEvent(0x02e0); -- Defeated Avatar
else
player:startEvent(0x02c7); -- Standard dialog
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x02dd and option == 1) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1545);
else
player:setVar("TrialSizeIce_date", 0);
player:addQuest(SANDORIA,TRIAL_SIZE_TRIAL_BY_ICE);
player:addItem(1545);
player:messageSpecial(ITEM_OBTAINED,1545);
end
elseif(csid == 0x02de and option == 0 or csid == 0x02e1) then
if(player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,1545);
else
player:addItem(1545);
player:messageSpecial(ITEM_OBTAINED,1545);
end
elseif(csid == 0x02de and option == 1) then
toCloisterOfFrost(player);
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/weaponskills/leaden_salute.lua | 2 | 4366 | -----------------------------------
-- Leaden Salute
-- Sword weapon skill
-- Skill Level: N/A
-- Delivers a Twofold attack. Damage varies with TP. Death Penalty: Aftermath effect varies with TP.
-- Available only after completing the Unlocking a Myth (Corsair) quest.
-- Aligned with the Shadow Gorget, Soil Gorget & Light Gorget.
-- Aligned with the Shadow Belt, Soil Belt & Light Belt.
-- Element: Darkness
-- Modifiers: AGI:30%
-- 100%TP 200%TP 300%TP
-- 4.00 4.25 4.75
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 4; params.ftp200 = 4.25; params.ftp300 = 4.75;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.3; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
if((player:getEquipID(SLOT_RANGED) == 19007) and (player:getMainJob() == JOB_COR)) then
if(damage > 0) then
-- AFTERMATH LEVEL 1
if ((player:getTP() >= 100) and (player:getTP() <= 110)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 3);
elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 3);
elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 3);
elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 3);
elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 3);
elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 3);
elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 3);
elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 3);
elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 3);
elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 3);
-- AFTERMATH LEVEL 2
elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 4);
elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 4);
elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 4);
elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 4);
elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 4);
elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 4);
elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 4);
elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 4);
elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 4);
elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 4);
-- AFTERMATH LEVEL 3
elseif ((player:getTP() == 300)) then
player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 2);
end
end
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/bowl_of_ocean_soup.lua | 1 | 1824 | -----------------------------------------
-- ID: 4285
-- Item: bowl_of_ocean_soup
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- HP % 5
-- MP 5
-- Dexterity 4
-- Mind -3
-- HP Recovered While Healing 9
-- Attack % 14 (cap 65)
-- Ranged Attack % 14 (cap 65)
-----------------------------------------
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,4285);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 5);
target:addMod(MOD_FOOD_HP_CAP, 999);
target:addMod(MOD_MP, 5);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_MND, -3);
target:addMod(MOD_HPHEAL, 9);
target:addMod(MOD_FOOD_ATTP, 14);
target:addMod(MOD_FOOD_ATT_CAP, 65);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 65);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 5);
target:delMod(MOD_FOOD_HP_CAP, 999);
target:delMod(MOD_MP, 5);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_MND, -3);
target:delMod(MOD_HPHEAL, 9);
target:delMod(MOD_FOOD_ATTP, 14);
target:delMod(MOD_FOOD_ATT_CAP, 65);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 65);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/slice_of_giant_sheep_meat.lua | 1 | 1298 | -----------------------------------------
-- ID: 4372
-- Item: slice_of_giant_sheep_meat
-- Food Effect: 5Min, Galka only
-----------------------------------------
-- Strength 2
-- Intelligence -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 8) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_MEAT) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4372);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 2);
target:addMod(MOD_INT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 2);
target:delMod(MOD_INT, -4);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Al_Zahbi/npcs/Shihu-Danhu.lua | 19 | 2097 | -----------------------------------
-- Area: Al Zahbi
-- NPC: Shihu-Danhu
-- Warp NPC
-- @pos 62.768 -1.98 -51.299 48
-----------------------------------
require("scripts/globals/besieged");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(getAstralCandescence() == 1) then
player:startEvent(0x0067);
else
player:messageSpecial(0); -- Missing the denied due to lack of Astral Candescence message.
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 == 0x0067 and option == 1) then
-- If you use TP, you need to wait 1 real day for using Kaduru TP
player:setVar("ShihuDanhu_TP_date",os.date("%j"));
-- Random TP positions
-- Coordinates marked {R} have been obtained by packet capture from retail. Don't change them.
-- TODO: if we have astral candesence, then
local warp = math.random(1,5);
if(warp == 1) then
player:setPos(-1.015, 8.999, -52.962, 192, 243); -- Ru Lude Gardens (H-9) {R}
elseif(warp == 2) then
player:setPos(382.398, 7.314, -106.298, 160, 105); -- Batallia Downs (K-8) {R}
elseif(warp == 3) then
player:setPos(-327.238, 2.914, 438.421, 130, 120); -- Sauromugue Champaign {R}
elseif(warp == 4) then
player:setPos(213.785, 16.356, 419.961, 218, 110); -- Rolanberry Fields (J-6) {R}
elseif(warp == 5) then
player:setPos(167.093, 18.095, -213.352, 73, 126); -- Qufim Island (I-9) {R}
end
-- TODO: elseif candesence is lost, then
-- tele to bat downs, rolanberry, qufim, sauro. POSITIONS ARE DIFFERENT. need packet captures.
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/spells/silencega.lua | 5 | 1206 | -----------------------------------------
-- Spell: Silence
-----------------------------------------
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local effectType = EFFECT_SILENCE;
if(target:hasStatusEffect(effectType)) then
spell:setMsg(75); -- no effect
return effectType;
end
--Pull base stats.
local dMND = (caster:getStat(MOD_MND) - target:getStat(MOD_MND));
--local bonus = AffinityBonus(caster, spell:getElement()); Removed: affinity bonus is added in applyResistance
--Duration, including resistance. May need more research.
local duration = 180;
--Resist
local resist = applyResistanceEffect(caster,spell,target,dMND,35,0,EFFECT_SILENCE);
if(resist >= 0.5) then --Do it!
if(target:addStatusEffect(effectType,1,0,duration * resist)) then
spell:setMsg(236);
else
spell:setMsg(75); -- no effect
end
else
spell:setMsg(85);
end
return effectType;
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/abilities/wild_flourish.lua | 2 | 1659 | -----------------------------------
-- Ability: Wild Flourish
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/weaponskills");
-----------------------------------
-- OnUseAbility
-----------------------------------
function OnAbilityCheck(player,target,ability)
if (player:getAnimation() ~= 1) then
return MSGBASIC_REQUIRES_COMBAT,0;
else
if (player:hasStatusEffect(EFFECT_FINISHING_MOVE_1)) then
return MSGBASIC_NO_FINISHINGMOVES,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_2)) then
player:delStatusEffect(EFFECT_FINISHING_MOVE_2);
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_3)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_3);
player:addStatusEffect(EFFECT_FINISHING_MOVE_1,1,0,7200);
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_4)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_4);
player:addStatusEffect(EFFECT_FINISHING_MOVE_2,1,0,7200);
return 0,0;
elseif (player:hasStatusEffect(EFFECT_FINISHING_MOVE_5)) then
player:delStatusEffectSilent(EFFECT_FINISHING_MOVE_5);
player:addStatusEffect(EFFECT_FINISHING_MOVE_3,1,0,7200);
return 0,0;
else
return MSGBASIC_NO_FINISHINGMOVES,0;
end
end
end;
function OnUseAbility(player, target, ability)
if (not target:hasStatusEffect(EFFECT_CHAINBOUND, 0) and not target:hasStatusEffect(EFFECT_SKILLCHAIN, 0)) then
target:addStatusEffectEx(EFFECT_CHAINBOUND, 0, 1, 0, 5, 0, 1);
else
ability:setMsg(156);
end
return 0, getFlourishAnimation(player:getWeaponSkillType(SLOT_MAIN)), 1;
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Windurst_Waters/npcs/Foi-Mui.lua | 36 | 1418 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Foi-Mui
-- Involved in Quest: Making the Grade
-- Working 100%
-- @zone = 238
-- @pos = 126 -6 162
-----------------------------------
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
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:getQuestStatus(WINDURST,MAKING_THE_GRADE) == QUEST_ACCEPTED) then
player:startEvent(0x01c1); -- During Making the GRADE
else
player:startEvent(0x01ae); -- Standard conversation
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Wedge009/wesnoth | data/ai/micro_ais/cas/ca_protect_unit_move.lua | 6 | 3243 | local LS = wesnoth.require "location_set"
local AH = wesnoth.require "ai/lua/ai_helper.lua"
local BC = wesnoth.require "ai/lua/battle_calcs.lua"
local F = wesnoth.require "functional"
local function get_protected_units(cfg)
local units = {}
for u in wml.child_range(cfg, "unit") do
table.insert(units, AH.get_units_with_moves { id = u.id, side = wesnoth.current.side }[1])
end
return units
end
local ca_protect_unit_move = {}
function ca_protect_unit_move:evaluation(cfg)
if get_protected_units(cfg)[1] then return 94999 end
return 0
end
function ca_protect_unit_move:execution(cfg, data)
-- Find and execute best (safest) move toward goal
local protected_units = get_protected_units(cfg)
-- Need to take the protected units off the map, as they don't count into the map scores
-- as long as they can still move
for _,unit in ipairs(protected_units) do unit:extract() end
local units = wesnoth.units.find_on_map { side = wesnoth.current.side }
local enemy_units = AH.get_attackable_enemies()
local attack_map = BC.get_attack_map(units).units -- enemy attack map
local enemy_attack_map = BC.get_attack_map(enemy_units).units -- enemy attack map
-- Now put the protected units back out there
for _,unit in ipairs(protected_units) do unit:to_map() end
-- We move the weakest (fewest HP unit) first
local unit = F.choose(protected_units, function(u) return - u.hitpoints end)
local goal = {}
for u in wml.child_range(cfg, "unit") do
if (unit.id == u.id) then goal = AH.get_named_loc_xy('goal', u) end
end
local reach_map = AH.get_reachable_unocc(unit)
local terrain_defense_map = LS.create()
reach_map:iter(function(x, y, data1)
terrain_defense_map:insert(x, y, unit:defense_on(wesnoth.current.map[{x, y}]))
end)
local goal_distance_map = LS.create()
reach_map:iter(function(x, y, data1)
goal_distance_map:insert(x, y, wesnoth.map.distance_between(x, y, goal[1], goal[2]))
end)
-- Configuration parameters (no option to change these enabled at the moment)
local enemy_weight = 100.
local my_unit_weight = 1.
local distance_weight = 3.
local terrain_weight = 0.1
-- If there are no enemies left, only distance to goal matters
-- This is to avoid rare situations where moving toward goal rating is canceled by rating for moving away from own units
if (not enemy_units[1]) then
enemy_weight = 0
my_unit_weight = 0
distance_weight = 3
terrain_weight = 0
end
local max_rating, best_hex = - math.huge, nil
for ind,_ in pairs(reach_map.values) do
local rating =
(attack_map.values[ind] or 0) * my_unit_weight
- (enemy_attack_map.values[ind] or 0) * enemy_weight
rating = rating - goal_distance_map.values[ind] * distance_weight
rating = rating + terrain_defense_map.values[ind] * terrain_weight
rating = rating + (enemy_attack_map.values[ind] or 0) / 10.
if (rating > max_rating) then
max_rating, best_hex = rating, ind
end
end
AH.movefull_stopunit(ai, unit, AH.get_LS_xy(best_hex))
end
return ca_protect_unit_move
| gpl-2.0 |
Adirelle/LibPlayerSpells-1.0 | data/Warlock.lua | 1 | 7277 | --[[
LibPlayerSpells-1.0 - Additional information about player spells.
(c) 2013-2014 Adirelle (adirelle@gmail.com)
This file is part of LibPlayerSpells-1.0.
LibPlayerSpells-1.0 is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
LibPlayerSpells-1.0 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 LibPlayerSpells-1.0. If not, see <http://www.gnu.org/licenses/>.
--]]
local lib = LibStub("LibPlayerSpells-1.0")
if not lib then return end
lib:__RegisterSpells("WARLOCK", 70000, 4, {
COOLDOWN = {
698, -- Ritual of Summoning
1122, -- Summon Infernal
6360, -- Whiplash (Succubus) (knockback)
17962, -- Conflagrate
18540, -- Summon Doomguard
29893, -- Create Soulwell
89792, -- Flee (Imp)
104316, -- Call Dreadstalkers
119909, -- Whiplash (Command Demon with Succubus) (knockback)
152108, -- Cataclysm
196586, -- Dimensional Rift (Destruction artifact)
205180, -- Summon Darkglare
211714, -- Thal'kiel's Consumption (Demonology artifact)
DISPEL = {
[ 89808] = "HELPFUL MAGIC", -- Singe Magic (Imp)
[111859] = "PERSONAL MAGIC", -- Grimoire: Imp
[171021] = "HARMFUL MAGIC", -- Torch Magic (Infernal with Grimoire of Supremacy)
},
INTERRUPT = {
19647, -- Spell Lock (Felhunter)
111897, -- Grimoire: Felhunter
119910, -- Spell Lock (Comand Demon with Felhunter)
171138, -- Shadow Lock (Doomguard with Grimoire of Supremacy)
171140, -- Shadow Lock (Command Demon with Doomguard)
},
AURA = {
HELPFUL = {
[ 20707] = "UNIQUE_AURA", -- Soulstone (battle res)
[113942] = "INVERT_AURA UNIQUE_AURA", -- Demonic Gateway
},
HARMFUL = {
17735, -- Suffering (Voidwalker)
48181, -- Haunt
80240, -- Havoc
170995, -- Criple (Doomguard with Grimoire of Supremacy) (slow)
171014, -- Seeth (Infernal with Grimoire of Supremacy)
205179, -- Phantom Singularity
205181, -- Shadowflame
CROWD_CTRL = {
[6789] = "INCAPACITATE", -- Mortal Coil (incapacitate)
DISORIENT = {
5484, -- Howl of Terror (disorient)
6358, -- Seduction (Succubus) (disorient)
},
STUN = {
22703, -- Infernal Awakening (Infernal) (stun)
30283, -- Shadowfury (stun)
89766, -- Axe Toss (Felguard) (stun)
171017, -- Meteor Strike (Infernal with Grimoire of Supremacy) (stun)
},
},
},
PERSONAL = {
48018, -- Demonic Circle
117828, -- Backdraft
119899, -- Cauterize Master (Imp)
196546, -- Conflagration of Chaos (Destruction artifact)
196099, -- Demonic Power
196674, -- Planeswalker (Destruction artifact)
215165, -- Devourer of Life (Destruction artifact)
216708, -- Deadwind Harvester (Affliction artifact)
[196098] = "BURST", -- Soul Harvest
SURVIVAL = {
104773, -- Unending Resolve
108416, -- Dark Pact
},
},
PET = {
755, -- Health Funnel
17767, -- Shadow Bulwark (Voidwalker)
30151, -- Pursuit (Felguard)
89751, -- Felstorm (Felguard)
},
},
},
AURA = {
HELPFUL = {
5697, -- Unending Breath
},
HARMFUL = {
603, -- Doom
689, -- Drain Life
980, -- Agony
27243, -- Seed of Corruption
30108, -- Unstable Affliction
30213, -- Legion Strike (Felguard)
63106, -- Siphon Life
146739, -- Curruption
157736, -- Immolate
196414, -- Eradication
198590, -- Drain Soul
205178, -- Soul Effigy
CROWD_CTRL = {
[ 710] = "INCAPACITATE", -- Banish (incapacitate)
[118699] = "DISORIENT", -- Fear (disorient)
},
},
PERSONAL = {
126, -- Eye of Kilrogg
111400, -- Burning Rush
193440, -- Demonwrath
196304, -- Eternal Struggle (Destruction artifact)
196606, -- Shadowy Inspiration
199281, -- Compounding Horror (Affliction artifact)
205146, -- Demonic Calling
211583, -- Stolen Power (Demonology artifact)
[196104] = "BURST", -- Mana Tap
},
PET = {
7870, -- Lesser Invisibility (Succubus)
112042, -- Threatening Presence (Voidwalker)
134477, -- Threatening Presence (Felguard)
171011, -- Burning Presence (Infernal with Grimoire of Supremacy)
193396, -- Demonic Empowerment
[ 1098] = "INVERT_AURA", -- Enslave Demon
},
},
}, {
-- map aura to provider(s)
[ 6358] = { -- Seduction (Succubus) (disorient)
6358, -- Seduction (Succubus)
111896, -- Grimoire: Succubus
},
[ 17735] = { -- Suffering (Voidwalker)
17735, -- Suffering (Voidwalker)
111895, -- Grimoire: Voidwalker
119907, -- Suffering (Command Demon with Voidwalker)
},
[ 22703] = 1122, -- Infernal Awakening (stun) <- Summon Infernal
[ 89751] = { -- Felstorm (Felguard)
89751, -- Felstorm (Felguard)
119914, -- Felstorm (Command Demon with Felguard)
},
[89766] = { -- Axe Toss (Felguard) (stun)
89766, -- Axe Toss (Felguard)
111898, -- Grimoire: Felguard
},
[113942] = 111771, -- Demonic Gateway
[117828] = 196406, -- Backdraft
[118699] = 5782, -- Fear (disorient)
[119899] = { -- Cauterize Master (Imp)
119899, -- Cauterize Master (Imp)
119905, -- Cauterize Master (Command Demon with Imp)
},
[146739] = 172, -- Curruption
[157736] = 348, -- Immolate
[171017] = { -- Meteor Strike (stun) (Infernal with Grimoire of Supremacy)
171017, -- Meteor Strike (Infernal with Grimoire of Supremacy)
171152, -- Meteor Strike (Command Demon with Infernal)
},
[196099] = 108503, -- Demonic Power <- Grimoire of Sacrifice
[196304] = 196305, -- Eternal Struggle (Destruction artifact)
[196414] = 196412, -- Eradication
[196546] = 219195, -- Conflagration of Chaos (Destruction artifact)
[196606] = 196269, -- Shadowy Inspiration
[196674] = 196675, -- Planeswalker (Destruction artifact)
[199281] = 199282, -- Compounding Horror (Affliction artifact)
[205146] = 205145, -- Demonic Calling
[211583] = 211530, -- Stolen Power (Demonology artifact)
[215165] = 196301, -- Devourer of Life (Destruction artifact)
[216708] = 216698, -- Deadwind Harvester (Affliction artifact) <- Reap Souls
}, {
-- map aura to modified spell(s)
[ 48018] = 48020, -- Demonic Circle -> Demonic Circle (Teleport)
[117828] = { -- Backdraft
29722, -- Incinerate
116858, -- Chaos Bolt
},
[196304] = 1454, -- Eternal Struggle (Destruction artifact) -> Life Tap
[196414] = 116858, -- Eradication -> Chaos Bolt
[196546] = 17962, -- Conflagration of Chaos (Destruction artifact) -> Conflagration
[196606] = { -- Shadowy Inspiration
686, -- Shadow Bolt
157695, -- Demonbolt
},
[196674] = 111771, -- Planeswalker (Destruction artifact) -> Demonic Gateway
[199281] = 30108, -- Compounding Horror (Affliction artifact) -> Unstable Affliction
[205146] = 104316, -- Demonic Calling -> Call Dreadstalkers
[211583] = { -- Stolen Power (Demonology artifact)
686, -- Shadow Bolt
157695, -- Demonbolt
},
[215165] = 689, -- Devourer of Life (Destruction artifact) -> Drain Life
})
| gpl-3.0 |
mam1/Pcon-TNG | ESP8266/MQTT/barn-unheated/init.lua | 1 | 2018 | -- init.lua
SSID="FrontierHSI" -- SSID
PASSWORD="passfire" -- SSID password
HOSTNAME="MQTT-DHT22-barn-unheated"
TIMEOUT=100000 -- timeout to check the network status
EXSENSOR1="tempumid.lua" -- module to run
MQTTSERVER="192.168.254.220" -- mqtt broker address
MQTTPORT="1883" -- mqtt broker port
MQTTQOS="0" -- qos used
print('\n *** MQTT init.lua ver 1.01')
-- setup I2c and connect display
-- function init_i2c_display()
-- -- SDA and SCL can be assigned freely to available GPIOs
-- local sda = 6
-- local scl = 5
-- local sla = 0x3c
-- print(" initializing I2c OLED display on pins "..sda.." and "..scl)
-- i2c.setup(0, sda, scl, i2c.SLOW)
-- disp = u8g2.ssd1306_i2c_128x64_noname(id, sla)
-- disp:setFont(u8g.font_6x10)
-- disp:setFontRefHeightExtendedText()
-- disp:setDefaultForegroundColor()
-- disp:setFontPosTop()
-- disp:setColorIndex(1)
-- end
-- function draw(str)
-- disp:drawStr(10,10,str)
-- end
-- Set the network parameters and get ip address
station_cfg={}
station_cfg.ssid=SSID
station_cfg.pwd=PASSWORD
station_cfg.save=true
wifi.sta.config(station_cfg)
wifi.sta.sethostname(HOSTNAME)
wifi.sta.autoconnect(0)
wifi.setmode(wifi.STATION)
print(' set mode=STATION (mode='..wifi.getmode()..')')
print(' MAC: ',wifi.sta.getmac())
print(' chip: ',node.chipid())
print(' heap: ',node.heap())
print(' ')
-- Check the network status after the TIMEOUT interval
wifi.sta.connect()
tmr.alarm(1,1000,1,function()
if wifi.sta.getip()==nil then
print(" IP unavailable, waiting")
else
tmr.stop(1)
print("\n Config done, IP is "..wifi.sta.getip())
print(" hostname: "..wifi.sta.gethostname())
print(" ESP8266 mode is: " .. wifi.getmode())
print(" MAC address is: " .. wifi.ap.getmac())
-- init_i2c_display()
print("\n starting sensor read loop")
print(" sending data to MQTT server @ " ..MQTTSERVER)
dofile("tempumid.lua")
end
end)
| mit |
shahabsaf1/arabic | bot/bot.lua | 3 | 6974 | 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 = {
"tagall",
"service_entergroup",
"banhammer",
"google",
"groupmanager",
"help",
"id",
"sticker",
"plugins",
"add_rem",
"version",
"link",
"moderation"},
sudo_users = {119989724},
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 |
smile-tmb/lua-mta-fairplay-roleplay | accounts/server/characters.lua | 1 | 13165 | --[[
The MIT License (MIT)
Copyright (c) 2014 Socialz (+ soc-i-alz GitHub organization)
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 defaultSpawnX, defaultSpawnY, defaultSpawnZ = 1731.03, -1912.05, 13.56
local defaultSpawnRotation = 90
local defaultSpawnInterior, defaultSpawnDimension = 0, 0
function getCharacter( id )
return exports.database:query_single( "SELECT * FROM `characters` WHERE `id` = ?", id )
end
function getCharacterByName( name, null )
return exports.database:query_single( "SELECT " .. ( null and "NULL" or "*" ) .. " FROM `characters` WHERE `name` = ?", name )
end
function verifyCharacterName( name )
name = name:gsub( "%c%d\!\?\=\)\(\\\/\"\#\&\%\[\]\{\}\*\^\~\:\;\>\<", "" ):gsub( "_", " " )
local nameParts = split( name, " " )
if ( #nameParts >= 2 ) then
for i, v in ipairs( nameParts ) do
if ( v:len( ) > 1 ) then
local firstLetter = v:sub( 1, 1 )
if ( firstLetter < 'A' ) or ( firstLetter > 'Z' ) then
return -3, i
end
else
return -2, i
end
end
if ( name:len( ) >= minimumNameLength ) then
if ( name:len( ) <= maximumNameLength ) then
return true
else
return -5
end
else
return -4
end
else
return -1
end
end
addEvent( "characters:create", true )
addEventHandler( "characters:create", root,
function( characterSkinModel, characterName, characterDateOfBirth, characterGender, characterSkinColor, characterOrigin, characterLook, characterLanguage )
if ( source ~= client ) then
return
end
if ( characterName ) and ( characterDateOfBirth ) and ( characterGender ) and ( characterSkinColor ) and ( characterOrigin ) and ( characterLook ) then
local verified, namePart = verifyCharacterName( characterName )
if ( verified == true ) then
characterName = characterName:gsub( "%s", "_" )
if ( not getCharacterByName( characterName ) ) then
local characterID = exports.database:insert_id( "INSERT INTO `characters` (`account`, `skin_id`, `name`, `pos_x`, `pos_y`, `pos_z`, `rotation`, `interior`, `dimension`, `date_of_birth`, `gender`, `skin_color`, `origin`, `look`, `created`) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW())", exports.common:getAccountID( client ), characterSkinModel, characterName, defaultSpawnX, defaultSpawnY, defaultSpawnZ, defaultSpawnRotation, defaultSpawnInterior, defaultSpawnDimension, characterDateOfBirth, characterGender, characterSkinColor, characterOrigin, characterLook )
if ( characterID ) then
exports.database:execute( "INSERT INTO `languages` (`character_id`, `language_1`, `created`) VALUES (?, ?, NOW())", characterID, characterLanguage or 1 )
exports.messages:destroyMessage( client, "selection" )
triggerClientEvent( client, "characters:closeGUI", client )
spawnCharacter( client, characterID, true )
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "selection" )
end
else
triggerClientEvent( client, "messages:create", client, "A character with this name already exists. Please try another name.", "selection" )
end
else
if ( verified == -1 ) then
triggerClientEvent( client, "messages:create", client, "Please enter your first and lastname (e.g. John Doe).", "selection" )
elseif ( verified == -2 ) then
local part = namePart == 1 and "firstname" or "lastname"
triggerClientEvent( client, "messages:create", client, "Please enter a longer " .. part .. ".", "selection" )
elseif ( verified == -3 ) then
local part = namePart == 1 and "firstname" or "lastname"
triggerClientEvent( client, "messages:create", client, "Please enter your " .. part .. " with the starting letter in capital.", "selection" )
elseif ( verified == -4 ) then
triggerClientEvent( client, "messages:create", client, "Character name must be at least " .. minimumNameLength .. " characters long.", "selection" )
elseif ( verified == -5 ) then
triggerClientEvent( client, "messages:create", client, "Character name must be at most " .. maximumNameLength .. " characters long.", "selection" )
end
end
else
triggerClientEvent( client, "messages:create", client, "Oops, something went wrong. Please try again.", "selection" )
end
end
)
addEvent( "characters:selection", true )
addEventHandler( "characters:selection", root,
function( )
if ( source ~= client ) then
return
end
characterSelection( client )
end
)
addEvent( "characters:play", true )
addEventHandler( "characters:play", root,
function( characterName )
if ( source ~= client ) then
return
end
exports.messages:destroyMessage( client, "selection" )
local accountID = exports.common:getAccountID( client )
if ( not accountID ) then
triggerClientEvent( client, "accounts:showLogin", client )
else
characterName = characterName:gsub( " ", "_" )
local character = exports.database:query_single( "SELECT * FROM `characters` WHERE `name` = ? AND `account` = ?", characterName, accountID )
if ( character ) then
if ( character.is_dead == 0 ) then
triggerClientEvent( client, "characters:closeGUI", client, true )
spawnCharacter( client, character, true )
else
outputChatBox( "That character is dead, you cannot play on it anymore.", client, 230, 95, 95 )
end
else
exports.messages:createMessage( client, "Unable to retrieve information for this character. Please try again.", "selection" )
end
end
end
)
function saveCharacter( player )
if ( not isElement( player ) ) then
return
end
if ( exports.common:isPlayerPlaying( player ) ) then
local x, y, z = getElementPosition( player )
local rotation = getPedRotation( player )
local interior = getElementInterior( player )
local dimension = getElementDimension( player )
local skinModel = getElementModel( player )
local characterID = exports.common:getCharacterID( player )
return exports.database:execute( "UPDATE `characters` SET `pos_x` = ?, `pos_y` = ?, `pos_z` = ?, `rotation` = ?, `interior` = ?, `dimension` = ?, `skin_id` = ?, `health` = ?, `armor` = ?, `last_played` = NOW() WHERE `id` = ?", x, y, z, rotation, interior, dimension, skinModel, getElementHealth( player ), getPedArmor( player ), characterID )
end
end
addCommandHandler( "saveme",
function( player )
if ( saveCharacter( player ) ) then
outputChatBox( "Your character has been successfully saved.", player, 95, 230, 95 )
end
end
)
addEventHandler( "onResourceStop", resourceRoot,
function( )
for _, player in ipairs( getElementsByType( "player" ) ) do
saveCharacter( player )
end
end
)
addEventHandler( "onPlayerQuit", root,
function( )
saveCharacter( source )
end
)
function characterSelection( player )
if ( not isElement( player ) ) then
return
end
saveCharacter( player )
triggerEvent( "admin:ticket_left", player )
removeElementData( player, "player:playing" )
removeElementData( player, "player:waiting" )
removeElementData( player, "character:id" )
removeElementData( player, "character:name" )
removeElementData( player, "character:gender" )
removeElementData( player, "character:skin_color" )
removeElementData( player, "character:origin" )
removeElementData( player, "character:look" )
removeElementData( player, "character:date_of_birth" )
removeElementData( player, "character:default_faction" )
removeElementData( player, "character:weight" )
removeElementData( player, "character:max_weight" )
for slot = 1, exports.chat:getMaxLanguages( ) do
removeElementData( player, "character:language_" .. slot )
removeElementData( player, "character:language_" .. slot .. "_skill" )
end
triggerClientEvent( player, "superman:stop", player )
triggerClientEvent( player, "scoreboard:hideHUD", player )
spawnPlayer( player, 0, 0, 0 )
setElementDimension( player, 6000 )
setCameraMatrix( player, 0, 0, 100, 100, 100, 100 )
triggerClientEvent( player, "messages:destroy", player, "selection" )
triggerClientEvent( player, "accounts:showCharacterSelection", player )
updateCharacters( player )
exports.messages:destroyMessage( player, "wait-for-admin" )
end
function spawnCharacter( player, character, fade )
if ( not isElement( player ) ) then
return
end
local character = type( character ) == "number" and getCharacter( character ) or ( type( character ) == "table" and character or nil )
if ( character ) then
function play( player, character )
if ( isElement( player ) ) then
exports.security:modifyElementData( player, "player:playing", true, true )
exports.security:modifyElementData( player, "character:id", character.id, true )
exports.security:modifyElementData( player, "character:name", character.name, true )
exports.security:modifyElementData( player, "character:gender", character.gender, true )
exports.security:modifyElementData( player, "character:skin_color", character.skin_color, true )
exports.security:modifyElementData( player, "character:origin", character.origin, true )
exports.security:modifyElementData( player, "character:look", character.look, true )
exports.security:modifyElementData( player, "character:date_of_birth", character.date_of_birth, true )
exports.security:modifyElementData( player, "character:default_faction", character.default_faction, true )
local languages = exports.database:query_single( "SELECT * FROM `languages` WHERE `character_id` = ?", character.id )
if ( languages ) then
for slot = 1, exports.chat:getMaxLanguages( ) do
exports.security:modifyElementData( player, "character:language_" .. slot, languages[ "language_" .. slot ] or 0, true )
exports.security:modifyElementData( player, "character:language_" .. slot .. "_skill", languages[ "skill_" .. slot ] or 0, true )
end
end
exports.database:query( "UPDATE `characters` SET `last_played` = NOW( ) WHERE `id` = ?", character.id )
triggerClientEvent( player, "accounts:hideView", player )
triggerClientEvent( player, "scoreboard:showHUD", player )
triggerClientEvent( player, "scoreboard:updateHUD", player )
spawnPlayer( player, character.pos_x, character.pos_y, character.pos_z )
setPedRotation( player, character.rotation )
setElementModel( player, character.skin_id )
setElementInterior( player, character.interior )
setElementDimension( player, character.dimension )
if ( character.health > 0 ) then
setElementHealth( player, character.health )
else
killPed( player )
end
setPedArmor( player, character.armor )
setPlayerName( player, character.name )
exports.items:loadItems( player )
exports.factions:loadPlayerFactions( player )
triggerClientEvent( player, "characters:onSpawn", player )
if ( not isPedDead( player ) ) then
setCameraTarget( player, player )
end
local pendingTutorial = get( exports.common:getAccountID( player ) ).tutorial == 0
if ( pendingTutorial ) then
triggerClientEvent( player, "accounts:showTutorial", player )
end
fadeCamera( player, true, 2.0 )
outputChatBox( "Welcome" .. ( not pendingTutorial and " back" or "" ) .. ", " .. character.name:gsub( "_", " " ) .. "!", player, 230, 180, 95 )
if ( not pendingTutorial ) and ( character.last_played ) then
outputChatBox( "You were last seen on this character on " .. exports.common:formatDate( character.last_played, true ) .. ".", player, 230, 180, 95 )
end
exports.admin:updateTickets( player )
end
end
if ( fade ) then
fadeCamera( player, false, 2.725 )
setTimer( play, 2725, 1, player, character )
else
play( )
end
end
end
function updateCharacters( player )
local accountID = exports.common:getAccountID( player )
if ( accountID ) then
local characters = exports.database:query( "SELECT * FROM `characters` WHERE `account` = ?", accountID )
if ( characters ) then
triggerClientEvent( player, "accounts:addCharacters", player, characters )
end
end
end | mit |
infernal1200/infernal | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
RockySeven3161/Unknown. | plugins/danbooru.lua | 616 | 1750 | do
local URL = "http://danbooru.donmai.us"
local URL_NEW = "/posts.json"
local URL_POP = "/explore/posts/popular.json"
local scale_day = "?scale=day"
local scale_week = "?scale=week"
local scale_month = "?scale=month"
local function get_post(url)
local b, c, h = http.request(url)
if c ~= 200 then return nil end
local posts = json:decode(b)
return posts[math.random(#posts)]
end
local function run(msg, matches)
local url = URL
if matches[1] == "!danbooru" then
url = url .. URL_NEW
else
url = url .. URL_POP
if matches[1] == "d" then
url = url .. scale_day
elseif matches[1] == "w" then
url = url .. scale_week
elseif matches[1] == "m" then
url = url .. scale_month
end
end
local post = get_post(url)
if post then
vardump(post)
local img = URL .. post.large_file_url
send_photo_from_url(get_receiver(msg), img)
local txt = ''
if post.tag_string_artist ~= '' then
txt = 'Artist: ' .. post.tag_string_artist .. '\n'
end
if post.tag_string_character ~= '' then
txt = txt .. 'Character: ' .. post.tag_string_character .. '\n'
end
if post.file_size ~= '' then
txt = txt .. '[' .. math.ceil(post.file_size/1000) .. 'kb] ' .. URL .. post.file_url
end
return txt
end
end
return {
description = "Gets a random fresh or popular image from Danbooru",
usage = {
"!danbooru - gets a random fresh image from Danbooru 🔞",
"!danboorud - random daily popular image 🔞",
"!danbooruw - random weekly popular image 🔞",
"!danboorum - random monthly popular image 🔞"
},
patterns = {
"^!danbooru$",
"^!danbooru ?(d)$",
"^!danbooru ?(w)$",
"^!danbooru ?(m)$"
},
run = run
}
end | gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Bastok_Mines/npcs/Trail_Markings.lua | 2 | 2779 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Trail Markings
-- Dynamis-Bastok Enter
-- @pos 99 1 -67 234
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/dynamis");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getVar("Dynamis_Status") == 1) then
player:startEvent(0x00CB); -- cs with Cornelia
elseif(player:getVar("DynaBastok_Win") == 1) then
player:startEvent(0x00d7,HYDRA_CORPS_EYEGLASS); -- Win CS
elseif(player:hasKeyItem(VIAL_OF_SHROUDED_SAND)) then -- and player:hasKeyItem(PRISMATIC_HOURGLASS)) then
local firstDyna = 0;
local realDay = os.time();
local dynaWaitxDay = player:getVar("dynaWaitxDay");
if(checkFirstDyna(player,2)) then -- First Dyna-Bastok => CS
firstDyna = 1;
end
if(player:getMainLvl() < DYNA_LEVEL_MIN) then
player:messageSpecial(PLAYERS_HAVE_NOT_REACHED_LEVEL,DYNA_LEVEL_MIN);
elseif((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay or player:getVar("DynamisID") == GetServerVariable("[DynaBastok]UniqueID")) then
player:startEvent(0x00c9,2,firstDyna,0,BETWEEN_2DYNA_WAIT_TIME,64,VIAL_OF_SHROUDED_SAND,4236,4237);
else
dayRemaining = math.floor(((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) - realDay)/3456);
player:messageSpecial(YOU_CANNOT_ENTER_DYNAMIS,dayRemaining,2);
end
else
player:messageSpecial(UNUSUAL_ARRANGEMENT_PEBBLES);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("updateRESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("finishRESULT: %u",option);
if(csid == 0x00CB) then
player:addKeyItem(VIAL_OF_SHROUDED_SAND);
player:messageSpecial(KEYITEM_OBTAINED,VIAL_OF_SHROUDED_SAND);
player:setVar("Dynamis_Status",0);
elseif(csid == 0x00d7) then
player:setVar("DynaBastok_Win",0);
elseif(csid == 0x00c9 and option == 0) then
if(checkFirstDyna(player,2)) then
player:setVar("Dynamis_Status",player:getVar("Dynamis_Status") + 4);
end
player:setPos(116.482,0.994,-72.121,128,0xba);
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Ship_bound_for_Selbina/npcs/Maera.lua | 3 | 1239 | -----------------------------------
-- Area: Ship bound for Selbina
-- NPC: Maera
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Ship_bound_for_Selbina/TextIDs"] = nil;
require("scripts/zones/Ship_bound_for_Selbina/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MAERA_SHOP_DIALOG);
stock = {0x1010,910, -- Potion
0x1020,4832, -- Ether
0x1034,316, -- Antidote
0x1036,2595, -- Eye Drops
0x1037,800} -- Echo Drops
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/mobskills/Dominion_Slash.lua | 10 | 1573 | ---------------------------------------------
-- Domionion Slash
--
-- Description: Performs an area of effect slashing weaponskill. Additional effect: Silence
-- Type: Physical
-- 2-3 Shadows
-- Range: Unknown radial
-- One source also mentions that it "can dispel important buffs."
---------------------------------------------
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)
-- TODO: Can skillchain? Unknown property.
local numhits = 1;
local accmod = 1;
local dmgmod = 3.25;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_2_SHADOW);
MobStatusEffectMove(mob, target, EFFECT_SILENCE, 1, 0, 60);
-- Due to conflicting information, making the dispel resistable. Correct/tweak if wrong.
-- Dispel has no status effect or resistance gear, so 0s instead of nulls.
local resist = applyPlayerResistance(mob,0,target,mob:getStat(MOD_INT)-target:getStat(MOD_INT),0,ELE_LIGHT);
if(resist > 0.0625) then
target:dispelStatusEffect();
end
-- TODO: Dispel message
-- Damage is HIGHLY conflicting. Witnessed anywhere from 300 to 900.
-- TP DMG VARIES can sort of account for this, but I feel like it's still not right.
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
cosmos53076/easy-quick-cocos2d-x | easy/ui/UITextList.lua | 1 | 4002 | --
-- Author: Jerry Lee
-- Date: 2014-11-04
--
local UIHTMLTextLabel = import(".UIHTMLTextLabel")
local UITextList = class("UITextList", cc.ui.UIListView)
-- 构造函数
function UITextList:ctor(params)
UITextList.super.ctor(self, params)
if params then
self.itemHistory_ = params.itemHistory or 0
self.textColor_ = params.textColor or "#FFFFFF"
self.textFont_ = params.textFont or "Microsoft Yahei"
self.textFontSize_ = params.textFontSize or 14
self.textLineWidth_ = params.textLineWidth or self.viewRect_.width
self.textLineSpace_ = params.textLineSpace or -2
self.shadowColor_ = params.shadowColor or nil
end
self.textList_ = {};
self.scaleToWorldSpace_ = self:scaleToParent_()
end
-- 设置条目显示记录上限
function UITextList:setItemHistory(itemHistory)
self.itemHistory_ = itemHistory or self.itemHistory_
end
-- 添加一条多颜色文本
function UITextList:addText(text, updateVisible, batchMode)
updateVisible = updateVisible or false
batchMode = batchMode or false
local oldX, oldY = self.scrollNode:getPosition()
local item = self:newItem()
local label = UIHTMLTextLabel.new({
color = self.textColor_,
font = self.textFont_,
fontSize = self.textFontSize_,
lineWidth = self.textLineWidth_,
lineSpace = self.textLineSpace_,
shadowColor = self.shadowColor_
})
label:setString(text)
label:setTouchEnabled(false)
local labelSize = label:getContentSize()
item:addContent(label)
item:setItemSize(labelSize.width, labelSize.height, true)
self:addItem(item)
table.insert(self.textList_, text);
if not batchMode then self:reload() end
local deleteFirst = false
local firstItemWidth, firstItemHeight = self.items_[1]:getItemSize()
if self.itemHistory_ > 0 and self:getItemCount() > self.itemHistory_ then
deleteFirst = true
self:removeTextByIndex(1)
end
if updateVisible then
-- 直接到最底部
self:gotToEnd(deleteFirst, firstItemWidth, firstItemHeight)
else
-- 返回原位置
self:moveTo(oldX, oldY - labelSize.height, labelSize.height, firstItemHeight)
end
end
-- 通过索引移除文本
function UITextList:removeTextByIndex(index)
if index > #self.textList_ then return end
self:removeItem(self.items_[index])
table.remove(self.textList_, index)
end
-- 移除整个文本列表
function UITextList:removeTextList()
self:removeAllItems()
self.textList_ = {}
end
-- 导入文本列表
function UITextList:importTextList(list, updateVisible)
updateVisible = updateVisible or false
for i, v in ipairs(list) do
self:addText(v, updateVisible, false)
end
self:reload()
if updateVisible then self:gotToEnd() end
end
-- 导出文本列表
function UITextList:exportTextList()
return self.textList_
end
-- 显示到文本末尾
function UITextList:gotToEnd(deleteFirst, firstItemWidth, firstItemHeight)
deleteFirst = deleteFirst or false
firstItemWidth = firstItemWidth or 0
firstItemHeight = firstItemHeight or 0
local x, y = self.scrollNode:getPosition()
local bound = self:getScrollNodeRect()
local yOffset = 0
if deleteFirst then yOffset = -firstItemHeight end
if bound.height >= self.viewRect_.height then
self.scrollNode:setPosition(x, yOffset)
end
end
-- 滚动结点移动到指定位置
function UITextList:moveTo(x, y, itemHeight, firstItemHeight)
local bound = self:getScrollNodeRect()
if bound.height >= self.viewRect_.height then
self.scrollNode:setPosition(x, y)
end
end
-- 布局方法
function UITextList:layout_()
UITextList.super.layout_(self)
for i, v in ipairs(self.items_) do
local content = v:getContent()
content:setAnchorPoint(0, 0)
end
end
-- 获取列表项数目
function UITextList:getItemCount()
if self.items_ then return #self.items_ else return 0 end
end
-- 阻止父类改变布局
function UITextList:setPositionByAlignment_(content, w, h, margin)
-- body
end
return UITextList | mit |
kidaa/FFXIOrgins | scripts/zones/Dynamis-Xarcabard/mobs/Marquis_Nebiros.lua | 2 | 1210 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Marquis Decarabia
-----------------------------------
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobFight Action
-----------------------------------
function onMobFight(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local Animate_Trigger = GetServerVariable("[DynaXarcabard]Boss_Trigger");
if(mob:isInBattlefieldList() == false) then
mob:addInBattlefieldList();
Animate_Trigger = Animate_Trigger + 16384;
SetServerVariable("[DynaXarcabard]Boss_Trigger",Animate_Trigger);
if(Animate_Trigger == 32767) then
SpawnMob(17330911); -- 142
SpawnMob(17330912); -- 143
SpawnMob(17330183); -- 177
SpawnMob(17330184); -- 178
activateAnimatedWeapon(); -- Change subanim of all animated weapon
end
end
if(Animate_Trigger == 32767) then
killer:messageSpecial(PRISON_OF_SOULS_HAS_SET_FREE);
end
end; | gpl-3.0 |
LipkeGu/OpenRA | mods/d2k/maps/harkonnen-03a/harkonnen03a-AI.lua | 2 | 1707 | --[[
Copyright 2007-2017 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AttackGroupSize =
{
easy = 6,
normal = 8,
hard = 10
}
AttackDelays =
{
easy = { DateTime.Seconds(4), DateTime.Seconds(9) },
normal = { DateTime.Seconds(2), DateTime.Seconds(7) },
hard = { DateTime.Seconds(1), DateTime.Seconds(5) }
}
AtreidesInfantryTypes = { "light_inf", "light_inf", "light_inf", "trooper", "trooper" }
AtreidesVehicleTypes = { "trike", "trike", "quad" }
ActivateAI = function()
IdlingUnits[atreides] = { }
LastHarvesterEaten[atreides] = true
DefendAndRepairBase(atreides, AtreidesBase, 0.75, AttackGroupSize[Difficulty])
AConyard.Produce(HarkonnenUpgrades[1])
AConyard.Produce(HarkonnenUpgrades[2])
local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end
local infantryToBuild = function() return { Utils.Random(AtreidesInfantryTypes) } end
local vehilcesToBuild = function() return { Utils.Random(AtreidesVehicleTypes) } end
local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5
-- Finish the upgrades first before trying to build something
Trigger.AfterDelay(DateTime.Seconds(14), function()
ProduceUnits(atreides, ABarracks, delay, infantryToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
ProduceUnits(atreides, ALightFactory, delay, vehilcesToBuild, AttackGroupSize[Difficulty], attackThresholdSize)
end)
end
| gpl-3.0 |
oralius/gto | plugins/azan.lua | 3 | 3158 | --[[
#
#
#
#
]]
do
function run_bash(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
return result
end
local api_key = nil
local base_api = "https://maps.googleapis.com/maps/api"
function get_latlong(area)
local api = base_api .. "/geocode/json?"
local parameters = "address=".. (URL.escape(area) or "")
if api_key ~= nil then
parameters = parameters .. "&key="..api_key
end
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
if (data.status == "ZERO_RESULTS") then
return nil
end
if (data.status == "OK") then
lat = data.results[1].geometry.location.lat
lng = data.results[1].geometry.location.lng
acc = data.results[1].geometry.location_type
types= data.results[1].types
return lat,lng,acc,types
end
end
function get_staticmap(area)
local api = base_api .. "/staticmap?"
local lat,lng,acc,types = get_latlong(area)
local scale = types[1]
if scale=="locality" then zoom=8
elseif scale=="country" then zoom=4
else zoom = 13 end
local parameters =
"size=600x300" ..
"&zoom=" .. zoom ..
"¢er=" .. URL.escape(area) ..
"&markers=color:red"..URL.escape("|"..area)
if api_key ~=nil and api_key ~= "" then
parameters = parameters .. "&key="..api_key
end
return lat, lng, api..parameters
end
function run(msg, matches)
local hash = 'usecommands:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
local receiver = get_receiver(msg)
local city = matches[1]
if matches[1] == 'azan' then
city = 'Tehran'
end
local lat,lng,url = get_staticmap(city)
local dumptime = run_bash('date +%s')
local code = http.request('http://api.aladhan.com/timings/'..dumptime..'?latitude='..lat..'&longitude='..lng..'&timezonestring=Asia/Tehran&method=7')
local jdat = json:decode(code)
local data = jdat.data.timings
local text = 'شهر: '..city
text = text..'\nاذان صبح: '..data.Fajr
text = text..'\nطلوع آفتاب: '..data.Sunrise
text = text..'\nاذان ظهر: '..data.Dhuhr
text = text..'\nغروب آفتاب: '..data.Sunset
text = text..'\nاذان مغرب: '..data.Maghrib
text = text..'\nعشاء : '..data.Isha
text = text..'\n\n@oralius'
if string.match(text, '0') then text = string.gsub(text, '0', '۰') end
if string.match(text, '1') then text = string.gsub(text, '1', '۱') end
if string.match(text, '2') then text = string.gsub(text, '2', '۲') end
if string.match(text, '3') then text = string.gsub(text, '3', '۳') end
if string.match(text, '4') then text = string.gsub(text, '4', '۴') end
if string.match(text, '5') then text = string.gsub(text, '5', '۵') end
if string.match(text, '6') then text = string.gsub(text, '6', '۶') end
if string.match(text, '7') then text = string.gsub(text, '7', '۷') end
if string.match(text, '8') then text = string.gsub(text, '8', '۸') end
if string.match(text, '9') then text = string.gsub(text, '9', '۹') end
return text
end
return {
patterns = {"^[Aa]zan (.*)$","^[/!#](azan)$","^[#!/][Aa]zan (.*)$","^(azan)$"},
run = run
}
end
| gpl-2.0 |
higankanshi/waifu2x | lib/iproc.lua | 2 | 4495 | local gm = require 'graphicsmagick'
local image = require 'image'
local iproc = {}
local clip_eps8 = (1.0 / 255.0) * 0.5 - (1.0e-7 * (1.0 / 255.0) * 0.5)
function iproc.crop_mod4(src)
local w = src:size(3) % 4
local h = src:size(2) % 4
return iproc.crop(src, 0, 0, src:size(3) - w, src:size(2) - h)
end
function iproc.crop(src, w1, h1, w2, h2)
local dest
if src:dim() == 3 then
dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]:clone()
else -- dim == 2
dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]:clone()
end
return dest
end
function iproc.crop_nocopy(src, w1, h1, w2, h2)
local dest
if src:dim() == 3 then
dest = src[{{}, { h1 + 1, h2 }, { w1 + 1, w2 }}]
else -- dim == 2
dest = src[{{ h1 + 1, h2 }, { w1 + 1, w2 }}]
end
return dest
end
function iproc.byte2float(src)
local conversion = false
local dest = src
if src:type() == "torch.ByteTensor" then
conversion = true
dest = src:float():div(255.0)
end
return dest, conversion
end
function iproc.float2byte(src)
local conversion = false
local dest = src
if src:type() == "torch.FloatTensor" then
conversion = true
dest = (src + clip_eps8):mul(255.0)
dest[torch.lt(dest, 0.0)] = 0
dest[torch.gt(dest, 255.0)] = 255.0
dest = dest:byte()
end
return dest, conversion
end
function iproc.scale(src, width, height, filter)
local conversion, color
src, conversion = iproc.byte2float(src)
filter = filter or "Box"
if src:size(1) == 3 then
color = "RGB"
else
color = "I"
end
local im = gm.Image(src, color, "DHW")
im:size(math.ceil(width), math.ceil(height), filter)
local dest = im:toTensor("float", color, "DHW")
if conversion then
dest = iproc.float2byte(dest)
end
return dest
end
function iproc.scale_with_gamma22(src, width, height, filter)
local conversion
src, conversion = iproc.byte2float(src)
filter = filter or "Box"
local im = gm.Image(src, "RGB", "DHW")
im:gammaCorrection(1.0 / 2.2):
size(math.ceil(width), math.ceil(height), filter):
gammaCorrection(2.2)
local dest = im:toTensor("float", "RGB", "DHW")
if conversion then
dest = iproc.float2byte(dest)
end
return dest
end
function iproc.padding(img, w1, w2, h1, h2)
local dst_height = img:size(2) + h1 + h2
local dst_width = img:size(3) + w1 + w2
local flow = torch.Tensor(2, dst_height, dst_width)
flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width))
flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width))
flow[1]:add(-h1)
flow[2]:add(-w1)
return image.warp(img, flow, "simple", false, "clamp")
end
function iproc.zero_padding(img, w1, w2, h1, h2)
local dst_height = img:size(2) + h1 + h2
local dst_width = img:size(3) + w1 + w2
local flow = torch.Tensor(2, dst_height, dst_width)
flow[1] = torch.ger(torch.linspace(0, dst_height -1, dst_height), torch.ones(dst_width))
flow[2] = torch.ger(torch.ones(dst_height), torch.linspace(0, dst_width - 1, dst_width))
flow[1]:add(-h1)
flow[2]:add(-w1)
return image.warp(img, flow, "simple", false, "pad", 0)
end
function iproc.white_noise(src, std, rgb_weights, gamma)
gamma = gamma or 0.454545
local conversion
src, conversion = iproc.byte2float(src)
std = std or 0.01
local noise = torch.Tensor():resizeAs(src):normal(0, std)
if rgb_weights then
noise[1]:mul(rgb_weights[1])
noise[2]:mul(rgb_weights[2])
noise[3]:mul(rgb_weights[3])
end
local dest
if gamma ~= 0 then
dest = src:clone():pow(gamma):add(noise)
dest[torch.lt(dest, 0.0)] = 0.0
dest[torch.gt(dest, 1.0)] = 1.0
dest:pow(1.0 / gamma)
else
dest = src + noise
end
if conversion then
dest = iproc.float2byte(dest)
end
return dest
end
local function test_conversion()
local a = torch.linspace(0, 255, 256):float():div(255.0)
local b = iproc.float2byte(a)
local c = iproc.byte2float(a)
local d = torch.linspace(0, 255, 256)
assert((a - c):abs():sum() == 0)
assert((d:float() - b:float()):abs():sum() == 0)
a = torch.FloatTensor({256.0, 255.0, 254.999}):div(255.0)
b = iproc.float2byte(a)
assert(b:float():sum() == 255.0 * 3)
a = torch.FloatTensor({254.0, 254.499, 253.50001}):div(255.0)
b = iproc.float2byte(a)
print(b)
assert(b:float():sum() == 254.0 * 3)
end
--test_conversion()
return iproc
| mit |
Fatalerror66/ffxi-a | scripts/zones/Apollyon/mobs/Apollyon_Cleaner.lua | 2 | 1585 | -----------------------------------
-- Area: Apollyon NE
-- NPC: Apollyon Cleaner
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
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(STATUS_NORMAL);
elseif(mobID ==16933085)then -- timer T1
GetNPCByID(16932864+139):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+139):setStatus(STATUS_NORMAL);
elseif(mobID ==16933087)then -- timer T2
GetNPCByID(16932864+85):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+85):setStatus(STATUS_NORMAL);
elseif(mobID ==16933092)then -- timer T3
GetNPCByID(16932864+94):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+94):setStatus(STATUS_NORMAL);
elseif(mobID ==16933095)then -- recover
GetNPCByID(16932864+141):setPos(mobX,mobY,mobZ);
GetNPCByID(16932864+141):setStatus(STATUS_NORMAL);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Bhaflau_Remnants/Zone.lua | 19 | 1071 | -----------------------------------
--
-- Zone: Bhaflau_Remnants
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Bhaflau_Remnants/TextIDs"] = nil;
require("scripts/zones/Bhaflau_Remnants/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Southern_San_dOria/npcs/Camereine.lua | 2 | 1751 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Camereine
-- Chocobo Vendor
-- @zone 230
-- @pos -8 1 -100
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
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)
price = 100;
gil = player:getGil();
hasLicense = player:hasKeyItem(CHOCOBO_LICENSE);
level = player:getMainLvl();
if (hasLicense and level >= 15) then
player:startEvent(0x0257,price,gil);
else
player:startEvent(0x025a,price,gil);
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("OPTION:",option);
local durationMod = 0;
durationMod = player:getMod(MOD_CHOCOBO_TIME) * 60;
local price = 100;
if (csid == 0x0257 and option == 0) then
if (player:delGil(price)) then
if (player:getMainLvl() >= 20) then
player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,(1800 + durationMod),true);
else
player:addStatusEffectEx(EFFECT_CHOCOBO,EFFECT_CHOCOBO,1,0,(900 + durationMod),true);
end
player:setPos(-126,-62,274,0x65,0x64);
end
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Tavnazian_Safehold/npcs/Chemioue.lua | 4 | 1045 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Chemioue
-- Type: NPC Quest
-- @zone: 26
-- @pos: 82.041 -34.964 67.636
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0118);
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 |
kidaa/FFXIOrgins | scripts/globals/items/timbre_timbers_taco.lua | 1 | 1507 | -----------------------------------------
-- ID: 5173
-- Item: timbre_timbers_taco
-- Food Effect: 1hour, All Races
-----------------------------------------
-- MP 20
-- Vitality -1
-- Agility 5
-- MP Recovered While Healing 3
-- Ranged Accuracy % 8 (cap 15)
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5173);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_MP, 20);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 5);
target:addMod(MOD_MPHEAL, 3);
target:addMod(MOD_FOOD_RACCP, 8);
target:addMod(MOD_FOOD_RACC_CAP, 15);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_MP, 20);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 5);
target:delMod(MOD_MPHEAL, 3);
target:delMod(MOD_FOOD_RACCP, 8);
target:delMod(MOD_FOOD_RACC_CAP, 15);
end;
| gpl-3.0 |
AntonioModer/shine | crt.lua | 8 | 4295 | --[[
The MIT License (MIT)
Copyright (c) 2015 Daniel Oaks
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.
]]--
return {
description = "CRT-like barrel distortion",
new = function(self)
self._x_distortion, self._y_distortion = 0.06, 0.065
self._outline = {25, 25, 26}
self._draw_outline = true
self.canvas = love.graphics.newCanvas()
self.shader = love.graphics.newShader[[
// How much we distort on the x and y axis.
// from 0 to 1
extern float x_distortion;
extern float y_distortion;
vec2 distort_coords(vec2 point)
{
// convert to coords we use for barrel distort function
// turn 0 -> 1 into -1 -> 1
point.x = ((point.x * 2.0) - 1.0);
point.y = ((point.y * -2.0) + 1.0);
// distort
point.x = point.x + (point.y * point.y) * point.x * x_distortion;
point.y = point.y + (point.x * point.x) * point.y * y_distortion;
// convert back to coords glsl uses
// turn -1 -> 1 into 0 -> 1
point.x = ((point.x + 1.0) / 2.0);
point.y = ((point.y - 1.0) / -2.0);
return point;
}
vec4 effect(vec4 color, Image texture, vec2 tc, vec2 _)
{
vec2 working_coords = distort_coords(tc);
return Texel(texture, working_coords);
}
]]
self.shader:send("x_distortion", self._x_distortion)
self.shader:send("y_distortion", self._y_distortion)
end,
distort = function(self, x, y)
local w = love.graphics.getWidth()
local h = love.graphics.getHeight()
-- turn 0 -> w/h into -1 -> 1
local distorted_x = (x / (w / 2)) - 1
local distorted_y = (y / (h / 2)) - 1
distorted_x = distorted_x + (distorted_y * distorted_y) * distorted_x * self._x_distortion
distorted_y = distorted_y + (distorted_x * distorted_x) * distorted_y * self._y_distortion
-- turn -1 -> 1 into 0 -> w/h
distorted_x = (distorted_x + 1) * (w / 2)
distorted_y = (distorted_y + 1) * (h / 2)
return distorted_x, distorted_y
end,
draw = function(self, func, ...)
local s = love.graphics.getShader()
local co = {love.graphics.getColor()}
local b = love.graphics.getBlendMode()
-- draw scene to canvas
self:_render_to_canvas(self.canvas, func, ...)
-- draw outline if required
if self._draw_outline then
love.graphics.setBlendMode('replace')
local width = love.graphics.getLineWidth()
love.graphics.setLineWidth(1)
self.canvas:renderTo(function()
local w = love.graphics.getWidth()
local h = love.graphics.getHeight()
love.graphics.setColor(self._outline)
love.graphics.line(0,0, w,0, w,h, 0,h, 0,0)
end)
love.graphics.setLineWidth(width)
end
-- apply shader to canvas
love.graphics.setColor(co)
love.graphics.setShader(self.shader)
love.graphics.setBlendMode('alpha', 'premultiplied')
love.graphics.draw(self.canvas, 0,0)
love.graphics.setBlendMode(b)
-- reset shader and canvas
love.graphics.setShader(s)
end,
set = function(self, key, value)
if key == "x" then
assert(type(value) == "number")
self._x_distortion = value
self.shader:send("x_distortion", value)
elseif key == "y" then
assert(type(value) == "number")
self._y_distortion = value
self.shader:send("y_distortion", value)
elseif key == "draw_outline" then
assert(type(value) == "boolean")
self._draw_outline = value
elseif key == "outline" then
assert(type(value) == "table")
self._outline = value
else
error("Unknown property: " .. tostring(key))
end
return self
end
}
| mit |
evil-morfar/RCLootCouncil2 | Classes/Data/MLDB.lua | 1 | 4895 | --- MLDB.lua Class for mldb handling.
-- @author Potdisc
-- Create Date: 15/10/2020
--- @type RCLootCouncil
local addon = select(2, ...)
--- @class Data.MLDB
local MLDB = addon.Init "Data.MLDB"
local Comms = addon.Require "Services.Comms"
local private = {
---@class MLDB
mldb = {},
isBuilt = false
}
local magicKey = "|"
local replacements = {
[magicKey .. "1"] = "selfVote",
[magicKey .. "2"] = "multiVote",
[magicKey .. "3"] = "anonymousVoting",
[magicKey .. "4"] = "sort",
[magicKey .. "5"] = "numButtons",
[magicKey .. "6"] = "hideVotes",
[magicKey .. "7"] = "observe",
[magicKey .. "8"] = "buttons",
[magicKey .. "9"] = "rejectTrade",
[magicKey .. "10"] = "requireNotes",
[magicKey .. "11"] = "responses",
[magicKey .. "12"] = "timeout",
[magicKey .. "13"] = "outOfRaid",
[magicKey .. "14"] = "default",
[magicKey .. "15"] = "text",
[magicKey .. "16"] = "color",
[magicKey .. "17"] = "autoGroupLoot"
}
local replacements_inv = tInvert(replacements)
--- Gets a transmittable version of the MLDB
--- @param input MLDB @MLDB to convert. Defaults to addon MLDB.
---@return table @MLDB that's ready for transmit.
function MLDB:GetForTransmit(input)
local mldb = input or (private.isBuilt and private.mldb or private:BuildMLDB())
return private:ReplaceMLDB(mldb, replacements_inv)
end
--- Restores a transmitted MLDB and returns it
---@param input table @Table as returned fr["m
---@see Data.MLDB#GetForTransmit
function MLDB:RestoreFromTransmit(input)
private.mldb = private:ReplaceMLDB(input, replacements)
return private.mldb
end
--- Sends the mldb to the target
--- @param target Player @The target to send to - defaults to "group"
function MLDB:Send(target)
Comms:Send {
target = target,
command = "mldb",
data = {self:GetForTransmit()}
}
end
function MLDB:Get()
return private.isBuilt and private.mldb or private:BuildMLDB()
end
function MLDB:Update()
return private:BuildMLDB()
end
--- Checks if a given value is part of the mldb
---@param val string Value to check
function MLDB:IsKey(val)
return replacements_inv[val] and true or false
end
function private:ReplaceMLDB(mldb, replacement_table)
local ret = {}
for k, v in pairs(mldb) do
if (type(v) == "table") then
v = self:ReplaceMLDB(v, replacement_table)
end
if replacement_table[k] then
ret[replacement_table[k]] = v
else
ret[k] = v
end
end
return ret
end
function private:BuildMLDB()
local db = addon:Getdb()
-- Extract changes to responses/buttons
local changedResponses = {}
for type, responses in pairs(db.responses) do
for i in ipairs(responses) do
if i > db.buttons[type].numButtons then
break
end
if
not addon.defaults.profile.responses[type] or
db.responses[type][i].text ~= addon.defaults.profile.responses[type][i].text or
unpack(db.responses[type][i].color) ~= unpack(addon.defaults.profile.responses[type][i].color)
then
if not changedResponses[type] then
changedResponses[type] = {}
end
changedResponses[type][i] = db.responses[type][i]
end
end
end
local changedButtons = {default = {}}
for type, buttons in pairs(db.buttons) do
for i in ipairs(buttons) do
if i > db.buttons[type].numButtons then
break
end
if
not addon.defaults.profile.buttons[type] or
db.buttons[type][i].text ~= addon.defaults.profile.buttons[type][i].text
then
if not changedButtons[type] then
changedButtons[type] = {}
end
changedButtons[type][i] = {text = db.buttons[type][i].text}
end
end
end
changedButtons.default.numButtons = db.buttons.default.numButtons -- Always include this
self.mldb = {
selfVote = db.selfVote or nil,
multiVote = db.multiVote or nil,
anonymousVoting = db.anonymousVoting or nil,
numButtons = db.buttons.default.numButtons, -- v2.9: Kept as to not break backwards compability on mldb comms. Not used any more
hideVotes = db.hideVotes or nil,
observe = db.observe or nil,
buttons = changedButtons, -- REVIEW I'm not sure if it's feasible to nil out empty tables
responses = changedResponses,
timeout = db.timeout,
rejectTrade = db.rejectTrade or nil,
requireNotes = db.requireNotes or nil,
outOfRaid = db.outOfRaid or nil,
autoGroupLoot = db.autoGroupLoot or nil
}
self.isBuilt = true
return self.mldb
end
| lgpl-3.0 |
ChaosForge/doomrl | bin/core/item.lua | 2 | 3418 | table.merge( item, thing )
function item:is_damaged()
if self.flags[ IF_NOREPAIR ] then return false end
return self.durability < self.maxdurability
end
function item:fix( amount )
if amount == nil then
self.durability = self.maxdurability
return true
else
self.durability = math.min(self.maxdurability, self.durability + amount)
return not self:is_damaged()
end
end
function item:get_mods()
local mods = {}
for c=string.byte("A"),string.byte("Z") do
local count = self:get_mod(string.char(c))
if count > 0 then
mods[string.char(c)] = count
end
end
return mods
end
function item:get_mod_ids()
local mods = {}
local function find( mod_letter )
for _,i in ipairs( items ) do
if i.mod_letter == mod_letter then
return i.id
end
end
return nil
end
for c=string.byte("A"),string.byte("Z") do
local count = self:get_mod(string.char(c))
if count > 0 then
local id = find( string.char(c) )
if id then table.insert( mods, id ) end
end
end
return mods
end
function item:can_overcharge( msg )
if self.flags[ IF_DESTROY ] then
ui.msg("The "..self.name.." is already overcharged!")
return false
end
if self.ammo ~= self.ammomax then
ui.msg("You need a full magazine to overcharge the "..self.name.."!")
return false
end
if not ui.msg_confirm("Are you sure you want to overcharge the "..self.name.."? "..msg, true) then
ui.msg("Chicken.")
return false
end
self.flags[ IF_DESTROY ] = true
self.flags[ IF_NOUNLOAD ] = true
ui.msg("You overcharge the "..self.name.."!")
self.name = "overcharged "..self.name
return true
end
function item:check_mod_array( nextmod, techbonus )
if self.flags[ IF_ASSEMBLED ] then return false end
if not self.flags[ IF_MODIFIED ] then return false end
local function match( sig,mod_array_proto )
if sig ~= mod_array_proto.sig then return false end
if mod_array_proto.request_id and mod_array_proto.request_id ~= self.id then return false end
if mod_array_proto.request_type and mod_array_proto.request_type ~= self.itype then return false end
if mod_array_proto.Match and not mod_array_proto.Match(self) then return false end
if mod_array_proto.level and mod_array_proto.level > techbonus then return false end
return true
end
local mods = self:get_mods()
if mods[nextmod] then
mods[nextmod] = mods[nextmod] + 1
else
mods[nextmod] = 1
end
local modsig = core.mod_list_signature( mods )
local found_mod_array = nil
for _,ma in ipairs(mod_arrays) do
if match(modsig,ma) then
found_mod_array = ma
break
end
end
if not found_mod_array then
return false
end
-- Consider making this string shorter? (e.g. "Special assembly possible! Assemble the "..found_mod_array.name.."?")
if not ui.msg_confirm("Special assembly possible! Do you want to assemble the "..found_mod_array.name.."?") then return false end
ui.msg("You assemble the "..found_mod_array.name..".")
found_mod_array.OnApply(self)
self.color = LIGHTCYAN
if techbonus == 2 then
self.flags[ IF_SINGLEMOD ] = true
else
self.flags[ IF_NONMODABLE ] = true
end
self.flags[ IF_MODIFIED ] = false
self.flags[ IF_ASSEMBLED ] = true
self:clear_mods()
player:add_assembly( found_mod_array.id )
-- Maybe we should add something that handles the correct article
player:add_history("On level @1 he assembled a "..found_mod_array.name.."!")
return true
end
setmetatable(item,getmetatable(thing))
| gpl-2.0 |
BTAxis/naev | dat/ai/tpl/merchant.lua | 5 | 2278 | include("dat/ai/include/basic.lua")
-- Variables
mem.enemy_close = 500 -- Distance enemy is too close for comfort
-- Required control rate
control_rate = 2
-- Required "control" function
function control ()
task = ai.taskname()
enemy = ai.getenemy()
-- Runaway if enemy is near
if task ~= "runaway" and enemy ~= nil and
(ai.dist(enemy) < mem.enemy_close or ai.haslockon()) then
if task ~= nil then
ai.poptask()
end
ai.pushtask("runaway",enemy)
-- Try to jump when far enough away
elseif task == "runaway" then
target = ai.target()
-- Check if should still run.
if not target:exists() then
ai.poptask()
return
end
dist = ai.dist( target )
if mem.attacked then
-- Increment distress
if mem.distressed == nil then
mem.distressed = 10 -- Distresses more quickly at first
else
mem.distressed = mem.distressed + 1
end
-- Check to see if should send distress signal.
if mem.distressed > 10 then
sos()
mem.distressed = 1
end
end
-- See if another enemy is closer
if enemy ~= nil and enemy ~= target then
ai.poptask()
ai.pushtask("runaway",enemy)
end
-- Try to jump.
if dist > 400 then
ai.hyperspace()
end
-- Find something to do
elseif task == nil then
planet = ai.landplanet()
-- planet must exist
if planet == nil then
ai.settimer(0, rnd.int(1000, 3000))
ai.pushtask("enterdelay")
else
mem.land = planet:pos()
ai.pushtask("hyperspace")
ai.pushtask("land")
end
end
end
-- Delays the ship when entering systems so that it doesn't leave right away
function enterdelay ()
if ai.timeup(0) then
ai.pushtask("hyperspace")
end
end
function sos ()
end
-- Required "attacked" function
function attacked ( attacker )
mem.attacked = true
if ai.taskname() ~= "runaway" then
-- Sir Robin bravely ran away
ai.pushtask("runaway", attacker)
else -- run away from the new baddie
ai.poptask()
ai.pushtask("runaway", attacker)
end
end
function create ()
end
| gpl-3.0 |
frutjus/OpenRA | mods/ra/maps/soviet-04b/main.lua | 15 | 4003 |
RunInitialActivities = function()
Harvester.FindResources()
Helper.Destroy()
IdlingUnits()
Trigger.AfterDelay(DateTime.Seconds(1), function()
BringPatrol1()
Trigger.AfterDelay(DateTime.Seconds(5), function()
BringPatrol2()
end)
BuildBase()
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == Greece and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == Greece and building.Health < 3/4 * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
Trigger.OnKilled(Powr, function(building)
BaseBuildings[1][4] = false
end)
Trigger.OnKilled(Barr, function(building)
BaseBuildings[2][4] = false
end)
Trigger.OnKilled(Proc, function(building)
BaseBuildings[3][4] = false
end)
Trigger.OnKilled(Weap, function(building)
BaseBuildings[4][4] = false
end)
Trigger.OnEnteredFootprint(VillageCamArea, function(actor, id)
if actor.Owner == player then
local camera = Actor.Create("camera", true, { Owner = player, Location = VillagePoint.Location })
Trigger.RemoveFootprintTrigger(id)
Trigger.OnAllKilled(Village, function()
camera.Destroy()
end)
end
end)
Trigger.OnAnyKilled(Civs, function()
Trigger.ClearAll(civ1)
Trigger.ClearAll(civ2)
Trigger.ClearAll(civ3)
Trigger.ClearAll(civ4)
local units = Reinforcements.Reinforce(Greece, Avengers, { NRoadPoint.Location }, 0)
Utils.Do(units, function(unit)
unit.Hunt()
end)
end)
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
Trigger.AfterDelay(DateTime.Minutes(2), ProduceArmor)
if Map.Difficulty == "Hard" or Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Seconds(5), ReinfInf)
end
Trigger.AfterDelay(DateTime.Minutes(1), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(3), ReinfInf)
Trigger.AfterDelay(DateTime.Minutes(2), ReinfArmor)
end
Tick = function()
if Greece.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillAll)
player.MarkCompletedObjective(KillRadar)
end
if player.HasNoRequiredUnits() then
Greece.MarkCompletedObjective(BeatUSSR)
end
if Greece.Resources >= Greece.ResourceCapacity * 0.75 then
Greece.Cash = Greece.Cash + Greece.Resources - Greece.ResourceCapacity * 0.25
Greece.Resources = Greece.ResourceCapacity * 0.25
end
if RCheck then
RCheck = false
if Map.Difficulty == "Hard" then
Trigger.AfterDelay(DateTime.Seconds(150), ReinfArmor)
elseif Map.Difficulty == "Medium" then
Trigger.AfterDelay(DateTime.Minutes(5), ReinfArmor)
else
Trigger.AfterDelay(DateTime.Minutes(8), ReinfArmor)
end
end
end
WorldLoaded = function()
player = Player.GetPlayer("USSR")
Greece = Player.GetPlayer("Greece")
RunInitialActivities()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
KillAll = player.AddPrimaryObjective("Defeat the Allied forces.")
BeatUSSR = Greece.AddPrimaryObjective("Defeat the Soviet forces.")
KillRadar = player.AddSecondaryObjective("Destroy Allied Radar Dome to stop enemy\nreinforcements.")
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnKilled(Radar, function()
player.MarkCompletedObjective(KillRadar)
Media.PlaySpeechNotification(player, "ObjectiveMet")
end)
Trigger.OnDamaged(Harvester, function()
Utils.Do(Guards, function(unit)
if not unit.IsDead and not Harvester.IsDead then
unit.AttackMove(Harvester.Location)
end
end)
end)
Camera.Position = StartCamPoint.CenterPosition
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Bastok_Mines/npcs/Sodragamm.lua | 38 | 1086 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Sodragamm
-- Type: Item Deliverer
-- @zone: 234
-- @pos -24.741 -1 -64.944
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, ITEM_DELIVERY_DIALOG);
player:openSendBox();
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 |
Rinnegatamante/Sunshell | LUA/modules/camera.lua | 1 | 3137 | -- Set private "Camera" mode
mode = "Camera"
-- Internal module settings
update_bottom_screen = true
ui_enabled = false
screenshots = false
SetBottomRefresh(false)
SetTopRefresh(false)
Camera.init(TOP_SCREEN, OUTER_CAM, PHOTO_MODE_NORMAL, false)
local scene = OUTER_CAM
local photo_mode = PHOTO_MODE_NORMAL
local resolution = VGA_RES
local function GetPhotoMode(pm)
if pm == PHOTO_MODE_NORMAL then
return "Normal"
elseif pm == PHOTO_MODE_PORTRAIT then
return "Portrait"
elseif pm == PHOTO_MODE_LANDSCAPE then
return "Landscape"
elseif pm == PHOTO_MODE_NIGHTVIEW then
return "Night Mode"
elseif pm == PHOTO_MODE_LETTER then
return "Letter"
end
end
local function GetResolution(pm)
if pm == VGA_RES then
return "VGA (640x480)"
elseif pm == QVGA_RES then
return "QVGA (320x240)"
elseif pm == QQVGA_RES then
return "QQVGA (160x120)"
elseif pm == CIF_RES then
return "CIF (352x288)"
elseif pm == QCIF_RES then
return "QCIF (176x144)"
elseif pm == DS_RES then
return "NDS (256x192)"
elseif pm == HDS_RES then
return "HDS (512x384)"
elseif pm == CTR_RES then
return "3DS (400x240)"
end
end
function UpdateBottomScreen()
-- Clear bottom screen
Screen.clear(BOTTOM_SCREEN)
-- Show controls info
Screen.debugPrint(0,0, "Controls:", selected, BOTTOM_SCREEN)
Screen.debugPrint(0,25, "L = Take Photo", white, BOTTOM_SCREEN)
Screen.debugPrint(0,40, "X = Swap camera scene", white, BOTTOM_SCREEN)
Screen.debugPrint(0,55, "Y = Change Photo Mode", white, BOTTOM_SCREEN)
Screen.debugPrint(0,70, "A = Change Photo Resolution", white, BOTTOM_SCREEN)
-- Show Photo settings
Screen.debugPrint(0,100, "Settings: ", selected, BOTTOM_SCREEN)
Screen.debugPrint(0,125, "Photo Mode: " .. GetPhotoMode(photo_mode), white, BOTTOM_SCREEN)
Screen.debugPrint(0,140, "Resolution: " .. GetResolution(resolution), white, BOTTOM_SCREEN)
end
-- Rendering functions
function AppTopScreenRender()
end
function AppBottomScreenRender()
end
-- Module main cycle
function AppMainCycle()
if update_bottom_screen then
OneshotPrint(UpdateBottomScreen)
update_bottom_screen = false
end
-- Show camera scene
Camera.getOutput()
-- Sets controls triggering
if Controls.check(pad, KEY_L) then
h,m,s = System.getTime()
Camera.takePhoto("/DCIM/"..h.."-"..m.."-"..s..".jpg", resolution, true)
elseif Controls.check(pad, KEY_Y) and not Controls.check(oldpad, KEY_Y) then
photo_mode = photo_mode + 1
if photo_mode > PHOTO_MODE_LETTER then
photo_mode = PHOTO_MODE_NORMAL
end
Camera.init(TOP_SCREEN, scene, photo_mode, false)
update_bottom_screen = true
elseif Controls.check(pad, KEY_A) and not Controls.check(oldpad, KEY_A) then
resolution = resolution + 1
if resolution > CTR_RES then
resolution = VGA_RES
end
update_bottom_screen = true
elseif Controls.check(pad, KEY_X) and not Controls.check(oldpad, KEY_X) then
Camera.term()
if scene == OUTER_CAM then
scene = INNER_CAM
else
scene = OUTER_CAM
end
Camera.init(TOP_SCREEN, scene, photo_mode, false)
elseif Controls.check(pad,KEY_B) or Controls.check(pad,KEY_START) then
Camera.term()
CallMainMenu()
end
end | gpl-3.0 |
dhiaayachi/dynx | resty/router/redis_kv_cache.lua | 1 | 3390 | local _M = {}
local mt = { __index = _M }
local setmetatable = setmetatable
local cjson = require("cjson")
local MINIMUM_TTL = 5
local DEFAULT_PREFIX = "resty_route:"
local client = nil
local function log(log_level, ...)
ngx.log(log_level, "router: " .. cjson.encode({...}))
end
function _M.new(self, index, cl)
client = cl
client:set_timeout(1000)
local _, _ = client:connect("redis-dyn", 6379)
client:select(index)
return setmetatable(self, mt)
end
function addPrefix(Rprefix, key)
local prefix = DEFAULT_PREFIX
if Rprefix ~= nil then
prefix = Rprefix
end
local prefix_key = prefix..key
log(ngx.INFO,"key:", prefix..key)
return prefix_key
end
function _M.set(key, upstream, ttl, Rprefix)
local prefix_key = addPrefix(Rprefix, key)
local res, err = client:hmset(prefix_key,"upstream",upstream,"ttl",ttl)
log(ngx.INFO,"res:", res,"err:",err,"p:",prefix_key,"u:",upstream,"t",ttl)
if not res or res == ngx.null then
return nil, cjson.encode({"Redis api not configured for", prefix_key, err})
end
return res, nil
end
function _M.unset(key,Rprefix)
local prefix = DEFAULT_PREFIX
if Rprefix ~= nil then
prefix = Rprefix
end
local prefix_key = prefix..key
log(ngx.INFO,"key:", prefix..key)
local res, err = client:multi()
if not res then
return nil, cjson.encode({"Redis api not configured 0 for", prefix_key, err})
end
res, err = client:hdel(prefix_key,"upstream")
log(ngx.INFO,"res:", res,"err:",err)
if not res or res == ngx.null then
return nil, cjson.encode({"Redis api not configured 1 for", prefix_key, err})
end
res, err = client:hdel(prefix_key,"ttl")
log(ngx.INFO,"res:", res,"err:",err)
if not res or res == ngx.null then
return nil, cjson.encode({"Redis api not configured 2 for", prefix_key, err})
end
res, err = client:exec()
if not res or res == ngx.null then
return nil, cjson.encode({"Redis api not configured 3 for", prefix_key, err})
end
return cjson.encode(res), nil
end
function _M.flushall()
local ok, err = client:multi()
if not ok then
return nil, cjson.encode({"Not able to clear the DB 1 ", err })
end
ok, err = client:select(1)
if not ok or ok == ngx.null then
return nil, cjson.encode({"Not able to clear the DB 2 ", err})
end
ok, err = client:flushdb()
if not ok or ok == ngx.null then
return nil, cjson.encode({"Not able to clear the DB 3 ", err})
end
ok, err = client:exec()
if not ok or ok == ngx.null then
return nil, cjson.encode({"Redis api not configured 4 ", err})
end
return cjson.encode(ok), nil
end
function _M.lookup(key, Rprefix)
local prefix = DEFAULT_PREFIX
if Rprefix ~= nil then
prefix = Rprefix
end
local prefix_key = prefix..key
log(ngx.INFO,"key:", prefix..key)
local answers, err = client:hmget(prefix_key,"upstream","ttl")
if not answers or #answers ~= 2 then
log(ngx.INFO,"1 - ans:", answers,"err:",err)
return nil, cjson.encode({"Redis query failure", prefix_key, err}), nil
end
if answers[1] == ngx.null then
log(ngx.INFO,"2 - ans:", answers,"err:",err)
return nil, nil, nil
end
local routes = {}
local ttl = MINIMUM_TTL
log(ngx.INFO,"Redis response", answers)
routes[1] = answers[1]
if answers[2] ~= ngx.null then
ttl = answers[2]
end
log(ngx.INFO,"3 - ans:", routes,"err:",err)
return routes, err, ttl
end
return _M
| apache-2.0 |
ceason/epgp-tfatf | libs/LibJSON-1.0/LibStub/LibStub.lua | 184 | 1367 | -- LibStub is a simple versioning stub meant for use in Libraries. http://www.wowace.com/wiki/LibStub for more info
-- LibStub is hereby placed in the Public Domain Credits: Kaelten, Cladhaire, ckknight, Mikk, Ammo, Nevcairiel, joshborke
local LIBSTUB_MAJOR, LIBSTUB_MINOR = "LibStub", 2 -- NEVER MAKE THIS AN SVN REVISION! IT NEEDS TO BE USABLE IN ALL REPOS!
local LibStub = _G[LIBSTUB_MAJOR]
if not LibStub or LibStub.minor < LIBSTUB_MINOR then
LibStub = LibStub or {libs = {}, minors = {} }
_G[LIBSTUB_MAJOR] = LibStub
LibStub.minor = LIBSTUB_MINOR
function LibStub:NewLibrary(major, minor)
assert(type(major) == "string", "Bad argument #2 to `NewLibrary' (string expected)")
minor = assert(tonumber(strmatch(minor, "%d+")), "Minor version must either be a number or contain a number.")
local oldminor = self.minors[major]
if oldminor and oldminor >= minor then return nil end
self.minors[major], self.libs[major] = minor, self.libs[major] or {}
return self.libs[major], oldminor
end
function LibStub:GetLibrary(major, silent)
if not self.libs[major] and not silent then
error(("Cannot find a library instance of %q."):format(tostring(major)), 2)
end
return self.libs[major], self.minors[major]
end
function LibStub:IterateLibraries() return pairs(self.libs) end
setmetatable(LibStub, { __call = LibStub.GetLibrary })
end
| bsd-3-clause |
Fatalerror66/ffxi-a | scripts/globals/items/plate_of_patlican_salata_+1.lua | 2 | 1163 | -----------------------------------------
-- ID: 5583
-- Item: plate_of_patlican_salata_+1
-- Food Effect: 4Hrs, All Races
-----------------------------------------
-- Agility 4
-- Vitality -1
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,5583);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, -1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, -1);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Temple_of_Uggalepih/npcs/_mf8.lua | 2 | 1438 | -----------------------------------
-- Area: Temple of Uggalepih
-- NPC: Granite Door
-- East Granite Door in Manipulator Room (opens with Prelate Key)
-- @pos -11 -8 -99 159
-----------------------------------
package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Temple_of_Uggalepih/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(1137,1) and trade:getItemCount() == 1) then -- Trade Prelate Key
player:tradeComplete();
player:messageSpecial(YOUR_KEY_BREAKS,0000,1137);
GetNPCByID(17428962):openDoor();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getXPos() <= -8) then
player:messageSpecial(THE_DOOR_IS_LOCKED,1137);
else
GetNPCByID(17428962):openDoor();
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Port_San_dOria/npcs/Gallijaux.lua | 2 | 3246 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Gallijaux
-- Starts The Rivalry
-- @zone: 232
-- @pos: -14 -2 -45
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Port_San_dOria/TextIDs");
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
count = trade:getItemCount();
MoatCarp = trade:getItemQty(4401)
ForestCarp = trade:getItemQty(4289)
fishCountVar = player:getVar("theCompetitionFishCountVar");
if(MoatCarp + ForestCarp > 0 and MoatCarp + ForestCarp == count) then
if(player:getQuestStatus(SANDORIA,THE_RIVALRY) == QUEST_ACCEPTED and fishCountVar >= 10000) then -- ultimate reward
player:tradeComplete();
player:addFame(SANDORIA,SAN_FAME*30);
player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp));
player:messageSpecial(GIL_OBTAINED,MoatCarp*10 + ForestCarp*15);
player:startEvent(0x012f);
elseif(player:getQuestStatus(SANDORIA,THE_RIVALRY) >= QUEST_ACCEPTED) then -- regular turn-ins. Still allowed after completion of the quest.
player:tradeComplete();
player:addFame(SANDORIA,SAN_FAME*30);
player:addGil((GIL_RATE*10*MoatCarp) + (GIL_RATE*15*ForestCarp));
totalFish = MoatCarp + ForestCarp + fishCountVar
player:setVar("theCompetitionFishCountVar",totalFish);
player:startEvent(0x012d);
player:messageSpecial(GIL_OBTAINED,MoatCarp*10 + ForestCarp*15);
else
player:startEvent(0x012e);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(SANDORIA,THE_COMPETITION) == QUEST_AVAILABLE and player:getQuestStatus(SANDORIA,THE_RIVALRY) == QUEST_AVAILABLE) then -- If you haven't started either quest yet
player:startEvent(0x012c);
end
-- Cannot find his "default" dialogue so he will not respond to being activated unless he is starting the quest event.
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 == 0x012f) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17386);
else
player:tradeComplete();
player:addItem(17386);
player:messageSpecial(ITEM_OBTAINED, 17386);
player:addTitle(CARP_DIEM);
player:addKeyItem(TESTIMONIAL);
player:messageSpecial(KEYITEM_OBTAINED,TESTIMONIAL);
player:setVar("theCompetitionFishCountVar",0);
player:completeQuest(SANDORIA,THE_RIVALRY);
end
elseif(csid == 0x012c and option == 700) then
player:addQuest(SANDORIA,THE_RIVALRY);
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/weaponskills/freezebite.lua | 6 | 1231 | -----------------------------------
-- Freezebite
-- Great Sword weapon skill
-- Skill Level: 100
-- Delivers an ice elemental attack. Damage varies with TP.
-- Aligned with the Snow Gorget & Breeze Gorget.
-- Aligned with the Snow Belt & Breeze Belt.
-- Element: Ice
-- Modifiers: STR:30% ; INT:20%
-- 100%TP 200%TP 300%TP
-- 1.00 1.50 3.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1.5; params.ftp300 = 3;
params.str_wsc = 0.3; 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;
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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Spire_of_Holla/npcs/_0h3.lua | 8 | 1257 | -----------------------------------
-- Area: Spire_of_Holla
-- NPC: web of regret
-----------------------------------
package.loaded["scripts/zones/Spire_of_Holla/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/zones/Spire_of_Holla/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(TradeBCNM(player,player:getZone(),trade,npc))then
return;
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(EventTriggerBCNM(player,npc))then
return 1;
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("onUpdate CSID: %u",csid);
--printf("onUpdate RESULT: %u",option);
if(EventUpdateBCNM(player,csid,option))then
return;
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("onFinish CSID: %u",csid);
--printf("onFinish RESULT: %u",option);
if(EventFinishBCNM(player,csid,option))then
return;
end
end; | gpl-3.0 |
TeleMafia/mafia | plugins/PL (3).lua | 2 | 97567 | -----my_name_is_ehsan*#@mafia_boy
-----@ENERGY_TEAM FOR UPDATE
-----لطفا پیام بالا رو پاک نکنید
local function modadd(msg)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_admin(msg) then
if not lang then
return '✖️_You are not bot admin_✖️'
else
return '✖️شما مدیر ربات نیستید✖️'
end
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.chat_id_)] then
if not lang then
return '_♻️Group is already added♻️_'
else
return '♻️گروه از قبل ثبت شده بود♻️'
end
end
-- create data array in moderation.json
data[tostring(msg.chat_id_)] = {
owners = {},
mods ={},
banned ={},
is_silent_users ={},
filterlist ={},
settings = {
lock_link = 'yes',
lock_tag = 'yes',
lock_fosh = 'yes',
lock_spam = 'no',
lock_webpage = 'yes',
lock_arabic = 'no',
lock_markdown = 'yes',
flood = 'yes',
lock_bots = 'yes',
lock_forward = 'no',
lock_audio = 'no',
lock_video = 'no',
lock_contact = 'no',
lock_text = 'no',
lock_photos = 'no',
lock_gif = 'no',
lock_location = 'no',
lock_document = 'no',
lock_sticker = 'no',
lock_voice = 'no',
lock_all = 'no'
}
}
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(groups)][tostring(msg.chat_id_)] = msg.chat_id_
save_data(_config.moderation.data, data)
if not lang then
return '*✔️Group has been added✔️*'
else
return '✔️گروه با موفقیت ثبت شد✔️'
end
end
local function modrem(msg)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
if not lang then
return '✖️_You are not bot admin_✖️'
else
return '✖️شما مدیر ربات نیستید✖️'
end
end
local data = load_data(_config.moderation.data)
local receiver = msg.chat_id_
if not data[tostring(msg.chat_id_)] then
if not lang then
return '✖️_Group is not added_✖️'
else
return '✖️گروه ثبت نشده است✖️'
end
end
data[tostring(msg.chat_id_)] = nil
save_data(_config.moderation.data, data)
local groups = 'groups'
if not data[tostring(groups)] then
data[tostring(groups)] = nil
save_data(_config.moderation.data, data)
end data[tostring(groups)][tostring(msg.chat_id_)] = nil
save_data(_config.moderation.data, data)
if not lang then
return '✖️*Group has been removed*✖️'
else
return '✖️گروه با موفقیت حذف شد✖️'
end
end
local function filter_word(msg, word)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.chat_id_)]['filterlist'] then
data[tostring(msg.chat_id_)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.chat_id_)]['filterlist'][(word)] then
if not lang then
return "_Word_ *"..word.."* _is already filtered_"
else
return "_کلمه_ *"..word.."* _از قبل فیلتر بود_"
end
end
data[tostring(msg.chat_id_)]['filterlist'][(word)] = true
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _added to filtered words list_"
else
return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_"
end
end
local function unfilter_word(msg, word)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
if not data[tostring(msg.chat_id_)]['filterlist'] then
data[tostring(msg.chat_id_)]['filterlist'] = {}
save_data(_config.moderation.data, data)
end
if data[tostring(msg.chat_id_)]['filterlist'][word] then
data[tostring(msg.chat_id_)]['filterlist'][(word)] = nil
save_data(_config.moderation.data, data)
if not lang then
return "_Word_ *"..word.."* _removed from filtered words list_"
elseif lang then
return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_"
end
else
if not lang then
return "_Word_ *"..word.."* _is not filtered_"
elseif lang then
return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_"
end
end
end
local function modlist(msg)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.chat_id_)] then
if not lang then
return "✖️_Group is not added_✖️"
else
return "✖️گروه ثبت نشده است✖️"
end
end
-- determine if table is empty
if next(data[tostring(msg.chat_id_)]['mods']) == nil then --fix way
if not lang then
return "✖️_No_ *moderator* _in this group_✖️"
else
return "✖️در حال حاضر هیچ مدیری برای گروه انتخاب نشده است✖️"
end
end
if not lang then
message = '*List of moderators :*\n'
else
message = '*لیست مدیران گروه:*\n'
end
for k,v in pairs(data[tostring(msg.chat_id_)]['mods'])
do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function ownerlist(msg)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local i = 1
if not data[tostring(msg.chat_id_)] then
if not lang then
return "✖️_Group is not added_✖️"
else
return "✖️گروه ثبت نشده است✖️"
end
end
-- determine if table is empty
if next(data[tostring(msg.chat_id_)]['owners']) == nil then --fix way
if not lang then
return "✖️_No_ *owner* _in this group_✖️"
else
return "✖️در حال حاضر هیچ مالکی برای گروه انتخاب نشده است✖️"
end
end
if not lang then
message = '*List of moderators :*\n'
else
message = '*لیست مدیران گروه:*\n'
end
for k,v in pairs(data[tostring(msg.chat_id_)]['owners']) do
message = message ..i.. '- '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function action_by_reply(arg, data)
local hash = "gp_lang:"..data.chat_id_
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not tonumber(data.sender_user_id_) then return false end
if data.sender_user_id_ then
if not administration[tostring(data.chat_id_)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه ثبت نشده است_", 0, "md")
end
end
if cmd == "setowner" then
local function owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "promote" then
local function promote_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "remowner" then
local function rem_owner_cb(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "demote" then
local function demote_cb(arg, data)
local administration = load_data(_config.moderation.data)
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
if cmd == "id" then
local function id_cb(arg, data)
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
tdcli_function ({
ID = "GetUser",
user_id_ = data.sender_user_id_
}, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_})
end
else
if lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_username(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "✖️_Group is not added_✖️", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "✖️_گروه ثبت نشده است_✖️", 0, "md")
end
end
if not arg.username then return false end
if data.id_ then
if data.type_.user_.username_ then
user_name = '@'..check_markdown(data.type_.user_.username_)
else
user_name = check_markdown(data.title_)
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "id" then
return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md")
end
if cmd == "res" then
if not lang then
text = "Result for [ ".. check_markdown(data.type_.user_.username_) .." ] :\n"
.. "".. check_markdown(data.title_) .."\n"
.. " [".. data.id_ .."]"
else
text = "اطلاعات برای [ ".. check_markdown(data.type_.user_.username_) .." ] :\n"
.. "".. check_markdown(data.title_) .."\n"
.. " [".. data.id_ .."]"
return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md')
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
local function action_by_id(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
local cmd = arg.cmd
local administration = load_data(_config.moderation.data)
if not administration[tostring(arg.chat_id)] then
if not lang then
return tdcli.sendMessage(data.chat_id_, "", 0, "✖️_Group is not added_✖️", 0, "md")
else
return tdcli.sendMessage(data.chat_id_, "", 0, "✖️_گروه ثبت نشده است_✖️", 0, "md")
end
end
if not tonumber(arg.user_id) then return false end
if data.id_ then
if data.first_name_ then
if data.username_ then
user_name = '@'..check_markdown(data.username_)
else
user_name = check_markdown(data.first_name_)
end
if cmd == "setowner" then
if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md")
end
end
if cmd == "promote" then
if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md")
end
end
if cmd == "remowner" then
if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md")
end
end
if cmd == "demote" then
if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md")
end
end
administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil
save_data(_config.moderation.data, administration)
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md")
end
end
if cmd == "whois" then
if data.username_ then
username = '@'..check_markdown(data.username_)
else
if not lang then
username = 'not found'
else
username = 'ندارد'
end
end
if not lang then
return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1)
else
return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1)
end
end
else
if not lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
end
end
else
if lang then
return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md")
else
return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md")
end
end
end
---------------Lock Link-------------------
local function lock_link(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "yes" then
if not lang then
return "🔐*Link* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐قفل لینک فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_link"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Link* _Posting Has Been Locked_🔐"
else
return "🔐قفل لینک فعال شد🔐"
end
end
end
local function unlock_link(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_link = data[tostring(target)]["settings"]["lock_link"]
if lock_link == "no" then
if not lang then
return "🔓*Link* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل لینک غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Link* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل لینک غیرفعال شد🔓"
end
end
end
---------------Lock fosh-------------------
local function lock_fosh(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_fosh = data[tostring(target)]["settings"]["lock_fosh"]
if lock_fosh == "yes" then
if not lang then
return "🔐*Fosh* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐فعال فحش فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_fosh"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Fosh* _ Has Been Locked_🔐"
else
return "🔐فعال فحش فعال شد🔐"
end
end
end
local function unlock_fosh(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_fosh = data[tostring(target)]["settings"]["lock_fosh"]
if lock_fosh == "no" then
if not lang then
return "🔓*Fosh* _Is Not Locked_🔓"
elseif lang then
return "🔓فعال فحش غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_fosh"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Fosh* _Has Been Unlocked_🔓"
else
return "🔓فعال فحش غیرفعال شد🔓"
end
end
end
---------------Lock Tag-------------------
local function lock_tag(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "yes" then
if not lang then
return "🔐*Tag* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐قفل تگ فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Tag* _Posting Has Been Locked_🔐"
else
return "🔐قفل تگ فعال شد🔐"
end
end
end
local function unlock_tag(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_tag = data[tostring(target)]["settings"]["lock_tag"]
if lock_tag == "no" then
if not lang then
return "🔓*Tag* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل تگ غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Tag* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل تگ غیرفعال شد🔓"
end
end
end
---------------Lock Mention-------------------
local function lock_mention(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "yes" then
if not lang then
return "🔐*Mention* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐قفل فراخوانی افراد فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Mention* _Posting Has Been Locked_🔐"
else
return "🔐قفل فراخوانی افراد فعال شد🔐"
end
end
end
local function unlock_mention(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_mention = data[tostring(target)]["settings"]["lock_mention"]
if lock_mention == "no" then
if not lang then
return "🔓*Mention* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل فراخوانی افراد غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Mention* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل فراخوانی افراد غیرفعال شد🔓"
end
end
end
---------------Lock Arabic--------------
local function lock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "yes" then
if not lang then
return "🔐*Arabic/Persian* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐قفل کلمات عربی/فارسی فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Arabic/Persian* _Posting Has Been Locked_🔐"
else
return "🔐قفل کلمات عربی/فارسی فعال شد🔐"
end
end
end
local function unlock_arabic(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"]
if lock_arabic == "no" then
if not lang then
return "🔓*Arabic/Persian* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل کلمات عربی/فارسی غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Arabic/Persian* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل کلمات عربی/فارسی غیرفعال شد🔓"
end
end
end
---------------Lock Edit-------------------
local function lock_edit(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "yes" then
if not lang then
return "🔐*Editing* _Is Already Locked_🔐"
elseif lang then
return "🔐ویرایش پیام فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Editing* _Has Been Locked_🔐"
else
return "🔐ویرایش پیام فعال شد🔐"
end
end
end
local function unlock_edit(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_edit = data[tostring(target)]["settings"]["lock_edit"]
if lock_edit == "no" then
if not lang then
return "🔓*Editing* _Is Not Locked_🔓"
elseif lang then
return "🔓ویرایش پیام غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Editing* _Has Been Unlocked_🔓"
else
return "🔓ویرایش پیام غیرفعال شد🔓"
end
end
end
---------------Lock spam-------------------
local function lock_spam(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "yes" then
if not lang then
return "🔐*Spam* _Is Already Locked_🔐"
elseif lang then
return "🔐قفل هرزنامه فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Spam* _Has Been Locked_🔐"
else
return "🔐قفل هرزنامه فعال شد🔐"
end
end
end
local function unlock_spam(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_spam = data[tostring(target)]["settings"]["lock_spam"]
if lock_spam == "no" then
if not lang then
return "🔓*Spam* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل هرزنامه غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_spam"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Spam* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل هرزنامه غیرفعال شد🔓"
end
end
end
---------------Lock Flood-------------------
local function lock_flood(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_flood = data[tostring(target)]["settings"]["flood"]
if lock_flood == "yes" then
if not lang then
return "🔐*Flooding* _Is Already Locked_🔐"
elseif lang then
return "🔐قفل پیام رگبار فعال بود🔐"
end
else
data[tostring(target)]["settings"]["flood"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Flooding* _Has Been Locked_🔐"
else
return "🔐قفل پیام رگبار فعال شد🔐"
end
end
end
local function unlock_flood(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_flood = data[tostring(target)]["settings"]["flood"]
if lock_flood == "no" then
if not lang then
return "🔓*Flooding* _Is Not Locked_🔓"
elseif lang then
return "🔓قفل پیام رگبار غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["flood"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Flooding* _Has Been Unlocked_🔓"
else
return "🔓قفل پیام رگبار غیرفعال شد🔓"
end
end
end
---------------Lock Bots-------------------
local function lock_bots(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "yes" then
if not lang then
return "🔐*Bots* _Protection Is Already Enabled_🔐"
elseif lang then
return "🔐محافظت از گروه در برابر ربات ها فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Bots* _Protection Has Been Enabled_🔐"
else
return "🔐محافظت از گروه در برابر ربات ها فعال شد🔐"
end
end
end
local function unlock_bots(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_bots = data[tostring(target)]["settings"]["lock_bots"]
if lock_bots == "no" then
if not lang then
return "🔓*Bots* _Protection Is Not Enabled_🔓"
elseif lang then
return "🔓محافظت از گروه در برابر ربات ها غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Bots* _Protection Has Been Disabled_🔓"
else
return "🔓محافظت از گروه در برابر ربات ها غیرفعال شد🔓"
end
end
end
---------------Lock Markdown-------------------
local function lock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "yes" then
if not lang then
return "🔐*Markdown* _Posting Is Already Locked_🔐"
elseif lang then
return "🔐قفل پیام های دارای فونت فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Markdown* _Posting Has Been Locked_🔐"
else
return "🔐قفل پیام های دارای فونت فعال شد🔐"
end
end
end
local function unlock_markdown(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"]
if lock_markdown == "no" then
if not lang then
return "🔓*Markdown* _Posting Is Not Locked_🔓"
elseif lang then
return "🔓قفل پیام های دارای فونت غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data)
if not lang then
return "🔓*Markdown* _Posting Has Been Unlocked_🔓"
else
return "🔓قفل پیام های دارای فونت غیرفعال شد🔓"
end
end
end
---------------Lock Webpage-------------------
local function lock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "شما مدیر گروه نیستید"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "yes" then
if not lang then
return "🔐*Webpage* _Is Already Locked_🔐"
elseif lang then
return "🔐قفل صفحات وب فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*Webpage* _Has Been Locked_🔐"
else
return "🔐قفل صفحات وب فعال شد🔐"
end
end
end
local function unlock_webpage(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"]
if lock_webpage == "no" then
if not lang then
return "🔓*Webpage* _Is Not Locked_🔓"
elseif lang then
return "🔓قفل صفحات وب غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_webpage"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*Webpage* _Has Been Unlocked_🔓"
else
return "🔓قفل صفحات وب غیرفعال شد🔓"
end
end
end
function group_settings(msg, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local data = load_data(_config.moderation.data)
local target = msg.chat_id_
if data[tostring(target)] then
if data[tostring(target)]["settings"]["num_msg_max"] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_edit"] then
data[tostring(target)]["settings"]["lock_edit"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_link"] then
data[tostring(target)]["settings"]["lock_link"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_fosh"] then
data[tostring(target)]["settings"]["lock_fosh"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_tag"] then
data[tostring(target)]["settings"]["lock_tag"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_arabic"] then
data[tostring(target)]["settings"]["lock_arabic"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_flood"] then
data[tostring(target)]["settings"]["lock_flood"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_spam"] then
data[tostring(target)]["settings"]["lock_spam"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_mention"] then
data[tostring(target)]["settings"]["lock_mention"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_webpage"] then
data[tostring(target)]["settings"]["lock_webpage"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["welcome"] then
data[tostring(target)]["settings"]["welcome"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_markdown"] then
data[tostring(target)]["settings"]["lock_markdown"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_bots"] then
data[tostring(target)]["settings"]["lock_bots"] = "yes"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_gif"] then
data[tostring(target)]["settings"]["lock_gif"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_text"] then
data[tostring(target)]["settings"]["lock_text"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_inline"] then
data[tostring(target)]["settings"]["lock_inline"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_game"] then
data[tostring(target)]["settings"]["lock_game"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_photo"] then
data[tostring(target)]["settings"]["lock_photo"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_video"] then
data[tostring(target)]["settings"]["lock_video"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_audio"] then
data[tostring(target)]["settings"]["lock_audio"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_voice"] then
data[tostring(target)]["settings"]["lock_voice"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_sticker"] then
data[tostring(target)]["settings"]["lock_sticker"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_contact"] then
data[tostring(target)]["settings"]["lock_contact"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_forward"] then
data[tostring(target)]["settings"]["lock_forward"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_location"] then
data[tostring(target)]["settings"]["lock_location"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_document"] then
data[tostring(target)]["settings"]["lock_document"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_tgservice"] then
data[tostring(target)]["settings"]["lock_tgservice"] = "no"
end
end
if data[tostring(target)]["settings"] then
if not data[tostring(target)]["settings"]["lock_all"] then
data[tostring(target)]["settings"]["lock_all"] = "no"
end
end
local expiretime = redis:hget('expiretime', msg.chat_id_)
local expire = ''
if not expiretime then
expire = expire..'Unlimited'
else
local now = tonumber(os.time())
expire = expire..math.floor((tonumber(expiretime) - tonumber(now)) / 86400) + 1
end
if not lang then
local settings = data[tostring(target)]["settings"]
text = "⚙️*Group Settings*⚙️\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n● 》_Lock edit ➢_ *"..settings.lock_edit.."*\n● 》_Lock links ➢_ *"..settings.lock_link.."*\n● 》_Lock fosh ➢_ *"..settings.lock_fosh.."*\n● 》_Lock tags ➢_ *"..settings.lock_tag.."*\n● 》_Lock Persian ➢_ *"..settings.lock_arabic.."*\n● 》_Lock flood ➢_ *"..settings.flood.."*\n● 》_Lock spam ➢_ *"..settings.lock_spam.."*\n● 》_Lock mention ➢_ *"..settings.lock_mention.."*\n● 》_Lock webpage ➢_ *"..settings.lock_webpage.."*\n● 》_welcome ➢_ *"..settings.welcome.."*\n● 》_Lock markdown ➢_ *"..settings.lock_markdown.."*\n● 》_Lock Bots ➢_ *"..settings.lock_bots.."*\n● 》_Lock gif ➢_ *"..settings.lock_gif.."*\n● 》_Lock text ➢_ *"..settings.lock_text.."*\n● 》_Lock inline ➢_ *"..settings.lock_inline.."*\n● 》_Lock game ➢_ *"..settings.lock_game.."*\n● 》_Lock photo ➢_ *"..settings.lock_photo.."*\n● 》_Lock video ➢_ *"..settings.lock_video.."*\n● 》_Lock audio ➢_ *"..settings.lock_audio.."*\n● 》_Lock voice ➢_ *"..settings.lock_voice.."*\n● 》_Lock sticker ➢_ *"..settings.lock_sticker.."*\n● 》_Lock contact ➢_ *"..settings.lock_contact.."*\n● 》_Lock forward ➢_ *"..settings.lock_forward.."*\n● 》_Lock location ➢_ *"..settings.lock_location.."*\n● 》_Lock document ➢_ *"..settings.lock_document.."*\n● 》_Lock TgService ➢_ *"..settings.lock_tgservice.."*\n● 》_Lock all : _ *"..settings.lock_all.."*\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n● 》_Set Flood ➢_ *"..NUM_MSG_MAX.."*\n● 》_Welcome ➢_ *"..settings.welcome.."*\n● 》_EXPIRE ➢_ *"..expire.."*\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n Enable✓ ➰ Disable✘ \n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n 🔖powered by: *@mafia_boy* \n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n*Language* : *EN*"
else
local settings = data[tostring(target)]["settings"]
text = "⚙️*تنظیمات سوپرگروه*⚙️\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n● 》_قفل ویرایش ↫_ *"..settings.lock_edit.."*\n● 》_قفل لینک ↫_ *"..settings.lock_link.."*\n● 》_قفل فحش ↫_ *"..settings.lock_fosh.."*\n● 》_قفل تگ ↫_ *"..settings.lock_tag.."*\n● 》_قفل فارسی ↫_ *"..settings.lock_arabic.."*\n● 》_قفل فلود ↫_ *"..settings.flood.."*\n● 》_قفل اسپم ↫_ *"..settings.lock_spam.."*\n● 》_قفل فراخوانی ↫_ *"..settings.lock_mention.."*\n● 》_قفل وبسایت ↫_ *"..settings.lock_webpage.."*\n● 》_قفل فونت ↫_ *"..settings.lock_markdown.."*\n● 》_قفل ربات ↫_ *"..settings.lock_bots.."*\n● 》_قفل گیف ↫_ *"..settings.lock_gif.."*\n● 》_قفل متن ↫_ *"..settings.lock_text.."*\n● 》_قفل اینلاین ↫_ *"..settings.lock_inline.."*\n● 》_قفل بازی ↫_ *"..settings.lock_game.."*\n● 》_قفل عکس ↫_ *"..settings.lock_photo.."*\n● 》_قفل فیلم ↫_ *"..settings.lock_video.."*\n● 》_قفل موزیک ↫_ *"..settings.lock_audio.."*\n● 》_قفل صدا ↫_ *"..settings.lock_voice.."*\n● 》_قفل استیکر ↫_ *"..settings.lock_sticker.."*\n● 》_قفل اطلاعات تماس ↫_ *"..settings.lock_contact.."*\n● 》_قفل فوروارد ↫_ *"..settings.lock_forward.."*\n● 》_قفل موقعیت ↫_ *"..settings.lock_location.."*\n● 》_قفل فایل ↫_ *"..settings.lock_document.."*\n● 》_قفل اعلانات ↫_ *"..settings.lock_tgservice.."*\n● 》_تنظیم فلود(رگبار) ↫_ *"..NUM_MSG_MAX.."*\n● 》_قفل همه ↫ _ *"..settings.lock_all.."*\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n● 》_تنظیم فلود(رگبار) ↫_ *"..NUM_MSG_MAX.."*\n● 》_خوشآمد گویی ↫_ *"..settings.welcome.."*\n● 》_شارژ گروه ↫_ *"..expire.."*\n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n فعال✓ ➰ غیرفعال✘ \n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n 🔖powered by: *@mafia_boy* \n*﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄*\n*زبان ربات* ↫ *فارسی*"
end
if not lang then
text = string.gsub(text, "yes", "✓")
text = string.gsub(text, "no", "✘")
else
text = string.gsub(text, "yes", "✓")
text = string.gsub(text, "no", "✘")
end
return text
end
--------locks---------
--------lock all------------------------
local function lock_all(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_all = data[tostring(target)]["settings"]["lock_all"]
if lock_all == "yes" then
if not lang then
return "🔐*lock All* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل همه(قفل گروه) فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_all"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock All* _Has Been Enabled_🔐"
else
return "🔐قفل همه(قفل گروه) فعال شد🔐"
end
end
end
local function unlock_all(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_all = data[tostring(target)]["settings"]["lock_all"]
if lock_all == "no" then
if not lang then
return "🔓*lock All* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل همه(قفل گروه) غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_all"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock All* _Has Been Disabled_🔓"
else
return "🔓قفل همه(قفل گروه) غیرفعال شد🔓"
end
end
end
---------------lock Gif-------------------
local function lock_gif(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_gif = data[tostring(target)]["settings"]["lock_gif"]
if lock_gif == "yes" then
if not lang then
return "🔐*lock Gif* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل گیف فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_gif"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Gif* _Has Been Enabled_🔓"
else
return "🔓قفل گیف فعال شد🔓"
end
end
end
local function unlock_gif(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_gif = data[tostring(target)]["settings"]["lock_gif"]
if lock_gif == "no" then
if not lang then
return "🔐*lock Gif* _Is Already Disabled_🔐"
elseif lang then
return "🔐قفل گیف غیرفعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_gif"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Gif* _Has Been Disabled_🔐"
else
return "🔐قفل گیف غیرفعال شد🔐"
end
end
end
---------------lock Game-------------------
local function lock_game(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_game = data[tostring(target)]["settings"]["lock_game"]
if lock_game == "yes" then
if not lang then
return "🔐*lock Game* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل بازی های تحت وب فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_game"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Game* _Has Been Enabled_🔐"
else
return "🔐قفل بازی های تحت وب فعال شد🔐"
end
end
end
local function unlock_game(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_game = data[tostring(target)]["settings"]["lock_game"]
if lock_game == "no" then
if not lang then
return "🔓*lock Game* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل بازی های تحت وب غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_game"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Game* _Has Been Disabled_🔓"
else
return "🔓قفل بازی های تحت وب غیرفعال شد🔓"
end
end
end
---------------lock Inline-------------------
local function lock_inline(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_inline = data[tostring(target)]["settings"]["lock_inline"]
if lock_inline == "yes" then
if not lang then
return "🔐*lock Inline* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل کیبورد شیشه ای فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_inline"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Inline* _Has Been Enabled_🔐"
else
return "🔐قفل کیبورد شیشه ای فعال شد🔐"
end
end
end
local function unlock_inline(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_inline = data[tostring(target)]["settings"]["lock_inline"]
if lock_inline == "no" then
if not lang then
return "🔓*lock Inline* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل کیبورد شیشه ای غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_inline"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Inline* _Has Been Disabled_🔓"
else
return "🔓قفل کیبورد شیشه ای غیرفعال شد🔓"
end
end
end
---------------lock Text-------------------
local function lock_text(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_text = data[tostring(target)]["settings"]["lock_text"]
if lock_text == "yes" then
if not lang then
return "🔐*lock Text* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل متن فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_text"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Text* _Has Been Enabled_🔐"
else
return "🔐قفل متن فعال شد🔐"
end
end
end
local function unlock_text(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_text = data[tostring(target)]["settings"]["lock_text"]
if lock_text == "no" then
if not lang then
return "🔓*lock Text* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل متن غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_text"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Text* _Has Been Disabled_🔓"
else
return "🔓قفل متن غیرفعال شد🔓"
end
end
end
---------------lock photo-------------------
local function lock_photo(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "🔐✖️_You're Not_ *Moderator*✖️🔐"
else
return "🔐✖️شما مدیر گروه نیستید✖️🔐"
end
end
local lock_photo = data[tostring(target)]["settings"]["lock_photo"]
if lock_photo == "yes" then
if not lang then
return "🔐*lock Photo* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل عکس فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_photo"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Photo* _Has Been Enabled_🔐"
else
return "🔐قفل عکس فعال شد🔐"
end
end
end
local function unlock_photo(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_photo = data[tostring(target)]["settings"]["lock_photo"]
if lock_photo == "no" then
if not lang then
return "🔓*lock Photo* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل عکس غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_photo"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Photo* _Has Been Disabled_🔓"
else
return "🔓قفل عکس غیرفعال شد🔓"
end
end
end
---------------lock Video-------------------
local function lock_video(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_video = data[tostring(target)]["settings"]["lock_video"]
if lock_video == "yes" then
if not lang then
return "🔐*lock Video* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل فیلم فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_video"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Video* _Has Been Enabled_🔐"
else
return "🔐قفل فیلم فعال شد🔐"
end
end
end
local function unlock_video(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_video = data[tostring(target)]["settings"]["lock_video"]
if lock_video == "no" then
if not lang then
return "🔓*lock Video* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل فیلم غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_video"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Video* _Has Been Disabled_🔓"
else
return "🔓قفل فیلم غیرفعال شد🔓"
end
end
end
---------------lock Audio-------------------
local function lock_audio(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_audio = data[tostring(target)]["settings"]["lock_audio"]
if lock_audio == "yes" then
if not lang then
return "🔐*lock Audio* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل آهنگ فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_audio"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Audio* _Has Been Enabled_🔐"
else
return "🔐قفل آهنگ فعال شد🔐"
end
end
end
local function unlock_audio(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_audio = data[tostring(target)]["settings"]["lock_audio"]
if lock_audio == "no" then
if not lang then
return "🔓*lock Audio* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل آهنگ غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_audio"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Audio* _Has Been Disabled_🔓"
else
return "🔓قفل آهنگ غیرفعال شد🔓"
end
end
end
---------------lock Voice-------------------
local function lock_voice(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_voice = data[tostring(target)]["settings"]["lock_voice"]
if lock_voice == "yes" then
if not lang then
return "🔐*lock Voice* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل صدا فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_voice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Voice* _Has Been Enabled_🔐"
else
return "🔐قفل صدا فعال شد🔐"
end
end
end
local function unlock_voice(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_voice = data[tostring(target)]["settings"]["lock_voice"]
if lock_voice == "no" then
if not lang then
return "🔓*lock Voice* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل صدا غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_voice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Voice* _Has Been Disabled_🔓"
else
return "🔓قفل صدا غیرفعال شد🔓"
end
end
end
---------------lock Sticker-------------------
local function lock_sticker(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_sticker = data[tostring(target)]["settings"]["lock_sticker"]
if lock_sticker == "yes" then
if not lang then
return "🔐*lock Sticker* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل استیکر فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_sticker"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Sticker* _Has Been Enabled_🔐"
else
return "🔐قفل استیکر فعال شد🔐"
end
end
end
local function unlock_sticker(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_sticker = data[tostring(target)]["settings"]["lock_sticker"]
if lock_sticker == "no" then
if not lang then
return "🔓*lock Sticker* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل استیکر غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_sticker"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Sticker* _Has Been Disabled_🔓"
else
return "🔓قفل استیکر غیرفعال شد🔓"
end
end
end
---------------lock Contact-------------------
local function lock_contact(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_contact = data[tostring(target)]["settings"]["lock_contact"]
if lock_contact == "yes" then
if not lang then
return "🔐*lock Contact* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل مخاطب فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_contact"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Contact* _Has Been Enabled_🔐"
else
return "🔐قفل مخاطب فعال شد🔐"
end
end
end
local function unlock_contact(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_contact = data[tostring(target)]["settings"]["lock_contact"]
if lock_contact == "no" then
if not lang then
return "🔓*lock Contact* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل مخاطب غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_contact"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Contact* _Has Been Disabled_🔓"
else
return "🔓قفل مخاطب غیرفعال شد🔓"
end
end
end
---------------lock Forward-------------------
local function lock_forward(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_forward = data[tostring(target)]["settings"]["lock_forward"]
if lock_forward == "yes" then
if not lang then
return "🔐*lock Forward* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل فوروارد فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_forward"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Forward* _Has Been Enabled_🔐"
else
return "🔐قفل فوروارد فعال شد🔐"
end
end
end
local function unlock_forward(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_forward = data[tostring(target)]["settings"]["lock_forward"]
if lock_forward == "no" then
if not lang then
return "🔓*lock Forward* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل فوروارد غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_forward"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Forward* _Has Been Disabled_🔓"
else
return "🔓قفل فوروارد غیرفعال شد🔓"
end
end
end
---------------lock Location-------------------
local function lock_location(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_location = data[tostring(target)]["settings"]["lock_location"]
if lock_location == "yes" then
if not lang then
return "🔐*lock Location* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل موقعیت فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_location"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Location* _Has Been Enabled_🔐"
else
return "🔐قفل موقعیت فعال شد🔐"
end
end
end
local function unlock_location(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_location = data[tostring(target)]["settings"]["lock_location"]
if lock_location == "no" then
if not lang then
return "🔓*lock Location* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل موقعیت غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_location"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Location* _Has Been Disabled_🔓"
else
return "🔓قفل موقعیت غیرفعال شد🔓"
end
end
end
---------------lock Document-------------------
local function lock_document(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_document = data[tostring(target)]["settings"]["lock_document"]
if lock_document == "yes" then
if not lang then
return "🔐*lock Document* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل فایل فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_document"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock Document* _Has Been Enabled_🔐"
else
return "🔐قفل فایل فعال شد🔐"
end
end
end
local function unlock_document(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_document = data[tostring(target)]["settings"]["lock_document"]
if lock_document == "no" then
if not lang then
return "🔓*lock Document* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل فایل غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_document"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock Document* _Has Been Disabled_🔓"
else
return "🔓قفل فایل غیرفعال شد🔓"
end
end
end
---------------lock TgService-------------------
local function lock_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_tgservice = data[tostring(target)]["settings"]["lock_tgservice"]
if lock_tgservice == "yes" then
if not lang then
return "🔐*lock TgService* _Is Already Enabled_🔐"
elseif lang then
return "🔐قفل سرویس تلگرام فعال بود🔐"
end
else
data[tostring(target)]["settings"]["lock_tgservice"] = "yes"
save_data(_config.moderation.data, data)
if not lang then
return "🔐*lock TgService* _Has Been Enabled_🔐"
else
return "🔐قفل سرویس تلگرام فعال شد🔐"
end
end
end
local function unlock_tgservice(msg, data, target)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
if not is_mod(msg) then
if not lang then
return "✖️_You're Not_ *Moderator*✖️"
else
return "✖️شما مدیر گروه نیستید✖️"
end
end
local lock_tgservice = data[tostring(target)]["settings"]["lock_tgservice"]
if lock_tgservice == "no" then
if not lang then
return "🔓*lock TgService* _Is Already Disabled_🔓"
elseif lang then
return "🔓قفل سرویس تلگرام غیرفعال بود🔓"
end
else
data[tostring(target)]["settings"]["lock_tgservice"] = "no"
save_data(_config.moderation.data, data)
if not lang then
return "🔓*lock TgService* _Has Been Disabled_🔓"
else
return "🔓قفل سرویس تلگرام غیرفعال شد🔓"
end
end
end
local function run(msg, matches)
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
local data = load_data(_config.moderation.data)
local chat = msg.chat_id_
local user = msg.sender_user_id_
if matches[1] == "مشخصات" then
if not matches[2] and tonumber(msg.reply_to_message_id_) == 0 then
if not lang then
return "●*Group Id ➢* _"..chat.."_\n*➖➖➖➖➖➖➖➖*\n●*Your Id ➢* _"..user.."_\n*➖➖➖➖➖➖➖➖*"
else
return "●*️ایدی گروه️↫* _"..chat.."_\n*➖➖➖➖➖➖➖➖*\n●*ایدی شما ↫* _"..user.."_\n*➖➖➖➖➖➖➖➖*"
end
end
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="id"})
end
if matches[2] and tonumber(msg.reply_to_message_id_) == 0 then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="id"})
end
end
if matches[1] == "سنجاق" and is_owner(msg) then
tdcli.pinChannelMessage(msg.chat_id_, msg.reply_to_message_id_, 1)
if not lang then
return "*Message Has Been Pinned*"
else
return "پیام سجاق شد"
end
end
if matches[1] == 'حذف سنجاق' and is_mod(msg) then
tdcli.unpinChannelMessage(msg.chat_id_)
if not lang then
return "*Pin message has been unpinned*"
else
return "پیام سنجاق شده پاک شد"
end
end
if matches[1] == "نصب" then
return modadd(msg)
end
if matches[1] == "حذف" then
return modrem(msg)
end
if matches[1] == "مدیر" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="setowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="setowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="setowner"})
end
end
if matches[1] == "حذف مدیر" and is_admin(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="remowner"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="remowner"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="remowner"})
end
end
if matches[1] == "ادمین" and is_owner(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="promote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="promote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="promote"})
end
end
if matches[1] == "حذف ادمین" and is_owner(msg) then
if not matches[2] and tonumber(msg.reply_to_message_id_) ~= 0 then
tdcli_function ({
ID = "GetMessage",
chat_id_ = msg.chat_id_,
message_id_ = msg.reply_to_message_id_
}, action_by_reply, {chat_id=msg.chat_id_,cmd="demote"})
end
if matches[2] and string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="demote"})
end
if matches[2] and not string.match(matches[2], '^%d+$') then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="demote"})
end
end
if matches[1] == "قفل" and is_mod(msg) then
local target = msg.chat_id_
if matches[2] == "لینک" then
return lock_link(msg, data, target)
end
if matches[2] == "فحش" then
return lock_fosh(msg, data, target)
end
if matches[2] == "تگ" then
return lock_tag(msg, data, target)
end
if matches[2] == "فراخوانی" then
return lock_mention(msg, data, target)
end
if matches[2] == "عربی" then
return lock_arabic(msg, data, target)
end
if matches[2] == "ویرایش" then
return lock_edit(msg, data, target)
end
if matches[2] == "اسپم" then
return lock_spam(msg, data, target)
end
if matches[2] == "فلود" then
return lock_flood(msg, data, target)
end
if matches[2] == "ربات" then
return lock_bots(msg, data, target)
end
if matches[2] == "فونت" then
return lock_markdown(msg, data, target)
end
if matches[2] == "وبسایت" then
return lock_webpage(msg, data, target)
end
end
if matches[1] == "باز کردن" and is_mod(msg) then
local target = msg.chat_id_
if matches[2] == "لینک" then
return unlock_link(msg, data, target)
end
if matches[2] == "فحش" then
return unlock_fosh(msg, data, target)
end
if matches[2] == "تگ" then
return unlock_tag(msg, data, target)
end
if matches[2] == "فراخوانی" then
return unlock_mention(msg, data, target)
end
if matches[2] == "عربی" then
return unlock_arabic(msg, data, target)
end
if matches[2] == "ویرایش" then
return unlock_edit(msg, data, target)
end
if matches[2] == "اسپم" then
return unlock_spam(msg, data, target)
end
if matches[2] == "فلود" then
return unlock_flood(msg, data, target)
end
if matches[2] == "ربات" then
return unlock_bots(msg, data, target)
end
if matches[2] == "فونت" then
return unlock_markdown(msg, data, target)
end
if matches[2] == "وبسایت" then
return unlock_webpage(msg, data, target)
end
end
if matches[1] == "قفل" and is_mod(msg) then
local target = msg.chat_id_
if matches[2] == "همه" then
return lock_all(msg, data, target)
end
if matches[2] == "گیف" then
return lock_gif(msg, data, target)
end
if matches[2] == "متن" then
return lock_text(msg ,data, target)
end
if matches[2] == "عکس" then
return lock_photo(msg ,data, target)
end
if matches[2] == "فیلم" then
return lock_video(msg ,data, target)
end
if matches[2] == "موزیک" then
return lock_audio(msg ,data, target)
end
if matches[2] == "صدا" then
return lock_voice(msg ,data, target)
end
if matches[2] == "استیکر" then
return lock_sticker(msg ,data, target)
end
if matches[2] == "مخاطب" then
return lock_contact(msg ,data, target)
end
if matches[2] == "فوروارد" then
return lock_forward(msg ,data, target)
end
if matches[2] == "مکان" then
return lock_location(msg ,data, target)
end
if matches[2] == "فایل" then
return lock_document(msg ,data, target)
end
if matches[2] == "اعلانات" then
return lock_tgservice(msg ,data, target)
end
if matches[2] == "اینلاین" then
return lock_inline(msg ,data, target)
end
if matches[2] == "بازی" then
return lock_game(msg ,data, target)
end
end
if matches[1] == "باز کردن" and is_mod(msg) then
local target = msg.chat_id_
if matches[2] == "همه" then
return unlock_all(msg, data, target)
end
if matches[2] == "گیف" then
return unlock_gif(msg, data, target)
end
if matches[2] == "متن" then
return unlock_text(msg, data, target)
end
if matches[2] == "عکس" then
return unlock_photo(msg ,data, target)
end
if matches[2] == "فیلم" then
return unlock_video(msg ,data, target)
end
if matches[2] == "موزیک" then
return unlock_audio(msg ,data, target)
end
if matches[2] == "صدا" then
return unlock_voice(msg ,data, target)
end
if matches[2] == "استیکر" then
return unlock_sticker(msg ,data, target)
end
if matches[2] == "مخاطب" then
return unlock_contact(msg ,data, target)
end
if matches[2] == "فوروارد" then
return unlock_forward(msg ,data, target)
end
if matches[2] == "مکان" then
return unlock_location(msg ,data, target)
end
if matches[2] == "فایل" then
return unlock_document(msg ,data, target)
end
if matches[2] == "اعلانات" then
return unlock_tgservice(msg ,data, target)
end
if matches[2] == "اینلاین" then
return unlock_inline(msg ,data, target)
end
if matches[2] == "بازی" then
return unlock_game(msg ,data, target)
end
end
if matches[1] == "اطلاعات گروه" and is_mod(msg) and gp_type(msg.chat_id_) == "channel" then
local function group_info(arg, data)
local hash = "gp_lang:"..arg.chat_id
local lang = redis:get(hash)
if not lang then
ginfo = "*📢Group Info :*📢\n👲_Admin Count :_ *"..data.administrator_count_.."*\n👥_Member Count :_ *"..data.member_count_.."*\n👿_Kicked Count :_ *"..data.kicked_count_.."*\n🆔_Group ID :_ *"..data.channel_.id_.."*"
print(serpent.block(data))
elseif lang then
ginfo = "📢*اطلاعات گروه*📢\n👲_تعداد مدیران :_ *"..data.administrator_count_.."*\n👥_تعداد اعضا :_ *"..data.member_count_.."*\n👿_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n🆔_شناسه گروه:_ *"..data.channel_.id_.."*"
print(serpent.block(data))
end
tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md')
end
tdcli.getChannelFull(msg.chat_id_, group_info, {chat_id=msg.chat_id_,msg_id=msg.id_})
end
if matches[1] == 'تنظیم لینک' and is_owner(msg) then
data[tostring(chat)]['settings']['linkgp'] = 'waiting'
save_data(_config.moderation.data, data)
if not lang then
return '_Please send the new group_ *link* _now_'
else
return 'لطفا لینک گروه خود را ارسال کنید'
end
end
if msg.content_.text_ then
local is_link = msg.content_.text_:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.content_.text_:match("^([https?://w]*.?t.me/joinchat/%S+)$")
if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then
data[tostring(chat)]['settings']['linkgp'] = msg.content_.text_
save_data(_config.moderation.data, data)
if not lang then
return "*Newlink* _has been set_"
else
return "لینک جدید ذخیره شد"
end
end
end
if matches[1] == 'لینک' and is_mod(msg) then
local linkgp = data[tostring(chat)]['settings']['linkgp']
if not linkgp then
if not lang then
return "_First set a link for group with using_ /setlink"
else
return "اول لینک گروه خود را ذخیره کنید با /setlink"
end
end
if not lang then
text = "<b>Group Link :</b>\n"..linkgp
else
text = "<b>لینک گروه:</b>\n"..linkgp
end
return tdcli.sendMessage(chat, msg.id_, 1, text, 1, 'html')
end
if matches[1] == "تنظیم قوانین" and matches[2] and is_mod(msg) then
data[tostring(chat)]['rules'] = matches[2]
save_data(_config.moderation.data, data)
if not lang then
return "*Group rules* _has been set_"
else
return "قوانین گروه ثبت شد"
end
end
if matches[1] == "قوانین" then
if not data[tostring(chat)]['rules'] then
if not lang then
rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n"
elseif lang then
rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام رگبار قفل.\n2⃣ اسپم قفل.\n3⃣ تبلیغ قفل.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی قفل .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n"
end
else
rules = "*Group Rules :*\n"..data[tostring(chat)]['rules']
end
return rules
end
if matches[1] == "مشخصات" and matches[2] and is_mod(msg) then
tdcli_function ({
ID = "SearchPublicChat",
username_ = matches[2]
}, action_by_username, {chat_id=msg.chat_id_,username=matches[2],cmd="res"})
end
if matches[1] == "چه کسی" and matches[2] and is_mod(msg) then
tdcli_function ({
ID = "GetUser",
user_id_ = matches[2],
}, action_by_id, {chat_id=msg.chat_id_,user_id=matches[2],cmd="whois"})
end
if matches[1] == 'تنظیم فلود' and is_mod(msg) then
if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then
return "_Wrong number, range is_ *[1-50]*"
end
local flood_max = matches[2]
data[tostring(chat)]['settings']['num_msg_max'] = flood_max
save_data(_config.moderation.data, data)
return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*"
end
if matches[1]:lower() == 'پاک کردن' and is_owner(msg) then
if matches[2] == 'mods' then
if next(data[tostring(chat)]['mods']) == nil then
if not lang then
return "_No_ *moderators* _in this group_"
else
return "هیچ مدیری برای گروه انتخاب نشده است"
end
end
for k,v in pairs(data[tostring(chat)]['mods']) do
data[tostring(chat)]['mods'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *moderators* _has been demoted_"
else
return "تمام مدیران گروه تنزیل مقام شدند"
end
end
if matches[2] == 'لیست فیلترها' then
if next(data[tostring(chat)]['filterlist']) == nil then
if not lang then
return "*Filtered words list* _is empty_"
else
return "_لیست کلمات فیلتر شده خالی است_"
end
end
for k,v in pairs(data[tostring(chat)]['filterlist']) do
data[tostring(chat)]['filterlist'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "*Filtered words list* _has been cleaned_"
else
return "_لیست کلمات فیلتر شده پاک شد_"
end
end
if matches[2] == 'قوانین' then
if not data[tostring(chat)]['rules'] then
if not lang then
return "_No_ *rules* _available_"
else
return "قوانین برای گروه ثبت نشده است"
end
end
data[tostring(chat)]['rules'] = nil
save_data(_config.moderation.data, data)
if not lang then
return "*Group rules* _has been cleaned_"
else
return "قوانین گروه پاک شد"
end
end
if matches[2] == 'درباره' then
if gp_type(chat) == "chat" then
if not data[tostring(chat)]['about'] then
if not lang then
return "_No_ *description* _available_"
else
return "پیامی مبنی بر درباره گروه ثبت نشده است"
end
end
data[tostring(chat)]['about'] = nil
save_data(_config.moderation.data, data)
elseif gp_type(chat) == "channel" then
tdcli.changeChannelAbout(chat, "", dl_cb, nil)
end
if not lang then
return "*Group description* _has been cleaned_"
else
return "پیام مبنی بر درباره گروه پاک شد"
end
end
end
if matches[1]:lower() == 'پاک کردن' and is_admin(msg) then
if matches[2] == 'owners' then
if next(data[tostring(chat)]['owners']) == nil then
if not lang then
return "_No_ *owners* _in this group_"
else
return "مالکی برای گروه انتخاب نشده است"
end
end
for k,v in pairs(data[tostring(chat)]['owners']) do
data[tostring(chat)]['owners'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
if not lang then
return "_All_ *owners* _has been demoted_"
else
return "تمامی مالکان گروه تنزیل مقام شدند"
end
end
end
if matches[1] == "تنظیم نام" and matches[2] and is_mod(msg) then
local gp_name = matches[2]
tdcli.changeChatTitle(chat, gp_name, dl_cb, nil)
end
if matches[1] == "تنظیم درباره" and matches[2] and is_mod(msg) then
if gp_type(chat) == "channel" then
tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil)
elseif gp_type(chat) == "chat" then
data[tostring(chat)]['about'] = matches[2]
save_data(_config.moderation.data, data)
end
if not lang then
return "*Group description* _has been set_"
else
return "پیام مبنی بر درباره گروه ثبت شد"
end
end
if matches[1] == "درباره" and gp_type(chat) == "chat" then
if not data[tostring(chat)]['about'] then
if not lang then
about = "_No_ *description* _available_"
elseif lang then
about = "پیامی مبنی بر درباره گروه ثبت نشده است"
end
else
about = "*Group Description :*\n"..data[tostring(chat)]['about']
end
return about
end
if matches[1] == 'فیلتر' and is_mod(msg) then
return filter_word(msg, matches[2])
end
if matches[1] == 'حذف فیلتر' and is_mod(msg) then
return unfilter_word(msg, matches[2])
end
if matches[1] == 'لیست فیلتر' and is_mod(msg) then
return filter_list(msg)
end
if matches[1] == "تنظیمات" then
return group_settings(msg, target)
end
if matches[1] == "لیست قفل" then
return locks(msg, target)
end
if matches[1] == "لیست ادمین ها" then
return modlist(msg)
end
if matches[1] == "لیست مدیران" and is_owner(msg) then
return ownerlist(msg)
end
if matches[1] == "setlang" and is_owner(msg) then
if matches[2] == "en" then
local hash = "gp_lang:"..msg.chat_id_
local lang = redis:get(hash)
redis:del(hash)
return "_Group Language Set To:_ EN"
elseif matches[2] == "fa" then
redis:set(hash, true)
return "*زبان گروه تنظیم شد به : فارسی*"
end
end
if matches[1] == "راهنما" and is_mod(msg) then
if not lang then
text = [[
[Help for ultra-energy]
⬛️》 ENERGY HELP ⬛️
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !mod help
◾️》راهنما مدیریت
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای مربوط به دستورات مدیریتی مخصوص مدیر گروه و ادمین ها نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !lock help
◾️》راهنما قفل
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای دستورات قفلی که از جمله قفل رسانه ها و لینک ها و... میباشد نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !sudo help
◾️》راهنما سودو
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای دستورات مربوط به سازنده ربات و سودو ها جهت مدیریت ربات نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
💡توجه: ابتدای هر دستور انگلیسی یکی از علامت های [!,/,#] را بگزارید.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔖powered by: *@mafia_boy*]]
elseif lang then
text = [[
[Help for ultra-energy]
⬛️》 ENERGY HELP ⬛️
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !mod help
◾️》راهنما مدیریت
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای مربوط به دستورات مدیریتی مخصوص مدیر گروه و ادمین ها نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !lock help
◾️》راهنما قفل
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای دستورات قفلی که از جمله قفل رسانه ها و لینک ها و... میباشد نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
◽️》 !sudo help
◾️》راهنما سودو
📮با فرستادن یکی از دو دستور بالا در گروه لیست راهنمای دستورات مربوط به سازنده ربات و سودو ها جهت مدیریت ربات نمایش داده میشود.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
💡توجه: ابتدای هر دستور انگلیسی یکی از علامت های [!,/,#] را بگزارید.
﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄﹃﹄
🔖powered by: *@mafia_boy*]]
end
return text
end
if matches[1] == "انلاینی" and is_mod(msg) then
text5 = [[
✔️اره انلاینم✔️
]]
return text5
end
end
-----------------------------------------
return {
patterns ={
"^(انلاینی)$",
"^(مشخصات)$",
"^(مشخصات) (.*)$",
"^(سنجاق)$",
"^(حذف سنجاق)$",
"^(اطلاعات گروه)$",
"^(تست)$",
"^(نصب)$",
"^(حذف)$",
"^(مدیر)$",
"^(مدیر) (.*)$",
"^(حذف مدیر)$",
"^(حذف مدیر) (.*)$",
"^(ادمین)$",
"^(ادمین) (.*)$",
"^(حذف ادمین)$",
"^(حذف ادمین) (.*)$",
"^(لیست ادمین ها)$",
"^(لیست مدیران)$",
"^(قفل) (.*)$",
"^(باز کردن) (.*)$",
"^(تنظیمات)$",
"^(لیست قفل)$",
"^(قفل) (.*)$",
"^(باز کردن) (.*)$",
"^(لینک)$",
"^(تنظیم لینک)$",
"^(قوانین)$",
"^(تنظیم قوانین) (.*)$",
"^(درباره)$",
"^(تنظیم درباره) (.*)$",
"^(تنظیم نام) (.*)$",
"^(پاک کردن) (.*)$",
"^(تنظیم فلود) (%d+)$",
"^(مشخصات) (.*)$",
"^(چه کسی) (%d+)$",
"^(راهنما)$",
"^(setlang) (.*)$",
"^(فیلتر) (.*)$",
"^(حذف فیلتر) (.*)$",
"^(لیست فیلتر)$",
"^([https?://w]*.?t.me/joinchat/%S+)$",
"^([https?://w]*.?telegram.me/joinchat/%S+)$",
"^(تنظیم ولکام) (.*)",
"^(ولکام) (.*)$"
},
run=run,
pre_process = pre_process
}
-- کد های پایین در ربات نشان داده نمیشوند
-- @RICH_ENERGY
-----my_name_is_ehsan*#@mafia_boy
-----@ENERGY_TEAM FOR UPDATE
-----لطفا پیام بالا رو پاک نکنید
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Southern_San_dOria_[S]/npcs/Geltpix.lua | 36 | 1165 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Geltpix
-- @zone 80
-- @pos 154 -2 103
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil;
require("scripts/zones/Southern_San_dOria_[S]/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc, 7043); -- Don't hurt poor Geltpix! Geltpix's just a merchant from Boodlix's Emporium in Jeuno. Kingdom vendors don't like gil, but Boodlix knows true value of new money.
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 |
Fatalerror66/ffxi-a | scripts/zones/Port_Jeuno/npcs/Home_Point.lua | 8 | 1184 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Home Point
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (HOMEPOINT_HEAL == 1) then
player:addHP(player:getMaxHP());
player:addMP(player:getMaxMP());
end
player:startEvent(0x2710);
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 (option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Southern_San_dOria/npcs/Rouva.lua | 2 | 1646 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Rouva
-- Involved in Quest: Lure of the Wildcat (San d'Oria)
-- @pos -17 2 10 230
-------------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then
if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WildcatSandy = player:getVar("WildcatSandy");
if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,2) == false) then
player:startEvent(0x0328);
else
player:startEvent(0x0298);
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 == 0x0328) then
player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",2,true);
end
end; | gpl-3.0 |
Yhgenomics/premake-core | src/base/rule.lua | 14 | 3133 | ---
-- base/rule.lua
-- Defines rule sets for generated custom rule files.
-- Copyright (c) 2014 Jason Perkins and the Premake project
---
local p = premake
p.rule = p.api.container("rule", p.global)
local rule = p.rule
---
-- Create a new rule container instance.
---
function rule.new(name)
local self = p.container.new(rule, name)
-- create a variable setting function. Do a version with lowercased
-- first letter(s) to match Premake's naming style for other calls
_G[name .. "Vars"] = function(vars)
rule.setVars(self, vars)
end
local lowerName = name:gsub("^%u+", string.lower)
_G[lowerName .. "Vars"] = _G[name .. "Vars"]
return self
end
---
-- Enumerate the property definitions for a rule.
---
function rule.eachProperty(self)
local props = self.propertydefinition
local i = 0
return function ()
i = i + 1
if i <= #props then
return props[i]
end
end
end
---
-- Find a property definition by its name.
--
-- @param name
-- The property name.
-- @returns
-- The property definition if found, nil otherwise.
---
function rule.getProperty(self, name)
local props = self.propertydefinition
for i = 1, #props do
local prop = props[i]
if prop.name == name then
return prop
end
end
end
---
-- Find the field definition for one this rule's properties. This field
-- can then be used with the api.* functions to manipulate the property's
-- values in the current configuration scope.
--
-- @param prop
-- The property definition.
-- @return
-- The field definition for the property; this will be created if it
-- does not already exist.
---
function rule.getPropertyField(self, prop)
if prop._field then
return prop._field
end
local kind = prop.kind or "string"
if kind == "list" then
kind = "list:string"
end
local fld = p.field.new {
name = "_rule_" .. self.name .. "_" .. prop.name,
scope = "config",
kind = kind,
tokens = true,
}
prop._field = fld
return fld
end
---
-- Given the value for a particular property, returns a formatted string.
--
-- @param prop
-- The property definition.
-- @param value
-- The value of the property to be formatted.
-- @returns
-- A string value.
---
function rule.getPropertyString(self, prop, value)
-- list?
if type(value) == "table" then
local sep = prop.separator or " "
return table.concat(value, sep)
end
-- enum?
if prop.values then
local i = table.indexof(prop.values, value)
return tostring(i)
end
-- primitive
value = tostring(value)
if #value > 0 then
return value
else
return nil
end
end
---
-- Set one or more rule variables in the current configuration scope.
--
-- @param vars
-- A key-value list of variables to set and their corresponding values.
---
function rule.setVars(self, vars)
for key, value in pairs(vars) do
local prop = rule.getProperty(self, key)
if not prop then
error (string.format("rule '%s' does not have property '%s'", self.name, key))
end
local fld = rule.getPropertyField(self, prop)
p.api.storeField(fld, value)
end
end
| bsd-3-clause |
kidaa/FFXIOrgins | scripts/zones/Alzadaal_Undersea_Ruins/npcs/qm1.lua | 15 | 1195 | -----------------------------------
-- Area: Alzadaal Undersea Ruins
-- NPC: ??? (Spawn Ob(ZNM T1))
-- @pos 542 0 -129 72
-----------------------------------
package.loaded["scripts/zones/Alzadaal_Undersea_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Alzadaal_Undersea_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(trade:hasItemQty(2592,1) and trade:getItemCount() == 1) then -- Trade Coq Lubricant
player:tradeComplete();
SpawnMob(17072171,180):updateEnmity(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_HAPPENS);
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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.