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 |
|---|---|---|---|---|---|
mrbangi/deviilbot | plugins/wlc.lua | 114 | 3529 | local add_user_cfg = load_from_file('data/add_user_cfg.lua')
local function template_add_user(base, to_username, from_username, chat_name, chat_id)
base = base or ''
to_username = '@' .. (to_username or '')
from_username = '@' .. (from_username or '')
chat_name = string.gsub(chat_name, '_', ' ') or ''
chat_id = "chat#id" .. (chat_id or '')
if to_username == "@" then
to_username = ''
end
if from_username == "@" then
from_username = ''
end
base = string.gsub(base, "{to_username}", to_username)
base = string.gsub(base, "{from_username}", from_username)
base = string.gsub(base, "{chat_name}", chat_name)
base = string.gsub(base, "{chat_id}", chat_id)
return base
end
function chat_new_user_link(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.from.username
local from_username = 'link (@' .. (msg.action.link_issuer.username or '') .. ')'
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
function chat_new_user(msg)
local pattern = add_user_cfg.initial_chat_msg
local to_username = msg.action.user.username
local from_username = msg.from.username
local chat_name = msg.to.print_name
local chat_id = msg.to.id
pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id)
if pattern ~= '' then
local receiver = get_receiver(msg)
send_msg(receiver, pattern, ok_cb, false)
end
end
local function description_rules(msg, nama)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
local about = ""
local rules = ""
if data[tostring(msg.to.id)]["description"] then
about = data[tostring(msg.to.id)]["description"]
about = "\nAbout :\n"..about.."\n"
end
if data[tostring(msg.to.id)]["rules"] then
rules = data[tostring(msg.to.id)]["rules"]
rules = "\nRules :\n"..rules.."\n"
end
local sambutan = "Hi "..nama.."\nWelcome to '"..string.gsub(msg.to.print_name, "_", " ").."'\nYou can use /help for see bot commands\n"
local text = sambutan..about..rules.."\n"
local receiver = get_receiver(msg)
send_large_msg(receiver, text, ok_cb, false)
end
end
local function run(msg, matches)
if not msg.service then
return "Are you trying to troll me?"
end
--vardump(msg)
if matches[1] == "chat_add_user" then
if not msg.action.user.username then
nama = string.gsub(msg.action.user.print_name, "_", " ")
else
nama = "@"..msg.action.user.username
end
chat_new_user(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_add_user_link" then
if not msg.from.username then
nama = string.gsub(msg.from.print_name, "_", " ")
else
nama = "@"..msg.from.username
end
chat_new_user_link(msg)
description_rules(msg, nama)
elseif matches[1] == "chat_del_user" then
local bye_name = msg.action.user.first_name
return 'Sikout '..bye_name
end
end
return {
description = "Welcoming Message",
usage = "send message to new member",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_add_user_link)$",
"^!!tgservice (chat_del_user)$",
},
run = run
}
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Ordelles_Caves/npcs/qm3.lua | 2 | 1668 | -----------------------------------
-- Area: Ordelle's Caves
-- NPC: ???
-- Involved in Quest: A Squire's Test II
-- @zone 193
-- @pos -139 0 264
-------------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/teleports");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local HasDew = player:hasKeyItem(STALACTITE_DEW);
if(os.time() - player:getVar("SquiresTestII") <= 60 and HasDew == false) then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_II);
player:addKeyItem(STALACTITE_DEW);
player:messageSpecial(KEYITEM_OBTAINED, STALACTITE_DEW);
player:setVar("SquiresTestII",0);
debugTeleport(player,17719359); -- Balasiel, zone 230, -138 x
elseif(HasDew)then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_III);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
player:setVar("SquiresTestII",0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end; | gpl-3.0 |
tboox/xmake-repo | packages/l/libxml2/xmake.lua | 1 | 1851 | package("libxml2")
set_homepage("http://xmlsoft.org/")
set_description("The XML C parser and toolkit of Gnome.")
set_urls("http://xmlsoft.org/sources/libxml2-$(version).tar.gz",
"https://ftp.osuosl.org/pub/blfs/conglomeration/libxml2/libxml2-$(version).tar.gz")
add_urls("https://gitlab.gnome.org/GNOME/libxml2.git")
add_versions("2.9.9", "94fb70890143e3c6549f265cee93ec064c80a84c42ad0f23e85ee1fd6540a871")
add_includedirs("include/libxml2")
if is_plat("windows") then
add_links("libxml2_a")
add_syslinks("wsock32", "ws2_32")
else
add_links("xml2")
end
on_load("macosx", "linux", "iphoneos", "android", function (package)
if package:gitref() then
package:add("deps", "autoconf", "automake", "libtool", "pkg-config")
end
end)
if is_plat("windows") and winos.version():gt("winxp") then
on_install("windows", function (package)
os.cd("win32")
os.vrun("cscript configure.js iso8859x=yes iconv=no compiler=msvc cruntime=/MT debug=%s prefix=\"%s\"", package:debug() and "yes" or "no", package:installdir())
os.vrun("nmake /f Makefile.msvc")
os.vrun("nmake /f Makefile.msvc install")
end)
end
on_install("macosx", "linux", "iphoneos", "android", function (package)
local configs = {"--disable-dependency-tracking",
"--without-python",
"--without-lzma",
"--without-zlib",
"--without-iconv",
"--enable-shared=no"}
import("package.tools.autoconf").install(package, configs)
end)
on_test(function (package)
assert(package:has_cfuncs("xmlNewNode", {includes = {"libxml/parser.h", "libxml/tree.h"}}))
end)
| apache-2.0 |
Fatalerror66/ffxi-a | scripts/zones/King_Ranperres_Tomb/Zone.lua | 2 | 1300 | -----------------------------------
--
-- Zone: King_Ranperres_Tomb (190)
--
-----------------------------------
package.loaded["scripts/zones/King_Ranperres_Tomb/TextIDs"] = nil;
require("scripts/globals/settings");
require("scripts/zones/King_Ranperres_Tomb/TextIDs");
-----------------------------------
-- 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(242.012,5.305,340.059,121);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Tavnazian_Safehold/npcs/Melleupaux.lua | 6 | 1256 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Melleupaux
-- Standard Merchant NPC
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
require("scripts/zones/Tavnazian_Safehold/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,MELLEUPAUX_SHOP_DIALOG);
stock = {0x4042,1867, --Dagger
0x40b6,8478, --Longsword
0x43B7,8, --Rusty Bolt
0x47C7,93240, --Falx (COP Chapter 4 Needed; not implemented yet)
0x4726,51905} --Voulge (COP Chapter 4 Needed; not implemented yet)
showShop(player, STATIC, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
actionless/awesome | lib/awful/popup.lua | 1 | 15095 | ---------------------------------------------------------------------------
--- An auto-resized, free floating or modal wibox built around a widget.
--
-- This type of widget box (wibox) is auto closed when being clicked on and is
-- automatically resized to the size of its main widget.
--
-- Note that the widget itself should have a finite size. If something like a
-- `wibox.layout.flex` is used, then the size would be unlimited and an error
-- will be printed. The `wibox.layout.fixed`, `wibox.container.constraint`,
-- `forced_width` and `forced_height` are recommended.
--
--@DOC_awful_popup_simple_EXAMPLE@
--
-- Here is an example of how to create an alt-tab like dialog by leveraging
-- the `awful.widget.tasklist`.
--
--@DOC_awful_popup_alttab_EXAMPLE@
--
-- @author Emmanuel Lepage Vallee
-- @copyright 2016 Emmanuel Lepage Vallee
-- @popupmod awful.popup
-- @supermodule wibox
---------------------------------------------------------------------------
local wibox = require( "wibox" )
local gtable = require( "gears.table" )
local placement = require( "awful.placement" )
local xresources= require("beautiful.xresources")
local timer = require( "gears.timer" )
local capi = {mouse = mouse}
local module = {}
local main_widget = {}
-- Get the optimal direction for the wibox
-- This (try to) avoid going offscreen
local function set_position(self)
-- First, if there is size to be applied, do it
if self._private.next_width then
self.width = self._private.next_width
self._private.next_width = nil
end
if self._private.next_height then
self.height = self._private.next_height
self._private.next_height = nil
end
local pf = self._private.placement
if pf == false then return end
if pf then
pf(self, {bounding_rect = self.screen.geometry})
return
end
local geo = self._private.widget_geo
if not geo then return end
local _, pos_name, anchor_name = placement.next_to(self, {
preferred_positions = self._private.preferred_directions,
geometry = geo,
preferred_anchors = self._private.preferred_anchors,
offset = self._private.offset or { x = 0, y = 0},
})
if pos_name ~= self._private.current_position then
local old = self._private.current_position
self._private.current_position = pos_name
self:emit_signal("property::current_position", pos_name, old)
end
if anchor_name ~= self._private.current_anchor then
local old = self._private.current_anchor
self._private.current_anchor = anchor_name
self:emit_signal("property::current_anchor", anchor_name, old)
end
end
-- Set the wibox size taking into consideration the limits
local function apply_size(self, width, height, set_pos)
local prev_geo = self:geometry()
width = math.max(self._private.minimum_width or 1, math.ceil(width or 1))
height = math.max(self._private.minimum_height or 1, math.ceil(height or 1))
if self._private.maximum_width then
width = math.min(self._private.maximum_width, width)
end
if self._private.maximum_height then
height = math.min(self._private.maximum_height, height)
end
self._private.next_width, self._private.next_height = width, height
if set_pos or width ~= prev_geo.width or height ~= prev_geo.height then
set_position(self)
end
end
-- Layout this widget
function main_widget:layout(context, width, height)
if self._private.widget then
local w, h = wibox.widget.base.fit_widget(
self,
context,
self._private.widget,
self._wb._private.maximum_width or 9999,
self._wb._private.maximum_height or 9999
)
timer.delayed_call(function()
apply_size(self._wb, w, h, true)
end)
return { wibox.widget.base.place_widget_at(self._private.widget, 0, 0, width, height) }
end
end
-- Set the widget that is drawn on top of the background
function main_widget:set_widget(widget)
if widget then
wibox.widget.base.check_widget(widget)
end
self._private.widget = widget
self:emit_signal("widget::layout_changed")
self:emit_signal("property::widget")
end
function main_widget:get_widget()
return self._private.widget
end
function main_widget:get_children_by_id(name)
return self._wb:get_children_by_id(name)
end
local popup = {}
--- Set the preferred popup position relative to its parent.
--
-- This allows, for example, to have a submenu that goes on the right of the
-- parent menu. If there is no space on the right, it tries on the left and so
-- on.
--
-- Valid directions are:
--
-- * left
-- * right
-- * top
-- * bottom
--
-- The basic use case for this method is to give it a parent wibox:
--
-- @DOC_awful_popup_position1_EXAMPLE@
--
-- As demonstrated by this second example, it is also possible to use a widget
-- as a parent object:
--
-- @DOC_awful_popup_position2_EXAMPLE@
--
-- @property preferred_positions
-- @tparam table|string preferred_positions A position name or an ordered
-- table of positions
-- @see awful.placement.next_to
-- @see awful.popup.preferred_anchors
-- @propemits true false
function popup:set_preferred_positions(pref_pos)
self._private.preferred_directions = pref_pos
set_position(self)
self:emit_signal("property::preferred_positions", pref_pos)
end
--- Set the preferred popup anchors relative to the parent.
--
-- The possible values are:
--
-- * front
-- * middle
-- * back
--
-- For details information, see the `awful.placement.next_to` documentation.
--
-- In this example, it is possible to see the effect of having a fallback
-- preferred anchors when the popup would otherwise not fit:
--
-- @DOC_awful_popup_anchors_EXAMPLE@
--
-- @property preferred_anchors
-- @tparam table|string preferred_anchors Either a single anchor name or a table
-- ordered by priority.
-- @propemits true false
-- @see awful.placement.next_to
-- @see awful.popup.preferred_positions
function popup:set_preferred_anchors(pref_anchors)
self._private.preferred_anchors = pref_anchors
set_position(self)
self:emit_signal("property::preferred_anchors", pref_anchors)
end
--- The current position relative to the parent object.
--
-- If there is a parent object (widget, wibox, wibar, client or the mouse), then
-- this property returns the current position. This is determined using
-- `preferred_positions`. It is usually the preferred position, but when there
-- isn't enough space, it can also be one of the fallback.
--
-- @property current_position
-- @tparam string current_position Either "left", "right", "top" or "bottom"
function popup:get_current_position()
return self._private.current_position
end
--- Get the current anchor relative to the parent object.
--
-- If there is a parent object (widget, wibox, wibar, client or the mouse), then
-- this property returns the current anchor. The anchor is the "side" of the
-- parent object on which the popup is based on. It will "grow" in the
-- opposite direction from the anchor.
--
-- @property current_anchor
-- @tparam string current_anchor Either "front", "middle", "back"
function popup:get_current_anchor()
return self._private.current_anchor
end
--- Move the wibox to a position relative to `geo`.
-- This will try to avoid overlapping the source wibox and auto-detect the right
-- direction to avoid going off-screen.
--
-- @param[opt=mouse] obj An object such as a wibox, client or a table entry
-- returned by `wibox:find_widgets()`.
-- @see awful.placement.next_to
-- @see awful.popup.preferred_positions
-- @see awful.popup.preferred_anchors
-- @treturn table The new geometry
-- @method move_next_to
function popup:move_next_to(obj)
if self._private.is_relative == false then return end
self._private.widget_geo = obj
obj = obj or capi.mouse
if obj._apply_size_now then
obj:_apply_size_now(false)
end
self.visible = true
self:_apply_size_now(true)
self._private.widget_geo = nil
end
--- Bind the popup to a widget button press.
--
-- @tparam widget widget The widget
-- @tparam[opt=1] number button The button index
-- @method bind_to_widget
function popup:bind_to_widget(widget, button)
if not self._private.button_for_widget then
self._private.button_for_widget = {}
end
self._private.button_for_widget[widget] = button or 1
widget:connect_signal("button::press", self._private.show_fct)
end
--- Unbind the popup from a widget button.
-- @tparam widget widget The widget
-- @method unbind_to_widget
function popup:unbind_to_widget(widget)
widget:disconnect_signal("button::press", self._private.show_fct)
end
--- Hide the popup when right clicked.
--
-- @property hide_on_right_click
-- @tparam[opt=false] boolean hide_on_right_click
-- @propemits true false
function popup:set_hide_on_right_click(value)
self[value and "connect_signal" or "disconnect_signal"](
self, "button::press", self._private.hide_fct
)
self:emit_signal("property::hide_on_right_click", value)
end
--- The popup minimum width.
--
-- @property minimum_width
-- @tparam[opt=1] number minimum_width The minimum width.
-- @propemits true false
--- The popup minimum height.
--
-- @property minimum_height
-- @tparam[opt=1] number minimum_height The minimum height.
-- @propemits true false
--- The popup maximum width.
--
-- @property maximum_width
-- @tparam[opt=1] number maximum_width The maximum width.
-- @propemits true false
--- The popup maximum height.
--
-- @property maximum_height
-- @tparam[opt=1] number maximum_height The maximum height.
-- @propemits true false
for _, orientation in ipairs {"_width", "_height"} do
for _, limit in ipairs {"minimum", "maximum"} do
local prop = limit..orientation
popup["set_"..prop] = function(self, value)
self._private[prop] = value
self._private.container:emit_signal("widget::layout_changed")
self:emit_signal("property::"..prop, value)
end
popup["get_"..prop] = function(self)
return self._private[prop]
end
end
end
--- The distance between the popup and its parent (if any).
--
-- Here is an example of 5 popups stacked one below the other with an y axis
-- offset (spacing).
--
-- @DOC_awful_popup_position3_EXAMPLE@
-- @property offset
-- @tparam table|number offset An integer value or a `{x=, y=}` table.
-- @tparam[opt=offset] number offset.x The horizontal distance.
-- @tparam[opt=offset] number offset.y The vertical distance.
-- @propemits true false
function popup:set_offset(offset)
if type(offset) == "number" then
offset = {
x = offset or 0,
y = offset or 0,
}
end
local oldoff = self._private.offset or {x=0, y=0}
if oldoff.x == offset.x and oldoff.y == offset.y then return end
offset.x, offset.y = offset.x or oldoff.x or 0, offset.y or oldoff.y or 0
self._private.offset = offset
self:_apply_size_now(false)
self:emit_signal("property::offset", offset)
end
--- Set the placement function.
--
-- @tparam[opt=next_to] function|string|boolean The placement function or name
-- (or false to disable placement)
-- @property placement
-- @param function
-- @propemits true false
-- @see awful.placement
function popup:set_placement(f)
if type(f) == "string" then
f = placement[f]
end
self._private.placement = f
self:_apply_size_now(false)
self:emit_signal("property::placement")
end
-- For the tests and the race condition when 2 popups are placed next to each
-- other.
function popup:_apply_size_now(skip_set)
if not self.widget then return end
local w, h = wibox.widget.base.fit_widget(
self.widget,
{dpi= self.screen.dpi or xresources.get_dpi()},
self.widget,
self._private.maximum_width or 9999,
self._private.maximum_height or 9999
)
-- It is important to do it for the obscure reason that calling `w:geometry()`
-- is actually mutating the state due to quantum determinism thanks to XCB
-- async nature... It is only true the very first time `w:geometry()` is
-- called
self.width = math.max(1, math.ceil(w or 1))
self.height = math.max(1, math.ceil(h or 1))
apply_size(self, w, h, skip_set ~= false)
end
function popup:set_widget(wid)
self._private.widget = wid
self._private.container:set_widget(wid)
self:emit_signal("property::widget", wid)
end
function popup:get_widget()
return self._private.widget
end
--- Create a new popup build around a passed in widget.
-- @tparam[opt=nil] table args
--@DOC_wibox_constructor_COMMON@
-- @tparam function args.placement The `awful.placement` function
-- @tparam string|table args.preferred_positions
-- @tparam string|table args.preferred_anchors
-- @tparam table|number args.offset The X and Y offset compared to the parent object
-- @tparam boolean args.hide_on_right_click Whether or not to hide the popup on
-- right clicks.
-- @constructorfct awful.popup
local function create_popup(_, args)
assert(args)
-- Temporarily remove the widget
local original_widget = args.widget
args.widget = nil
assert(original_widget, "The `awful.popup` requires a `widget` constructor argument")
local child_widget = wibox.widget.base.make_widget_from_value(original_widget)
local ii = wibox.widget.base.make_widget(child_widget, "awful.popup", {
enable_properties = true
})
gtable.crush(ii, main_widget, true)
-- Create a wibox to host the widget
local w = wibox(args or {})
rawset(w, "_private", {
container = ii,
preferred_directions = { "right", "left", "top", "bottom" },
preferred_anchors = { "back", "front", "middle" },
widget = child_widget
})
gtable.crush(w, popup)
ii:set_widget(child_widget)
-- Create the signal handlers
function w._private.show_fct(wdg, _, _, button, _, geo)
if button == w._private.button_for_widget[wdg] then
w:move_next_to(geo)
end
end
function w._private.hide_fct()
w.visible = false
end
-- Restore
args.widget = original_widget
-- Cross-link the wibox and widget
ii._wb = w
wibox.set_widget(w, ii)
--WARNING The order is important
-- First, apply the limits to avoid a flicker with large width or height
-- when set_position is called before the limits
for _,v in ipairs{"minimum_width", "minimum_height", "maximum_height",
"maximum_width", "offset", "placement","preferred_positions",
"preferred_anchors", "hide_on_right_click"} do
if args[v] ~= nil then
w["set_"..v](w, args[v])
end
end
-- Default to visible
if args.visible ~= false then
w.visible = true
end
return w
end
--@DOC_wibox_COMMON@
return setmetatable(module, {__call = create_popup})
| gpl-2.0 |
actionless/awesome | lib/awful/widget/prompt.lua | 1 | 6748 | ---------------------------------------------------------------------------
-- The widget version of `awful.prompt`.
--
-- @DOC_wibox_awidget_defaults_prompt_EXAMPLE@
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2009 Julien Danjou
-- @copyright 2018 Aire-One
-- @widgetmod awful.widget.prompt
-- @supermodule wibox.container.background
---------------------------------------------------------------------------
--- The prompt foreground color.
-- @beautiful beautiful.prompt_fg
-- @param color
-- @see gears.color
--- The prompt background color.
-- @beautiful beautiful.prompt_bg
-- @param color
-- @see gears.color
local setmetatable = setmetatable
local completion = require("awful.completion")
local gfs = require("gears.filesystem")
local gdebug = require("gears.debug")
local spawn = require("awful.spawn")
local prompt = require("awful.prompt")
local beautiful = require("beautiful")
local textbox = require("wibox.widget.textbox")
local background = require("wibox.container.background")
local type = type
local widgetprompt = { mt = {} }
--- Run method for promptbox.
--
-- @param promptbox The promptbox to run.
local function run(promptbox)
return prompt.run {
prompt = promptbox.prompt,
textbox = promptbox.widget,
fg_cursor = promptbox.fg_cursor,
bg_cursor = promptbox.bg_cursor,
ul_cursor = promptbox.ul_cursor,
font = promptbox.font,
autoexec = promptbox.autoexec,
highlighter = promptbox.highlighter,
exe_callback = promptbox.exe_callback,
completion_callback = promptbox.completion_callback,
history_path = promptbox.history_path,
history_max = promptbox.history_max,
done_callback = promptbox.done_callback,
changed_callback = promptbox.changed_callback,
keypressed_callback = promptbox.keypressed_callback,
keyreleased_callback = promptbox.keyreleased_callback,
hooks = promptbox.hooks
}
end
local function spawn_and_handle_error(self, ...)
local f = self.with_shell and spawn.with_shell or spawn
local result = f(...)
if type(result) == "string" then
self.widget:set_text(result)
end
end
--- Always spawn using a shell.
--
-- When using the default `exe_callback`, use `awful.spawn.with_shell` instead
-- of `awful.spawn`. Depending on the ammount of customization to your shell
-- environment, this can increase startup time.
-- @property with_shell
-- @param[opt=false] boolean
--- Create a prompt widget which will launch a command.
-- For additional documentation about `args` parameter, please refer to
-- @{awful.prompt} and @{awful.prompt.run}.
--
-- @tparam table args Prompt arguments.
-- @tparam[opt="Run: "] string args.prompt Prompt text.
-- @tparam[opt=`beautiful.prompt_bg` or `beautiful.bg_normal`] color args.bg
-- Prompt background color.
-- @tparam[opt=`beautiful.prompt_fg` or `beautiful.fg_normal`] color args.fg
-- Prompt foreground color.
-- @tparam[opt] gears.color args.fg_cursor
-- @tparam[opt] gears.color args.bg_cursor
-- @tparam[opt] gears.color args.ul_cursor
-- @tparam[opt] string args.font
-- @tparam[opt] boolean args.autoexec
-- @tparam[opt] function args.highlighter A function to add syntax highlighting
-- to the command.
-- @tparam[opt] function args.exe_callback The callback function to call with
-- command as argument when finished.
-- @tparam[opt=false] boolean args.with_shell Use a (terminal) shell to execute this.
-- @tparam[opt=`awful.completion.shell`] function args.completion_callback
-- The callback function to call to get completion. See @{awful.prompt.run}
-- for details.
-- @tparam[opt=`gears.filesystem.get_cache_dir() .. '/history'`] string
-- args.history_path File path where the history should be saved.
-- @tparam[opt=50] integer args.history_max Set the maximum entries in
-- history file.
-- @tparam[opt] function args.done_callback
-- The callback function to always call without arguments, regardless of
-- whether the prompt was cancelled. See @{awful.prompt.run} for details.
-- @tparam[opt] function args.changed_callback The callback function to call
-- with command as argument when a command was changed.
-- @tparam[opt] function args.keypressed_callback The callback function to call
-- with mod table, key and command as arguments when a key was pressed.
-- @tparam[opt] function args.keyreleased_callback The callback function to call
-- with mod table, key and command as arguments when a key was pressed.
-- @tparam[opt] table args.hooks Similar to @{awful.key}. It will call a function
-- for the matching modifiers + key. See @{awful.prompt.run} for details.
-- @return An instance of prompt widget, inherits from
-- `wibox.container.background`.
-- @constructorfct awful.widget.prompt
function widgetprompt.new(args)
args = args or {}
local promptbox = background()
promptbox.widget = textbox()
promptbox.widget:set_ellipsize("start")
promptbox.run = run
promptbox.spawn_and_handle_error = spawn_and_handle_error
promptbox.prompt = args.prompt or "Run: "
promptbox.fg = args.fg or beautiful.prompt_fg or beautiful.fg_normal
promptbox.bg = args.bg or beautiful.prompt_bg or beautiful.bg_normal
promptbox.fg_cursor = args.fg_cursor or nil
promptbox.bg_cursor = args.bg_cursor or nil
promptbox.ul_cursor = args.ul_cursor or nil
promptbox.font = args.font or nil
promptbox.autoexec = args.autoexec or nil
promptbox.highlighter = args.highlighter or nil
promptbox.exe_callback = args.exe_callback or function (...)
promptbox:spawn_and_handle_error(...)
end
promptbox.completion_callback = args.completion_callback or completion.shell
promptbox.history_path = args.history_path or
gfs.get_cache_dir() .. 'history'
promptbox.history_max = args.history_max or nil
promptbox.done_callback = args.done_callback or nil
promptbox.changed_callback = args.changed_callback or nil
promptbox.keypressed_callback = args.keypressed_callback or nil
promptbox.keyreleased_callback = args.keyreleased_callback or nil
if args.hook and not args.hooks then
gdebug.deprecate("Use `args.hooks` instead of `args.hook`",
{deprecated_in=5})
args.hooks = args.hook
end
promptbox.hooks = args.hooks or nil
return promptbox
end
function widgetprompt.mt:__call(...)
return widgetprompt.new(...)
end
return setmetatable(widgetprompt, widgetprompt.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
kidaa/FFXIOrgins | scripts/zones/Port_San_dOria/npcs/Nazar.lua | 7 | 1033 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Nazar
-- Type: Standard NPC
-- @zone: 232
-- @pos -31.922 -3 44.240
--
-- Auto-Script: Requires Verification (Verified by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x02bf);
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/globals/items/head_of_napa.lua | 2 | 1134 | -----------------------------------------
-- ID: 5235
-- Item: head_of_napa
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 1
-- Vitality -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,300,5235);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 1);
target:addMod(MOD_VIT, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 1);
target:delMod(MOD_VIT, -3);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Northern_San_dOria/npcs/Hunt_Registry.lua | 2 | 1086 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Hunt Registry
-- @zone 231
-- @pos -174.000, 4.000, 74.000
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x05DC);
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/globals/weaponskills/crescent_moon.lua | 6 | 1453 | -----------------------------------
-- Crescent Moon
-- Great Sword weapon skill
-- Skill level: 175
-- Delivers a single-hit attack. Damage varies with TP.
-- Modifiers: STR:35%
-- 100%TP 200%TP 300%TP
-- 1.0 1.75 2.5
-----------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/weaponskills");
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
--ftp damage mods (for Damage Varies with TP; lines are calculated in the function
params.ftp100 = 1; params.ftp200 = 1.75; params.ftp300 = 2.5;
--wscs are in % so 0.2=20%
params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
--critical mods, again in % (ONLY USE FOR CRITICAL HIT VARIES WITH TP)
params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0;
params.canCrit = false;
--params.accuracy mods (ONLY USE FOR ACCURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp.
params.acc100 = 0; params.acc200=0; params.acc300=0;
--attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default.
params.atkmulti = 1;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/weaponskills/camlanns_torment.lua | 4 | 1127 | -----------------------------------
-- Camlann's Torment
-- Polearm weapon skill
-- Skill Level: EMPYREAN
-- Delivers a triple damage attack. DEF ignored varies with TP.
-- Will stack with Sneak Attack.
-- Element: None
-- Modifiers: VIT:60%
-- 100%TP 200%TP 300%TP
-- 3.00 3 3
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; 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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/serving_of_flounder_meuniere_+1.lua | 1 | 1594 | -----------------------------------------
-- ID: 4345
-- Item: serving_of_flounder_meuniere_+1
-- Food Effect: 240Min, All Races
-----------------------------------------
-- Dexterity 6
-- Vitality 1
-- Mind -1
-- Ranged ACC 15
-- Ranged ATT % 14
-- Ranged ATT Cap 30
-- Enmity -3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,14400,4345);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 6);
target:addMod(MOD_VIT, 1);
target:addMod(MOD_MND, -1);
target:addMod(MOD_RACC, 15);
target:addMod(MOD_FOOD_RATTP, 14);
target:addMod(MOD_FOOD_RATT_CAP, 30);
target:addMod(MOD_ENMITY, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 6);
target:delMod(MOD_VIT, 1);
target:delMod(MOD_MND, -1);
target:delMod(MOD_RACC, 15);
target:delMod(MOD_FOOD_RATTP, 14);
target:delMod(MOD_FOOD_RATT_CAP, 30);
target:delMod(MOD_ENMITY, -3);
end;
| gpl-3.0 |
jiang42/Algorithm-Implementations | Shell_Sort/Lua/Yonaba/shell_sort_test.lua | 27 | 1367 | -- Tests for shell_sort.lua
local shell_sort = require 'shell_sort'
local total, pass = 0, 0
local function dec(str, len)
return #str < len
and str .. (('.'):rep(len-#str))
or str:sub(1,len)
end
local function run(message, f)
total = total + 1
local ok, err = pcall(f)
if ok then pass = pass + 1 end
local status = ok and 'PASSED' or 'FAILED'
print(('%02d. %68s: %s'):format(total, dec(message,68), status))
end
-- Comparison functions
local function le(a,b) return a <= b end
local function ge(a,b) return a >= b end
-- Checks if list is sorted
function is_sorted(list, comp)
comp = comp or le
for i = 2, #list do
if not comp(list[i-1],list[i]) then return false end
end
return true
end
-- Generates a table of n random values
local function gen(n)
local t = {}
for i = 1, n do t[i] = math.random(n) end
return t
end
math.randomseed(os.time())
run('Empty arrays', function()
local t = {}
assert(is_sorted(shell_sort({})))
end)
run('Already sorted array', function()
local t = {1, 2, 3, 4, 5}
assert(is_sorted(shell_sort(t)))
end)
run('Sorting a large array (1e3 values)', function()
local t = gen(1e3)
assert(is_sorted(shell_sort(t)))
assert(is_sorted(shell_sort(t, ge), ge))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
MyAOSP/external_skia | tools/lua/skia.lua | 207 | 1863 | -- Experimental helpers for skia --
function string.startsWith(String,Start)
return string.sub(String,1,string.len(Start))==Start
end
function string.endsWith(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
Sk = {}
function Sk.isFinite(x)
return x * 0 == 0
end
-------------------------------------------------------------------------------
Sk.Rect = { left = 0, top = 0, right = 0, bottom = 0 }
Sk.Rect.__index = Sk.Rect
function Sk.Rect.new(l, t, r, b)
local rect
if r then
-- 4 arguments
rect = { left = l, top = t, right = r, bottom = b }
elseif l then
-- 2 arguments
rect = { right = l, bottom = t }
else
-- 0 arguments
rect = {}
end
setmetatable(rect, Sk.Rect)
return rect;
end
function Sk.Rect:width()
return self.right - self.left
end
function Sk.Rect:height()
return self.bottom - self.top
end
function Sk.Rect:isEmpty()
return self:width() <= 0 or self:height() <= 0
end
function Sk.Rect:isFinite()
local value = self.left * 0
value = value * self.top
value = value * self.right
value = value * self.bottom
return 0 == value
end
function Sk.Rect:setEmpty()
self.left = 0
self.top = 0
self.right = 0
self.bottom = 0
end
function Sk.Rect:set(l, t, r, b)
self.left = l
self.top = t
self.right = r
self.bottom = b
end
function Sk.Rect:offset(dx, dy)
dy = dy or dx
self.left = self.left + dx
self.top = self.top + dy
self.right = self.right + dx
self.bottom = self.bottom + dy
end
function Sk.Rect:inset(dx, dy)
dy = dy or dx
self.left = self.left + dx
self.top = self.top + dy
self.right = self.right - dx
self.bottom = self.bottom - dy
end
-------------------------------------------------------------------------------
| bsd-3-clause |
sapohl/data-pipeline | hindsight/modules/fx/ping.lua | 2 | 5998 | -- This Source Code Form is subject to the terms of the Mozilla Public
-- License, v. 2.0. If a copy of the MPL was not distributed with this
-- file, You can obtain one at http://mozilla.org/MPL/2.0/.
local M = {}
local ipairs = ipairs
local pairs = pairs
local pcall = pcall
local tonumber = tonumber
local type = type
local read_message = read_message
local cjson = require "cjson"
local dt = require "date_time"
local l = require "lpeg"
l.locale(l)
local format = require "string".format
setfenv(1, M) -- Remove external access to contain everything in the module
local crash_date = dt.build_strftime_grammar("%Y-%m-%d")
local integer = l.digit^1/tonumber
local flash_ver_grammar = l.Ct(integer * "." * integer * "." * integer * "." * integer)
local cache = {} -- cache to store the parsed json components while working with a message
local SEC_IN_HOUR = 60 * 60
local SEC_IN_DAY = SEC_IN_HOUR * 24
function clear_cache()
cache = {}
end
function build()
if not cache.build then
local json = read_message("Fields[environment.build]")
local ok
ok, cache.build = pcall(cjson.decode, json)
if not ok then cache.build = {} end
end
return cache.build
end
function system()
if not cache.system then
local json = read_message("Fields[environment.system]")
local ok
ok, cache.system = pcall(cjson.decode, json)
if not ok then cache.system = {} end
if type(cache.system.os) ~= "table" then
cache.system.os = {}
end
end
return cache.system
end
function addons()
if not cache.addons then
local json = read_message("Fields[environment.addons]")
local ok
ok, cache.addons = pcall(cjson.decode, json)
if not ok then cache.addons = {} end
if type(cache.addons.activeExperiment) ~= "table" then
cache.addons.activeExperiment = {}
end
end
return cache.addons
end
function num_active_addons()
local addons = addons()
local cnt = 0
if type(addons.activeAddons) == "table" then
for k,v in pairs(addons.activeAddons) do
cnt = cnt + 1
end
end
return cnt
end
function flash_version()
local addons = addons()
local version
if type(addons.activePlugins) == "table" then
for i,v in ipairs(addons.activePlugins) do
if type(v) == "table" and v.name == "Shockwave Flash" then
if type(v.version) ~= "string" then v.version = "" end
local sv = flash_ver_grammar:match(v.version)
if sv then
if not version
or sv[1] > version[1]
or sv[2] > version[2]
or sv[3] > version[3]
or sv[4] > version[4] then
sv[5] = v.version
version = sv
end
end
end
end
if version then version = version[5] end
end
return version
end
function settings()
if not cache.settings then
local json = read_message("Fields[environment.settings]")
local ok
ok, cache.settings = pcall(cjson.decode, json)
if not ok then cache.settings = {} end
end
return cache.settings
end
function is_default_browser()
local settings = settings()
local b = settings.isDefaultBrowser
if type(b) == "boolean" then
return b
end
return false
end
function profile()
if not cache.profile then
local json = read_message("Fields[environment.profile]")
local ok
ok, cache.profile = pcall(cjson.decode, json)
if not ok then cache.profile = {} end
end
return cache.profile
end
function profile_creation_timestamp()
local profile = profile()
local days = profile.creationDate
if type(days) == "number" and days > 0 then
return days * SEC_IN_DAY * 1e9
end
return 0
end
function khist()
if not cache.khist then
local json = read_message("Fields[payload.keyedHistograms]")
local ok
ok, cache.khist = pcall(cjson.decode, json)
if not ok then cache.khist = {} end
end
return cache.khist
end
function khist_sum(section, key)
local khist = khist()
local t = khist[section]
if type(t) == "table" then
t = t[key]
if type(t) == "table" then
local sum = t.sum
if type(sum) == "number" and sum > 0 then
return sum
end
end
end
end
function info()
if not cache.info then
local json = read_message("Fields[payload.info]")
local ok
ok, cache.info = pcall(cjson.decode, json)
if not ok then cache.info = {} end
end
return cache.info
end
function hours()
local uptime = info().subsessionLength
if type(uptime) ~= "number" or uptime < 0 or uptime >= 180 * SEC_IN_DAY then
return 0
end
return uptime / SEC_IN_HOUR
end
function payload()
if not cache.payload then
local json = read_message("Payload")
local ok
ok, cache.payload = pcall(cjson.decode, json)
if not ok then cache.payload = {} end
if type(cache.payload.payload) ~= "table" then
cache.payload.payload = {}
end
end
return cache.payload
end
function get_timestamp(d)
if type(d) == "string" then
local t = dt.rfc3339:match(d)
if t then
return dt.time_to_ns(t)
else -- some dates are not RFC compliant
t = crash_date:match(d)
if t then
return dt.time_to_ns(t)
end
end
end
end
function get_date(d)
if type(d) == "string" then
local t = crash_date:match(d)
if t then
return format("%s-%s-%s", t.year, t.month, t.day)
end
end
end
return M
| mpl-2.0 |
roboxt/ss | plugins/id.lua | 2 | 6343 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
--------------------------------------------------
local function usernameinfo (user)
if user.username then
return '@'..user.username
end
if user.print_name then
return user.print_name
end
local text = ''
if user.first_name then
text = user.last_name..' '
end
if user.lastname then
text = text..user.last_name
end
return text
end
local function whoisname(cb_extra, success, result)
chat_type = cb_extra.chat_type
chat_id = cb_extra.chat_id
user_id = result.peer_id
user_username = result.username
if chat_type == 'chat' then
send_msg('chat#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..user_username..' ('..user_id..')', ok_cb, false)
elseif chat_type == 'channel' then
send_msg('channel#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..user_username..' ('..user_id..')', ok_cb, false)
end
end
local function whoisid(cb_extra, success, result)
chat_id = cb_extra.chat_id
user_id = cb_extra.user_id
if cb_extra.chat_type == 'chat' then
send_msg('chat#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..result.username..' ('..user_id..')', ok_cb, false)
elseif cb_extra.chat_type == 'channel' then
send_msg('channel#id'..chat_id, '👤 '..lang_text(chat_id, 'user')..' @'..result.username..' ('..user_id..')', ok_cb, false)
end
end
local function channelUserIDs (extra, success, result)
local receiver = extra.receiver
print('Result')
vardump(result)
local text = ''
for k,user in ipairs(result) do
local id = user.peer_id
local username = usernameinfo (user)
text = text..("%s - %s\n"):format(username, id)
end
send_large_msg(receiver, text)
end
local function get_id_who(extra, success, result)
result = backward_msg_format(result)
local msg = result
local chat = msg.to.id
local user = msg.from.id
if msg.to.type == 'chat' then
send_msg('chat#id'..msg.to.id, '🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false)
elseif msg.to.type == 'channel' then
send_msg('channel#id'..msg.to.id, '🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false)
end
end
local function returnids (extra, success, result)
local receiver = extra.receiver
local chatname = result.print_name
local id = result.peer_id
local text = ('ID for chat %s (%s):\n'):format(chatname, id)
for k,user in ipairs(result.members) do
local username = usernameinfo(user)
local id = user.peer_id
local userinfo = ("%s - %s\n"):format(username, id)
text = text .. userinfo
end
send_large_msg(receiver, text)
end
local function run(msg, matches)
local receiver = get_receiver(msg)
local chat = msg.to.id
-- Id of the user and info about group / channel
if matches[1] == "ایدی" then
if permissions(msg.from.id, msg.to.id, "id") then
if msg.to.type == 'channel' then
send_msg(msg.to.peer_id, '🔠 '..lang_text(chat, 'supergroupName')..': '..msg.to.print_name:gsub("_", " ")..'\n👥 '..lang_text(chat, 'supergroup')..' ID: '..msg.to.id..'\n🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false)
elseif msg.to.type == 'chat' then
send_msg(msg.to.peer_id, '🔠 '..lang_text(chat, 'chatName')..': '..msg.to.print_name:gsub("_", " ")..'\n👥 '..lang_text(chat, 'chat')..' ID: '..msg.to.id..'\n🆔 '..lang_text(chat, 'user')..' ID: '..msg.from.id, ok_cb, false)
end
end
elseif matches[1] == 'کیه' then
if permissions(msg.from.id, msg.to.id, "whois") then
chat_type = msg.to.type
chat_id = msg.to.id
if msg.reply_id then
get_message(msg.reply_id, get_id_who, {receiver=get_receiver(msg)})
return
end
if is_id(matches[2]) then
print(1)
user_info('user#id'..matches[2], whoisid, {chat_type=chat_type, chat_id=chat_id, user_id=matches[2]})
return
else
local member = string.gsub(matches[2], '@', '')
resolve_username(member, whoisname, {chat_id=chat_id, member=member, chat_type=chat_type})
return
end
else
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
elseif matches[1] == 'chat' or matches[1] == 'channel' then
if permissions(msg.from.id, msg.to.id, "whois") then
local type = matches[1]
local chanId = matches[2]
-- !ids? (chat) (%d+)
if chanId then
local chan = ("%s#id%s"):format(type, chanId)
if type == 'chat' then
chat_info(chan, returnids, {receiver=receiver})
else
channel_get_users(chan, channelUserIDs, {receiver=receiver})
end
else
-- !id chat/channel
local chan = ("%s#id%s"):format(msg.to.type, msg.to.id)
if msg.to.type == 'channel' then
channel_get_users(chan, channelUserIDs, {receiver=receiver})
end
if msg.to.type == 'chat' then
chat_info(chan, returnids, {receiver=receiver})
end
end
else
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
end
end
return {
description = "Simplest plugin ever!",
usage = "!id [whatever]: echoes the msg",
patterns = {
"^(کیه)$",
"^(ایدی)$",
"^ids? (chat)$",
"^ids? (channel)$",
"^(کیه) (.*)$"
},
run = run
}
| gpl-2.0 |
mahdibagheri/mahdi1234 | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
hfjgjfg/seed48 | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
kiarash14/tel | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
mrbangi/mr--bangi | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/globals/spells/dia_ii.lua | 2 | 1894 | -----------------------------------------
-- Spell: Dia II
-- Lowers an enemy's defense and gradually deals light elemental damage.
-----------------------------------------
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/magic");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
--calculate raw damage
local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 4;
local dmg = calculateMagicDamage(basedmg,3,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false);
-- Softcaps at 8, should always do at least 1
dmg = utils.clamp(dmg, 1, 8);
--get resist multiplier (1x if no resist)
local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0);
--get the resisted damage
dmg = dmg*resist;
--add on bonuses (staff/day/weather/jas/mab/etc all go in this function)
dmg = addBonuses(caster,spell,target,dmg);
--add in target adjustment
dmg = adjustForTarget(target,dmg);
--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() <= 2) or (DIA_OVERWRITE == 1 and bio:getPower() < 2)) then
target:addStatusEffect(EFFECT_DIA,2,3,duration,FLAG_ERASABLE, 10);
spell:setMsg(2);
else
spell:setMsg(75);
end
-- Try to kill same tier Bio
if(BIO_OVERWRITE == 1 and bio ~= nil) then
if(bio:getPower() <= 2) then
target:delStatusEffect(EFFECT_BIO);
end
end
return final;
end; | gpl-3.0 |
aliafshar250/b | bot/permissions.lua | 43 | 1333 | local sudos = {
"plugins",
"rank_admin",
"bot",
"lang_install",
"set_lang",
"tosupergroup",
"gban_installer"
}
local admins = {
"rank_mod",
"gban",
"ungban",
"setrules",
"setphoto",
"creategroup",
"setname",
"addbots",
"setlink",
"rank_guest",
"description",
"export_gban"
}
local mods = {
"whois",
"kick",
"add",
"ban",
"unban",
"lockmember",
"mute",
"unmute",
"admins",
"members",
"welcome",
"mods",
"flood",
"commands",
"lang",
"settings",
"mod_commands",
"no_flood_ban",
"muteall",
"rules",
"pre_process"
}
local function get_tag(plugin_tag)
for v,tag in pairs(sudos) do
if tag == plugin_tag then
return 3
end
end
for v,tag in pairs(admins) do
if tag == plugin_tag then
return 2
end
end
for v,tag in pairs(mods) do
if tag == plugin_tag then
return 1
end
end
return 0
end
local function user_num(user_id, chat_id)
if new_is_sudo(user_id) then
return 3
elseif is_admin(user_id) then
return 2
elseif is_mod(chat_id, user_id) then
return 1
else
return 0
end
end
function permissions(user_id, chat_id, plugin_tag)
local user_is = get_tag(plugin_tag)
local user_n = user_num(user_id, chat_id)
if user_n >= user_is then
return true
else
return false
end
end
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/globals/items/uskumru.lua | 3 | 1194 | -----------------------------------------
-- ID: 5452
-- Item: Uskumru
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:getRace() ~= 7) then
result = 247;
end
if(target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,5452);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/abilities/pets/hydro_breath.lua | 4 | 1222 | ---------------------------------------------------
-- Hydro Breath
---------------------------------------------------
require("/scripts/globals/settings");
require("/scripts/globals/status");
require("/scripts/globals/monstertpmoves");
---------------------------------------------------
function OnAbilityCheck(player, target, ability)
return 0,0;
end;
function OnPetAbility(target, pet, skill, master)
---------- Deep Breathing ----------
-- 0 for none
-- 1 for first merit
-- 0.25 for each merit after the first
-- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*)
local deep = 1;
if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then
deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25;
pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST);
end
local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath
local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_WATER); -- Works out to (hp/6) + 15, as desired
dmgmod = (dmgmod * (1+gear))*deep;
local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_WATER,MOBPARAM_IGNORE_SHADOWS);
target:delHP(dmg);
return dmg;
end | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Port_Windurst/npcs/Hohbiba-Mubiba.lua | 17 | 1689 | -----------------------------------
-- Area: Port Windurst
-- NPC: Hohbiba-Mubiba
-- Standard Merchant NPC
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,HOHBIBAMUBIBA_SHOP_DIALOG);
stock = {
0x429B, 1440,1, --Yew Wand
0x42A3, 91,1, --Bronze Rod
0x42C2, 3642,1, --Elm Staff
0x42C9, 18422,1, --Elm Pole
0x429A, 340,2, --Willow Wand
0x4282, 4945,2, --Bone Cudgel
0x42C1, 584,2, --Holly Staff
0x42C8, 4669,2, --Holly Pole
0x4299, 47,3, --Maple Wand
0x4280, 66,3, --Ash Club
0x4281, 1600,3, --Chestnut Club
0x42C0, 58,3, --Ash Staff
0x42C7, 386,3, --Ash Pole
0x4040, 143,3 --Bronze Dagger
}
showNationShop(player, WINDURST, stock);
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/items/balik_sis_+1.lua | 2 | 1603 | -----------------------------------------
-- ID: 5601
-- Item: Balik Sis +1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Dexterity 5
-- Mind -2
-- Attack % 15
-- Attack Cap 45
-- Ranged ACC 1
-- Ranged ATT % 15
-- Ranged ATT Cap 45
-----------------------------------------
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,3600,5601);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 5);
target:addMod(MOD_MND, -2);
target:addMod(MOD_FOOD_ATTP, 15);
target:addMod(MOD_FOOD_ATT_CAP, 45);
target:addMod(MOD_RACC, 1);
target:addMod(MOD_FOOD_RATTP, 15);
target:addMod(MOD_FOOD_RATT_CAP, 45);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 5);
target:delMod(MOD_MND, -2);
target:delMod(MOD_FOOD_ATTP, 15);
target:delMod(MOD_FOOD_ATT_CAP, 45);
target:delMod(MOD_RACC, 1);
target:delMod(MOD_FOOD_RATTP, 15);
target:delMod(MOD_FOOD_RATT_CAP, 45);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/spells/victory_march.lua | 6 | 1418 | -----------------------------------------
-- Spell: Victory March
-- Gives party members Haste
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnSpellCast
-----------------------------------------
function OnMagicCastingCheck(caster,target,spell)
return 0;
end;
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(SKILL_SNG); -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(SLOT_RANGED);
local power = 43;
if (sLvl+iLvl > 300) then
power = power + math.floor((sLvl+iLvl-300) / 7);
end
if(power >= 96) then
power = 96;
end
local iBoost = caster:getMod(MOD_MARCH_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT);
power = power + iBoost*16;
if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then
power = power * 2;
elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then
power = power * 1.5;
end
caster:delStatusEffect(EFFECT_MARCATO);
local duration = 120;
duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1);
if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then
duration = duration * 2;
end
if not (target:addBardSong(caster,EFFECT_MARCH,power,0,duration,caster:getID(), 0, 2)) then
spell:setMsg(75);
end
return EFFECT_MARCH;
end; | gpl-3.0 |
rigeirani/1kh | plugins/webshot.lua | 110 | 1424 | local helpers = require "OAuth.helpers"
local base = 'https://screenshotmachine.com/'
local url = base .. 'processor.php'
local function get_webshot_url(param)
local response_body = {}
local request_constructor = {
url = url,
method = "GET",
sink = ltn12.sink.table(response_body),
headers = {
referer = base,
dnt = "1",
origin = base,
["User-Agent"] = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36"
},
redirect = false
}
local arguments = {
urlparam = param,
size = "FULL"
}
request_constructor.url = url .. "?" .. helpers.url_encode_arguments(arguments)
local ok, response_code, response_headers, response_status_line = https.request(request_constructor)
if not ok or response_code ~= 200 then
return nil
end
local response = table.concat(response_body)
return string.match(response, "href='(.-)'")
end
local function run(msg, matches)
local find = get_webshot_url(matches[1])
if find then
local imgurl = base .. find
local receiver = get_receiver(msg)
send_photo_from_url(receiver, imgurl)
end
end
return {
description = "Website Screen Shot",
usage = {
"/web (url) : screen shot of website"
},
patterns = {
"^[!/]web (https?://[%w-_%.%?%.:/%+=&]+)$",
},
run = run
}
| gpl-2.0 |
sini370/flux | plugins/groupcontrol.lua | 1 | 42882 | do
-- make sure to set with value that not higher than stats.lua
local NUM_MSG_MAX = 4
local TIME_CHECK = 4 -- seconds
local function generate_link(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local user_id = cb_extra.user_id
local chat_id = string.gsub(receiver, '.+#id', '')
if success == 0 then
return send_large_msg(receiver, "Can't generate invite link for this group")
end
data[tostring(chat_id)]['link'] = result
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Link sent by PM')
return send_large_msg('user#id'..user_id,'=> '..result)
end
local function kick_user(user_id, chat_id)
local chat = 'chat#id'..chat_id
local user = 'user#id'..user_id
chat_del_user(chat, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but he should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function kick_user_chan(user_id, chat_id)
local channel = 'channel#id'..chat_id
local user = 'user#id'..user_id
channel_kick_user(channel, user, function (data, success, result)
if success ~= 1 then
local text = 'I can\'t kick '..data.user..' but he should be kicked'
send_msg(data.chat, '', ok_cb, nil)
end
end, {chat=chat, user=user})
end
local function del_msg(msg_id)
delete_msg(msg_id, ok_cb, false)
end
local function set_description(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..deskripsi
end
local function set_description_chan(msg, data, deskripsi)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند !"
end
local data_cat = 'description'
data[tostring(msg.to.id)][data_cat] = deskripsi
save_data(_config.moderation.data, data)
channel_set_about('channel#id'..msg.to.id, deskripsi, ok_cb, false)
return 'Set group description to:\n'..deskripsi
end
local function get_description(msg, data)
local data_cat = 'description'
if not data[tostring(msg.to.id)][data_cat] then
return 'No description available.'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'About '..about
end
local function set_rules(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local data_cat = 'rules'
data[tostring(msg.to.id)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function get_rules(msg, data)
local data_cat = 'rules'
if not data[tostring(msg.to.id)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules
return rules
end
local function lock_group_name(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند !"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'نام گروه از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ')
save_data(_config.moderation.data, data)
return 'Group name has been locked'
end
end
local function unlock_group_name(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(msg.to.id)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل نام گروه باز شد'
end
end
local function lock_group_member(msg, data)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'اعضای گروه از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_member(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(msg.to.id)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل اعضای گروه باز شد'
end
end
local function lock_group_bot(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bot']
if group_bot_lock == 'yes' then
return 'ورود ربات ها از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_bot'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ورود ربات ها قفل شد '
end
local function unlock_group_bot(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_bot_lock = data[tostring(msg.to.id)]['settings']['lock_bot']
if group_bot_lock == 'no' then
return 'ورود ربات ها قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_bot'] = 'no'
save_data(_config.moderation.data, data)
return 'ورود ربات ها باز شد '
end
end
local function lock_group_link(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_link_lock = data[tostring(msg.to.id)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'ارسال لینک از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ارسال لینک قفل شد'
end
local function unlock_group_link(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_link_lock = data[tostring(msg.to.id)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'ارسال لینک قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال لینک باز شد'
end
end
local function lock_group_inviteme(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند !"
end
local group_inviteme_lock = data[tostring(msg.to.id)]['settings']['lock_inviteme']
if group_inviteme_lock == 'yes' then
return 'Join group already locked'
else
data[tostring(msg.to.id)]['settings']['lock_inviteme'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'عضویت در گروه قفل شد'
end
local function unlock_group_inviteme(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_inviteme_lock = data[tostring(msg.to.id)]['settings']['lock_inviteme']
if group_inviteme_lock == 'no' then
return 'عضویت در گروه قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_inviteme'] = 'no'
save_data(_config.moderation.data, data)
return 'عضویت در گروه باز شد'
end
end
local function lock_group_photo(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'yes' then
return 'عکس گروه از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
end
return 'عکس جدید را ارسال کنید'
end
local function unlock_group_photo(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'عکس گروه قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل عکس گروه باز شد'
end
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Photo saved!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
-- show group settings
local function show_group_settings(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
if msg.to.type == 'chat' then
local settings = data[tostring(msg.to.id)]['settings']
local wordlist = ''
for k,v in pairs(data[tostring(msg.to.id)]['blocked_words']) do
wordlist = wordlist..' / '..k
end
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nLock bot : "..settings.lock_bot.."\nLock share link : "..settings.lock_link.."\nLock for public : "..settings.lock_inviteme.."\nAnti sticker : "..settings.lock_sticker.."\nLock share image : "..settings.lock_image.."\nLock share file : "..settings.lock_file.."\n\nBlocked words : "..wordlist
return text
else
local settings = data[tostring(msg.to.id)]['settings']
local wordlist = ''
for k,v in pairs(data[tostring(msg.to.id)]['blocked_words']) do
wordlist = wordlist..' / '..k
end
local text = "Group settings:\nLock group member : "..settings.lock_member.."\nLock bot : "..settings.lock_bot.."\nLock share link : "..settings.lock_link.."\nLock for public : "..settings.lock_inviteme.."\nAnti sticker : "..settings.lock_sticker.."\nLock share image : "..settings.lock_image.."\nLock share file : "..settings.lock_file.."\nLock talking : "..settings.lock_talk.."\n\nBlocked words : "..wordlist
return text
end
end
--lock/unlock anti sticker
local function lock_group_sticker(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_sticker_lock = data[tostring(msg.to.id)]['settings']['lock_sticker']
if group_sticker_lock == 'yes' then
return 'قفل استیکر از قبل فعال است'
else
data[tostring(msg.to.id)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'قفل استیکر فعال شد'
end
local function unlock_group_sticker(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_sticker_lock = data[tostring(msg.to.id)]['settings']['lock_sticker']
if group_sticker_lock == 'no' then
return 'قفل استیکر فعال نیست'
else
data[tostring(msg.to.id)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل استیکر غیر فعال شد'
end
end
local function lock_group_image(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_image_lock = data[tostring(msg.to.id)]['settings']['lock_image']
if group_image_lock == 'yes' then
return 'ارسال عکس از قبل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_image'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ارسال عکس قفل شد'
end
local function unlock_group_image(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_image_lock = data[tostring(msg.to.id)]['settings']['lock_image']
if group_image_lock == 'no' then
return 'ارسال عکس قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_image'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال عکس قفل شد'
end
end
--[[local function lock_group_video(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_video_lock = data[tostring(msg.to.id)]['settings']['lock_sticker']
if group_video_lock == 'yes' then
return 'ارسال ویدیو قفل شد '
else
data[tostring(msg.to.id)]['settings']['lock_sticker'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ارسال ویدیو فعال شد'
end
local function unlock_group_video(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_video_lock = data[tostring(msg.to.id)]['settings']['lock_sticker']
if group_video_lock == 'no' then
return 'ارسال ویدیو قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_sticker'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل ارسال ویدیو غیر فعال شد'
end
end
local function lock_group_audio(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_audio_lock = data[tostring(msg.to.id)]['settings']['lock_audio']
if group_audio_lock == 'yes' then
return 'ارسال صدا قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_audio'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ارسال صدا قفل شد'
end
local function unlock_group_audio(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_audio_lock = data[tostring(msg.to.id)]['settings']['lock_audio']
if group_audio_lock == 'no' then
return 'ارسال صدا قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_audio'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل ارسال صدا غیر فعال شد'
end
end]]
local function lock_group_file(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_file_lock = data[tostring(msg.to.id)]['settings']['lock_file']
if group_file_lock == 'yes' then
return 'ارسال فایل قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_file'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ارسال فایل قفل است'
end
local function unlock_group_file(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_file_lock = data[tostring(msg.to.id)]['settings']['lock_file']
if group_file_lock == 'no' then
return 'ارسال فایل قفل نیست'
else
data[tostring(msg.to.id)]['settings']['lock_file'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل ارسال فایل غیر فعال شد'
end
end
local function lock_group_talk(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_talk_lock = data[tostring(msg.to.id)]['settings']['lock_talk']
if group_talk_lock == 'yes' then
return 'چت کردن در گروه قفل است'
else
data[tostring(msg.to.id)]['settings']['lock_talk'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'قفل چت فعال شد'
end
local function unlock_group_talk(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
local group_talk_lock = data[tostring(msg.to.id)]['settings']['lock_talk']
if group_talk_lock == 'no' then
return 'قفل چت فعال است'
else
data[tostring(msg.to.id)]['settings']['lock_talk'] = 'no'
save_data(_config.moderation.data, data)
return 'قفل چت غیرفعال شد'
end
end
local function lock_group_all(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
return 'lock all'
end
local function unlock_group_all(msg, data)
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
return 'unlock all'
end
local function is_word_allowed(chat_id,text)
local var = true
local data = load_data(_config.moderation.data)
if not data[tostring(chat_id)] then
return true
end
local wordlist = ''
if data[tostring(chat_id)]['blocked_words'] then
for k,v in pairs(data[tostring(chat_id)]['blocked_words']) do
if string.find(string.lower(text), string.lower(k)) then
return false
end
end
end
return var
end
local function pre_process(msg)
--vardump(msg)
if not msg.text and msg.media then
msg.text = '['..msg.media.type..']'
end
if msg.to.type == 'chat' then
local receiver = get_receiver(msg)
-- spam detector
local hash = 'floodc:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':floodc'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
if not is_momod(msg) then
send_large_msg(receiver, 'Don\'t spam!')
chat_del_user(receiver, 'user#id'..msg.from.id, ok_cb, true)
msg = nil
return nil
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
-- end spam detect
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return msg
end
local settings = data[tostring(msg.to.id)]['settings']
if msg.action and msg.action.type then
local action = msg.action.type
if action == 'chat_rename' then
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if action == 'chat_add_user' or action == 'chat_add_user_link' then
if msg.action.link_issuer then
user_id = 'user#id'..msg.from.id
else
user_id = 'user#id'..msg.action.user.id
end
if settings.lock_member == 'yes' and msg.from.id ~= 0 and not is_momod(msg) then
local kick_a = chat_del_user(receiver, user_id, ok_cb, true)
local kick_b = chat_del_user(receiver, 'user#id'..msg.from.id, ok_cb, true)
end
if action == 'chat_add_user' and msg.action.user.flags == 1 then -- NEED FIX
if settings.lock_bot == 'yes' and not is_momod(msg) then
--chat_del_user(receiver, user_id, ok_cb, true)
end
end
end
end
if action == 'chat_delete_photo' then
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
end
end
if action == 'chat_change_photo' and msg.from.id ~= 0 then
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
end
end
if msg.media and not is_momod(msg) then
if msg.media.type == 'document' and msg.media.caption == 'sticker.webp' then
if data[tostring(msg.to.id)]['settings']['lock_sticker'] == 'yes' then
kick_user(msg.from.id,msg.to.id)
return 'Don\'t send sticker'
end
end
if msg.media.type == 'photo' then
if data[tostring(msg.to.id)]['settings']['lock_image'] == 'yes' then
kick_user(msg.from.id,msg.to.id)
return 'Don\'t send image'
end
end
if msg.media.type == 'document' then
if data[tostring(msg.to.id)]['settings']['lock_file'] == 'yes' then
kick_user(msg.from.id,msg.to.id)
return 'Don\'t send file'
end
end
end
if is_word_allowed(msg.to.id, msg.text) then
print('word allowed')
else
print('word is not allowed')
if not is_momod(msg) then
chat_del_user(receiver, 'user#id'..msg.from.id, ok_cb, true)
return 'That word is not allowed'
end
end
if string.find(msg.text, "https?://[%w-_%.%?%.:/%+=&]+") then
if is_momod(msg) then
print('link detected, but he is privileged user')
else
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)]['settings']['lock_link'] == 'yes' then
chat_del_user(receiver, 'user#id'..msg.from.id, ok_cb, true)
return 'Don\'t share link!'
end
end
end
return msg
end
if msg.to.type == 'channel' then -- THIS IS SUPERGROUPPPPPPPPPPPPPPPPPPPPP
local receiver = get_receiver(msg)
-- spam detect
local hash = 'floodc:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':floodc'
local msgs = tonumber(redis:get(hash) or 0)
if msgs > NUM_MSG_MAX then
if not is_momod(msg) then
send_large_msg(receiver, 'Don\'t spam!')
channel_kick_user(receiver, 'user#id'..msg.from.id, ok_cb, true)
delete_msg(msg.id, ok_cb, false)
msg = nil
end
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
-- spam detect
local data = load_data(_config.moderation.data)
if not data[tostring(msg.to.id)] then
return msg
end
local settings = data[tostring(msg.to.id)]['settings']
if settings.lock_talk == 'yes' then
if not is_momod(msg) then
return del_msg(msg.id)
end
end
if msg.action and msg.action.type then
local action = msg.action.type
if action == 'chat_add_user' or action == 'chat_add_user_link' then
if msg.action.link_issuer then
user_id = 'user#id'..msg.from.id
else
user_id = 'user#id'..msg.action.user.id
end
if group_member_lock == 'yes' and msg.from.id ~= 0 and not is_momod(msg) then
channel_kick_user(receiver, user_id, ok_cb, true)
end
if action == 'chat_add_user' and msg.action.user.flags == 1 then -- Need fix
if settings.lock_bot == 'yes' and not is_momod(msg) then
--channel_kick_user(receiver, user_id, ok_cb, true)
end
end
end
return msg
end
if msg.media and not is_momod(msg) then
if msg.media.type == 'document' and msg.media.caption == 'sticker.webp' then
if data[tostring(msg.to.id)]['settings']['lock_sticker'] == 'yes' then
delete_msg(msg.id, ok_cb, false)
return 'Don\'t send sticker'
end
end
if msg.media.type == 'photo' then
if data[tostring(msg.to.id)]['settings']['lock_image'] == 'yes' then
delete_msg(msg.id, ok_cb, false)
return 'Don\'t send image'
end
end
if msg.media.type == 'document' then
if data[tostring(msg.to.id)]['settings']['lock_file'] == 'yes' then
delete_msg(msg.id, ok_cb, false)
return 'Don\'t send file'
end
end
end
if is_word_allowed(msg.to.id, msg.text) then
print('word allowed')
else
print('word is not allowed')
if not is_momod(msg) then
delete_msg(msg.id, ok_cb, false)
return 'That word is not allowed'
end
end
if string.find(msg.text, "https?://[%w-_%.%?%.:/%+=&]+") then
if is_momod(msg) then
print('link detected, but he is privileged user')
else
if data[tostring(msg.to.id)]['settings']['lock_link'] == 'yes' then
delete_msg(msg.id, ok_cb, false)
return 'Don\'t share link!'
end
end
end
return msg
end
return msg
end
local function block_word(receiver, wordblock)
local chat_id = string.gsub(receiver, '.+#id', '')
local data = load_data(_config.moderation.data)
data[tostring(chat_id)]['blocked_words'][(wordblock)] = true
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Word "'..wordblock..'" has been added to blocked list.')
end
local function unblock_word(receiver, wordblock)
local chat_id = string.gsub(receiver, '.+#id', '')
local data = load_data(_config.moderation.data)
if data[tostring(chat_id)]['blocked_words'][wordblock] then
data[tostring(chat_id)]['blocked_words'][(wordblock)] = nil
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'Word "'..wordblock..'" has been removed from blocked list.')
else
send_large_msg(receiver, 'Word "'..wordblock..'" isn\'t in blocked list.')
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if is_chat_msg(msg) then
if msg.media and is_momod(msg) then
if msg.media.type == 'photo' and data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then
load_photo(msg.id, set_group_photo, msg)
end
end
end
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
local get_cmd = matches[1]
if matches[1] == 'block' and matches[2] then
if not is_momod(msg) then
return "فقط مدیر گروه میتوانید!"
end
return block_word(receiver, matches[2])
end
if matches[1] == 'unblock' and matches[2] then
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
return unblock_word(receiver, matches[2])
end
if matches[1] == 'getlink' then
if not is_momod(msg) then
return "فقط مدیر گروه میتواند!"
end
if data[tostring(msg.to.id)]['link'] then
local link = data[tostring(msg.to.id)]['link']
local text = string.gsub(msg.to.print_name, '_', ' ')..'\n'..link
send_large_msg('user#id'..msg.from.id, text)
else
export_chat_link(receiver, generate_link, {receiver=receiver, data=data, user_id=msg.from.id})
end
end
if matches[1] == 'relink'then
if not is_momod(msg) then
return "فقط مدیر!"
end
if matches[2] == tostring(msg.to.id) then
export_chat_link(receiver, generate_link, {receiver=receiver, data=data, user_id=msg.from.id})
else
return "Group ID didn't match. Reset invite link failed!"
end
end
if matches[1] == 'setabout' and matches[2] then
deskripsi = matches[2]
return set_description(msg, data)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'no' then --group lock *
if matches[2] == 'name' then
return lock_group_name(msg, data)
end
if matches[2] == 'member' then
return lock_group_member(msg, data)
end
if matches[2] == 'photo' then
return lock_group_photo(msg, data)
end
--if matches[2] == 'bot' then
-- return lock_group_bot(msg, data)
--end
if matches[2] == 'link' then
return lock_group_link(msg, data)
end
if matches[2] == 'join' then
return lock_group_inviteme(msg, data)
end
if matches[2] == 'sticker' then
return lock_group_sticker(msg, data)
end
if matches[2] == 'image' then
return lock_group_image(msg, data)
end
if matches[2] == 'file' then
return lock_group_file(msg, data)
end
--if matches[2] == 'chat' then
-- return lock_group_chat(msg, data)
--end
if matches[2] == 'all' then
return lock_group_all(msg, data)
end
end
if matches[1] == 'yes' then --group unlock *
if matches[2] == 'name' then
return unlock_group_name(msg, data)
end
if matches[2] == 'member' then
return unlock_group_member(msg, data)
end
if matches[2] == 'photo' then
return unlock_group_photo(msg, data)
end
--if matches[2] == 'bot' then
-- return unlock_group_bot(msg, data)
--end
if matches[2] == 'link' then
return unlock_group_link(msg, data)
end
if matches[2] == 'join' then
return unlock_group_inviteme(msg, data)
end
if matches[2] == 'sticker' then
return unlock_group_sticker(msg, data)
end
if matches[2] == 'image' then
return unlock_group_image(msg, data)
end
if matches[2] == 'file' then
return unlock_group_file(msg, data)
end
--if matches[2] == 'chat' then
-- return unlock_group_chat(msg, data)
--end
if matches[2] == 'all' then
return unlock_group_all(msg, data)
end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end
end
end
if is_channel_msg(msg) then -- For ChANNEL O SUPERGROUPSSSS
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
local get_cmd = matches[1]
if matches[1] == 'block' and matches[2] then
if not is_momod(msg) then
return "For moderators only!"
end
return block_word(receiver, matches[2])
end
if matches[1] == 'unblock' and matches[2] then
if not is_momod(msg) then
return "For moderators only!"
end
return unblock_word(receiver, matches[2])
end
if matches[1] == 'getlink' then
if not is_momod(msg) then
return "For moderators only!"
end
if data[tostring(msg.to.id)]['link'] then
local link = data[tostring(msg.to.id)]['link']
local text = string.gsub(msg.to.print_name, '_', ' ')..'\n'..link
send_large_msg('user#id'..msg.from.id, text)
else
export_channel_link(receiver, generate_link, {receiver=receiver, data=data, user_id=msg.from.id})
end
end
if matches[1] == 'relink'then
if not is_momod(msg) then
return "Moderators only!"
end
if matches[2] == tostring(msg.to.id) then
export_channel_link(receiver, generate_link, {receiver=receiver, data=data, user_id=msg.from.id})
else
return "Group ID didn't match. Reset invite link failed!"
end
end
if matches[1] == 'setabout' and matches[2] then
local deskripsi = matches[2]
return set_description_chan(msg, data, deskripsi)
end
if matches[1] == 'about' then
return get_description(msg, data)
end
if matches[1] == 'setrules' then
rules = matches[2]
return set_rules(msg, data)
end
if matches[1] == 'rules' then
return get_rules(msg, data)
end
if matches[1] == 'no' then --group lock *
--[[if matches[2] == 'name' then
return lock_group_name(msg, data)
end
if matches[2] == 'member' then
return lock_group_member(msg, data)
end
if matches[2] == 'photo' then
return lock_group_photo(msg, data)
end
if matches[2] == 'bot' then
return lock_group_bot(msg, data)
end]]
if matches[2] == 'link' then
return lock_group_link(msg, data)
end
if matches[2] == 'join' then
return lock_group_inviteme(msg, data)
end
if matches[2] == 'sticker' then
return lock_group_sticker(msg, data)
end
if matches[2] == 'image' then
return lock_group_image(msg, data)
end
if matches[2] == 'file' then
return lock_group_file(msg, data)
end
if matches[2] == 'chat' then
return lock_group_talk(msg, data)
end
--if matches[2] == 'all' then
-- return lock_group_all(msg, data)
--end
end
if matches[1] == 'yes' then --group unlock *
--[[if matches[2] == 'name' then
return unlock_group_name(msg, data)
end
if matches[2] == 'member' then
return unlock_group_member(msg, data)
end
if matches[2] == 'photo' then
return unlock_group_photo(msg, data)
end
if matches[2] == 'bot' then
return unlock_group_bot(msg, data)
end]]
if matches[2] == 'link' then
return unlock_group_link(msg, data)
end
if matches[2] == 'join' then
return unlock_group_inviteme(msg, data)
end
if matches[2] == 'sticker' then
return unlock_group_sticker(msg, data)
end
if matches[2] == 'image' then
return unlock_group_image(msg, data)
end
if matches[2] == 'file' then
return unlock_group_file(msg, data)
end
if matches[2] == 'chat' then
return unlock_group_talk(msg, data)
end
--if matches[2] == 'all' then
-- return unlock_group_all(msg, data)
--end
end
if matches[1] == 'group' and matches[2] == 'settings' then
return show_group_settings(msg, data)
end
--[[if matches[1] == 'setname' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'setphoto' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'Please send me new group photo now'
end]]
end
else
if matches[1] == 'join' and matches[2] then
if string.match(matches[2], '^%d+$') then
if not data[tostring(matches[2])] then
return 'Group id is not recognized'
end
if data[tostring(matches[2])]['settings']['lock_inviteme'] == 'yes' then
return 'Sorry, group is locked, i cant invite you'
else
if data[tostring(matches[2])]['group_type'] == 'chat' then
chat_add_user("chat#id"..matches[2], "user#id"..msg.from.id, callback, false)
else
channel_invite_user("channel#id"..matches[2], "user#id"..msg.from.id, callback, false)
end
end
end
end
end
end
return {
description = "Plugin to manage group chat.",
usage = {
user = {
"/about : Read group description",
"/rules : Read group rules",
},
moderator = {
"/block <word> : Block word in group",
"/unblock <word> : Unblock word from blocked list",
"/getlink : Show group invite link",
"/relink <group_id> : Reset group invite link",
"/setabout <description> : Set group description",
"/setrules <rules> : Set group rules",
"/setname <new_name> : Set group name",
"/setphoto : Set group photo",
"/<no|yes> name : Lock/unlock group name",
"/<no|yes> photo : Lock/unlock group photo",
"/<no|yes> member : Lock/unlock group member",
"/<no|yes> spam : Enable/disable spam protection",
"/<no|yes> sticker : Enable/disable anti sticker",
"/<no|yes> antilink : Enable/disable anti link",
"/group settings : Show group settings",
"/join <group id> : Join to any group by ID (if not locked)",
},
},
patterns = {
"^/(block) (.+)$",
"^/(unblock) (.+)$",
"^/(getlink)$",
"^/(relink) (.+)$",
"^/(setabout) (.*)$",
"^/(about)$",
"^/(setrules) (.*)$",
"^/(rules)$",
"^/(setname) (.*)$",
"^/(setphoto)$",
"^/(no) (.*)$",
"^/(yes) (.*)$",
"^/(group) (settings)$",
"^/(join) (.+)$",
"%[(photo)%]",
"%[(document)%]",
},
run = run,
pre_process = pre_process
}
end
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Inner_Horutoto_Ruins/npcs/_5ct.lua | 2 | 2450 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: Magical Gizmo #5 (T out of P, Q, R, S, T, U)
-- Involved In Mission: The Horutoto Ruins Experiment
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- The Magical Gizmo Number, this number will be compared to the random
-- value created by the mission The Horutoto Ruins Experiment, when you
-- reach the Gizmo Door and have the cutscene
magical_gizmo_no = 5; -- of the 6
-- Check if we are on Windurst Mission 1-1
if(player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then
-- Check if we found the correct Magical Gizmo or not
if(player:getVar("MissionStatus_rv") == magical_gizmo_no) then
player:startEvent(0x0038);
else
if(player:getVar("MissionStatus_op5") == 2) then
-- We've already examined this
player:messageSpecial(EXAMINED_RECEPTACLE);
else
-- Opened the wrong one
player:startEvent(0x0039);
end
end
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- If we just finished the cutscene for Windurst Mission 1-1
-- The cutscene that we opened the correct Magical Gizmo
if(csid == 0x0038) then
player:setVar("MissionStatus",3);
player:setVar("MissionStatus_rv", 0);
player:addKeyItem(CRACKED_MANA_ORBS);
player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS);
elseif(csid == 0x0039) then
-- Opened the wrong one
player:setVar("MissionStatus_op5", 2);
-- Give the message that thsi orb is not broken
player:messageSpecial(NOT_BROKEN_ORB);
end
end; | gpl-3.0 |
e1d1s1/OpenRA | mods/cnc/maps/nod05/nod05.lua | 10 | 10833 | NodUnitsVehicle = { 'bike', 'bike', 'bggy', 'ltnk', 'bike', 'bike' }
NodUnitsRocket = { 'e1', 'e1', 'e1', 'e1' }
NodUnitsGunner = { 'e3', 'e3', 'e3', 'e3' }
GDIReinforceUnits = { 'e2', 'e2', 'e2', 'e2', 'e2' }
Gdi1Units = { ['e1'] = 3, ['e2'] = 1 }
Gdi2Units = { ['e1'] = 2, ['e2'] = 1 }
Gdi3Units = { ['jeep'] = 1 }
Gdi4Units = { ['mtnk'] = 1 }
Gdi5Units = { ['e1'] = 1, ['e2'] = 2 }
Gdi6Units = { ['e1'] = 3 }
Gdi7Units = { ['e2'] = 2 }
Gdi8Units = { ['e2'] = 5 }
AllUnits = { Gdi1Units, Gdi2Units, Gdi3Units, Gdi4Units, Gdi5Units, Gdi6Units, Gdi7Units, Gdi8Units }
AirstrikeDelay = DateTime.Minutes(1) + DateTime.Seconds(40)
YyyyTriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(30)
ZzzzTriggerFunctionTime = DateTime.Minutes(2) + DateTime.Seconds(30)
Grd1TriggerFunctionTime = DateTime.Seconds(3)
Atk2TriggerFunctionTime = DateTime.Minutes(1) + DateTime.Seconds(10)
Atk3TriggerFunctionTime = DateTime.Minutes(3) + DateTime.Seconds(10)
Atk4TriggerFunctionTime = DateTime.Minutes(4) + DateTime.Seconds(40)
Atk6TriggerFunctionTime = DateTime.Minutes(2) + DateTime.Seconds(30)
DelyCellTriggerActivator = { CPos.New(29,30), CPos.New(28,30), CPos.New(27,30), CPos.New(26,30), CPos.New(25,30), CPos.New(24,30), CPos.New(23,30), CPos.New(22,30), CPos.New(21,30), CPos.New(29,29), CPos.New(28,29), CPos.New(27,29), CPos.New(26,29), CPos.New(25,29), CPos.New(24,29), CPos.New(23,29), CPos.New(22,29) }
DelzCellTriggerActivator = { CPos.New(29,27), CPos.New(28,27), CPos.New(27,27), CPos.New(26,27), CPos.New(25,27), CPos.New(24,27), CPos.New(29,26), CPos.New(28,26), CPos.New(27,26), CPos.New(26,26), CPos.New(25,26), CPos.New(24,26) }
Atk5CellTriggerActivator = { CPos.New(10,33), CPos.New(9,33), CPos.New(8,33), CPos.New(9,32), CPos.New(8,32), CPos.New(7,32), CPos.New(8,31), CPos.New(7,31), CPos.New(6,31) }
Atk1CellTriggerActivator = { CPos.New(10,33), CPos.New(9,33), CPos.New(8,33), CPos.New(9,32), CPos.New(8,32), CPos.New(7,32), CPos.New(8,31), CPos.New(7,31), CPos.New(6,31) }
Gdi1Waypoints = { waypoint0, waypoint1, waypoint3, waypoint4 }
Gdi2Waypoints = { waypoint0, waypoint1, waypoint3, waypoint4, waypoint5 }
Gdi3Waypoints = { waypoint0, waypoint1, waypoint2 }
Gdi5Waypoints = { waypoint0, waypoint1, waypoint3, waypoint1, waypoint6 }
Gdi11Waypoints = { waypoint0, waypoint1, waypoint3, waypoint4, waypoint7, waypoint8 }
Gdi12Waypoints = { waypoint0, waypoint1, waypoint3, waypoint11, waypoint12 }
AllWaypoints = { Gdi1Waypoints, Gdi2Waypoints, Gdi3Waypoints, Gdi5Waypoints, Gdi11Waypoints, Gdi12Waypoints }
PrimaryTargets = { Tower1, Tower2, Radar, Silo1, Silo2, Silo3, Refinery, Barracks, Plant1, Plant2, Yard, Factory }
GDIStartUnits = { }
SendGDIAirstrike = function()
if not Radar.IsDead and Radar.Owner == enemy then
local target = getAirstrikeTarget()
if target then
Radar.SendAirstrike(target, false, Facing.NorthEast + 4)
Trigger.AfterDelay(AirstrikeDelay, SendGDIAirstrike)
else
Trigger.AfterDelay(AirstrikeDelay/4, SendGDIAirstrike)
end
end
end
YyyyTriggerFunction = function()
if not YyyyTriggerSwitch then
for type, count in pairs(Gdi2Units) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, Gdi2Waypoints)
end)
end
end
end
ZzzzTriggerFunction = function()
if not ZzzzTriggerSwitch then
for type, count in pairs(Gdi1Units) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, Gdi1Waypoints)
end)
end
end
end
Grd1TriggerFunction = function()
MyActors = Utils.Take(2, enemy.GetActorsByType('jeep'))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, Gdi5Waypoints)
end)
end
Atk5TriggerFunction = function()
WaypointMovementAndHunt(enemy.GetActorsByType('mtnk')[1], Gdi12Waypoints)
end
Atk2TriggerFunction = function()
for type, count in pairs(Gdi1Units) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, Gdi1Waypoints)
end)
end
end
Atk3TriggerFunction = function()
for type, count in pairs(Gdi2Units) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, Gdi2Waypoints)
end)
end
end
Atk4TriggerFunction = function()
WaypointMovementAndHunt(enemy.GetActorsByType('jeep')[1], Gdi3Waypoints)
end
Atk6TriggerFunction = function()
WaypointMovementAndHunt(enemy.GetActorsByType('mtnk')[1], Gdi2Waypoints)
end
Atk1TriggerFunction = function()
Reinforcements.ReinforceWithTransport(enemy, 'tran', GDIReinforceUnits, { waypoint9.Location, waypoint26.Location }, nil,
function(transport, cargo)
transport.UnloadPassengers()
Utils.Do(cargo, function(actor)
IdleHunt(actor)
end)
end)
end
AutoTriggerFunction = function()
local units = AllUnits[DateTime.GameTime % #AllUnits + 1]
local waypoints = AllWaypoints[DateTime.GameTime % #AllWaypoints + 1]
for type, count in pairs(units) do
MyActors = Utils.Take(count, enemy.GetActorsByType(type))
Utils.Do(MyActors, function(actor)
WaypointMovementAndHunt(actor, waypoints)
end)
end
end
HuntTriggerFunction = function()
local list = enemy.GetGroundAttackers()
Utils.Do(list, function(unit)
IdleHunt(unit)
end)
end
WaypointMovementAndHunt = function(unit, waypoints)
if unit ~= nil then
Utils.Do(waypoints, function(waypoint)
unit.AttackMove(waypoint.Location)
end)
IdleHunt(unit)
end
end
InsertNodUnits = function()
Camera.Position = UnitsEntry.CenterPosition
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, NodUnitsVehicle, { UnitsEntry.Location, UnitsRallyVehicle.Location }, 1)
Reinforcements.Reinforce(player, NodUnitsRocket, { UnitsEntry.Location, UnitsRallyRocket.Location }, 50)
Reinforcements.Reinforce(player, NodUnitsGunner, { UnitsEntry.Location, UnitsRallyGunner.Location }, 50)
Trigger.AfterDelay(DateTime.Seconds(6), function()
Reinforcements.Reinforce(player, { 'mcv' }, { UnitsEntry.Location, UnitsRallyMCV.Location })
end)
end
WorldLoaded = function()
player = Player.GetPlayer("Nod")
enemy = Player.GetPlayer("GDI")
InsertNodUnits()
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)
Trigger.OnPlayerWon(player, function()
Media.PlaySpeechNotification(player, "Win")
end)
Trigger.OnPlayerLost(player, function()
Media.PlaySpeechNotification(player, "Lose")
end)
NodObjective1 = player.AddPrimaryObjective("Build 3 SAMs.")
NodObjective2 = player.AddPrimaryObjective("Destroy the GDI base.")
GDIObjective = enemy.AddPrimaryObjective("Kill all enemies.")
Trigger.AfterDelay(AirstrikeDelay, SendGDIAirstrike)
Trigger.AfterDelay(YyyyTriggerFunctionTime, YyyyTriggerFunction)
Trigger.AfterDelay(ZzzzTriggerFunctionTime, ZzzzTriggerFunction)
Trigger.OnEnteredFootprint(DelyCellTriggerActivator, function(a, id)
if a.Owner == player then
YyyyTriggerSwitch = true
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnEnteredFootprint(DelzCellTriggerActivator, function(a, id)
if a.Owner == player then
ZzzzTriggerSwitch = true
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(Grd1TriggerFunctionTime, Grd1TriggerFunction)
Trigger.OnEnteredFootprint(Atk5CellTriggerActivator, function(a, id)
if a.Owner == player then
Atk5TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(Atk2TriggerFunctionTime, Atk2TriggerFunction)
Trigger.AfterDelay(Atk3TriggerFunctionTime, Atk3TriggerFunction)
Trigger.AfterDelay(Atk4TriggerFunctionTime, Atk4TriggerFunction)
Trigger.AfterDelay(Atk6TriggerFunctionTime, Atk6TriggerFunction)
Trigger.OnEnteredFootprint(Atk1CellTriggerActivator, function(a, id)
if a.Owner == player then
Atk1TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.OnDiscovered(Tower1, AutoTriggerFunction)
Trigger.OnDiscovered(Tower2, AutoTriggerFunction)
Trigger.OnAllKilledOrCaptured(PrimaryTargets, function()
player.MarkCompletedObjective(NodObjective2)
HuntTriggerFunction()
end)
Trigger.AfterDelay(0, getStartUnits)
end
Tick = function()
if player.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
enemy.MarkCompletedObjective(GDIObjective)
end
end
if not player.IsObjectiveCompleted(NodObjective1) and CheckForSams(player) then
player.MarkCompletedObjective(NodObjective1)
end
if DateTime.GameTime % DateTime.Seconds(3) == 0 then
checkProduction(enemy)
end
if DateTime.GameTime % DateTime.Seconds(45) == 0 then
AutoTriggerFunction()
end
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
CheckForSams = function(player)
local sams = player.GetActorsByType("sam")
return #sams >= 3
end
checkProduction = function(player)
local Units = Utils.Where(Map.ActorsInWorld, function(actor)
return actor.Owner == enemy
end)
local UnitsType = { }
for type, count in pairs(GDIStartUnits) do
counter = 0
Utils.Do(Units, function(unit)
if unit.Type == type then
counter = counter + 1
end
end)
if counter < count then
for i = 1, count - counter, 1 do
UnitsType[i] = type
end
end
if #UnitsType > 0 then
if (type == 'jeep' or type == 'mtnk') and not Factory.IsDead and Factory.Owner == enemy then
Factory.Build(UnitsType)
elseif (type == 'e1' or type == 'e2') and not Barracks.IsDead and Barracks.Owner == enemy then
Barracks.Build(UnitsType)
end
end
UnitsType = { }
end
end
getStartUnits = function()
local Units = Utils.Where(Map.ActorsInWorld, function(actor)
return actor.Owner == enemy and ( actor.Type == 'e2' or actor.Type == 'e1' or actor.Type == 'jeep' or actor.Type == 'mtnk')
end)
Utils.Do(Units, function(unit)
if not GDIStartUnits[unit.Type] then
GDIStartUnits[unit.Type] = 1
else
GDIStartUnits[unit.Type] = GDIStartUnits[unit.Type] + 1
end
end)
end
searches = 0
getAirstrikeTarget = function()
local list = player.GetGroundAttackers()
if #list == 0 then
return
end
local target = list[DateTime.GameTime % #list + 1].CenterPosition
local sams = Map.ActorsInCircle(target, WDist.New(8 * 1024), function(actor)
return actor.Type == "sam" end)
if #sams == 0 then
searches = 0
return target
elseif searches < 6 then
searches = searches + 1
return getAirstrikeTarget()
else
searches = 0
return nil
end
end
| gpl-3.0 |
e-m-c/x-y | libs/JSON.lua | 2 | 35894 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
-- | gpl-2.0 |
ld-test/adoc_cmd_ext | test/cmd_util_spec.lua | 3 | 1519 | local CU = require( "adoc_cmd_ext.cmd_util" )
local U = require( "adoc_cmd_ext.util" )
local cmdStr = [=[/=
sub_def[:name: final][ :salt: ]
-->
== {name}[[{name}]]
{salt}
=/]=]
local multiCmdStr = [=[
/=
sub_def[:name: final]
-->
== {name}[[{name}]]
=/
/=
sub[:name:]
-->
<<{name}>>
=/
]=]
local multiSingleLineCmdStr = [=[
/= sub_def[:name: final] --> == {name}[[{name}]] =/
/= sub[:name:] --> <<{name}>> =/
]=]
describe( "cmd_util", function()
test( "raw_cmd_definitions", function()
local t = CU.raw_cmd_definitions( multiCmdStr )
assert.is.same( #t, 2 )
t = CU.raw_cmd_definitions( multiSingleLineCmdStr )
assert.is.same( #t, 2 )
end )
test( "scan_parameter", function()
local n1, i1 = CU.scan_parameter( "[:name: final]" )
assert.is.same( n1, "name" )
assert.is.same( i1, "final" )
local n2, i2 = CU.scan_parameter( "[ :salt: ]" )
assert.is.same( n2, "salt" )
assert.is.same( i2, "" )
local n3, i3 = CU.scan_parameter( "[ :tip: don't use drugs ]" )
assert.is.same( n3, "tip" )
assert.is.same( i3, "don't use drugs" )
end )
test( "scan_cmd_definition", function()
local cmd = CU.scan_cmd_definition( cmdStr )
assert.is.same( cmd.name, "sub_def" )
assert.is.same( "name", cmd.order[ 1 ] )
assert.is.same( "salt", cmd.order[ 2 ] )
assert.is.same( cmd.para.name, "final" )
assert.is.same( cmd.para.salt, "" )
assert.is.same( #cmd.repl, 7 )
end )
end )
| mit |
kidaa/FFXIOrgins | scripts/zones/FeiYin/npcs/Grounds_Tome.lua | 30 | 1074 | -----------------------------------
-- Area: Fei'Yin
-- NPC: Grounds Tome
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/groundsofvalor");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
startGov(GOV_EVENT_FEIYIN,player);
end;
-----------------------------------
-- onEventSelection
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
updateGov(player,csid,option,711,712,713,714,715,716,717,718,0,0);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
finishGov(player,csid,option,711,712,713,714,715,716,717,718,0,0,GOV_MSG_FEIYIN);
end;
| gpl-3.0 |
LuaDist2/adoc_cmd_ext | lib/adoc_cmd_ext/pattern.lua | 3 | 2132 | local L = require( "lpeg" )
local LU = require( "adoc_cmd_ext.lpeg_util" )
--------------------------------------------------------------------------------
local function nP( p )
return ( 1 - p )^0
end
--------------------------------------------------------------------------------
-- /=
-- sub_def[:name:]
-- -->
-- == {name}[[{name}]]
-- =/
local spc = L.S" \t\n"^0
local alpha = L.R"az" + L.R"AZ"
local alphaNum = alpha + L.R"09"
local name = alpha * ( alpha + L.P"_" + L.P"-" + L.R"09" )^0
--------------------------------------------------------------------------------
local attrName = name
local attrValue = nP( L.P"]" )
local attrDecl = L.P":" * name * L.P":"
local attrDef = attrDecl * spc * attrValue * spc
local attrUseBegin = L.P"{"
local attrUseEnd = L.P"}"
local attrUse = attrUseBegin * name * attrUseEnd
local cmdDefBegin = L.P"/=" * spc
local cmdDefSep = spc * L.P"-->" * spc
local cmdDefEnd = spc * L.P"=/"
local notCmdBegin = nP( cmdDefBegin )
local notCmdEnd = nP( cmdDefEnd )
local cmdDefCont = nP( cmdDefEnd )
local cmdName = name
local paraBegin = L.P"[" * spc
local paraEnd = spc * L.P"]"
local paraSig = paraBegin * spc * attrDef * spc * paraEnd
local cmdDefSig = cmdName * paraSig^1
local cmdDefBetween = cmdDefSig * cmdDefSep * cmdDefCont
local cmdDef = cmdDefBegin * cmdDefBetween * cmdDefEnd
--------------------------------------------------------------------------------
local cmdInsBegin = L.P"/:"
local para = ( paraBegin * spc * attrValue * spc * paraEnd ) +
( paraBegin * spc * paraEnd )
local cmdIns = cmdInsBegin * cmdName * para^1
--------------------------------------------------------------------------------
--
--------------------------------------------------------------------------------
return {
attrUseBegin = attrUseBegin,
attrUseEnd = attrUseEnd,
attrUse = attrUse,
attrDecl = attrDecl,
cmdName = cmdName,
cmdParaSig = paraSig,
paraBegin = paraBegin,
paraEnd = paraEnd,
cmdDefBegin = cmdDefBegin,
cmdDefSep = cmdDefSep,
cmdDefEnd = cmdDefEnd,
cmdDef = cmdDef,
cmdIns = cmdIns,
cmdInsPara = para
}
| mit |
Fatalerror66/ffxi-a | scripts/zones/Misareaux_Coast/npcs/qm1.lua | 2 | 1338 | -----------------------------------
-- Area: Misareaux_Coast
-- NPC: ??? (Spawn Gration)
-- Pzone 25
-- @pos 113.563 -16.302 38.912 25
-------------------------------------
package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Misareaux_Coast/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- Trade Hickory Shield OR Picaroon's Shield
if(GetMobAction(16879899) == 0 and (trade:hasItemQty(12370,1) or trade:hasItemQty(12359,1)) and trade:getItemCount() == 1)then
player:tradeComplete();
SpawnMob(16879899,900):updateEnmity(player);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
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/bunch_of_pamamas.lua | 36 | 2212 | -----------------------------------------
-- ID: 4468
-- Item: Bunch of Pamamas
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Strength -3
-- Intelligence 1
-- Additional Effect with Opo-Opo Crown
-- HP 50
-- MP 50
-- CHR 14
-- Additional Effect with Kinkobo or
-- Primate Staff
-- DELAY -90
-- ACC 10
-- Additional Effect with Primate Staff +1
-- DELAY -80
-- ACC 12
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,PamamasEquip(target),0,1800,4468);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower();
if (power == 1 or power == 4 or power == 5) then
target:addMod(MOD_HP, 50);
target:addMod(MOD_MP, 50);
target:addMod(MOD_AGI, -3);
target:addMod(MOD_CHR, 14);
end
if (power == 2 or power == 4) then
target:addMod(MOD_DELAY, -90);
target:addMod(MOD_ACC, 10);
end
if (power == 3 or power == 5) then
target:addMod(MOD_DELAY, -80);
target:addMod(MOD_ACC, 12);
end
target:addMod(MOD_STR, -3);
target:addMod(MOD_INT, 1);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
local power = effect:getPower();
if (power == 1 or power == 4 or power == 5) then
target:delMod(MOD_HP, 50);
target:delMod(MOD_MP, 50);
target:delMod(MOD_AGI, -3);
target:delMod(MOD_CHR, 14);
end
if (power == 2 or power == 4) then
target:delMod(MOD_DELAY, -90);
target:delMod(MOD_ACC, 10);
end
if (power == 3 or power == 5) then
target:delMod(MOD_DELAY, -80);
target:delMod(MOD_ACC, 12);
end
target:delMod(MOD_STR, -3);
target:delMod(MOD_INT, 1);
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Windurst_Waters/npcs/Prestapiq.lua | 16 | 1546 | -----------------------------------
-- Area: Windurst Waters
-- NPC: Prestapiq
-- Only sells when Windurst controls Movalpolos
-- Confirmed shop stock, August 2013
-----------------------------------
require("scripts/globals/shop");
require("scripts/globals/conquest");
package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil;
require("scripts/zones/Windurst_Waters/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
RegionOwner = GetRegionOwner(MOVALPOLOS);
if (RegionOwner ~= WINDURST) then
player:showText(npc,PRESTAPIQ_CLOSED_DIALOG);
else
player:showText(npc,PRESTAPIQ_OPEN_DIALOG);
stock = {
0x0280, 11, --Copper Ore
0x1162, 694, --Coral Fungus
0x1117, 4032, --Danceshroom
0x0672, 6500, --Kopparnickel Ore
0x142D, 736 --Movalpolos Water
}
showShop(player,WINDURST,stock);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
DeNA/dworker | lib/lua/fetchWorkersToRecover.lua | 1 | 1255 | -- Input parameters
-- KEYS[1] global hash key. (gh) - unused
-- KEYS[2] worker list hash. (wh)
-- KEYS[3] broker list hash. (bh) - unused
-- KEYS[4] recovery sets (rz)
-- ARGV[1] Current time.
-- ARGV[2] Worker TTL in milliseconds
-- ARGV[3] Max number of workers to fetch
-- Output parameters
local now = tonumber(ARGV[1])
local ttl = tonumber(ARGV[2])
local nMaxFetch = tonumber(ARGV[3])
local kWh = KEYS[2]
local kRz = KEYS[4]
local results = {}
while redis.call("ZCARD", kRz) > 0 do
local res = redis.call("ZRANGE", kRz, 0, 0, 'withscores')
local workerId = res[1]
local createdAt = tonumber(res[2])
local tmp = redis.call("HGET", kWh, workerId)
if tmp then
local workerInfo
if pcall(function () workerInfo = cjson.decode(tmp) end) then
if workerInfo.attributes.recoverable then
if ttl == 0 or now - createdAt < ttl then
workerInfo.id = workerId
table.insert(results, cjson.encode(workerInfo))
end
end
end
end
-- Remove the worker from rz
redis.call("ZREM", kRz, workerId)
if #results >= nMaxFetch then
break
end
end
return { results, redis.call("ZCARD", kRz) }
| mit |
AIE-Guild/GreenWall | Settings.lua | 1 | 10297 | --[[-----------------------------------------------------------------------
The MIT License (MIT)
Copyright (c) 2010-2020 Mark Rogaski
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.
--]] -----------------------------------------------------------------------
--[[-----------------------------------------------------------------------
Imported Libraries
--]] -----------------------------------------------------------------------
--[[-----------------------------------------------------------------------
Class Variables
--]] -----------------------------------------------------------------------
GwSettings = {}
GwSettings.__index = GwSettings
--- GwSettings constructor function.
-- @return An initialized GwSettings instance.
function GwSettings:new()
-- Object instantiation
local self = {}
setmetatable(self, GwSettings)
-- Default Settings
self._default = {
mode = {
value = GW_MODE_ACCOUNT,
compat = GW_MODE_CHARACTER,
desc = 'settings mode: account or character',
meta = true,
opts = { GW_MODE_ACCOUNT, GW_MODE_CHARACTER }
},
tag = {
value = true,
desc = "co-guild tagging"
},
roster = {
value = true,
desc = "co-guild roster announcements"
},
debug = {
value = GW_LOG_NONE,
min = 0,
max = 5,
desc = "debugging level"
},
verbose = {
value = false,
desc = "verbose debugging"
},
log = {
value = false,
desc = "event logging"
},
logsize = {
value = 2048,
min = 0,
max = 8192,
desc = "maximum log buffer size"
},
ochat = {
value = false,
desc = "officer chat bridging"
},
redact = {
value = true,
desc = "obfuscate sensitive data"
},
joindelay = {
value = 30,
min = 0,
max = 120,
step = 1,
desc = "channel join delay"
}
}
for k, v in pairs(self._default) do
self._default[k].type = type(v.value)
end
-- Initialize saved settings
local compat = false
if type(GreenWall) == 'table' then
compat = true
end
GreenWallMeta = self:initialize(GreenWallMeta, true, compat)
GreenWall = self:initialize(GreenWall, false)
GreenWallAccount = self:initialize(GreenWallAccount, false)
self._meta = GreenWallMeta
self._data = {
[GW_MODE_CHARACTER] = GreenWall,
[GW_MODE_ACCOUNT] = GreenWallAccount
}
-- Initialize user log
if GreenWallLog == nil then
GreenWallLog = {}
end
self._log = GreenWallLog
gw.Debug(GW_LOG_INFO, 'settings initialized')
return self
end
--- Set the default values and attributes.
-- @param svtable Settings table reference (may be nil).
-- @param meta True if the table is metadata for settings, false otherwise.
-- @param compat True is compatibility with a previous installation is needed, false otherwsie.
-- @return An initialized settings table reference.
function GwSettings:initialize(svtable, meta, compat)
local store
local init = false
gw.Debug(GW_LOG_INFO, 'initializing settings (meta=%s)', tostring(meta))
-- Create the store if necessary
if svtable == nil then
local ts = date('%Y-%m-%d %H:%M:%S')
store = {
created = ts,
updated = ts
}
init = true
else
store = svtable
end
-- Groom the valid variables
for k, v in pairs(self._default) do
if not meta == not v.meta then -- Negate both to coerce any to false
if store[k] == nil or self:validate(k, store[k]) then
if compat then
store[k] = v.compat
else
store[k] = v.value
end
gw.Debug(GW_LOG_DEBUG, 'initialized %s to "%s"', k, tostring(store[k]))
end
end
end
-- Update the metadata
store.version = gw.version
return store
end
--- Reset options to default values.
-- @param svtable Settings table reference
-- @param meta True if meta options should be reset, false otherwise.
function GwSettings:reset(svtable, meta)
for k, v in pairs(self._default) do
if not v.meta or meta then
if svtable[k] == nil or self:validate(k, svtable[k]) then
svtable[k] = v.value
end
end
end
end
--- Check if a setting exists.
-- @param name The name of the setting.
-- @return True if the setting exists, false otherwise.
function GwSettings:exists(name)
return self._default[name] ~= nil
end
--- Get a user setting attribute.
-- @param name The name of the setting.
-- @param attr The setting attribute.
-- @return The setting attribute value.
function GwSettings:getattr(name, attr)
if self._default[name] == nil then
return
else
return self._default[name][attr]
end
end
--- Check if a setting is a meta variable.
-- @param name The name of the setting.
-- @return True if the setting is a meta variable, false otherwise.
function GwSettings:is_meta(name)
if self:exists(name) then
if self:getattr(name, 'meta') then
return true
else
return false
end
else
return false
end
end
--- Return settings mode.
-- @return GW_MODE_CHARACTER or GW_MODE_ACCOUNT.
function GwSettings:mode()
return self._meta.mode
end
--- Get a user setting value.
-- @param name The name of the setting.
-- @param mode An optional mode to specify which settings to retrieve, GW_MODE_CHARACTER or GW_MODE_ACCOUNT.
-- @return The setting value.
function GwSettings:get(name, mode)
if self:exists(name) then
local value
if self:is_meta(name) then
value = self._meta[name]
else
if mode then
value = self._data[mode][name]
else
value = self._data[self:mode()][name]
end
end
return value
else
return
end
end
--- Set a user setting value.
-- @param name The name of the setting.
-- @param value The value of the setting.
-- @return A string containing an error message on failure, nil on success.
function GwSettings:validate(name, value)
local function contains(list, item)
for _, value in ipairs(list) do
if value == item then
return true
end
end
return false
end
if not self:exists(name) then
return string.format('%s is not a valid setting', name)
else
local opt_type = self:getattr(name, 'type')
if type(value) ~= opt_type then
return string.format('%s must be a %s value', name, opt_type)
end
if opt_type == 'number' then
if self:getattr(name, 'min') and self:getattr(name, 'min') > value then
return string.format('%s must be greater than or equal to %d',
name, self:getattr(name, 'min'))
end
if self:getattr(name, 'max') and self:getattr(name, 'max') < value then
return string.format('%s must be less than or equal to %d',
name, self:getattr(name, 'max'))
end
elseif opt_type == 'string' then
if self:getattr(name, 'opts') and not contains(self:getattr(name, 'opts'), value) then
return string.format('invalid option for %s: %s', name, value)
end
end
end
return
end
--- Set a user setting value.
-- @param name The name of the setting.
-- @param value The value of the setting.
-- @param mode An optional mode to specify which settings to update, GW_MODE_CHARACTER or GW_MODE_ACCOUNT.
-- @return True on success, false on failure.
function GwSettings:set(name, value, mode)
-- Validate the new value
local err = self:validate(name, value)
if err then
gw.Error(err)
return false
end
-- Apply the new setting
local curr = self:get(name, mode)
if self:is_meta(name) then
self._meta[name] = value
self._meta.updated = date('%Y-%m-%d %H:%M:%S')
else
if not mode then
mode = self:mode()
end
self._data[mode][name] = value
self._data[mode].updated = date('%Y-%m-%d %H:%M:%S')
end
-- Special handling for value changes
if curr ~= value then
gw.Debug(GW_LOG_INFO, 'changed %s from "%s" to "%s" (%s)',
name, tostring(curr), tostring(value), tostring(self:mode()))
if name == 'logsize' then
gw.Debug(GW_LOG_INFO, 'trimming user log')
while #self._log > value do
tremove(self._log, 1)
end
elseif name == 'joindelay' then
gw.Debug(GW_LOG_INFO, 'updating channel timers')
gw.config.timer.channel:set(value)
elseif name == 'ochat' then
gw.Debug(GW_LOG_INFO, 'reloading officer chat channel')
gw.config:reload()
end
end
return true
end
| mit |
kidaa/FFXIOrgins | scripts/zones/Spire_of_Mea/npcs/_0l2.lua | 8 | 1251 | -----------------------------------
-- Area: Spire_of_Mea
-- NPC: web of regret
-----------------------------------
package.loaded["scripts/zones/Spire_of_Mea/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/bcnm");
require("scripts/zones/Spire_of_Mea/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 |
LingJiJian/uLui | build/luajit-2.1.0/dynasm/dasm_ppc.lua | 1 | 59408 | ------------------------------------------------------------------------------
-- DynASM PPC/PPC64 module.
--
-- Copyright (C) 2005-2015 Mike Pall. All rights reserved.
-- See dynasm.lua for full copyright notice.
--
-- Support for various extensions contributed by Caio Souza Oliveira.
------------------------------------------------------------------------------
-- Module information:
local _info = {
arch = "ppc",
description = "DynASM PPC module",
version = "1.3.0",
vernum = 10300,
release = "2015-01-14",
author = "Mike Pall",
license = "MIT",
}
-- Exported glue functions for the arch-specific module.
local _M = { _info = _info }
-- Cache library functions.
local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs
local assert, setmetatable = assert, setmetatable
local _s = string
local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char
local match, gmatch = _s.match, _s.gmatch
local concat, sort = table.concat, table.sort
local bit = bit or require("bit")
local band, shl, shr, sar = bit.band, bit.lshift, bit.rshift, bit.arshift
local tohex = bit.tohex
-- Inherited tables and callbacks.
local g_opt, g_arch
local wline, werror, wfatal, wwarn
-- Action name list.
-- CHECK: Keep this in sync with the C code!
local action_names = {
"STOP", "SECTION", "ESC", "REL_EXT",
"ALIGN", "REL_LG", "LABEL_LG",
"REL_PC", "LABEL_PC", "IMM", "IMMSH"
}
-- Maximum number of section buffer positions for dasm_put().
-- CHECK: Keep this in sync with the C code!
local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines.
-- Action name -> action number.
local map_action = {}
for n,name in ipairs(action_names) do
map_action[name] = n-1
end
-- Action list buffer.
local actlist = {}
-- Argument list for next dasm_put(). Start with offset 0 into action list.
local actargs = { 0 }
-- Current number of section buffer positions for dasm_put().
local secpos = 1
------------------------------------------------------------------------------
-- Dump action names and numbers.
local function dumpactions(out)
out:write("DynASM encoding engine action codes:\n")
for n,name in ipairs(action_names) do
local num = map_action[name]
out:write(format(" %-10s %02X %d\n", name, num, num))
end
out:write("\n")
end
-- Write action list buffer as a huge static C array.
local function writeactions(out, name)
local nn = #actlist
if nn == 0 then nn = 1; actlist[0] = map_action.STOP end
out:write("static const unsigned int ", name, "[", nn, "] = {\n")
for i = 1,nn-1 do
assert(out:write("0x", tohex(actlist[i]), ",\n"))
end
assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n"))
end
------------------------------------------------------------------------------
-- Add word to action list.
local function wputxw(n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[#actlist+1] = n
end
-- Add action to list with optional arg. Advance buffer pos, too.
local function waction(action, val, a, num)
local w = assert(map_action[action], "bad action name `"..action.."'")
wputxw(w * 0x10000 + (val or 0))
if a then actargs[#actargs+1] = a end
if a or num then secpos = secpos + (num or 1) end
end
-- Flush action list (intervening C code or buffer pos overflow).
local function wflush(term)
if #actlist == actargs[1] then return end -- Nothing to flush.
if not term then waction("STOP") end -- Terminate action list.
wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true)
actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put().
secpos = 1 -- The actionlist offset occupies a buffer position, too.
end
-- Put escaped word.
local function wputw(n)
if n <= 0xffffff then waction("ESC") end
wputxw(n)
end
-- Reserve position for word.
local function wpos()
local pos = #actlist+1
actlist[pos] = ""
return pos
end
-- Store word to reserved position.
local function wputpos(pos, n)
assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range")
actlist[pos] = n
end
------------------------------------------------------------------------------
-- Global label name -> global label number. With auto assignment on 1st use.
local next_global = 20
local map_global = setmetatable({}, { __index = function(t, name)
if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end
local n = next_global
if n > 2047 then werror("too many global labels") end
next_global = n + 1
t[name] = n
return n
end})
-- Dump global labels.
local function dumpglobals(out, lvl)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("Global labels:\n")
for i=20,next_global-1 do
out:write(format(" %s\n", t[i]))
end
out:write("\n")
end
-- Write global label enum.
local function writeglobals(out, prefix)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("enum {\n")
for i=20,next_global-1 do
out:write(" ", prefix, t[i], ",\n")
end
out:write(" ", prefix, "_MAX\n};\n")
end
-- Write global label names.
local function writeglobalnames(out, name)
local t = {}
for name, n in pairs(map_global) do t[n] = name end
out:write("static const char *const ", name, "[] = {\n")
for i=20,next_global-1 do
out:write(" \"", t[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Extern label name -> extern label number. With auto assignment on 1st use.
local next_extern = 0
local map_extern_ = {}
local map_extern = setmetatable({}, { __index = function(t, name)
-- No restrictions on the name for now.
local n = next_extern
if n > 2047 then werror("too many extern labels") end
next_extern = n + 1
t[name] = n
map_extern_[n] = name
return n
end})
-- Dump extern labels.
local function dumpexterns(out, lvl)
out:write("Extern labels:\n")
for i=0,next_extern-1 do
out:write(format(" %s\n", map_extern_[i]))
end
out:write("\n")
end
-- Write extern label names.
local function writeexternnames(out, name)
out:write("static const char *const ", name, "[] = {\n")
for i=0,next_extern-1 do
out:write(" \"", map_extern_[i], "\",\n")
end
out:write(" (const char *)0\n};\n")
end
------------------------------------------------------------------------------
-- Arch-specific maps.
local map_archdef = { sp = "r1" } -- Ext. register name -> int. name.
local map_type = {} -- Type name -> { ctype, reg }
local ctypenum = 0 -- Type number (for Dt... macros).
-- Reverse defines for registers.
function _M.revdef(s)
if s == "r1" then return "sp" end
return s
end
local map_cond = {
lt = 0, gt = 1, eq = 2, so = 3,
ge = 4, le = 5, ne = 6, ns = 7,
}
------------------------------------------------------------------------------
local map_op, op_template
local function op_alias(opname, f)
return function(params, nparams)
if not params then return "-> "..opname:sub(1, -3) end
f(params, nparams)
op_template(params, map_op[opname], nparams)
end
end
-- Template strings for PPC instructions.
map_op = {
tdi_3 = "08000000ARI",
twi_3 = "0c000000ARI",
mulli_3 = "1c000000RRI",
subfic_3 = "20000000RRI",
cmplwi_3 = "28000000XRU",
cmplwi_2 = "28000000-RU",
cmpldi_3 = "28200000XRU",
cmpldi_2 = "28200000-RU",
cmpwi_3 = "2c000000XRI",
cmpwi_2 = "2c000000-RI",
cmpdi_3 = "2c200000XRI",
cmpdi_2 = "2c200000-RI",
addic_3 = "30000000RRI",
["addic._3"] = "34000000RRI",
addi_3 = "38000000RR0I",
li_2 = "38000000RI",
la_2 = "38000000RD",
addis_3 = "3c000000RR0I",
lis_2 = "3c000000RI",
lus_2 = "3c000000RU",
bc_3 = "40000000AAK",
bcl_3 = "40000001AAK",
bdnz_1 = "42000000K",
bdz_1 = "42400000K",
sc_0 = "44000000",
b_1 = "48000000J",
bl_1 = "48000001J",
rlwimi_5 = "50000000RR~AAA.",
rlwinm_5 = "54000000RR~AAA.",
rlwnm_5 = "5c000000RR~RAA.",
ori_3 = "60000000RR~U",
nop_0 = "60000000",
oris_3 = "64000000RR~U",
xori_3 = "68000000RR~U",
xoris_3 = "6c000000RR~U",
["andi._3"] = "70000000RR~U",
["andis._3"] = "74000000RR~U",
lwz_2 = "80000000RD",
lwzu_2 = "84000000RD",
lbz_2 = "88000000RD",
lbzu_2 = "8c000000RD",
stw_2 = "90000000RD",
stwu_2 = "94000000RD",
stb_2 = "98000000RD",
stbu_2 = "9c000000RD",
lhz_2 = "a0000000RD",
lhzu_2 = "a4000000RD",
lha_2 = "a8000000RD",
lhau_2 = "ac000000RD",
sth_2 = "b0000000RD",
sthu_2 = "b4000000RD",
lmw_2 = "b8000000RD",
stmw_2 = "bc000000RD",
lfs_2 = "c0000000FD",
lfsu_2 = "c4000000FD",
lfd_2 = "c8000000FD",
lfdu_2 = "cc000000FD",
stfs_2 = "d0000000FD",
stfsu_2 = "d4000000FD",
stfd_2 = "d8000000FD",
stfdu_2 = "dc000000FD",
ld_2 = "e8000000RD", -- NYI: displacement must be divisible by 4.
ldu_2 = "e8000001RD",
lwa_2 = "e8000002RD",
std_2 = "f8000000RD",
stdu_2 = "f8000001RD",
subi_3 = op_alias("addi_3", function(p) p[3] = "-("..p[3]..")" end),
subis_3 = op_alias("addis_3", function(p) p[3] = "-("..p[3]..")" end),
subic_3 = op_alias("addic_3", function(p) p[3] = "-("..p[3]..")" end),
["subic._3"] = op_alias("addic._3", function(p) p[3] = "-("..p[3]..")" end),
rotlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
rotrwi_3 = op_alias("rlwinm_5", function(p)
p[3] = "32-("..p[3]..")"; p[4] = "0"; p[5] = "31"
end),
rotlw_3 = op_alias("rlwnm_5", function(p)
p[4] = "0"; p[5] = "31"
end),
slwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[4] = "0"
end),
srwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "32-("..p[3]..")"; p[5] = "31"
end),
clrlwi_3 = op_alias("rlwinm_5", function(p)
p[4] = p[3]; p[3] = "0"; p[5] = "31"
end),
clrrwi_3 = op_alias("rlwinm_5", function(p)
p[5] = "31-("..p[3]..")"; p[3] = "0"; p[4] = "0"
end),
-- Primary opcode 4:
mulhhwu_3 = "10000010RRR.",
machhwu_3 = "10000018RRR.",
mulhhw_3 = "10000050RRR.",
nmachhw_3 = "1000005cRRR.",
machhwsu_3 = "10000098RRR.",
machhws_3 = "100000d8RRR.",
nmachhws_3 = "100000dcRRR.",
mulchwu_3 = "10000110RRR.",
macchwu_3 = "10000118RRR.",
mulchw_3 = "10000150RRR.",
macchw_3 = "10000158RRR.",
nmacchw_3 = "1000015cRRR.",
macchwsu_3 = "10000198RRR.",
macchws_3 = "100001d8RRR.",
nmacchws_3 = "100001dcRRR.",
mullhw_3 = "10000350RRR.",
maclhw_3 = "10000358RRR.",
nmaclhw_3 = "1000035cRRR.",
maclhwsu_3 = "10000398RRR.",
maclhws_3 = "100003d8RRR.",
nmaclhws_3 = "100003dcRRR.",
machhwuo_3 = "10000418RRR.",
nmachhwo_3 = "1000045cRRR.",
machhwsuo_3 = "10000498RRR.",
machhwso_3 = "100004d8RRR.",
nmachhwso_3 = "100004dcRRR.",
macchwuo_3 = "10000518RRR.",
macchwo_3 = "10000558RRR.",
nmacchwo_3 = "1000055cRRR.",
macchwsuo_3 = "10000598RRR.",
macchwso_3 = "100005d8RRR.",
nmacchwso_3 = "100005dcRRR.",
maclhwo_3 = "10000758RRR.",
nmaclhwo_3 = "1000075cRRR.",
maclhwsuo_3 = "10000798RRR.",
maclhwso_3 = "100007d8RRR.",
nmaclhwso_3 = "100007dcRRR.",
vaddubm_3 = "10000000VVV",
vmaxub_3 = "10000002VVV",
vrlb_3 = "10000004VVV",
vcmpequb_3 = "10000006VVV",
vmuloub_3 = "10000008VVV",
vaddfp_3 = "1000000aVVV",
vmrghb_3 = "1000000cVVV",
vpkuhum_3 = "1000000eVVV",
vmhaddshs_4 = "10000020VVVV",
vmhraddshs_4 = "10000021VVVV",
vmladduhm_4 = "10000022VVVV",
vmsumubm_4 = "10000024VVVV",
vmsummbm_4 = "10000025VVVV",
vmsumuhm_4 = "10000026VVVV",
vmsumuhs_4 = "10000027VVVV",
vmsumshm_4 = "10000028VVVV",
vmsumshs_4 = "10000029VVVV",
vsel_4 = "1000002aVVVV",
vperm_4 = "1000002bVVVV",
vsldoi_4 = "1000002cVVVP",
vpermxor_4 = "1000002dVVVV",
vmaddfp_4 = "1000002eVVVV~",
vnmsubfp_4 = "1000002fVVVV~",
vaddeuqm_4 = "1000003cVVVV",
vaddecuq_4 = "1000003dVVVV",
vsubeuqm_4 = "1000003eVVVV",
vsubecuq_4 = "1000003fVVVV",
vadduhm_3 = "10000040VVV",
vmaxuh_3 = "10000042VVV",
vrlh_3 = "10000044VVV",
vcmpequh_3 = "10000046VVV",
vmulouh_3 = "10000048VVV",
vsubfp_3 = "1000004aVVV",
vmrghh_3 = "1000004cVVV",
vpkuwum_3 = "1000004eVVV",
vadduwm_3 = "10000080VVV",
vmaxuw_3 = "10000082VVV",
vrlw_3 = "10000084VVV",
vcmpequw_3 = "10000086VVV",
vmulouw_3 = "10000088VVV",
vmuluwm_3 = "10000089VVV",
vmrghw_3 = "1000008cVVV",
vpkuhus_3 = "1000008eVVV",
vaddudm_3 = "100000c0VVV",
vmaxud_3 = "100000c2VVV",
vrld_3 = "100000c4VVV",
vcmpeqfp_3 = "100000c6VVV",
vcmpequd_3 = "100000c7VVV",
vpkuwus_3 = "100000ceVVV",
vadduqm_3 = "10000100VVV",
vmaxsb_3 = "10000102VVV",
vslb_3 = "10000104VVV",
vmulosb_3 = "10000108VVV",
vrefp_2 = "1000010aV-V",
vmrglb_3 = "1000010cVVV",
vpkshus_3 = "1000010eVVV",
vaddcuq_3 = "10000140VVV",
vmaxsh_3 = "10000142VVV",
vslh_3 = "10000144VVV",
vmulosh_3 = "10000148VVV",
vrsqrtefp_2 = "1000014aV-V",
vmrglh_3 = "1000014cVVV",
vpkswus_3 = "1000014eVVV",
vaddcuw_3 = "10000180VVV",
vmaxsw_3 = "10000182VVV",
vslw_3 = "10000184VVV",
vmulosw_3 = "10000188VVV",
vexptefp_2 = "1000018aV-V",
vmrglw_3 = "1000018cVVV",
vpkshss_3 = "1000018eVVV",
vmaxsd_3 = "100001c2VVV",
vsl_3 = "100001c4VVV",
vcmpgefp_3 = "100001c6VVV",
vlogefp_2 = "100001caV-V",
vpkswss_3 = "100001ceVVV",
vadduhs_3 = "10000240VVV",
vminuh_3 = "10000242VVV",
vsrh_3 = "10000244VVV",
vcmpgtuh_3 = "10000246VVV",
vmuleuh_3 = "10000248VVV",
vrfiz_2 = "1000024aV-V",
vsplth_3 = "1000024cVV3",
vupkhsh_2 = "1000024eV-V",
vminuw_3 = "10000282VVV",
vminud_3 = "100002c2VVV",
vcmpgtud_3 = "100002c7VVV",
vrfim_2 = "100002caV-V",
vcmpgtsb_3 = "10000306VVV",
vcfux_3 = "1000030aVVA~",
vaddshs_3 = "10000340VVV",
vminsh_3 = "10000342VVV",
vsrah_3 = "10000344VVV",
vcmpgtsh_3 = "10000346VVV",
vmulesh_3 = "10000348VVV",
vcfsx_3 = "1000034aVVA~",
vspltish_2 = "1000034cVS",
vupkhpx_2 = "1000034eV-V",
vaddsws_3 = "10000380VVV",
vminsw_3 = "10000382VVV",
vsraw_3 = "10000384VVV",
vcmpgtsw_3 = "10000386VVV",
vmulesw_3 = "10000388VVV",
vctuxs_3 = "1000038aVVA~",
vspltisw_2 = "1000038cVS",
vminsd_3 = "100003c2VVV",
vsrad_3 = "100003c4VVV",
vcmpbfp_3 = "100003c6VVV",
vcmpgtsd_3 = "100003c7VVV",
vctsxs_3 = "100003caVVA~",
vupklpx_2 = "100003ceV-V",
vsububm_3 = "10000400VVV",
["bcdadd._4"] = "10000401VVVy.",
vavgub_3 = "10000402VVV",
vand_3 = "10000404VVV",
["vcmpequb._3"] = "10000406VVV",
vmaxfp_3 = "1000040aVVV",
vsubuhm_3 = "10000440VVV",
["bcdsub._4"] = "10000441VVVy.",
vavguh_3 = "10000442VVV",
vandc_3 = "10000444VVV",
["vcmpequh._3"] = "10000446VVV",
vminfp_3 = "1000044aVVV",
vpkudum_3 = "1000044eVVV",
vsubuwm_3 = "10000480VVV",
vavguw_3 = "10000482VVV",
vor_3 = "10000484VVV",
["vcmpequw._3"] = "10000486VVV",
vpmsumw_3 = "10000488VVV",
["vcmpeqfp._3"] = "100004c6VVV",
["vcmpequd._3"] = "100004c7VVV",
vpkudus_3 = "100004ceVVV",
vavgsb_3 = "10000502VVV",
vavgsh_3 = "10000542VVV",
vorc_3 = "10000544VVV",
vbpermq_3 = "1000054cVVV",
vpksdus_3 = "1000054eVVV",
vavgsw_3 = "10000582VVV",
vsld_3 = "100005c4VVV",
["vcmpgefp._3"] = "100005c6VVV",
vpksdss_3 = "100005ceVVV",
vsububs_3 = "10000600VVV",
mfvscr_1 = "10000604V--",
vsum4ubs_3 = "10000608VVV",
vsubuhs_3 = "10000640VVV",
mtvscr_1 = "10000644--V",
["vcmpgtuh._3"] = "10000646VVV",
vsum4shs_3 = "10000648VVV",
vupkhsw_2 = "1000064eV-V",
vsubuws_3 = "10000680VVV",
vshasigmaw_4 = "10000682VVYp",
veqv_3 = "10000684VVV",
vsum2sws_3 = "10000688VVV",
vmrgow_3 = "1000068cVVV",
vshasigmad_4 = "100006c2VVYp",
vsrd_3 = "100006c4VVV",
["vcmpgtud._3"] = "100006c7VVV",
vupklsw_2 = "100006ceV-V",
vupkslw_2 = "100006ceV-V",
vsubsbs_3 = "10000700VVV",
vclzb_2 = "10000702V-V",
vpopcntb_2 = "10000703V-V",
["vcmpgtsb._3"] = "10000706VVV",
vsum4sbs_3 = "10000708VVV",
vsubshs_3 = "10000740VVV",
vclzh_2 = "10000742V-V",
vpopcnth_2 = "10000743V-V",
["vcmpgtsh._3"] = "10000746VVV",
vsubsws_3 = "10000780VVV",
vclzw_2 = "10000782V-V",
vpopcntw_2 = "10000783V-V",
["vcmpgtsw._3"] = "10000786VVV",
vsumsws_3 = "10000788VVV",
vmrgew_3 = "1000078cVVV",
vclzd_2 = "100007c2V-V",
vpopcntd_2 = "100007c3V-V",
["vcmpbfp._3"] = "100007c6VVV",
["vcmpgtsd._3"] = "100007c7VVV",
-- Primary opcode 19:
mcrf_2 = "4c000000XX",
isync_0 = "4c00012c",
crnor_3 = "4c000042CCC",
crnot_2 = "4c000042CC=",
crandc_3 = "4c000102CCC",
crxor_3 = "4c000182CCC",
crclr_1 = "4c000182C==",
crnand_3 = "4c0001c2CCC",
crand_3 = "4c000202CCC",
creqv_3 = "4c000242CCC",
crset_1 = "4c000242C==",
crorc_3 = "4c000342CCC",
cror_3 = "4c000382CCC",
crmove_2 = "4c000382CC=",
bclr_2 = "4c000020AA",
bclrl_2 = "4c000021AA",
bcctr_2 = "4c000420AA",
bcctrl_2 = "4c000421AA",
bctar_2 = "4c000460AA",
bctarl_2 = "4c000461AA",
blr_0 = "4e800020",
blrl_0 = "4e800021",
bctr_0 = "4e800420",
bctrl_0 = "4e800421",
-- Primary opcode 31:
cmpw_3 = "7c000000XRR",
cmpw_2 = "7c000000-RR",
cmpd_3 = "7c200000XRR",
cmpd_2 = "7c200000-RR",
tw_3 = "7c000008ARR",
lvsl_3 = "7c00000cVRR",
subfc_3 = "7c000010RRR.",
subc_3 = "7c000010RRR~.",
mulhdu_3 = "7c000012RRR.",
addc_3 = "7c000014RRR.",
mulhwu_3 = "7c000016RRR.",
isel_4 = "7c00001eRRRC",
isellt_3 = "7c00001eRRR",
iselgt_3 = "7c00005eRRR",
iseleq_3 = "7c00009eRRR",
mfcr_1 = "7c000026R",
mfocrf_2 = "7c100026RG",
mtcrf_2 = "7c000120GR",
mtocrf_2 = "7c100120GR",
lwarx_3 = "7c000028RR0R",
ldx_3 = "7c00002aRR0R",
lwzx_3 = "7c00002eRR0R",
slw_3 = "7c000030RR~R.",
cntlzw_2 = "7c000034RR~",
sld_3 = "7c000036RR~R.",
and_3 = "7c000038RR~R.",
cmplw_3 = "7c000040XRR",
cmplw_2 = "7c000040-RR",
cmpld_3 = "7c200040XRR",
cmpld_2 = "7c200040-RR",
lvsr_3 = "7c00004cVRR",
subf_3 = "7c000050RRR.",
sub_3 = "7c000050RRR~.",
lbarx_3 = "7c000068RR0R",
ldux_3 = "7c00006aRR0R",
dcbst_2 = "7c00006c-RR",
lwzux_3 = "7c00006eRR0R",
cntlzd_2 = "7c000074RR~",
andc_3 = "7c000078RR~R.",
td_3 = "7c000088ARR",
lvewx_3 = "7c00008eVRR",
mulhd_3 = "7c000092RRR.",
addg6s_3 = "7c000094RRR",
mulhw_3 = "7c000096RRR.",
dlmzb_3 = "7c00009cRR~R.",
ldarx_3 = "7c0000a8RR0R",
dcbf_2 = "7c0000ac-RR",
lbzx_3 = "7c0000aeRR0R",
lvx_3 = "7c0000ceVRR",
neg_2 = "7c0000d0RR.",
lharx_3 = "7c0000e8RR0R",
lbzux_3 = "7c0000eeRR0R",
popcntb_2 = "7c0000f4RR~",
not_2 = "7c0000f8RR~%.",
nor_3 = "7c0000f8RR~R.",
stvebx_3 = "7c00010eVRR",
subfe_3 = "7c000110RRR.",
sube_3 = "7c000110RRR~.",
adde_3 = "7c000114RRR.",
stdx_3 = "7c00012aRR0R",
["stwcx._3"] = "7c00012dRR0R.",
stwx_3 = "7c00012eRR0R",
prtyw_2 = "7c000134RR~",
stvehx_3 = "7c00014eVRR",
stdux_3 = "7c00016aRR0R",
["stqcx._3"] = "7c00016dR:R0R.",
stwux_3 = "7c00016eRR0R",
prtyd_2 = "7c000174RR~",
stvewx_3 = "7c00018eVRR",
subfze_2 = "7c000190RR.",
addze_2 = "7c000194RR.",
["stdcx._3"] = "7c0001adRR0R.",
stbx_3 = "7c0001aeRR0R",
stvx_3 = "7c0001ceVRR",
subfme_2 = "7c0001d0RR.",
mulld_3 = "7c0001d2RRR.",
addme_2 = "7c0001d4RR.",
mullw_3 = "7c0001d6RRR.",
dcbtst_2 = "7c0001ec-RR",
stbux_3 = "7c0001eeRR0R",
bpermd_3 = "7c0001f8RR~R",
lvepxl_3 = "7c00020eVRR",
add_3 = "7c000214RRR.",
lqarx_3 = "7c000228R:R0R",
dcbt_2 = "7c00022c-RR",
lhzx_3 = "7c00022eRR0R",
cdtbcd_2 = "7c000234RR~",
eqv_3 = "7c000238RR~R.",
lvepx_3 = "7c00024eVRR",
eciwx_3 = "7c00026cRR0R",
lhzux_3 = "7c00026eRR0R",
cbcdtd_2 = "7c000274RR~",
xor_3 = "7c000278RR~R.",
mfspefscr_1 = "7c0082a6R",
mfxer_1 = "7c0102a6R",
mflr_1 = "7c0802a6R",
mfctr_1 = "7c0902a6R",
lwax_3 = "7c0002aaRR0R",
lhax_3 = "7c0002aeRR0R",
mftb_1 = "7c0c42e6R",
mftbu_1 = "7c0d42e6R",
lvxl_3 = "7c0002ceVRR",
lwaux_3 = "7c0002eaRR0R",
lhaux_3 = "7c0002eeRR0R",
popcntw_2 = "7c0002f4RR~",
divdeu_3 = "7c000312RRR.",
divweu_3 = "7c000316RRR.",
sthx_3 = "7c00032eRR0R",
orc_3 = "7c000338RR~R.",
ecowx_3 = "7c00036cRR0R",
sthux_3 = "7c00036eRR0R",
or_3 = "7c000378RR~R.",
mr_2 = "7c000378RR~%.",
divdu_3 = "7c000392RRR.",
divwu_3 = "7c000396RRR.",
mtspefscr_1 = "7c0083a6R",
mtxer_1 = "7c0103a6R",
mtlr_1 = "7c0803a6R",
mtctr_1 = "7c0903a6R",
dcbi_2 = "7c0003ac-RR",
nand_3 = "7c0003b8RR~R.",
dsn_2 = "7c0003c6-RR",
stvxl_3 = "7c0003ceVRR",
divd_3 = "7c0003d2RRR.",
divw_3 = "7c0003d6RRR.",
popcntd_2 = "7c0003f4RR~",
cmpb_3 = "7c0003f8RR~R.",
mcrxr_1 = "7c000400X",
lbdx_3 = "7c000406RRR",
subfco_3 = "7c000410RRR.",
subco_3 = "7c000410RRR~.",
addco_3 = "7c000414RRR.",
ldbrx_3 = "7c000428RR0R",
lswx_3 = "7c00042aRR0R",
lwbrx_3 = "7c00042cRR0R",
lfsx_3 = "7c00042eFR0R",
srw_3 = "7c000430RR~R.",
srd_3 = "7c000436RR~R.",
lhdx_3 = "7c000446RRR",
subfo_3 = "7c000450RRR.",
subo_3 = "7c000450RRR~.",
lfsux_3 = "7c00046eFR0R",
lwdx_3 = "7c000486RRR",
lswi_3 = "7c0004aaRR0A",
sync_0 = "7c0004ac",
lwsync_0 = "7c2004ac",
ptesync_0 = "7c4004ac",
lfdx_3 = "7c0004aeFR0R",
lddx_3 = "7c0004c6RRR",
nego_2 = "7c0004d0RR.",
lfdux_3 = "7c0004eeFR0R",
stbdx_3 = "7c000506RRR",
subfeo_3 = "7c000510RRR.",
subeo_3 = "7c000510RRR~.",
addeo_3 = "7c000514RRR.",
stdbrx_3 = "7c000528RR0R",
stswx_3 = "7c00052aRR0R",
stwbrx_3 = "7c00052cRR0R",
stfsx_3 = "7c00052eFR0R",
sthdx_3 = "7c000546RRR",
["stbcx._3"] = "7c00056dRRR",
stfsux_3 = "7c00056eFR0R",
stwdx_3 = "7c000586RRR",
subfzeo_2 = "7c000590RR.",
addzeo_2 = "7c000594RR.",
stswi_3 = "7c0005aaRR0A",
["sthcx._3"] = "7c0005adRRR",
stfdx_3 = "7c0005aeFR0R",
stddx_3 = "7c0005c6RRR",
subfmeo_2 = "7c0005d0RR.",
mulldo_3 = "7c0005d2RRR.",
addmeo_2 = "7c0005d4RR.",
mullwo_3 = "7c0005d6RRR.",
dcba_2 = "7c0005ec-RR",
stfdux_3 = "7c0005eeFR0R",
stvepxl_3 = "7c00060eVRR",
addo_3 = "7c000614RRR.",
lhbrx_3 = "7c00062cRR0R",
lfdpx_3 = "7c00062eF:RR",
sraw_3 = "7c000630RR~R.",
srad_3 = "7c000634RR~R.",
lfddx_3 = "7c000646FRR",
stvepx_3 = "7c00064eVRR",
srawi_3 = "7c000670RR~A.",
sradi_3 = "7c000674RR~H.",
eieio_0 = "7c0006ac",
lfiwax_3 = "7c0006aeFR0R",
divdeuo_3 = "7c000712RRR.",
divweuo_3 = "7c000716RRR.",
sthbrx_3 = "7c00072cRR0R",
stfdpx_3 = "7c00072eF:RR",
extsh_2 = "7c000734RR~.",
stfddx_3 = "7c000746FRR",
divdeo_3 = "7c000752RRR.",
divweo_3 = "7c000756RRR.",
extsb_2 = "7c000774RR~.",
divduo_3 = "7c000792RRR.",
divwou_3 = "7c000796RRR.",
icbi_2 = "7c0007ac-RR",
stfiwx_3 = "7c0007aeFR0R",
extsw_2 = "7c0007b4RR~.",
divdo_3 = "7c0007d2RRR.",
divwo_3 = "7c0007d6RRR.",
dcbz_2 = "7c0007ec-RR",
["tbegin._1"] = "7c00051d1",
["tbegin._0"] = "7c00051d",
["tend._1"] = "7c00055dY",
["tend._0"] = "7c00055d",
["tendall._0"] = "7e00055d",
tcheck_1 = "7c00059cX",
["tsr._1"] = "7c0005dd1",
["tsuspend._0"] = "7c0005dd",
["tresume._0"] = "7c2005dd",
["tabortwc._3"] = "7c00061dARR",
["tabortdc._3"] = "7c00065dARR",
["tabortwci._3"] = "7c00069dARS",
["tabortdci._3"] = "7c0006ddARS",
["tabort._1"] = "7c00071d-R-",
["treclaim._1"] = "7c00075d-R",
["trechkpt._0"] = "7c0007dd",
lxsiwzx_3 = "7c000018QRR",
lxsiwax_3 = "7c000098QRR",
mfvsrd_2 = "7c000066-Rq",
mfvsrwz_2 = "7c0000e6-Rq",
stxsiwx_3 = "7c000118QRR",
mtvsrd_2 = "7c000166QR",
mtvsrwa_2 = "7c0001a6QR",
lxvdsx_3 = "7c000298QRR",
lxsspx_3 = "7c000418QRR",
lxsdx_3 = "7c000498QRR",
stxsspx_3 = "7c000518QRR",
stxsdx_3 = "7c000598QRR",
lxvw4x_3 = "7c000618QRR",
lxvd2x_3 = "7c000698QRR",
stxvw4x_3 = "7c000718QRR",
stxvd2x_3 = "7c000798QRR",
-- Primary opcode 30:
rldicl_4 = "78000000RR~HM.",
rldicr_4 = "78000004RR~HM.",
rldic_4 = "78000008RR~HM.",
rldimi_4 = "7800000cRR~HM.",
rldcl_4 = "78000010RR~RM.",
rldcr_4 = "78000012RR~RM.",
rotldi_3 = op_alias("rldicl_4", function(p)
p[4] = "0"
end),
rotrdi_3 = op_alias("rldicl_4", function(p)
p[3] = "64-("..p[3]..")"; p[4] = "0"
end),
rotld_3 = op_alias("rldcl_4", function(p)
p[4] = "0"
end),
sldi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"
end),
srdi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "64-("..p[3]..")"
end),
clrldi_3 = op_alias("rldicl_4", function(p)
p[4] = p[3]; p[3] = "0"
end),
clrrdi_3 = op_alias("rldicr_4", function(p)
p[4] = "63-("..p[3]..")"; p[3] = "0"
end),
-- Primary opcode 56:
lq_2 = "e0000000R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 57:
lfdp_2 = "e4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 59:
fdivs_3 = "ec000024FFF.",
fsubs_3 = "ec000028FFF.",
fadds_3 = "ec00002aFFF.",
fsqrts_2 = "ec00002cF-F.",
fres_2 = "ec000030F-F.",
fmuls_3 = "ec000032FF-F.",
frsqrtes_2 = "ec000034F-F.",
fmsubs_4 = "ec000038FFFF~.",
fmadds_4 = "ec00003aFFFF~.",
fnmsubs_4 = "ec00003cFFFF~.",
fnmadds_4 = "ec00003eFFFF~.",
fcfids_2 = "ec00069cF-F.",
fcfidus_2 = "ec00079cF-F.",
dadd_3 = "ec000004FFF.",
dqua_4 = "ec000006FFFZ.",
dmul_3 = "ec000044FFF.",
drrnd_4 = "ec000046FFFZ.",
dscli_3 = "ec000084FF6.",
dquai_4 = "ec000086SF~FZ.",
dscri_3 = "ec0000c4FF6.",
drintx_4 = "ec0000c61F~FZ.",
dcmpo_3 = "ec000104XFF",
dtstex_3 = "ec000144XFF",
dtstdc_3 = "ec000184XF6",
dtstdg_3 = "ec0001c4XF6",
drintn_4 = "ec0001c61F~FZ.",
dctdp_2 = "ec000204F-F.",
dctfix_2 = "ec000244F-F.",
ddedpd_3 = "ec000284ZF~F.",
dxex_2 = "ec0002c4F-F.",
dsub_3 = "ec000404FFF.",
ddiv_3 = "ec000444FFF.",
dcmpu_3 = "ec000504XFF",
dtstsf_3 = "ec000544XFF",
drsp_2 = "ec000604F-F.",
dcffix_2 = "ec000644F-F.",
denbcd_3 = "ec000684YF~F.",
diex_3 = "ec0006c4FFF.",
-- Primary opcode 60:
xsaddsp_3 = "f0000000QQQ",
xsmaddasp_3 = "f0000008QQQ",
xxsldwi_4 = "f0000010QQQz",
xsrsqrtesp_2 = "f0000028Q-Q",
xssqrtsp_2 = "f000002cQ-Q",
xxsel_4 = "f0000030QQQQ",
xssubsp_3 = "f0000040QQQ",
xsmaddmsp_3 = "f0000048QQQ",
xxpermdi_4 = "f0000050QQQz",
xsresp_2 = "f0000068Q-Q",
xsmulsp_3 = "f0000080QQQ",
xsmsubasp_3 = "f0000088QQQ",
xxmrghw_3 = "f0000090QQQ",
xsdivsp_3 = "f00000c0QQQ",
xsmsubmsp_3 = "f00000c8QQQ",
xsadddp_3 = "f0000100QQQ",
xsmaddadp_3 = "f0000108QQQ",
xscmpudp_3 = "f0000118XQQ",
xscvdpuxws_2 = "f0000120Q-Q",
xsrdpi_2 = "f0000124Q-Q",
xsrsqrtedp_2 = "f0000128Q-Q",
xssqrtdp_2 = "f000012cQ-Q",
xssubdp_3 = "f0000140QQQ",
xsmaddmdp_3 = "f0000148QQQ",
xscmpodp_3 = "f0000158XQQ",
xscvdpsxws_2 = "f0000160Q-Q",
xsrdpiz_2 = "f0000164Q-Q",
xsredp_2 = "f0000168Q-Q",
xsmuldp_3 = "f0000180QQQ",
xsmsubadp_3 = "f0000188QQQ",
xxmrglw_3 = "f0000190QQQ",
xsrdpip_2 = "f00001a4Q-Q",
xstsqrtdp_2 = "f00001a8X-Q",
xsrdpic_2 = "f00001acQ-Q",
xsdivdp_3 = "f00001c0QQQ",
xsmsubmdp_3 = "f00001c8QQQ",
xsrdpim_2 = "f00001e4Q-Q",
xstdivdp_3 = "f00001e8XQQ",
xvaddsp_3 = "f0000200QQQ",
xvmaddasp_3 = "f0000208QQQ",
xvcmpeqsp_3 = "f0000218QQQ",
xvcvspuxws_2 = "f0000220Q-Q",
xvrspi_2 = "f0000224Q-Q",
xvrsqrtesp_2 = "f0000228Q-Q",
xvsqrtsp_2 = "f000022cQ-Q",
xvsubsp_3 = "f0000240QQQ",
xvmaddmsp_3 = "f0000248QQQ",
xvcmpgtsp_3 = "f0000258QQQ",
xvcvspsxws_2 = "f0000260Q-Q",
xvrspiz_2 = "f0000264Q-Q",
xvresp_2 = "f0000268Q-Q",
xvmulsp_3 = "f0000280QQQ",
xvmsubasp_3 = "f0000288QQQ",
xxspltw_3 = "f0000290QQg~",
xvcmpgesp_3 = "f0000298QQQ",
xvcvuxwsp_2 = "f00002a0Q-Q",
xvrspip_2 = "f00002a4Q-Q",
xvtsqrtsp_2 = "f00002a8X-Q",
xvrspic_2 = "f00002acQ-Q",
xvdivsp_3 = "f00002c0QQQ",
xvmsubmsp_3 = "f00002c8QQQ",
xvcvsxwsp_2 = "f00002e0Q-Q",
xvrspim_2 = "f00002e4Q-Q",
xvtdivsp_3 = "f00002e8XQQ",
xvadddp_3 = "f0000300QQQ",
xvmaddadp_3 = "f0000308QQQ",
xvcmpeqdp_3 = "f0000318QQQ",
xvcvdpuxws_2 = "f0000320Q-Q",
xvrdpi_2 = "f0000324Q-Q",
xvrsqrtedp_2 = "f0000328Q-Q",
xvsqrtdp_2 = "f000032cQ-Q",
xvsubdp_3 = "f0000340QQQ",
xvmaddmdp_3 = "f0000348QQQ",
xvcmpgtdp_3 = "f0000358QQQ",
xvcvdpsxws_2 = "f0000360Q-Q",
xvrdpiz_2 = "f0000364Q-Q",
xvredp_2 = "f0000368Q-Q",
xvmuldp_3 = "f0000380QQQ",
xvmsubadp_3 = "f0000388QQQ",
xvcmpgedp_3 = "f0000398QQQ",
xvcvuxwdp_2 = "f00003a0Q-Q",
xvrdpip_2 = "f00003a4Q-Q",
xvtsqrtdp_2 = "f00003a8X-Q",
xvrdpic_2 = "f00003acQ-Q",
xvdivdp_3 = "f00003c0QQQ",
xvmsubmdp_3 = "f00003c8QQQ",
xvcvsxwdp_2 = "f00003e0Q-Q",
xvrdpim_2 = "f00003e4Q-Q",
xvtdivdp_3 = "f00003e8XQQ",
xsnmaddasp_3 = "f0000408QQQ",
xxland_3 = "f0000410QQQ",
xscvdpsp_2 = "f0000424Q-Q",
xscvdpspn_2 = "f000042cQ-Q",
xsnmaddmsp_3 = "f0000448QQQ",
xxlandc_3 = "f0000450QQQ",
xsrsp_2 = "f0000464Q-Q",
xsnmsubasp_3 = "f0000488QQQ",
xxlor_3 = "f0000490QQQ",
xscvuxdsp_2 = "f00004a0Q-Q",
xsnmsubmsp_3 = "f00004c8QQQ",
xxlxor_3 = "f00004d0QQQ",
xscvsxdsp_2 = "f00004e0Q-Q",
xsmaxdp_3 = "f0000500QQQ",
xsnmaddadp_3 = "f0000508QQQ",
xxlnor_3 = "f0000510QQQ",
xscvdpuxds_2 = "f0000520Q-Q",
xscvspdp_2 = "f0000524Q-Q",
xscvspdpn_2 = "f000052cQ-Q",
xsmindp_3 = "f0000540QQQ",
xsnmaddmdp_3 = "f0000548QQQ",
xxlorc_3 = "f0000550QQQ",
xscvdpsxds_2 = "f0000560Q-Q",
xsabsdp_2 = "f0000564Q-Q",
xscpsgndp_3 = "f0000580QQQ",
xsnmsubadp_3 = "f0000588QQQ",
xxlnand_3 = "f0000590QQQ",
xscvuxddp_2 = "f00005a0Q-Q",
xsnabsdp_2 = "f00005a4Q-Q",
xsnmsubmdp_3 = "f00005c8QQQ",
xxleqv_3 = "f00005d0QQQ",
xscvsxddp_2 = "f00005e0Q-Q",
xsnegdp_2 = "f00005e4Q-Q",
xvmaxsp_3 = "f0000600QQQ",
xvnmaddasp_3 = "f0000608QQQ",
["xvcmpeqsp._3"] = "f0000618QQQ",
xvcvspuxds_2 = "f0000620Q-Q",
xvcvdpsp_2 = "f0000624Q-Q",
xvminsp_3 = "f0000640QQQ",
xvnmaddmsp_3 = "f0000648QQQ",
["xvcmpgtsp._3"] = "f0000658QQQ",
xvcvspsxds_2 = "f0000660Q-Q",
xvabssp_2 = "f0000664Q-Q",
xvcpsgnsp_3 = "f0000680QQQ",
xvnmsubasp_3 = "f0000688QQQ",
["xvcmpgesp._3"] = "f0000698QQQ",
xvcvuxdsp_2 = "f00006a0Q-Q",
xvnabssp_2 = "f00006a4Q-Q",
xvnmsubmsp_3 = "f00006c8QQQ",
xvcvsxdsp_2 = "f00006e0Q-Q",
xvnegsp_2 = "f00006e4Q-Q",
xvmaxdp_3 = "f0000700QQQ",
xvnmaddadp_3 = "f0000708QQQ",
["xvcmpeqdp._3"] = "f0000718QQQ",
xvcvdpuxds_2 = "f0000720Q-Q",
xvcvspdp_2 = "f0000724Q-Q",
xvmindp_3 = "f0000740QQQ",
xvnmaddmdp_3 = "f0000748QQQ",
["xvcmpgtdp._3"] = "f0000758QQQ",
xvcvdpsxds_2 = "f0000760Q-Q",
xvabsdp_2 = "f0000764Q-Q",
xvcpsgndp_3 = "f0000780QQQ",
xvnmsubadp_3 = "f0000788QQQ",
["xvcmpgedp._3"] = "f0000798QQQ",
xvcvuxddp_2 = "f00007a0Q-Q",
xvnabsdp_2 = "f00007a4Q-Q",
xvnmsubmdp_3 = "f00007c8QQQ",
xvcvsxddp_2 = "f00007e0Q-Q",
xvnegdp_2 = "f00007e4Q-Q",
-- Primary opcode 61:
stfdp_2 = "f4000000F:D", -- NYI: displacement must be divisible by 4.
-- Primary opcode 62:
stq_2 = "f8000002R:D", -- NYI: displacement must be divisible by 8.
-- Primary opcode 63:
fdiv_3 = "fc000024FFF.",
fsub_3 = "fc000028FFF.",
fadd_3 = "fc00002aFFF.",
fsqrt_2 = "fc00002cF-F.",
fsel_4 = "fc00002eFFFF~.",
fre_2 = "fc000030F-F.",
fmul_3 = "fc000032FF-F.",
frsqrte_2 = "fc000034F-F.",
fmsub_4 = "fc000038FFFF~.",
fmadd_4 = "fc00003aFFFF~.",
fnmsub_4 = "fc00003cFFFF~.",
fnmadd_4 = "fc00003eFFFF~.",
fcmpu_3 = "fc000000XFF",
fcpsgn_3 = "fc000010FFF.",
fcmpo_3 = "fc000040XFF",
mtfsb1_1 = "fc00004cA",
fneg_2 = "fc000050F-F.",
mcrfs_2 = "fc000080XX",
mtfsb0_1 = "fc00008cA",
fmr_2 = "fc000090F-F.",
frsp_2 = "fc000018F-F.",
fctiw_2 = "fc00001cF-F.",
fctiwz_2 = "fc00001eF-F.",
ftdiv_2 = "fc000100X-F.",
fctiwu_2 = "fc00011cF-F.",
fctiwuz_2 = "fc00011eF-F.",
mtfsfi_2 = "fc00010cAA", -- NYI: upshift.
fnabs_2 = "fc000110F-F.",
ftsqrt_2 = "fc000140X-F.",
fabs_2 = "fc000210F-F.",
frin_2 = "fc000310F-F.",
friz_2 = "fc000350F-F.",
frip_2 = "fc000390F-F.",
frim_2 = "fc0003d0F-F.",
mffs_1 = "fc00048eF.",
-- NYI: mtfsf, mtfsb0, mtfsb1.
fctid_2 = "fc00065cF-F.",
fctidz_2 = "fc00065eF-F.",
fmrgow_3 = "fc00068cFFF",
fcfid_2 = "fc00069cF-F.",
fctidu_2 = "fc00075cF-F.",
fctiduz_2 = "fc00075eF-F.",
fmrgew_3 = "fc00078cFFF",
fcfidu_2 = "fc00079cF-F.",
daddq_3 = "fc000004F:F:F:.",
dquaq_4 = "fc000006F:F:F:Z.",
dmulq_3 = "fc000044F:F:F:.",
drrndq_4 = "fc000046F:F:F:Z.",
dscliq_3 = "fc000084F:F:6.",
dquaiq_4 = "fc000086SF:~F:Z.",
dscriq_3 = "fc0000c4F:F:6.",
drintxq_4 = "fc0000c61F:~F:Z.",
dcmpoq_3 = "fc000104XF:F:",
dtstexq_3 = "fc000144XF:F:",
dtstdcq_3 = "fc000184XF:6",
dtstdgq_3 = "fc0001c4XF:6",
drintnq_4 = "fc0001c61F:~F:Z.",
dctqpq_2 = "fc000204F:-F:.",
dctfixq_2 = "fc000244F:-F:.",
ddedpdq_3 = "fc000284ZF:~F:.",
dxexq_2 = "fc0002c4F:-F:.",
dsubq_3 = "fc000404F:F:F:.",
ddivq_3 = "fc000444F:F:F:.",
dcmpuq_3 = "fc000504XF:F:",
dtstsfq_3 = "fc000544XF:F:",
drdpq_2 = "fc000604F:-F:.",
dcffixq_2 = "fc000644F:-F:.",
denbcdq_3 = "fc000684YF:~F:.",
diexq_3 = "fc0006c4F:FF:.",
-- Primary opcode 4, SPE APU extension:
evaddw_3 = "10000200RRR",
evaddiw_3 = "10000202RAR~",
evsubw_3 = "10000204RRR~",
evsubiw_3 = "10000206RAR~",
evabs_2 = "10000208RR",
evneg_2 = "10000209RR",
evextsb_2 = "1000020aRR",
evextsh_2 = "1000020bRR",
evrndw_2 = "1000020cRR",
evcntlzw_2 = "1000020dRR",
evcntlsw_2 = "1000020eRR",
brinc_3 = "1000020fRRR",
evand_3 = "10000211RRR",
evandc_3 = "10000212RRR",
evxor_3 = "10000216RRR",
evor_3 = "10000217RRR",
evmr_2 = "10000217RR=",
evnor_3 = "10000218RRR",
evnot_2 = "10000218RR=",
eveqv_3 = "10000219RRR",
evorc_3 = "1000021bRRR",
evnand_3 = "1000021eRRR",
evsrwu_3 = "10000220RRR",
evsrws_3 = "10000221RRR",
evsrwiu_3 = "10000222RRA",
evsrwis_3 = "10000223RRA",
evslw_3 = "10000224RRR",
evslwi_3 = "10000226RRA",
evrlw_3 = "10000228RRR",
evsplati_2 = "10000229RS",
evrlwi_3 = "1000022aRRA",
evsplatfi_2 = "1000022bRS",
evmergehi_3 = "1000022cRRR",
evmergelo_3 = "1000022dRRR",
evcmpgtu_3 = "10000230XRR",
evcmpgtu_2 = "10000230-RR",
evcmpgts_3 = "10000231XRR",
evcmpgts_2 = "10000231-RR",
evcmpltu_3 = "10000232XRR",
evcmpltu_2 = "10000232-RR",
evcmplts_3 = "10000233XRR",
evcmplts_2 = "10000233-RR",
evcmpeq_3 = "10000234XRR",
evcmpeq_2 = "10000234-RR",
evsel_4 = "10000278RRRW",
evsel_3 = "10000278RRR",
evfsadd_3 = "10000280RRR",
evfssub_3 = "10000281RRR",
evfsabs_2 = "10000284RR",
evfsnabs_2 = "10000285RR",
evfsneg_2 = "10000286RR",
evfsmul_3 = "10000288RRR",
evfsdiv_3 = "10000289RRR",
evfscmpgt_3 = "1000028cXRR",
evfscmpgt_2 = "1000028c-RR",
evfscmplt_3 = "1000028dXRR",
evfscmplt_2 = "1000028d-RR",
evfscmpeq_3 = "1000028eXRR",
evfscmpeq_2 = "1000028e-RR",
evfscfui_2 = "10000290R-R",
evfscfsi_2 = "10000291R-R",
evfscfuf_2 = "10000292R-R",
evfscfsf_2 = "10000293R-R",
evfsctui_2 = "10000294R-R",
evfsctsi_2 = "10000295R-R",
evfsctuf_2 = "10000296R-R",
evfsctsf_2 = "10000297R-R",
evfsctuiz_2 = "10000298R-R",
evfsctsiz_2 = "1000029aR-R",
evfststgt_3 = "1000029cXRR",
evfststgt_2 = "1000029c-RR",
evfststlt_3 = "1000029dXRR",
evfststlt_2 = "1000029d-RR",
evfststeq_3 = "1000029eXRR",
evfststeq_2 = "1000029e-RR",
efsadd_3 = "100002c0RRR",
efssub_3 = "100002c1RRR",
efsabs_2 = "100002c4RR",
efsnabs_2 = "100002c5RR",
efsneg_2 = "100002c6RR",
efsmul_3 = "100002c8RRR",
efsdiv_3 = "100002c9RRR",
efscmpgt_3 = "100002ccXRR",
efscmpgt_2 = "100002cc-RR",
efscmplt_3 = "100002cdXRR",
efscmplt_2 = "100002cd-RR",
efscmpeq_3 = "100002ceXRR",
efscmpeq_2 = "100002ce-RR",
efscfd_2 = "100002cfR-R",
efscfui_2 = "100002d0R-R",
efscfsi_2 = "100002d1R-R",
efscfuf_2 = "100002d2R-R",
efscfsf_2 = "100002d3R-R",
efsctui_2 = "100002d4R-R",
efsctsi_2 = "100002d5R-R",
efsctuf_2 = "100002d6R-R",
efsctsf_2 = "100002d7R-R",
efsctuiz_2 = "100002d8R-R",
efsctsiz_2 = "100002daR-R",
efststgt_3 = "100002dcXRR",
efststgt_2 = "100002dc-RR",
efststlt_3 = "100002ddXRR",
efststlt_2 = "100002dd-RR",
efststeq_3 = "100002deXRR",
efststeq_2 = "100002de-RR",
efdadd_3 = "100002e0RRR",
efdsub_3 = "100002e1RRR",
efdcfuid_2 = "100002e2R-R",
efdcfsid_2 = "100002e3R-R",
efdabs_2 = "100002e4RR",
efdnabs_2 = "100002e5RR",
efdneg_2 = "100002e6RR",
efdmul_3 = "100002e8RRR",
efddiv_3 = "100002e9RRR",
efdctuidz_2 = "100002eaR-R",
efdctsidz_2 = "100002ebR-R",
efdcmpgt_3 = "100002ecXRR",
efdcmpgt_2 = "100002ec-RR",
efdcmplt_3 = "100002edXRR",
efdcmplt_2 = "100002ed-RR",
efdcmpeq_3 = "100002eeXRR",
efdcmpeq_2 = "100002ee-RR",
efdcfs_2 = "100002efR-R",
efdcfui_2 = "100002f0R-R",
efdcfsi_2 = "100002f1R-R",
efdcfuf_2 = "100002f2R-R",
efdcfsf_2 = "100002f3R-R",
efdctui_2 = "100002f4R-R",
efdctsi_2 = "100002f5R-R",
efdctuf_2 = "100002f6R-R",
efdctsf_2 = "100002f7R-R",
efdctuiz_2 = "100002f8R-R",
efdctsiz_2 = "100002faR-R",
efdtstgt_3 = "100002fcXRR",
efdtstgt_2 = "100002fc-RR",
efdtstlt_3 = "100002fdXRR",
efdtstlt_2 = "100002fd-RR",
efdtsteq_3 = "100002feXRR",
efdtsteq_2 = "100002fe-RR",
evlddx_3 = "10000300RR0R",
evldd_2 = "10000301R8",
evldwx_3 = "10000302RR0R",
evldw_2 = "10000303R8",
evldhx_3 = "10000304RR0R",
evldh_2 = "10000305R8",
evlwhex_3 = "10000310RR0R",
evlwhe_2 = "10000311R4",
evlwhoux_3 = "10000314RR0R",
evlwhou_2 = "10000315R4",
evlwhosx_3 = "10000316RR0R",
evlwhos_2 = "10000317R4",
evstddx_3 = "10000320RR0R",
evstdd_2 = "10000321R8",
evstdwx_3 = "10000322RR0R",
evstdw_2 = "10000323R8",
evstdhx_3 = "10000324RR0R",
evstdh_2 = "10000325R8",
evstwhex_3 = "10000330RR0R",
evstwhe_2 = "10000331R4",
evstwhox_3 = "10000334RR0R",
evstwho_2 = "10000335R4",
evstwwex_3 = "10000338RR0R",
evstwwe_2 = "10000339R4",
evstwwox_3 = "1000033cRR0R",
evstwwo_2 = "1000033dR4",
evmhessf_3 = "10000403RRR",
evmhossf_3 = "10000407RRR",
evmheumi_3 = "10000408RRR",
evmhesmi_3 = "10000409RRR",
evmhesmf_3 = "1000040bRRR",
evmhoumi_3 = "1000040cRRR",
evmhosmi_3 = "1000040dRRR",
evmhosmf_3 = "1000040fRRR",
evmhessfa_3 = "10000423RRR",
evmhossfa_3 = "10000427RRR",
evmheumia_3 = "10000428RRR",
evmhesmia_3 = "10000429RRR",
evmhesmfa_3 = "1000042bRRR",
evmhoumia_3 = "1000042cRRR",
evmhosmia_3 = "1000042dRRR",
evmhosmfa_3 = "1000042fRRR",
evmwhssf_3 = "10000447RRR",
evmwlumi_3 = "10000448RRR",
evmwhumi_3 = "1000044cRRR",
evmwhsmi_3 = "1000044dRRR",
evmwhsmf_3 = "1000044fRRR",
evmwssf_3 = "10000453RRR",
evmwumi_3 = "10000458RRR",
evmwsmi_3 = "10000459RRR",
evmwsmf_3 = "1000045bRRR",
evmwhssfa_3 = "10000467RRR",
evmwlumia_3 = "10000468RRR",
evmwhumia_3 = "1000046cRRR",
evmwhsmia_3 = "1000046dRRR",
evmwhsmfa_3 = "1000046fRRR",
evmwssfa_3 = "10000473RRR",
evmwumia_3 = "10000478RRR",
evmwsmia_3 = "10000479RRR",
evmwsmfa_3 = "1000047bRRR",
evmra_2 = "100004c4RR",
evdivws_3 = "100004c6RRR",
evdivwu_3 = "100004c7RRR",
evmwssfaa_3 = "10000553RRR",
evmwumiaa_3 = "10000558RRR",
evmwsmiaa_3 = "10000559RRR",
evmwsmfaa_3 = "1000055bRRR",
evmwssfan_3 = "100005d3RRR",
evmwumian_3 = "100005d8RRR",
evmwsmian_3 = "100005d9RRR",
evmwsmfan_3 = "100005dbRRR",
evmergehilo_3 = "1000022eRRR",
evmergelohi_3 = "1000022fRRR",
evlhhesplatx_3 = "10000308RR0R",
evlhhesplat_2 = "10000309R2",
evlhhousplatx_3 = "1000030cRR0R",
evlhhousplat_2 = "1000030dR2",
evlhhossplatx_3 = "1000030eRR0R",
evlhhossplat_2 = "1000030fR2",
evlwwsplatx_3 = "10000318RR0R",
evlwwsplat_2 = "10000319R4",
evlwhsplatx_3 = "1000031cRR0R",
evlwhsplat_2 = "1000031dR4",
evaddusiaaw_2 = "100004c0RR",
evaddssiaaw_2 = "100004c1RR",
evsubfusiaaw_2 = "100004c2RR",
evsubfssiaaw_2 = "100004c3RR",
evaddumiaaw_2 = "100004c8RR",
evaddsmiaaw_2 = "100004c9RR",
evsubfumiaaw_2 = "100004caRR",
evsubfsmiaaw_2 = "100004cbRR",
evmheusiaaw_3 = "10000500RRR",
evmhessiaaw_3 = "10000501RRR",
evmhessfaaw_3 = "10000503RRR",
evmhousiaaw_3 = "10000504RRR",
evmhossiaaw_3 = "10000505RRR",
evmhossfaaw_3 = "10000507RRR",
evmheumiaaw_3 = "10000508RRR",
evmhesmiaaw_3 = "10000509RRR",
evmhesmfaaw_3 = "1000050bRRR",
evmhoumiaaw_3 = "1000050cRRR",
evmhosmiaaw_3 = "1000050dRRR",
evmhosmfaaw_3 = "1000050fRRR",
evmhegumiaa_3 = "10000528RRR",
evmhegsmiaa_3 = "10000529RRR",
evmhegsmfaa_3 = "1000052bRRR",
evmhogumiaa_3 = "1000052cRRR",
evmhogsmiaa_3 = "1000052dRRR",
evmhogsmfaa_3 = "1000052fRRR",
evmwlusiaaw_3 = "10000540RRR",
evmwlssiaaw_3 = "10000541RRR",
evmwlumiaaw_3 = "10000548RRR",
evmwlsmiaaw_3 = "10000549RRR",
evmheusianw_3 = "10000580RRR",
evmhessianw_3 = "10000581RRR",
evmhessfanw_3 = "10000583RRR",
evmhousianw_3 = "10000584RRR",
evmhossianw_3 = "10000585RRR",
evmhossfanw_3 = "10000587RRR",
evmheumianw_3 = "10000588RRR",
evmhesmianw_3 = "10000589RRR",
evmhesmfanw_3 = "1000058bRRR",
evmhoumianw_3 = "1000058cRRR",
evmhosmianw_3 = "1000058dRRR",
evmhosmfanw_3 = "1000058fRRR",
evmhegumian_3 = "100005a8RRR",
evmhegsmian_3 = "100005a9RRR",
evmhegsmfan_3 = "100005abRRR",
evmhogumian_3 = "100005acRRR",
evmhogsmian_3 = "100005adRRR",
evmhogsmfan_3 = "100005afRRR",
evmwlusianw_3 = "100005c0RRR",
evmwlssianw_3 = "100005c1RRR",
evmwlumianw_3 = "100005c8RRR",
evmwlsmianw_3 = "100005c9RRR",
-- NYI: Book E instructions.
}
-- Add mnemonics for "." variants.
do
local t = {}
for k,v in pairs(map_op) do
if type(v) == "string" and sub(v, -1) == "." then
local v2 = sub(v, 1, 7)..char(byte(v, 8)+1)..sub(v, 9, -2)
t[sub(k, 1, -3).."."..sub(k, -2)] = v2
end
end
for k,v in pairs(t) do
map_op[k] = v
end
end
-- Add more branch mnemonics.
for cond,c in pairs(map_cond) do
local b1 = "b"..cond
local c1 = shl(band(c, 3), 16) + (c < 4 and 0x01000000 or 0)
-- bX[l]
map_op[b1.."_1"] = tohex(0x40800000 + c1).."K"
map_op[b1.."y_1"] = tohex(0x40a00000 + c1).."K"
map_op[b1.."l_1"] = tohex(0x40800001 + c1).."K"
map_op[b1.."_2"] = tohex(0x40800000 + c1).."-XK"
map_op[b1.."y_2"] = tohex(0x40a00000 + c1).."-XK"
map_op[b1.."l_2"] = tohex(0x40800001 + c1).."-XK"
-- bXlr[l]
map_op[b1.."lr_0"] = tohex(0x4c800020 + c1)
map_op[b1.."lrl_0"] = tohex(0x4c800021 + c1)
map_op[b1.."ctr_0"] = tohex(0x4c800420 + c1)
map_op[b1.."ctrl_0"] = tohex(0x4c800421 + c1)
-- bXctr[l]
map_op[b1.."lr_1"] = tohex(0x4c800020 + c1).."-X"
map_op[b1.."lrl_1"] = tohex(0x4c800021 + c1).."-X"
map_op[b1.."ctr_1"] = tohex(0x4c800420 + c1).."-X"
map_op[b1.."ctrl_1"] = tohex(0x4c800421 + c1).."-X"
end
------------------------------------------------------------------------------
local function parse_gpr(expr)
local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$")
local tp = map_type[tname or expr]
if tp then
local reg = ovreg or tp.reg
if not reg then
werror("type `"..(tname or expr).."' needs a register override")
end
expr = reg
end
local r = match(expr, "^r([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r, tp end
end
werror("bad register name `"..expr.."'")
end
local function parse_fpr(expr)
local r = match(expr, "^f([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vr(expr)
local r = match(expr, "^v([1-3]?[0-9])$")
if r then
r = tonumber(r)
if r <= 31 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_vs(expr)
local r = match(expr, "^vs([1-6]?[0-9])$")
if r then
r = tonumber(r)
if r <= 63 then return r end
end
werror("bad register name `"..expr.."'")
end
local function parse_cr(expr)
local r = match(expr, "^cr([0-7])$")
if r then return tonumber(r) end
werror("bad condition register name `"..expr.."'")
end
local function parse_cond(expr)
local r, cond = match(expr, "^4%*cr([0-7])%+(%w%w)$")
if r then
r = tonumber(r)
local c = map_cond[cond]
if c and c < 4 then return r*4+c end
end
werror("bad condition bit name `"..expr.."'")
end
local parse_ctx = {}
local loadenv = setfenv and function(s)
local code = loadstring(s, "")
if code then setfenv(code, parse_ctx) end
return code
end or function(s)
return load(s, "", nil, parse_ctx)
end
-- Try to parse simple arithmetic, too, since some basic ops are aliases.
local function parse_number(n)
local x = tonumber(n)
if x then return x end
local code = loadenv("return "..n)
if code then
local ok, y = pcall(code)
if ok then return y end
end
return nil
end
local function parse_imm(imm, bits, shift, scale, signed)
local n = parse_number(imm)
if n then
local m = sar(n, scale)
if shl(m, scale) == n then
if signed then
local s = sar(m, bits-1)
if s == 0 then return shl(m, shift)
elseif s == -1 then return shl(m + shl(1, bits), shift) end
else
if sar(m, bits) == 0 then return shl(m, shift) end
end
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^[rfv]([1-3]?[0-9])$") or
match(imm, "^vs([1-6]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm)
return 0
end
end
local function parse_shiftmask(imm, isshift)
local n = parse_number(imm)
if n then
if shr(n, 6) == 0 then
local lsb = band(n, 31)
local msb = n - lsb
return isshift and (shl(lsb, 11)+shr(msb, 4)) or (shl(lsb, 6)+msb)
end
werror("out of range immediate `"..imm.."'")
elseif match(imm, "^r([1-3]?[0-9])$") or
match(imm, "^([%w_]+):(r[1-3]?[0-9])$") then
werror("expected immediate operand, got register")
else
waction("IMMSH", isshift and 1 or 0, imm)
return 0;
end
end
local function parse_disp(disp)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 16, 0, 0, true)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_u5disp(disp, scale)
local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$")
if imm then
local r = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
return shl(r, 16) + parse_imm(imm, 5, 11, scale, false)
end
local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$")
if reg and tailr ~= "" then
local r, tp = parse_gpr(reg)
if r == 0 then werror("cannot use r0 in displacement") end
if tp then
waction("IMM", scale*1024+5*32+11, format(tp.ctypefmt, tailr))
return shl(r, 16)
end
end
werror("bad displacement `"..disp.."'")
end
local function parse_label(label, def)
local prefix = sub(label, 1, 2)
-- =>label (pc label reference)
if prefix == "=>" then
return "PC", 0, sub(label, 3)
end
-- ->name (global label reference)
if prefix == "->" then
return "LG", map_global[sub(label, 3)]
end
if def then
-- [1-9] (local label definition)
if match(label, "^[1-9]$") then
return "LG", 10+tonumber(label)
end
else
-- [<>][1-9] (local label reference)
local dir, lnum = match(label, "^([<>])([1-9])$")
if dir then -- Fwd: 1-9, Bkwd: 11-19.
return "LG", lnum + (dir == ">" and 0 or 10)
end
-- extern label (extern label reference)
local extname = match(label, "^extern%s+(%S+)$")
if extname then
return "EXT", map_extern[extname]
end
end
werror("bad label `"..label.."'")
end
------------------------------------------------------------------------------
-- Handle opcodes defined with template strings.
op_template = function(params, template, nparams)
if not params then return sub(template, 9) end
local op = tonumber(sub(template, 1, 8), 16)
local n, rs = 1, 26
-- Limit number of section buffer positions used by a single dasm_put().
-- A single opcode needs a maximum of 3 positions (rlwinm).
if secpos+3 > maxsecpos then wflush() end
local pos = wpos()
-- Process each character.
for p in gmatch(sub(template, 9), ".") do
if p == "R" then
rs = rs - 5; op = op + shl(parse_gpr(params[n]), rs); n = n + 1
elseif p == "F" then
rs = rs - 5; op = op + shl(parse_fpr(params[n]), rs); n = n + 1
elseif p == "V" then
rs = rs - 5; op = op + shl(parse_vr(params[n]), rs); n = n + 1
elseif p == "Q" then
local vs = parse_vs(params[n]); n = n + 1; rs = rs - 5
local sh = rs == 6 and 2 or 3 + band(shr(rs, 1), 3)
op = op + shl(band(vs, 31), rs) + shr(band(vs, 32), sh)
elseif p == "q" then
local vs = parse_vs(params[n]); n = n + 1
op = op + shl(band(vs, 31), 21) + shr(band(vs, 32), 5)
elseif p == "A" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, false); n = n + 1
elseif p == "S" then
rs = rs - 5; op = op + parse_imm(params[n], 5, rs, 0, true); n = n + 1
elseif p == "I" then
op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1
elseif p == "U" then
op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1
elseif p == "D" then
op = op + parse_disp(params[n]); n = n + 1
elseif p == "2" then
op = op + parse_u5disp(params[n], 1); n = n + 1
elseif p == "4" then
op = op + parse_u5disp(params[n], 2); n = n + 1
elseif p == "8" then
op = op + parse_u5disp(params[n], 3); n = n + 1
elseif p == "C" then
rs = rs - 5; op = op + shl(parse_cond(params[n]), rs); n = n + 1
elseif p == "X" then
rs = rs - 5; op = op + shl(parse_cr(params[n]), rs+2); n = n + 1
elseif p == "1" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs, 0, false); n = n + 1
elseif p == "g" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs, 0, false); n = n + 1
elseif p == "3" then
rs = rs - 5; op = op + parse_imm(params[n], 3, rs, 0, false); n = n + 1
elseif p == "P" then
rs = rs - 5; op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "p" then
op = op + parse_imm(params[n], 4, rs, 0, false); n = n + 1
elseif p == "6" then
rs = rs - 6; op = op + parse_imm(params[n], 6, rs, 0, false); n = n + 1
elseif p == "Y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+4, 0, false); n = n + 1
elseif p == "y" then
rs = rs - 5; op = op + parse_imm(params[n], 1, rs+3, 0, false); n = n + 1
elseif p == "Z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+3, 0, false); n = n + 1
elseif p == "z" then
rs = rs - 5; op = op + parse_imm(params[n], 2, rs+2, 0, false); n = n + 1
elseif p == "W" then
op = op + parse_cr(params[n]); n = n + 1
elseif p == "G" then
op = op + parse_imm(params[n], 8, 12, 0, false); n = n + 1
elseif p == "H" then
op = op + parse_shiftmask(params[n], true); n = n + 1
elseif p == "M" then
op = op + parse_shiftmask(params[n], false); n = n + 1
elseif p == "J" or p == "K" then
local mode, n, s = parse_label(params[n], false)
if p == "K" then n = n + 2048 end
waction("REL_"..mode, n, s, 1)
n = n + 1
elseif p == "0" then
if band(shr(op, rs), 31) == 0 then werror("cannot use r0") end
elseif p == "=" or p == "%" then
local t = band(shr(op, p == "%" and rs+5 or rs), 31)
rs = rs - 5
op = op + shl(t, rs)
elseif p == "~" then
local mm = shl(31, rs)
local lo = band(op, mm)
local hi = band(op, shl(mm, 5))
op = op - lo - hi + shl(lo, 5) + shr(hi, 5)
elseif p == ":" then
if band(shr(op, rs), 1) ~= 0 then werror("register pair expected") end
elseif p == "-" then
rs = rs - 5
elseif p == "." then
-- Ignored.
else
assert(false)
end
end
wputpos(pos, op)
end
map_op[".template__"] = op_template
------------------------------------------------------------------------------
-- Pseudo-opcode to mark the position where the action list is to be emitted.
map_op[".actionlist_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeactions(out, name) end)
end
-- Pseudo-opcode to mark the position where the global enum is to be emitted.
map_op[".globals_1"] = function(params)
if not params then return "prefix" end
local prefix = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobals(out, prefix) end)
end
-- Pseudo-opcode to mark the position where the global names are to be emitted.
map_op[".globalnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeglobalnames(out, name) end)
end
-- Pseudo-opcode to mark the position where the extern names are to be emitted.
map_op[".externnames_1"] = function(params)
if not params then return "cvar" end
local name = params[1] -- No syntax check. You get to keep the pieces.
wline(function(out) writeexternnames(out, name) end)
end
------------------------------------------------------------------------------
-- Label pseudo-opcode (converted from trailing colon form).
map_op[".label_1"] = function(params)
if not params then return "[1-9] | ->global | =>pcexpr" end
if secpos+1 > maxsecpos then wflush() end
local mode, n, s = parse_label(params[1], true)
if mode == "EXT" then werror("bad label definition") end
waction("LABEL_"..mode, n, s, 1)
end
------------------------------------------------------------------------------
-- Pseudo-opcodes for data storage.
map_op[".long_*"] = function(params)
if not params then return "imm..." end
for _,p in ipairs(params) do
local n = tonumber(p)
if not n then werror("bad immediate `"..p.."'") end
if n < 0 then n = n + 2^32 end
wputw(n)
if secpos+2 > maxsecpos then wflush() end
end
end
-- Alignment pseudo-opcode.
map_op[".align_1"] = function(params)
if not params then return "numpow2" end
if secpos+1 > maxsecpos then wflush() end
local align = tonumber(params[1])
if align then
local x = align
-- Must be a power of 2 in the range (2 ... 256).
for i=1,8 do
x = x / 2
if x == 1 then
waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1.
return
end
end
end
werror("bad alignment")
end
------------------------------------------------------------------------------
-- Pseudo-opcode for (primitive) type definitions (map to C types).
map_op[".type_3"] = function(params, nparams)
if not params then
return nparams == 2 and "name, ctype" or "name, ctype, reg"
end
local name, ctype, reg = params[1], params[2], params[3]
if not match(name, "^[%a_][%w_]*$") then
werror("bad type name `"..name.."'")
end
local tp = map_type[name]
if tp then
werror("duplicate type `"..name.."'")
end
-- Add #type to defines. A bit unclean to put it in map_archdef.
map_archdef["#"..name] = "sizeof("..ctype..")"
-- Add new type and emit shortcut define.
local num = ctypenum + 1
map_type[name] = {
ctype = ctype,
ctypefmt = format("Dt%X(%%s)", num),
reg = reg,
}
wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype))
ctypenum = num
end
map_op[".type_2"] = map_op[".type_3"]
-- Dump type definitions.
local function dumptypes(out, lvl)
local t = {}
for name in pairs(map_type) do t[#t+1] = name end
sort(t)
out:write("Type definitions:\n")
for _,name in ipairs(t) do
local tp = map_type[name]
local reg = tp.reg or ""
out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg))
end
out:write("\n")
end
------------------------------------------------------------------------------
-- Set the current section.
function _M.section(num)
waction("SECTION", num)
wflush(true) -- SECTION is a terminal action.
end
------------------------------------------------------------------------------
-- Dump architecture description.
function _M.dumparch(out)
out:write(format("DynASM %s version %s, released %s\n\n",
_info.arch, _info.version, _info.release))
dumpactions(out)
end
-- Dump all user defined elements.
function _M.dumpdef(out, lvl)
dumptypes(out, lvl)
dumpglobals(out, lvl)
dumpexterns(out, lvl)
end
------------------------------------------------------------------------------
-- Pass callbacks from/to the DynASM core.
function _M.passcb(wl, we, wf, ww)
wline, werror, wfatal, wwarn = wl, we, wf, ww
return wflush
end
-- Setup the arch-specific module.
function _M.setup(arch, opt)
g_arch, g_opt = arch, opt
end
-- Merge the core maps and the arch-specific maps.
function _M.mergemaps(map_coreop, map_def)
setmetatable(map_op, { __index = map_coreop })
setmetatable(map_def, { __index = map_archdef })
return map_op, map_def
end
return _M
------------------------------------------------------------------------------
| mit |
kidaa/FFXIOrgins | scripts/zones/Southern_San_dOria_[S]/npcs/Achtelle1.lua | 38 | 1029 | -----------------------------------
-- Area: Southern SandOria [S]
-- NPC: Achtelle
-- @zone 80
-- @pos 108 2 -11
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
--player:startEvent(0x01FE); Event doesnt work but this is her default dialogue, threw in something below til it gets fixed
player:showText(npc, 13454); -- (Couldn't find default dialogue) How very good to see you again!
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/Ifrits_Cauldron/npcs/Flame_Spout.lua | 2 | 1640 | ----------------------------------
-- Area: Ifrit's Cauldron
-- NPC: Flame Spout
-- @pos 205
-- @pos 193.967 -0.400 19.492 205
-----------------------------------
require("scripts/zones/Ifrits_Cauldron/TextIDs");
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local npcid = npc:getID();
if (trade:getItemCount() == 1 and trade:hasItemQty(4105,1) == true) then -- Ice Cluster Trade
GetNPCByID(npcid+5):openDoor(90);
player:tradeComplete();
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- printf("%u",npc:getID())
local npcid = npc:getID();
-- Commented out to preserve CSIDs for the quest, since the workaround was removed.
--[[if(npcid == 17617198) then
player:startEvent(0x000b);
elseif(npcid == 17617199) then
player:startEvent(0x000c);
elseif(npcid == 17617200) then
player:startEvent(0x000d);
elseif(npcid == 17617201) then
player:startEvent(0x000e);
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 |
BTAxis/naev | dat/missions/shark/sh06_arandon.lua | 1 | 4633 | --[[
This is the seventh mission of the Shark's teeth campaign. The player has to meet the FLF in Arandon.
Stages :
0) Way to Arandon
1) Way back to Darkshed
--]]
include "numstring.lua"
title = {}
text = {}
osd_msg = {}
npc_desc = {}
bar_desc = {}
title[1] = _("Let's go")
text[1] = _([["Is your ship ready for the dangers of the Nebula?"]])
refusetitle = _("...Or not")
refusetext = _([["Come back when you are ready."]])
title[2] = _("Go")
text[2] = _([[Smith once again steps in your ship in order to go to a meeting.]])
title[3] = _("Well done!")
text[3] = _([[Smith thanks you for the job well done. "Here is your pay," he says. "I will be in the bar if I have another task for you."]])
title[4] = _("The Meeting")
text[4] = _([[As you board, Arnold Smith insists on entering the FLF's ship alone. A few hours later, he comes back, satisfied. It seems this time luck is on his side. He mentions that he had good results with a smile on his face before directing you to take him back to %s.]])
title[5] = _("Hail")
text[5] = _([[The Pacifier commander answers you and stops his ship, waiting to be boarded.]])
title[6] = _("Let's wait")
text[6] = _([["Mm. It looks like the other ones have not arrived yet." Smith says. "Just wait close to the jump point, they should arrive soon."]])
-- Mission details
misn_title = _("A Journey To %s")
misn_reward = _("%s credits")
misn_desc = _("You are to transport Arnold Smith to %s so that he can talk about a deal.")
-- NPC
npc_desc[1] = _("Arnold Smith")
bar_desc[1] = _([[He's waiting for you.]])
-- OSD
osd_title = _("A Journey To %s")
osd_msg[1] = _("Go to %s and wait for the FLF ship, then hail and board it.")
osd_msg[2] = _("Go back to %s in %s")
function create ()
--Change here to change the planets and the systems
missys = system.get("Arandon")
pplname = "Darkshed"
psyname = "Alteris"
paysys = system.get(psyname)
paypla = planet.get(pplname)
if not misn.claim(missys) then
misn.finish(false)
end
misn.setNPC(npc_desc[1], "neutral/male1")
misn.setDesc(bar_desc[1])
end
function accept()
stage = 0
reward = 750000
if tk.yesno(title[1], text[1]) then
misn.accept()
tk.msg(title[2], text[2])
osd_msg[1] = osd_msg[1]:format(missys:name())
osd_msg[2] = osd_msg[2]:format(paypla:name(), paysys:name())
misn.setTitle(misn_title:format(missys:name()))
misn.setReward(misn_reward:format(numstring(reward)))
misn.setDesc(misn_desc:format(missys:name()))
osd = misn.osdCreate(osd_title:format(missys:name()), osd_msg)
misn.osdActive(1)
marker = misn.markerAdd(missys, "low")
smith = misn.cargoAdd("Person", 0) --Adding the cargo
landhook = hook.land("land")
enterhook = hook.enter("enter")
else
tk.msg(refusetitle, refusetext)
misn.finish(false)
end
end
function land()
--Job is done
if stage == 1 and planet.cur() == paypla then
if misn.cargoRm(smith) then
tk.msg(title[3], text[3])
player.pay(reward)
misn.osdDestroy(osd)
hook.rm(enterhook)
hook.rm(landhook)
misn.finish(true)
end
end
end
function enter()
--Entering in Arandon in order to find the FLF Pacifier
if system.cur() == missys then
--Lets unspawn everybody (if any)
pilot.clear()
pilot.toggleSpawn(false)
--Waiting to spawn the FLF in order to let the player's shield decrease
hook.timer(2000,"wait_msg")
hook.timer(10000,"flf_people")
end
end
function wait_msg()
-- Prevents the player from being impatient
tk.msg(title[6], text[6])
end
function flf_people()
pacifier = pilot.add( "FLF Pacifier", nil, "Doeston" )[1]
pacifier:setFriendly()
pacifier:setInvincible(true)
hook.pilot(pacifier, "hail", "hail_pacifier")
hook.pilot( pacifier, "death", "dead" )
hook.pilot( pacifier, "jump", "jump" )
end
function hail_pacifier()
--hailing the pacifier
tk.msg(title[5], text[5])
pacifier:control()
pacifier:brake()
pacifier:setActiveBoard(true)
hook.pilot(pacifier, "board", "board")
end
function board()
--boarding the pacifier
tk.msg(title[4], text[4]:format(paysys:name()))
player.unboard()
pacifier:control(false)
pacifier:setActiveBoard(false)
stage = 1
misn.osdActive(2)
misn.markerRm(marker)
marker2 = misn.markerAdd(paysys, "low")
end
function dead() --Actually, I don't know how it could happend...
misn.finish(false)
end
function jump()
misn.finish(false)
end
function abort()
misn.cargoRm(smith)
misn.finish(false)
end
| gpl-3.0 |
FilthyPeasantDEV/PokeBot | main.lua | 1 | 4697 | -- OPTIONS
RESET_FOR_TIME = false -- Set to true if you're trying to break the record, not just finish a run
BEAST_MODE = false -- WARNING: Do not engage. Will yolo everything, and reset at every opportunity in the quest for 1:47.
INITIAL_SPEED = 750
AFTER_BROCK_SPEED = 350
RUNS_FILE = "C:/Users/rjrhy/Desktop/Pokebot/Github work/PokeBotBad/wiki/red/runs.txt" -- Use / insted of \ otherwise it will not work
local CUSTOM_SEED = nil -- Set to a known seed to replay it, or leave nil for random runs
local NIDORAN_NAME = "A" -- Set this to the single character to name Nidoran (note, to replay a seed, it MUST match!)
local PAINT_ON = true -- Display contextual information while the bot runs
-- START CODE (hard hats on)
VERSION = "2.4.6"
local Data = require "data.data"
Data.init()
local Battle = require "action.battle"
local Textbox = require "action.textbox"
local Walk = require "action.walk"
local Combat = require "ai.combat"
local Control = require "ai.control"
local Strategies = require("ai."..Data.gameName..".strategies")
local Pokemon = require "storage.pokemon"
local Bridge = require "util.bridge"
local Input = require "util.input"
local Memory = require "util.memory"
local Paint = require "util.paint"
local Utils = require "util.utils"
local Settings = require "util.settings"
local hasAlreadyStartedPlaying = false
local oldSeconds
local running = true
local previousMap
-- HELPERS
function resetAll()
Strategies.softReset()
Combat.reset()
Control.reset()
Walk.reset()
Paint.reset()
Bridge.reset()
Utils.reset()
oldSeconds = 0
running = false
client.speedmode(INITIAL_SPEED)
if CUSTOM_SEED then
Data.run.seed = CUSTOM_SEED
Strategies.replay = true
p("RUNNING WITH A FIXED SEED ("..NIDORAN_NAME.." "..Data.run.seed.."), every run will play out identically!", true)
else
Data.run.seed = os.time()
print("PokeBot v"..VERSION..": "..(BEAST_MODE and "BEAST MODE seed" or "Seed:").." "..Data.run.seed)
end
math.randomseed(Data.run.seed)
end
-- EXECUTE
p("Welcome to PokeBot "..Utils.capitalize(Data.gameName).." v"..VERSION, true)
Control.init()
Utils.init()
STREAMING_MODE = true
if CUSTOM_SEED then
Strategies.reboot()
else
hasAlreadyStartedPlaying = Utils.ingame()
end
Strategies.init(hasAlreadyStartedPlaying)
if hasAlreadyStartedPlaying and RESET_FOR_TIME then
RESET_FOR_TIME = false
p("Disabling time-limit resets as the game is already running. Please reset the emulator and restart the script if you'd like to go for a fast time.", true)
end
if STREAMING_MODE then
if not CUSTOM_SEED or BEAST_MODE then
RESET_FOR_TIME = true
end
Bridge.init(Data.gameName)
else
if PAINT_ON then
Input.setDebug(true)
end
end
-- LOOP
local function generateNextInput(currentMap)
if not Utils.ingame() then
Bridge.pausegametime()
if currentMap == 0 then
if running then
if not hasAlreadyStartedPlaying then
if emu.framecount() ~= 1 then Strategies.reboot() end
hasAlreadyStartedPlaying = true
else
resetAll()
end
else
Settings.startNewAdventure()
end
else
if not running then
Bridge.liveSplit()
running = true
end
Settings.choosePlayerNames()
end
else
Bridge.time()
Utils.splitCheck()
local battleState = Memory.value("game", "battle")
Control.encounter(battleState)
local curr_hp = Combat.hp()
Combat.updateHP(curr_hp)
if curr_hp == 0 and not Control.canDie() and Pokemon.index(0) > 0 then
Strategies.death(currentMap)
elseif Walk.strategy then
if Strategies.execute(Walk.strategy) then
if Walk.traverse(currentMap) == false then
return generateNextInput(currentMap)
end
end
elseif battleState > 0 then
if not Control.shouldCatch() then
Battle.automate()
end
elseif Textbox.handle() then
if Walk.traverse(currentMap) == false then
return generateNextInput(currentMap)
end
end
end
end
while true do
local currentMap = Memory.value("game", "map")
if currentMap ~= previousMap then
Input.clear()
previousMap = currentMap
end
if Strategies.frames then
if Memory.value("game", "battle") == 0 then
Strategies.frames = Strategies.frames + 1
end
Utils.drawText(0, 80, Strategies.frames)
end
if Bridge.polling then
Settings.pollForResponse(NIDORAN_NAME)
end
if not Input.update() then
generateNextInput(currentMap)
end
if STREAMING_MODE then
local newSeconds = Memory.value("time", "seconds")
if newSeconds ~= oldSeconds and (newSeconds > 0 or Memory.value("time", "frames") > 0) then
Bridge.time(Utils.elapsedTime())
oldSeconds = newSeconds
end
elseif PAINT_ON then
Paint.draw(currentMap)
end
Input.advance()
emu.frameadvance()
end
Bridge.close()
| mit |
kidaa/FFXIOrgins | scripts/zones/Dynamis-Qufim/bcnms/dynamis_Qufim.lua | 8 | 1057 | -----------------------------------
-- Area: dynamis_Qufim
-- Name: dynamis_Qufim
-----------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function OnBcnmRegister(player,instance)
SetServerVariable("[DynaQufim]UniqueID",player:getDynamisUniqueID(1288));
SetServerVariable("[DynaQufim]Boss_Trigger",0);
SetServerVariable("[DynaQufim]Already_Received",0);
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function OnBcnmEnter(player,instance)
player:setVar("DynamisID",GetServerVariable("[DynaQufim]UniqueID"));
player:setVar("dynaWaitxDay",os.time());
end;
-- Leaving the Dynamis by every mean possible, given by the LeaveCode
-- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3)
-- 4=Finish he dynamis
function OnBcnmLeave(player,instance,leavecode)
--print("leave code "..leavecode);
if(leavecode == 2 or leavecode == 3 or leavecode == 4) then
player:setPos(18,-19,162,240, 126);
end
if(leavecode == 4) then
SetServerVariable("[DynaQufim]UniqueID",0);
end
end; | gpl-3.0 |
Wedge009/wesnoth | data/campaigns/World_Conquest/lua/game_mechanics/bonus_point_definitions.lua | 7 | 15850 | local _ = wesnoth.textdomain 'wesnoth-wc'
local STR_BONUS_SHIP_NAMES = { _"Point", _"Rest", _"Ruin", _"Rocks", _"Bane", _"Waters", _"Route", _"Vestige", _"Disaster", _"Massacre", _"Expedition", _"Cargo" }
local STR_BONUS_BONES_NAMES = { _"Point", _"Rest", _"Lair", _"Exile", _"Bane", _"Passage", _"Curse" }
local STR_BONUS_BONES_SWAMP_NAMES = { _"Point", _"Rest", _"Lair", _"Exile", _"Bane", _"Death", _"Passage", _"Curse", _"Quagmire" }
local STR_BONUS_DEAD_OAK_NAMES = { _"Rest", _"Point", _"Lair", _"Exile", _"Bane", _"Death", _"Curse", _"Wasteland", _"Desolation", _"Despair", _"Desert", _"Route", _"Passage", _"Cemetery" }
local STR_BONUS_VILLAGE_RUINED_NAMES = { _"Rest", _"Ruin", _"Lair", _"Exile", _"Bane", _"Curse", _"Destruction", _"Desolation", _"Vestige", _"Disaster" }
local STR_BONUS_BURIAL_NAMES = { _"Point", _"Rest", _"Lair", _"Passage", _"Bane", _"Massacre", _"Curse", _"Disaster", _"Cemetery" }
local STR_BONUS_BURIAL_SAND_NAMES = { _"Point", _"Rest", _"Lair", _"Exile", _"Passage", _"Bane", _"Massacre", _"Curse", _"Disaster" }
local STR_BONUS_BURIAL_CAVE_NAMES = { _"Rest", _"Lair", _"Passage", _"Bane", _"Grotto", _"Curse", _"Cave", _"Cemetery", _"Graveyard" }
local STR_BONUS_DETRITUS_NAMES = { _"Point", _"Rest", _"Ruin", _"Lair", _"Exile", _"Passage", _"Bane", _"Massacre", _"Curse", _"Quagmire", _"Bog", _"Hideout", _"Desolation" }
local STR_BONUS_TRAPDOOR_NAMES = { _"Rest", _"Ruin", _"Lair", _"Passage", _"Bane", _"Despair", _"Curse", _"Cave", _"Dungeon", _"Secret", _"Hideout", _"Mine", _"Grotto", _"Den" }
local STR_BONUS_COFFIN_NAMES = { _"Rest", _"Ruin", _"Lair", _"Exile", _"Passage", _"Bane", _"Dream", _"Crypt", _"Grotto", _"Graveyard", _"Secret", _"Curse", _"Mausoleum", _"Ossuary" }
local STR_BONUS_MINE_NAMES = { _"Lair", _"Passage", _"Bane", _"Peak", _"Mine", _"Curse", _"Den", _"Site", _"Quarry", _"Dungeon" }
local STR_BONUS_DOORS_NAMES = { _"Rest", _"Lair", _"Passage", _"Bane", _"Peak", _"Mine", _"Destiny", _"Door", _"Gate", _"Curse", _"Domain", _"Secret", _"Dungeon" }
local STR_BONUS_SHOP_NAMES = { _"Path", _"Road", _"Route", _"Market", _"Fair", _"Festival", _"Tournament", _"Enclave", _"Armory" }
local STR_BONUS_SHOP_GRASS_NAMES = { _"Route", _"Market", _"Enclave", _"Fair", _"Festival", _"Tournament", _"Armory", _"Refuge" }
local STR_BONUS_SIGNPOST_NAMES = { _"Rest", _"Path", _"Point", _"Passage", _"Road", _"Route", _"Domain" }
local STR_BONUS_ROCK_CAIRN_NAMES = { _"Rest", _"Memory", _"Triumph", _"Vestige", _"Point", _"Passage", _"Domain", _"Route", _"Rock" }
local STR_BONUS_ROCK_CAIRN_CAVE_NAMES = { _"Rest", _"Memory", _"Vestige", _"Grotto", _"Passage", _"Domain", _"Secret", _"Curse", _"Rock" }
local STR_BONUS_DOLMEN_NAMES = { _"Rest", _"Memory", _"Triumph", _"Vestige", _"Point", _"Passage", _"Domain", _"Route", _"Ruin", _"Road", _"Path" }
local STR_BONUS_MONOLITH_NAMES = { _"Rest", _"Memory", _"Triumph", _"Vestige", _"Point", _"Path", _"Domain", _"Route", _"Monolith", _"Road" }
local STR_BONUS_OBELISK_NAMES = { _"Rest", _"Memory", _"Triumph", _"Vestige", _"Point", _"Path", _"Domain", _"Route", _"Obelisk", _"Road" }
local STR_BONUS_WELL_GRASS_NAMES = { _"Rest", _"Lair", _"Exile", _"Point", _"Passage", _"Ruin", _"Route", _"Refuge", _"Enclave", _"Domain" }
local STR_BONUS_WELL_ROAD_NAMES = { _"Rest", _"Point", _"Desire", _"Route", _"Passage", _"Refuge", _"Enclave", _"Path", _"Road", _"Market" }
local STR_BONUS_WELL_CAVE_NAMES = { _"Rest", _"Lair", _"Exile", _"Passage", _"Ruin", _"Well", _"Mine", _"Grotto", _"Den", _"Secret" }
local STR_BONUS_WELL_CRYSTAL_NAMES = { _"Bane", _"Lair", _"Curse", _"Passage", _"Grotto", _"Cave", _"Mine", _"Site", _"Quarry", _"Secret" }
local STR_BONUS_MONOLITH_HILLS_NAMES = { _"Rest", _"Point", _"Passage", _"Ruin", _"Lair", _"Exile", _"Plateau", _"Cliff", _"Domain", _"Route", _"Vestige" }
local STR_BONUS_LIGHTHOUSE_NAMES = { _"Port", _"Seaport", _"Harbor", _"Enclave", _"Bay", _"Coast", _"Shore", _"Lighthouse", _"Domain" }
local STR_BONUS_CAMPFIRE_NAMES = { _"Port", _"Seaport", _"Harbor", _"Bay", _"Coast", _"Shore", _"Cliff", _"Domain", _"Signal", _"Beacon", _"Enclave" }
local STR_BONUS_LILIES_NAMES = { _"Point", _"Passage", _"Lair", _"Rest", _"Waters", _"Domain", _"Curse", _"Secret", _"Hideout", _"Bane" }
local STR_BONUS_LILIES_SWAMP_NAMES = { _"Point", _"Passage", _"Rest", _"Lair", _"Exile", _"Domain", _"Curse", _"Secret", _"Hideout", _"Bane", _"Marsh" }
local STR_BONUS_ROCK_SAND_NAMES = { _"Rest", _"Point", _"Passage", _"Ruin", _"Lair", _"Exile", _"Delirium", _"Graveyard", _"Cemetery", _"Ossuary", _"Domain", _"Route", _"Vestige" }
local STR_BONUS_ROCK_NAMES = { _"Rest", _"Point", _"Passage", _"Ruin", _"Lair", _"Exile", _"Domain", _"Route", _"Vestige" }
local STR_BONUS_DOLMEN_GRASS_NAMES = { _"Rest", _"Point", _"Passage", _"Ruin", _"Lair", _"Domain", _"Route", _"Vestige", _"Conclave", _"Graveyard" }
local STR_BONUS_WINDMILL_NAMES = { _"Meadow", _"Prairie", _"Grassland", _"Refuge", _"Windmill", _"Enclave", _"Domain", _"Farm", _"Granary", _"Field", _"Shire" }
local STR_BONUS_TENT_NAMES = { _"Exile", _"Route", _"Enclave", _"Domain", _"Outpost", _"Refuge" }
local STR_BONUS_TENT_FANCY_GRASS_NAMES = { _"Exile", _"Route", _"Enclave", _"Domain", _"Outpost", _"Refuge", _"Festival", _"Fair", _"Tournament" }
local STR_BONUS_TENT_FANCY_ROAD_NAMES = { _"Route", _"Road", _"Path", _"Enclave", _"Domain", _"Outpost", _"Refuge", _"Festival", _"Fair", _"Tournament", _"Market", _"Armory" }
local STR_BONUS_SHELTER_NAMES = { _"Passage", _"Exile", _"Route", _"Refuge", _"Domain", _"Shelter", _"Shelter", _"Quarry", _"Plateau", _"Site", _"Outpost", _"Enclave", _"Passage" }
local STR_BONUS_TENT_OUTPOST_NAMES = { _"Exile", _"Route", _"Refuge", _"Domain", _"Outpost", _"Site", _"Expedition", _"Enclave" }
local STR_BONUS_ALTAR_NAMES = { _"Rest", _"Passage", _"Ruin", _"Lair", _"Oracle", _"Altar", _"Secret", _"Ossuary", _"Conclave", _"Curse", _"Grotto" }
local STR_BONUS_ALTAR_CRYSTAL_NAMES = { _"Passage", _"Lair", _"Curse", _"Domain", _"Bane", _"Cave", _"Secret" }
local STR_BONUS_TEMPLE_NAMES = { _"Rest", _"Ruin", _"Lair", _"Oracle", _"Temple", _"Sanctuary", _"Shrine", _"Conclave", _"Refuge", _"Library", _"Academy", _"School", _"Mausoleum", _"Crypt", _"Memory" }
local STR_BONUS_TEMPLE_ROAD_NAMES = { _"Rest", _"Route", _"Oracle", _"Temple", _"Sanctuary", _"Shrine", _"Refuge", _"Road", _"Library", _"Path", _"Market", _"Academy", _"School", _"Conclave", _"Mausoleum", _"Crypt" }
local STR_BONUS_TEMPLE_GRASS_NAMES = { _"Rest", _"Ruin", _"Oracle", _"Temple", _"Sanctuary", _"Shrine", _"Refuge", _"Library", _"Academy", _"School", _"Conclave", _"Mausoleum", _"Crypt", _"Market" }
local STR_BONUS_TEMPLE_MOUNTAIN_NAMES = { _"Rest", _"Passage", _"Ruin", _"Lair", _"Exile", _"Oracle", _"Temple", _"Sanctuary", _"Shrine", _"Refuge", _"Peak", _"Domain", _"Conclave", _"Mausoleum", _"Crypt", _"Memory" }
local STR_BONUS_TEMPLE_HILLS_NAMES = { _"Rest", _"Passage", _"Ruin", _"Lair", _"Refuge", _"Cliff", _"Domain", _"Route", _"Sanctuary", _"Conclave", _"Temple", _"Shrine", _"Oracle", _"Crypt", _"Mausoleum", _"Route" }
local STR_BONUS_TEMPLE_GREEN_NAMES = { _"Rest", _"Passage", _"Ruin", _"Lair", _"Exile", _"Oracle", _"Domain", _"Curse", _"Bane", _"Vestige", _"Perversion", _"Decay", _"Moor", _"Crypt", _"Mausoleum", _"Ossuary" }
local STR_BONUS_TREE_NAMES = { _"Conclave", _"Enclave", _"Meadow", _"Prairie", _"Field", _"Route", _"Refuge", _"Tree", _"Glade", _"Domain", _"Shire" }
local STR_BONUS_ROCK_TOWER_NAMES = { _"Rest", _"Vestige", _"Lair", _"Domain", _"Tower", _"Ruin", _"Refuge", _"Sanctuary", _"Observatory", _"Observatory", _"Enclave", _"Conclave", _"Crypt" }
local STR_BONUS_ROCK_SWAMP_NAMES = { _"Rest", _"Point", _"Decay", _"Passage", _"Ruin", _"Lair", _"Exile", _"Bog", _"Domain", _"Bane", _"Curse", _"Vestige", _"Secret" }
local STR_BONUS_GENERIC_NAMES = { _"Rest", _"Point", _"Passage", _"Ruin", _"Lair", _"Exile", _"Vestige" }
local strings = {
detritus = STR_BONUS_DETRITUS_NAMES,
detritus2 = STR_BONUS_DETRITUS_NAMES,
lilies = STR_BONUS_LILIES_NAMES,
lilies_s = STR_BONUS_LILIES_SWAMP_NAMES,
oak1 = STR_BONUS_TREE_NAMES,
oak2 = STR_BONUS_TREE_NAMES,
oak3 = STR_BONUS_TREE_NAMES,
oak4 = STR_BONUS_TREE_NAMES,
oak5 = STR_BONUS_TREE_NAMES,
oak6 = STR_BONUS_TREE_NAMES,
oak7 = STR_BONUS_TREE_NAMES,
oak_dead = STR_BONUS_DEAD_OAK_NAMES,
oak_dead2 = STR_BONUS_DEAD_OAK_NAMES,
obelisk = STR_BONUS_OBELISK_NAMES,
rock1 = STR_BONUS_ROCK_SAND_NAMES,
rock3 = STR_BONUS_ROCK_SWAMP_NAMES,
rock4 = STR_BONUS_ROCK_NAMES,
tower_r1 = STR_BONUS_ROCK_TOWER_NAMES,
tower_r4 = STR_BONUS_GENERIC_NAMES,
crystal = STR_BONUS_WELL_CRYSTAL_NAMES,
crystal3 = STR_BONUS_ALTAR_CRYSTAL_NAMES,
ship1 = STR_BONUS_SHIP_NAMES,
ship2 = STR_BONUS_SHIP_NAMES,
bones = STR_BONUS_BONES_NAMES,
bones_s = STR_BONUS_BONES_SWAMP_NAMES,
village = STR_BONUS_VILLAGE_RUINED_NAMES,
burial = STR_BONUS_BURIAL_NAMES,
burial_s = STR_BONUS_BURIAL_SAND_NAMES,
burial_c = STR_BONUS_BURIAL_CAVE_NAMES,
trapdoor = STR_BONUS_TRAPDOOR_NAMES,
coffin = STR_BONUS_COFFIN_NAMES,
mine = STR_BONUS_MINE_NAMES,
doors = STR_BONUS_DOORS_NAMES,
tent1 = STR_BONUS_TENT_NAMES,
shelter = STR_BONUS_SHELTER_NAMES,
tent2 = STR_BONUS_TENT_NAMES,
tent2_g = STR_BONUS_TENT_FANCY_GRASS_NAMES,
tent2_r = STR_BONUS_TENT_FANCY_ROAD_NAMES,
shop = STR_BONUS_SHOP_NAMES,
shop_g = STR_BONUS_SHOP_GRASS_NAMES,
outpost = STR_BONUS_TENT_OUTPOST_NAMES,
signpost = STR_BONUS_SIGNPOST_NAMES,
rock_cairn = STR_BONUS_ROCK_CAIRN_NAMES,
rock_cairn_c = STR_BONUS_ROCK_CAIRN_CAVE_NAMES,
dolmen = STR_BONUS_DOLMEN_NAMES,
monolith1 = STR_BONUS_MONOLITH_HILLS_NAMES,
monolith1_r = STR_BONUS_GENERIC_NAMES,
monolith2 = STR_BONUS_MONOLITH_NAMES,
monolith3 = STR_BONUS_ROCK_NAMES,
dolmen_g = STR_BONUS_DOLMEN_GRASS_NAMES,
monolith4 = STR_BONUS_MONOLITH_HILLS_NAMES,
monolith4_r = STR_BONUS_GENERIC_NAMES,
well_g = STR_BONUS_WELL_GRASS_NAMES,
well_r = STR_BONUS_WELL_ROAD_NAMES,
well = STR_BONUS_WELL_CAVE_NAMES,
lighthouse = STR_BONUS_LIGHTHOUSE_NAMES,
campfire = STR_BONUS_CAMPFIRE_NAMES,
temple = STR_BONUS_TEMPLE_NAMES,
temple2 = STR_BONUS_TEMPLE_ROAD_NAMES,
temple2_g = STR_BONUS_TEMPLE_GRASS_NAMES,
temple3 = STR_BONUS_TEMPLE_MOUNTAIN_NAMES,
temple4 = STR_BONUS_TEMPLE_HILLS_NAMES,
temple_green_h = STR_BONUS_TEMPLE_GREEN_NAMES,
temple_green_h2 = STR_BONUS_TEMPLE_GREEN_NAMES,
temple_green_g = STR_BONUS_TEMPLE_GREEN_NAMES,
temple_green_g2 = STR_BONUS_TEMPLE_GREEN_NAMES,
altar = STR_BONUS_ALTAR_NAMES,
windmill = STR_BONUS_WINDMILL_NAMES
}
local IMG_DETRITUS = "misc/blank-hex.png~BLIT(terrain/misc/detritus/detritusC-3.png~CROP(0,18,66,54),6,13)~BLIT(terrain/misc/detritus/detritusC-2.png~CROP(8,0,35,70),0,2)~BLIT(terrain/misc/detritus/detritusC-2.png~CROP(43,44,29,26),36,46)"
local IMG_DETRITUS_2 = "misc/blank-hex.png~BLIT(terrain/misc/detritus/detritusC-2.png~CROP(0,4,59,68),13,0)~BLIT(terrain/misc/detritus/detritusC-5.png~CROP(17,0,55,63),0,9)"
local IMG_LILIES = "terrain/embellishments/water-lilies-flower-small4.png~BLIT(terrain/embellishments/water-lilies-flower-small5.png~CROP(40,28,17,17),40,28)"
local IMG_LILIES_2 = "misc/blank-hex.png~BLIT(terrain/embellishments/water-lilies-flower5.png~CROP(21,12,72,72))~BLIT(terrain/embellishments/water-lilies-flower-small2.png~CROP(0,8,55,64),17,0)"
local IMG_OAK_1 = "terrain/embellishments/flowers-mixed4.png~MASK(scenery/whirlpool.png)~BLIT(scenery/oak-leaning.png)"
local IMG_OAK_2 = "terrain/embellishments/flowers-mixed3.png~MASK(scenery/whirlpool.png)~BLIT(scenery/oak-leaning.png)"
-- custom image
local IMG_OAK_3 = "scenery/treehouse.png"
-- custom image
local IMG_OAK_4 = "scenery/treehouse.png"
local IMG_OAK_5 = "terrain/embellishments/flower-purple.png~MASK(scenery/whirlpool.png)~BLIT(scenery/oak-leaning.png)"
-- custom image
local IMG_OAK_6 = "scenery/treehouse.png"
-- custom image
local IMG_OAK_7 = "scenery/treehouse.png"
local IMG_ROCK_1 = "misc/blank-hex.png~BLIT(scenery/rock1.png~CROP(1,11,71,61),0,0)"
local IMG_ROCK_3 = "misc/blank-hex.png~BLIT(scenery/rock3.png~CROP(0,11,66,61),6,0)"
local IMG_ROCK_4 = "misc/blank-hex.png~BLIT(scenery/rock4.png~CROP(0,8,66,64),6,0)"
-- custom image
local IMG_ROCK_1_TOWER = "misc/blank-hex.png~BLIT(scenery/wct-tower.png)"
-- custom image
local IMG_ROCK_4_TOWER = "misc/blank-hex.png~BLIT(scenery/wct-tower.png)"
-- custom image
local IMG_OBELISK_POST = "misc/blank-hex.png~BLIT(scenery/wct-obelisk.png)"
-- custom image
local IMG_ROCK_CAIRN_DOLMEN = "misc/blank-hex.png~BLIT(scenery/wct-dolmen.png~SCALE(75,75)~CROP(0,0,72,62),0,10)"
-- custom image
local IMG_MONOLITH_DOLMEN = "misc/blank-hex.png~BLIT(scenery/wct-dolmen2.png~SCALE(75,75)~CROP(0,0,72,62),0,10)"
-- custom image
local IMG_TEMPLE_2 = "misc/blank-hex.png~BLIT(scenery/wct-temple.png~SCALE(60,60),6,3)"
-- custom image
local IMG_TEMPLE_3 = "scenery/wct-temple2.png"
-- custom image
local IMG_TEMPLE_GREEN_HILLS = "misc/blank-hex.png~BLIT(scenery/wct-temple4.png~SCALE(65,65),4,4)"
-- custom image
local IMG_TEMPLE_GREEN_HILLS_2 = "misc/blank-hex.png~BLIT(scenery/wct-temple5.png~SCALE(63,63),6,2)"
-- custom image
local IMG_TEMPLE_GREEN_GRASS = "misc/blank-hex.png~BLIT(scenery/wct-temple3.png)"
-- custom image
local IMG_TEMPLE_GREEN_GRASS_2 = "misc/blank-hex.png~BLIT(scenery/wct-temple5.png~SCALE(63,63),6,2)"
-- custom image
local IMG_DETRITUS_OAK_1 = "scenery/wct-oak-dead.png"
-- custom image
local IMG_DETRITUS_OAK_2 = "scenery/wct-oak-dead2.png"
-- custom image
local IMG_CRYSTAL_WELL = "scenery/wct-crystal.png"
-- custom image
local IMG_CRYSTALS_ALTAR = "misc/blank-hex.png~BLIT(scenery/wct-crystal3.png~SCALE(59,59),6,4)"
-- custom image
local IMG_TENT_OUTPOST = "scenery/wct-outpost.png"
local images = {
rock1 = IMG_ROCK_1,
rock3 = IMG_ROCK_3,
rock4 = IMG_ROCK_4,
tower_r1 = IMG_ROCK_1_TOWER,
tower_r4 = IMG_ROCK_4_TOWER,
lilies = IMG_LILIES,
lilies_s = IMG_LILIES_2,
detritus = IMG_DETRITUS,
detritus2 = IMG_DETRITUS_2,
oak1 = IMG_OAK_1,
oak2 = IMG_OAK_2,
oak3 = IMG_OAK_3,
oak4 = IMG_OAK_4,
oak5 = IMG_OAK_5,
oak6 = IMG_OAK_6,
oak7 = IMG_OAK_7,
obelisk = IMG_OBELISK_POST,
dolmen = IMG_ROCK_CAIRN_DOLMEN,
dolmen_g = IMG_MONOLITH_DOLMEN,
oak_dead = IMG_DETRITUS_OAK_1,
oak_dead2 = IMG_DETRITUS_OAK_2,
crystal = IMG_CRYSTAL_WELL,
crystal3 = IMG_CRYSTALS_ALTAR,
outpost = IMG_TENT_OUTPOST,
ship1 = "scenery/shipwreck-1.png",
ship2 = "scenery/wreck.png",
bones = "items/bones.png",
bones_s = "items/bones.png",
village = "scenery/village-human-burned2.png",
burial = "items/burial.png",
burial_s = "items/burial.png",
burial_c = "items/burial.png",
trapdoor = "scenery/trapdoor-open.png",
coffin = "items/coffin-closed.png",
mine = "scenery/mine-abandoned.png",
doors = "scenery/dwarven-doors-closed.png",
tent1 = "scenery/tent-ruin-1.png",
shelter = "scenery/tent-ruin-1.png",
tent2 = "scenery/tent-fancy-red.png",
tent2_g = "scenery/tent-fancy-red.png",
tent2_r = "scenery/tent-fancy-red.png",
shop = "scenery/tent-shop-weapons.png",
shop_g = "scenery/tent-shop-weapons.png",
signpost = "scenery/signpost.png",
rock_cairn = "scenery/rock-cairn.png",
rock_cairn_c = "scenery/rock-cairn.png",
monolith1 = "scenery/monolith1.png",
monolith1_r = "scenery/monolith1.png",
monolith2 = "scenery/monolith2.png",
monolith3 = "scenery/monolith3.png",
monolith4 = "scenery/monolith4.png",
monolith4_r = "scenery/monolith4.png",
well_g = "scenery/well.png",
well_r = "scenery/well.png",
well = "scenery/well.png",
lighthouse = "scenery/lighthouse.png",
temple = "scenery/temple1.png",
temple2 = IMG_TEMPLE_2,
temple2_g = IMG_TEMPLE_2,
temple3 = IMG_TEMPLE_2,
temple4 = IMG_TEMPLE_3,
temple_green_h = IMG_TEMPLE_GREEN_HILLS,
temple_green_h2 = IMG_TEMPLE_GREEN_HILLS_2,
temple_green_g = IMG_TEMPLE_GREEN_GRASS,
temple_green_g2 = IMG_TEMPLE_GREEN_GRASS_2,
altar = "items/altar.png",
}
return strings, images
| gpl-2.0 |
Wedge009/wesnoth | data/lua/wml/modify_side.lua | 7 | 2993 | local utils = wesnoth.require "wml-utils"
local T = wml.tag
local side_changes_needing_redraw = {
'shroud', 'fog', 'reset_map', 'reset_view', 'shroud_data',
'share_vision', 'share_maps', 'share_view',
'color', 'flag',
}
function wesnoth.wml_actions.modify_side(cfg)
local sides = utils.get_sides(cfg)
for i,side in ipairs(sides) do
if cfg.team_name then
side.team_name = cfg.team_name
end
if cfg.user_team_name then
side.user_team_name = cfg.user_team_name
end
if cfg.side_name then
side.side_name = cfg.side_name
end
if cfg.controller then
side.controller = cfg.controller
end
if cfg.defeat_condition then
side.defeat_condition = cfg.defeat_condition
end
if cfg.recruit then
side.recruit = cfg.recruit:split()
end
if cfg.village_support then
side.village_support = cfg.village_support
end
if cfg.village_gold then
side.village_gold = cfg.village_gold
end
if cfg.income then
side.base_income = cfg.income + wesnoth.game_config.base_income
end
if cfg.gold then
side.gold = cfg.gold
end
if cfg.hidden ~= nil then
side.hidden = cfg.hidden
end
if cfg.color or cfg.flag then
side:set_id(cfg.flag, cfg.color)
end
if cfg.flag_icon then
side.flag_icon = cfg.flag_icon
end
if cfg.suppress_end_turn_confirmation ~= nil then
side.suppress_end_turn_confirmation = cfg.suppress_end_turn_confirmation
end
if cfg.scroll_to_leader ~= nil then
side.scroll_to_leader = cfg.scroll_to_leader
end
if cfg.shroud ~= nil then
side.shroud = cfg.shroud
end
if cfg.reset_maps then
side:override_shroud({})
end
if cfg.fog ~= nil then
side.fog = cfg.fog
end
if cfg.reset_view then
side:place_fog({}, true)
end
if cfg.shroud_data then
side.shroud_data = cfg.shroud_data
end
if cfg.share_vision then
side.share_vision = cfg.share_vision
end
-- Legacy support
if cfg.share_view ~= nil or cfg.share_maps ~= nil then
if cfg.share_view then
side.share_vision = 'all'
elseif cfg.share_maps then
side.share_vision = 'shroud'
else
side.share_vision = 'none'
end
end
local ai, replace_ai = {}, false
for k, v in ipairs(cfg) do
local tag, content = v[1], v[2]
if tag == "ai" then
table.insert(ai, T.ai(content))
if content.ai_algorithm then
replace_ai = true
end
elseif tag == "set_variable" then
wesnoth.wml_actions.set_variable(v[2], side.variables)
elseif tag == "clear_variable" then
wesnoth.wml_actions.clear_variable(cfg, side.variables)
elseif tag == "variables" then
side.variables.__cfg = wml.merge(side.variables.__cfg, content, cfg.var_merge_mode or "replace")
end
end
if cfg.switch_ai then
side:switch_ai(cfg.switch_ai)
end
if #ai > 0 then
if replace_ai then
side:switch_ai(ai)
else
side:append_ai(ai)
end
end
end
for i,key in ipairs(side_changes_needing_redraw) do
if cfg[key] ~= nil then
wesnoth.wml_actions.redraw{}
return
end
end
end
| gpl-2.0 |
frutjus/OpenRA | mods/cnc/maps/gdi05b/gdi05b.lua | 19 | 5853 | AllToHuntTrigger =
{
Silo1, Proc1, Silo2, Silo3, Silo4, Afld1, Hand1, Nuke1, Nuke2, Nuke3, Fact1
}
AtkRoute1 = { waypoint4.Location, waypoint5.Location, waypoint6.Location, waypoint7.Location, waypoint8.Location }
AtkRoute2 = { waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location }
AutoCreateTeams =
{
{ { ['e1'] = 1, ['e3'] = 3 }, AtkRoute2 },
{ { ['e1'] = 3, ['e3'] = 1 }, AtkRoute2 },
{ { ['e3'] = 4 } , AtkRoute1 },
{ { ['e1'] = 4 } , AtkRoute1 },
{ { ['bggy'] = 1 } , AtkRoute1 },
{ { ['bggy'] = 1 } , AtkRoute2 },
{ { ['ltnk'] = 1 } , AtkRoute1 },
{ { ['ltnk'] = 1 } , AtkRoute2 }
}
RepairThreshold = 0.6
Atk1Delay = DateTime.Seconds(40)
Atk2Delay = DateTime.Seconds(60)
Atk3Delay = DateTime.Seconds(70)
Atk4Delay = DateTime.Seconds(90)
AutoAtkStartDelay = DateTime.Seconds(115)
AutoAtkMinDelay = DateTime.Seconds(45)
AutoAtkMaxDelay = DateTime.Seconds(90)
Atk5CellTriggers =
{
CPos.New(17,55), CPos.New(16,55), CPos.New(15,55), CPos.New(50,54), CPos.New(49,54),
CPos.New(48,54), CPos.New(16,54), CPos.New(15,54), CPos.New(14,54), CPos.New(50,53),
CPos.New(49,53), CPos.New(48,53), CPos.New(50,52), CPos.New(49,52)
}
GdiBase = { GdiNuke1, GdiProc1, GdiWeap1, GdiNuke2, GdiPyle1, GdiSilo1, GdiSilo2, GdiHarv }
GdiUnits = { "e2", "e2", "e2", "e2", "e1", "e1", "e1", "e1", "mtnk", "mtnk", "jeep", "jeep", "apc" }
NodSams = { Sam1, Sam2, Sam3, Sam4 }
AllToHunt = function()
local list = nod.GetGroundAttackers()
Utils.Do(list, function(unit)
unit.Hunt()
end)
end
MoveThenHunt = function(actors, path)
Utils.Do(actors, function(actor)
actor.Patrol(path, false)
IdleHunt(actor)
end)
end
AutoCreateTeam = function()
local team = Utils.Random(AutoCreateTeams)
for type, count in pairs(team[1]) do
MoveThenHunt(Utils.Take(count, nod.GetActorsByType(type)), team[2])
end
Trigger.AfterDelay(Utils.RandomInteger(AutoAtkMinDelay, AutoAtkMaxDelay), AutoCreateTeam)
end
DiscoverGdiBase = function(actor, discoverer)
if baseDiscovered or not discoverer == gdi then
return
end
Utils.Do(GdiBase, function(actor)
actor.Owner = gdi
end)
GdiHarv.FindResources()
baseDiscovered = true
gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area.")
gdi.MarkCompletedObjective(gdiObjective1)
end
Atk1TriggerFunction = function()
MoveThenHunt(Utils.Take(2, nod.GetActorsByType('e1')), AtkRoute1)
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e3')), AtkRoute1)
end
Atk2TriggerFunction = function()
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e1')), AtkRoute2)
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e3')), AtkRoute2)
end
Atk3TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('bggy')), AtkRoute1)
end
Atk4TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('bggy')), AtkRoute2)
end
Atk5TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('ltnk')), AtkRoute2)
end
StartProduction = function(type)
if Hand1.IsInWorld and Hand1.Owner == nod then
Hand1.Build(type)
Trigger.AfterDelay(DateTime.Seconds(30), function() StartProduction(type) end)
end
end
InsertGdiUnits = function()
Media.PlaySpeechNotification(gdi, "Reinforce")
Reinforcements.Reinforce(gdi, GdiUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
WorldLoaded = function()
gdi = Player.GetPlayer("GDI")
gdiBase = Player.GetPlayer("AbandonedBase")
nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(gdi, function()
Media.PlaySpeechNotification(gdi, "Win")
end)
Trigger.OnPlayerLost(gdi, function()
Media.PlaySpeechNotification(gdi, "Lose")
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == nod and building.Health < RepairThreshold * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base.")
gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support.")
nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops.")
Trigger.AfterDelay(Atk1Delay, Atk1TriggerFunction)
Trigger.AfterDelay(Atk2Delay, Atk2TriggerFunction)
Trigger.AfterDelay(Atk3Delay, Atk3TriggerFunction)
Trigger.AfterDelay(Atk4Delay, Atk4TriggerFunction)
Trigger.OnEnteredFootprint(Atk5CellTriggers, function(a, id)
if a.Owner == gdi then
Atk5TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(AutoAtkStartDelay, AutoCreateTeam)
Trigger.OnAllRemovedFromWorld(AllToHuntTrigger, AllToHunt)
Trigger.AfterDelay(DateTime.Seconds(40), function() StartProduction({ "e1" }) end)
Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase)
Trigger.OnAllKilled(NodSams, function()
gdi.MarkCompletedObjective(gdiObjective2)
Actor.Create("airstrike.proxy", true, { Owner = gdi })
end)
Camera.Position = UnitsRally.CenterPosition
InsertGdiUnits()
end
Tick = function()
if gdi.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
nod.MarkCompletedObjective(nodObjective)
end
end
if baseDiscovered and nod.HasNoRequiredUnits() then
gdi.MarkCompletedObjective(gdiObjective3)
end
end
| gpl-3.0 |
pquentin/wesnoth | data/lua/backwards-compatibility.lua | 22 | 1644 | --! #textdomain wesnoth
-- This file may provide an implementation of Lua functions removed from the engine.
local helper = wesnoth.require "lua/helper.lua"
local get_side = function(i)
return wesnoth.sides[i]
end
wesnoth.get_side = helper.deprecate("wesnoth.get_side is deprecated, use wesnoth.sides instead", get_side)
local get_side_count = function()
return #wesnoth.sides
end
wesnoth.get_side_count = helper.deprecate("wesnoth.get_side_count is deprecated, use #wesnoth.sides instead", get_side_count)
local get_unit_type_ids = function()
local t = {}
for k,v in pairs(wesnoth.unit_types) do
table.insert(t, k)
end
table.sort(t)
return t
end
wesnoth.get_unit_type_ids = helper.deprecate("wesnoth.get_unit_type_ids is deprecated, use wesnoth.unit_types instead", get_unit_type_ids)
local get_unit_type = function(t)
return wesnoth.unit_types[t]
end
wesnoth.get_unit_type = helper.deprecate("wesnoth.get_unit_type is deprecated, use wesnoth.unit_types instead", get_unit_type)
local register_wml_action = function(name, handler)
local old = wesnoth.wml_actions[name]
wesnoth.wml_actions[name] = handler
return old
end
wesnoth.register_wml_action = helper.deprecate("wesnoth.register_wml_action is deprecated, use wesnoth.wml_actions instead", register_wml_action)
-- Calling wesnoth.fire isn't the same as calling wesnoth.wml_actions[name] due to the passed vconfig userdata
-- which also provides "constness" of the passed wml object from the point of view of the caller.
-- So please don't remove since it's not deprecated.
function wesnoth.fire(name, cfg)
wesnoth.wml_actions[name](wesnoth.tovconfig(cfg or {}))
end
| gpl-2.0 |
kidaa/FFXIOrgins | scripts/globals/items/clump_of_beaugreens.lua | 1 | 1166 | -----------------------------------------
-- ID: 4571
-- Item: clump_of_beaugreens
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility 2
-- Vitality -4
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4571);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 2);
target:addMod(MOD_VIT, -4);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 2);
target:delMod(MOD_VIT, -4);
end;
| gpl-3.0 |
paintdream/DontStarveLuaJIT | src/luajit/src/host/genminilua.lua | 9 | 11962 | ----------------------------------------------------------------------------
-- Lua script to generate a customized, minified version of Lua.
-- The resulting 'minilua' is used for the build process of LuaJIT.
----------------------------------------------------------------------------
-- Copyright (C) 2005-2016 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
local sub, match, gsub = string.sub, string.match, string.gsub
local LUA_VERSION = "5.1.5"
local LUA_SOURCE
local function usage()
io.stderr:write("Usage: ", arg and arg[0] or "genminilua",
" lua-", LUA_VERSION, "-source-dir\n")
os.exit(1)
end
local function find_sources()
LUA_SOURCE = arg and arg[1]
if not LUA_SOURCE then usage() end
if sub(LUA_SOURCE, -1) ~= "/" then LUA_SOURCE = LUA_SOURCE.."/" end
local fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then
LUA_SOURCE = LUA_SOURCE.."src/"
fp = io.open(LUA_SOURCE .. "lua.h")
if not fp then usage() end
end
local all = fp:read("*a")
fp:close()
if not match(all, 'LUA_RELEASE%s*"Lua '..LUA_VERSION..'"') then
io.stderr:write("Error: version mismatch\n")
usage()
end
end
local LUA_FILES = {
"lmem.c", "lobject.c", "ltm.c", "lfunc.c", "ldo.c", "lstring.c", "ltable.c",
"lgc.c", "lstate.c", "ldebug.c", "lzio.c", "lopcodes.c",
"llex.c", "lcode.c", "lparser.c", "lvm.c", "lapi.c", "lauxlib.c",
"lbaselib.c", "ltablib.c", "liolib.c", "loslib.c", "lstrlib.c", "linit.c",
}
local REMOVE_LIB = {}
gsub([[
collectgarbage dofile gcinfo getfenv getmetatable load print rawequal rawset
select tostring xpcall
foreach foreachi getn maxn setn
popen tmpfile seek setvbuf __tostring
clock date difftime execute getenv rename setlocale time tmpname
dump gfind len reverse
LUA_LOADLIBNAME LUA_MATHLIBNAME LUA_DBLIBNAME
]], "%S+", function(name)
REMOVE_LIB[name] = true
end)
local REMOVE_EXTINC = { ["<assert.h>"] = true, ["<locale.h>"] = true, }
local CUSTOM_MAIN = [[
typedef unsigned int UB;
static UB barg(lua_State *L,int idx){
union{lua_Number n;U64 b;}bn;
bn.n=lua_tonumber(L,idx)+6755399441055744.0;
if (bn.n==0.0&&!lua_isnumber(L,idx))luaL_typerror(L,idx,"number");
return(UB)bn.b;
}
#define BRET(b) lua_pushnumber(L,(lua_Number)(int)(b));return 1;
static int tobit(lua_State *L){
BRET(barg(L,1))}
static int bnot(lua_State *L){
BRET(~barg(L,1))}
static int band(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b&=barg(L,i);BRET(b)}
static int bor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b|=barg(L,i);BRET(b)}
static int bxor(lua_State *L){
int i;UB b=barg(L,1);for(i=lua_gettop(L);i>1;i--)b^=barg(L,i);BRET(b)}
static int lshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b<<n)}
static int rshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET(b>>n)}
static int arshift(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((int)b>>n)}
static int rol(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b<<n)|(b>>(32-n)))}
static int ror(lua_State *L){
UB b=barg(L,1),n=barg(L,2)&31;BRET((b>>n)|(b<<(32-n)))}
static int bswap(lua_State *L){
UB b=barg(L,1);b=(b>>24)|((b>>8)&0xff00)|((b&0xff00)<<8)|(b<<24);BRET(b)}
static int tohex(lua_State *L){
UB b=barg(L,1);
int n=lua_isnone(L,2)?8:(int)barg(L,2);
const char *hexdigits="0123456789abcdef";
char buf[8];
int i;
if(n<0){n=-n;hexdigits="0123456789ABCDEF";}
if(n>8)n=8;
for(i=(int)n;--i>=0;){buf[i]=hexdigits[b&15];b>>=4;}
lua_pushlstring(L,buf,(size_t)n);
return 1;
}
static const struct luaL_Reg bitlib[] = {
{"tobit",tobit},
{"bnot",bnot},
{"band",band},
{"bor",bor},
{"bxor",bxor},
{"lshift",lshift},
{"rshift",rshift},
{"arshift",arshift},
{"rol",rol},
{"ror",ror},
{"bswap",bswap},
{"tohex",tohex},
{NULL,NULL}
};
int main(int argc, char **argv){
lua_State *L = luaL_newstate();
int i;
luaL_openlibs(L);
luaL_register(L, "bit", bitlib);
if (argc < 2) return sizeof(void *);
lua_createtable(L, 0, 1);
lua_pushstring(L, argv[1]);
lua_rawseti(L, -2, 0);
lua_setglobal(L, "arg");
if (luaL_loadfile(L, argv[1]))
goto err;
for (i = 2; i < argc; i++)
lua_pushstring(L, argv[i]);
if (lua_pcall(L, argc - 2, 0, 0)) {
err:
fprintf(stderr, "Error: %s\n", lua_tostring(L, -1));
return 1;
}
lua_close(L);
return 0;
}
]]
local function read_sources()
local t = {}
for i, name in ipairs(LUA_FILES) do
local fp = assert(io.open(LUA_SOURCE..name, "r"))
t[i] = fp:read("*a")
assert(fp:close())
end
t[#t+1] = CUSTOM_MAIN
return table.concat(t)
end
local includes = {}
local function merge_includes(src)
return gsub(src, '#include%s*"([^"]*)"%s*\n', function(name)
if includes[name] then return "" end
includes[name] = true
local fp = assert(io.open(LUA_SOURCE..name, "r"))
local src = fp:read("*a")
assert(fp:close())
src = gsub(src, "#ifndef%s+%w+_h\n#define%s+%w+_h\n", "")
src = gsub(src, "#endif%s*$", "")
return merge_includes(src)
end)
end
local function get_license(src)
return match(src, "/%*+\n%* Copyright %(.-%*/\n")
end
local function fold_lines(src)
return gsub(src, "\\\n", " ")
end
local strings = {}
local function save_str(str)
local n = #strings+1
strings[n] = str
return "\1"..n.."\2"
end
local function save_strings(src)
src = gsub(src, '"[^"\n]*"', save_str)
return gsub(src, "'[^'\n]*'", save_str)
end
local function restore_strings(src)
return gsub(src, "\1(%d+)\2", function(numstr)
return strings[tonumber(numstr)]
end)
end
local function def_istrue(def)
return def == "INT_MAX > 2147483640L" or
def == "LUAI_BITSINT >= 32" or
def == "SIZE_Bx < LUAI_BITSINT-1" or
def == "cast" or
def == "defined(LUA_CORE)" or
def == "MINSTRTABSIZE" or
def == "LUA_MINBUFFER" or
def == "HARDSTACKTESTS" or
def == "UNUSED"
end
local head, defs = {[[
#ifdef _MSC_VER
typedef unsigned __int64 U64;
#else
typedef unsigned long long U64;
#endif
int _CRT_glob = 0;
]]}, {}
local function preprocess(src)
local t = { match(src, "^(.-)#") }
local lvl, on, oldon = 0, true, {}
for pp, def, txt in string.gmatch(src, "#(%w+) *([^\n]*)\n([^#]*)") do
if pp == "if" or pp == "ifdef" or pp == "ifndef" then
lvl = lvl + 1
oldon[lvl] = on
on = def_istrue(def)
elseif pp == "else" then
if oldon[lvl] then
if on == false then on = true else on = false end
end
elseif pp == "elif" then
if oldon[lvl] then
on = def_istrue(def)
end
elseif pp == "endif" then
on = oldon[lvl]
lvl = lvl - 1
elseif on then
if pp == "include" then
if not head[def] and not REMOVE_EXTINC[def] then
head[def] = true
head[#head+1] = "#include "..def.."\n"
end
elseif pp == "define" then
local k, sp, v = match(def, "([%w_]+)(%s*)(.*)")
if k and not (sp == "" and sub(v, 1, 1) == "(") then
defs[k] = gsub(v, "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
else
t[#t+1] = "#define "..def.."\n"
end
elseif pp ~= "undef" then
error("unexpected directive: "..pp.." "..def)
end
end
if on then t[#t+1] = txt end
end
return gsub(table.concat(t), "%a[%w_]*", function(tok)
return defs[tok] or tok
end)
end
local function merge_header(src, license)
local hdr = string.format([[
/* This is a heavily customized and minimized copy of Lua %s. */
/* It's only used to build LuaJIT. It does NOT have all standard functions! */
]], LUA_VERSION)
return hdr..license..table.concat(head)..src
end
local function strip_unused1(src)
return gsub(src, '( {"?([%w_]+)"?,%s+%a[%w_]*},\n)', function(line, func)
return REMOVE_LIB[func] and "" or line
end)
end
local function strip_unused2(src)
return gsub(src, "Symbolic Execution.-}=", "")
end
local function strip_unused3(src)
src = gsub(src, "extern", "static")
src = gsub(src, "\nstatic([^\n]-)%(([^)]*)%)%(", "\nstatic%1 %2(")
src = gsub(src, "#define lua_assert[^\n]*\n", "")
src = gsub(src, "lua_assert%b();?", "")
src = gsub(src, "default:\n}", "default:;\n}")
src = gsub(src, "lua_lock%b();", "")
src = gsub(src, "lua_unlock%b();", "")
src = gsub(src, "luai_threadyield%b();", "")
src = gsub(src, "luai_userstateopen%b();", "{}")
src = gsub(src, "luai_userstate%w+%b();", "")
src = gsub(src, "%(%(c==.*luaY_parser%)", "luaY_parser")
src = gsub(src, "trydecpoint%(ls,seminfo%)",
"luaX_lexerror(ls,\"malformed number\",TK_NUMBER)")
src = gsub(src, "int c=luaZ_lookahead%b();", "")
src = gsub(src, "luaL_register%(L,[^,]*,co_funcs%);\nreturn 2;",
"return 1;")
src = gsub(src, "getfuncname%b():", "NULL:")
src = gsub(src, "getobjname%b():", "NULL:")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)\n[^\n]*\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*%)%b{}\n", "")
src = gsub(src, "if%([^\n]*hookmask[^\n]*&&\n[^\n]*%b{}\n", "")
src = gsub(src, "(twoto%b()%()", "%1(size_t)")
src = gsub(src, "i<sizenode", "i<(int)sizenode")
return gsub(src, "\n\n+", "\n")
end
local function strip_comments(src)
return gsub(src, "/%*.-%*/", " ")
end
local function strip_whitespace(src)
src = gsub(src, "^%s+", "")
src = gsub(src, "%s*\n%s*", "\n")
src = gsub(src, "[ \t]+", " ")
src = gsub(src, "(%W) ", "%1")
return gsub(src, " (%W)", "%1")
end
local function rename_tokens1(src)
src = gsub(src, "getline", "getline_")
src = gsub(src, "struct ([%w_]+)", "ZX%1")
return gsub(src, "union ([%w_]+)", "ZY%1")
end
local function rename_tokens2(src)
src = gsub(src, "ZX([%w_]+)", "struct %1")
return gsub(src, "ZY([%w_]+)", "union %1")
end
local function func_gather(src)
local nodes, list = {}, {}
local pos, len = 1, #src
while pos < len do
local d, w = match(src, "^(#define ([%w_]+)[^\n]*\n)", pos)
if d then
local n = #list+1
list[n] = d
nodes[w] = n
else
local s
d, w, s = match(src, "^(([%w_]+)[^\n]*([{;])\n)", pos)
if not d then
d, w, s = match(src, "^(([%w_]+)[^(]*%b()([{;])\n)", pos)
if not d then d = match(src, "^[^\n]*\n", pos) end
end
if s == "{" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
if sub(d, -2) == "{\n" then
d = d..sub(match(src, "^%b{}[^;\n]*;?\n", pos+#d-2), 3)
end
end
local k, v = nil, d
if w == "typedef" then
if match(d, "^typedef enum") then
head[#head+1] = d
else
k = match(d, "([%w_]+);\n$")
if not k then k = match(d, "^.-%(.-([%w_]+)%)%(") end
end
elseif w == "enum" then
head[#head+1] = v
elseif w ~= nil then
k = match(d, "^[^\n]-([%w_]+)[(%[=]")
if k then
if w ~= "static" and k ~= "main" then v = "static "..d end
else
k = w
end
end
if w and k then
local o = nodes[k]
if o then nodes["*"..k] = o end
local n = #list+1
list[n] = v
nodes[k] = n
end
end
pos = pos + #d
end
return nodes, list
end
local function func_visit(nodes, list, used, n)
local i = nodes[n]
for m in string.gmatch(list[i], "[%w_]+") do
if nodes[m] then
local j = used[m]
if not j then
used[m] = i
func_visit(nodes, list, used, m)
elseif i < j then
used[m] = i
end
end
end
end
local function func_collect(src)
local nodes, list = func_gather(src)
local used = {}
func_visit(nodes, list, used, "main")
for n,i in pairs(nodes) do
local j = used[n]
if j and j < i then used["*"..n] = j end
end
for n,i in pairs(nodes) do
if not used[n] then list[i] = "" end
end
return table.concat(list)
end
find_sources()
local src = read_sources()
src = merge_includes(src)
local license = get_license(src)
src = fold_lines(src)
src = strip_unused1(src)
src = save_strings(src)
src = strip_unused2(src)
src = strip_comments(src)
src = preprocess(src)
src = strip_whitespace(src)
src = strip_unused3(src)
src = rename_tokens1(src)
src = func_collect(src)
src = rename_tokens2(src)
src = restore_strings(src)
src = merge_header(src, license)
io.write(src)
| mit |
kidaa/FFXIOrgins | scripts/zones/RuLude_Gardens/npcs/Magian_Moogle_Blue.lua | 48 | 1855 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Magian Moogle (Blue Bobble)
-- Type: Magian Trials NPC (Relic Armor)
-- @pos -6.843 2.459 121.9 64
-----------------------------------
package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil;
package.loaded["scripts/globals/magiantrials"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/RuLude_Gardens/TextIDs");
require("scripts/globals/magiantrials");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (trade:getItemCount() == 1) then
local ItemID = trade:getItem();
local TrialInfo = getRelicTrialInfo(ItemID);
local invalid = 0;
if (TrialInfo.t1 == 0 and TrialInfo.t2 == 0 and TrialInfo.t3 == 0 and TrialInfo.t4 == 0) then
invalid = 1;
end
player:startEvent(10143, TrialInfo.t1, TrialInfo.t2, TrialInfo.t3, TrialInfo.t4, 0, ItemID, 0, invalid);
else
-- placeholder for multi item trades such as "Forgotten Hope" etc.
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:hasKeyItem(MAGIAN_TRIAL_LOG) == false) then
player:startEvent(10141);
else
player:startEvent(10142); -- parameters unknown
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 |
UB12/mr690 | plugins/ingroup.lua | 24 | 53144 | do
-- Check Member
local function check_member_autorealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'به ریلیم جدید ما خوش آمدید')
end
end
end
local function check_member_realm_add(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Realm',
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = {}
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'ریلیم اضافه شد!')
end
end
end
function check_member_group(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
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.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'شما صاحب گروه شدید')
end
end
end
local function check_member_modadd(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration
data[tostring(msg.to.id)] = {
group_type = 'Group',
moderators = {},
set_owner = member_id ,
settings = {
set_name = string.gsub(msg.to.print_name, '_', ' '),
lock_name = 'yes',
lock_photo = 'no',
lock_member = 'no',
flood = 'yes',
lock_link = 'yes',
sticker = 'ok',
version = '3.5',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_arabic = 'no',
welcome = 'group'
}
}
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.to.id)] = msg.to.id
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'گروه اضافه شد و شما صاحب آن شدید')
end
end
end
local function automodadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg})
end
end
local function autorealmadd(msg)
local data = load_data(_config.moderation.data)
if msg.action.type == 'chat_created' then
receiver = get_receiver(msg)
chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg})
end
end
local function check_member_realmrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Realm configuration removal
data[tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
local realms = 'realms'
if not data[tostring(realms)] then
data[tostring(realms)] = nil
save_data(_config.moderation.data, data)
end
data[tostring(realms)][tostring(msg.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'ریلیم حذف شد')
end
end
end
local function check_member_modrem(cb_extra, success, result)
local receiver = cb_extra.receiver
local data = cb_extra.data
local msg = cb_extra.msg
for k,v in pairs(result.members) do
local member_id = v.id
if member_id ~= our_id then
-- Group configuration removal
data[tostring(msg.to.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.to.id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, 'گروه حذف شد')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local bots_protection = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
local leave_ban = "no"
if data[tostring(msg.to.id)]['settings']['leave_ban'] then
leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
end
local lock_link = "Yes"
if data[tostring(msg.to.id)]['settings']['lock_link'] then
lock_link = data[tostring(msg.to.id)]['settings']['lock_link']
end
local sticker = "ok"
if data[tostring(msg.to.id)]['settings']['sticker'] then
sticker = data[tostring(msg.to.id)]['settings']['sticker']
end
local tag = "no"
if data[tostring(msg.to.id)]['settings']['tag'] then
tag = data[tostring(msg.to.id)]['settings']['tag']
end
local lock_badw = "no"
if data[tostring(msg.to.id)]['settings']['lock_badw'] then
lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw']
end
local lock_english = "no"
if data[tostring(msg.to.id)]['settings']['lock_english'] then
lock_username = data[tostring(msg.to.id)]['settings']['lock_english']
end
local lock_arabic = "no"
if data[tostring(msg.to.id)]['settings']['lock_arabic'] then
lock_arabic = data[tostring(msg.to.id)]['settings']['lock_arabic']
end
local welcome = "group"
if data[tostring(msg.to.id)]['settings']['welcome'] then
welcome = data[tostring(msg.to.id)]['settings']['welcome']
end
local settings = data[tostring(target)]['settings']
local text = "تنظیمات گروه:\n⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙⚙\n>قفل نام گروه : "..settings.lock_name.."\n>قفل عکس گروه : "..settings.lock_photo.."\n>قفل اعضا : "..settings.lock_member.."\n>ممنوعیت ارسال لینک : "..lock_link.."\n>حساسیت اسپم : "..NUM_MSG_MAX.."\n>قفل ربات ها : "..bots_protection.."\n>قفل تگ : "..tag.."\n>قفل اینگلیسی :"..lock_english.."\n>قفل فحش : "..lock_badw.."\n>Sbss Open Source Version\n"
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "قفط مدیران"
end
local data_cat = 'توضیحات'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'توضیحات گروه به این متن تغییر یافت:\n'..about
end
local function get_description(msg, data)
local data_cat = 'توضیحات'
if not data[tostring(msg.to.id)][data_cat] then
return 'توضیحی موجود نیست'
end
local about = data[tostring(msg.to.id)][data_cat]
local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about
return 'درباره'..about
end
local function lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'عربی از قبل قفل است'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'عربی قفل شد'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'عربی از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'عربی آزاد شد'
end
end
local function lock_group_tag(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'yes' then
return 'تگ کردن از قبل قفل است🔒'
else
data[tostring(target)]['settings']['tag'] = 'yes'
save_data(_config.moderation.data, data)
return 'تگردن ممنوع شد✅🔒'
end
end
local function unlock_group_tag(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_tag_lock = data[tostring(target)]['settings']['tag']
if group_tag_lock == 'no' then
return 'تگ کردن از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['tag'] = 'no'
save_data(_config.moderation.data, data)
return 'تگ کردن آزاد شد✅🔓'
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران❗️"
end
local group_english_lock = data[tostring(target)]['settings']['lock_english']
if group_english_lock == 'yes' then
return 'ایگلیسی از قبل قفل است🔒'
else
data[tostring(target)]['settings']['lock_english'] = 'yes'
save_data(_config.moderation.data, data)
return 'اینگلیسی قفل شد✅🔒'
end
end
local function unlock_group_english(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران❗️"
end
local group_english_lock = data[tostring(target)]['settings']['lock_english']
if group_english_lock == 'no' then
return 'اینگلیسی از قبل باز است🔓'
else
data[tostring(target)]['settings']['lock_english'] = 'no'
save_data(_config.moderation.data, data)
return 'اینگلیسی ازاد شد✅🔓'
end
end
local function lock_group_badw(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_badw_lock = data[tostring(target)]['settings']['lock_badw']
if group_badw_lock == 'yes' then
return 'فحاشی از قبل ممنوع است🔒'
else
data[tostring(target)]['settings']['lock_badw'] = 'yes'
save_data(_config.moderation.data, data)
return 'فحاشی قفل شد✅🔒'
end
end
local function unlock_group_badw(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_badw_lock = data[tostring(target)]['settings']['lock_badw']
if group_badw_lock == 'no' then
return 'فحاشی از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_badw'] = 'no'
save_data(_config.moderation.data, data)
return 'فحاشی آزاد شد✅🔓'
end
end
local function lock_group_link(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'yes' then
return 'ارسال لینک از قبل ممنوع است🔒'
else
data[tostring(target)]['settings']['lock_link'] = 'yes'
save_data(_config.moderation.data, data)
return 'ارسال لینک ممنوع شد✅🔒'
end
end
local function unlock_group_link(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_link_lock = data[tostring(target)]['settings']['lock_link']
if group_link_lock == 'no' then
return 'ارسال لینک از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_link'] = 'no'
save_data(_config.moderation.data, data)
return 'lارسال لینک آزاد شد✅🔓'
end
end
local function lock_group_username(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران❗️"
end
local group_username_lock = data[tostring(target)]['settings']['lock_username']
if group_username_lock == 'yes' then
return 'یوزر نیم از قبل قفل است🔒'
else
data[tostring(target)]['settings']['lock_username'] = 'yes'
save_data(_config.moderation.data, data)
return 'یوزر نیم آزاد شد✅🔒'
end
end
local function unlock_group_username(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران❗️"
end
local group_username_lock = data[tostring(target)]['settings']['lock_username']
if group_username_lock == 'no' then
return 'ارسال یوزر نیم از قبل آزاد است🔓'
else
data[tostring(target)]['settings']['lock_username'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال یوزر نیم آژاد شد✅🔓'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'قفل ربات ها از قبل فعال است'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'ورود ربات ها قفل شد'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'ورود ربات ها از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'ورود ربات ها ازاد شد'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'نام گروه از قبل قفل است'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'نام گروه قفل شد'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'نام گروه از قبل باز است'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'نام گروه باز شد'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "فقط توسط گلوبال ادمین ها"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'ارسال پیام سریع ممنوع از قبل ممنوع بود'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'اسپم قفل شد'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "فقط برای گلوبال ادمین ها"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'اسپم قفل نیست!'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال سریع پیام آزاد شد'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'ورود اعضا از قبل قفل است'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'ورود اعضا قفل شد'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'عضو گیری ازاد است'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'عضو گیری ازاد شد'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "فقط برای مدیران"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'خروج از قبل ممنوع بود'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'کسانی که خارج میشوند بن خواهند شد'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'خروج آزاد بود'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'خروج آزاد شد'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'عکس گروه قفل نیست'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'عکس گروه باز شد'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local data_cat = 'قوانین'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'قوانین گروه به این متن تغییر یافت:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'گروه از قبل اد شده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg})
end
local function realmadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'ریلیم از قبل اد شده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg})
end
-- Global functions
function modrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'گروه اضافه نشده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg})
end
function realmrem(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "شما ادمین نیستید"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'ریلیم اد نشده'
end
receiver = get_receiver(msg)
chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg})
end
local function get_rules(msg, data)
local data_cat = 'قوانین'
if not data[tostring(msg.to.id)][data_cat] then
return 'قانونی موجود نیست'
end
local rules = data[tostring(msg.to.id)][data_cat]
local rules = 'قوانین گروه:\n'..rules
return rules
end
local function set_group_photo(msg, success, result)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
chat_set_photo (receiver, file, ok_cb, false)
data[tostring(msg.to.id)]['settings']['set_photo'] = file
save_data(_config.moderation.data, data)
data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes'
save_data(_config.moderation.data, data)
send_large_msg(receiver, 'عکس ذخیره شد!', ok_cb, false)
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function promote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'گروه اضافه نشده')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' از قبل مدیر است')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' ترفیع یافت')
end
local function promote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'.. msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_username, member_id)
end
end
local function demote(receiver, member_username, member_id)
local data = load_data(_config.moderation.data)
local group = string.gsub(receiver, 'chat#id', '')
if not data[group] then
return send_large_msg(receiver, 'گروه اضافه نشده')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' مدیر نیست !')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' تنزل یافت')
end
local function demote_by_reply(extra, success, result)
local msg = result
local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '')
if msg.from.username then
member_username = '@'..msg.from.username
else
member_username = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_username, member_id)
end
end
local function setleader_by_reply(extra, success, result)
local msg = result
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
local name_log = msg.from.print_name:gsub("_", " ")
data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id)
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as leader")
local text = msg.from.print_name:gsub("_", " ").." اکنون صاحب گروه است "
return send_large_msg(receiver, text)
end
local function promote_demote_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local member_username = "@"..result.username
local chat_id = extra.chat_id
local mod_cmd = extra.mod_cmd
local receiver = "chat#id"..chat_id
if mod_cmd == 'ترفیع' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'تنزل' then
return demote(receiver, member_username, member_id)
end
end
local function modlist(msg)
local data = load_data(_config.moderation.data)
local groups = "groups"
if not data[tostring(groups)][tostring(msg.to.id)] then
return 'گروه اد نشده'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'دراین گروه هیچ مدیری وجود ندارد'
end
local i = 1
local message = '\nلیست مدیر های گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
message = message ..i..' - '..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function callbackres(extra, success, result)
--vardump(result)
local user = result.id
local name = string.gsub(result.print_name, "_", " ")
local chat = 'chat#id'..extra.chatid
send_large_msg(chat, user..'\n'..name)
return user
end
local function help()
local help_text = tostring(_config.help_text)
return help_text
end
local function cleanmember(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user(v.id, result.id)
end
end
local function killchat(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function killrealm(cb_extra, success, result)
local receiver = cb_extra.receiver
local chat_id = "chat#id"..result.id
local chatname = result.print_name
for k,v in pairs(result.members) do
kick_user_any(v.id, result.id)
end
end
local function user_msgs(user_id, chat_id)
local user_info
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info = tonumber(redis:get(um_hash) or 0)
return user_info
end
local function kick_zero(cb_extra, success, result)
local chat_id = cb_extra.chat_id
local chat = "chat#id"..chat_id
local ci_user
local re_user
for k,v in pairs(result.members) do
local si = false
ci_user = v.id
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
for i = 1, #users do
re_user = users[i]
if tonumber(ci_user) == tonumber(re_user) then
si = true
end
end
if not si then
if ci_user ~= our_id then
if not is_momod2(ci_user, chat_id) then
chat_del_user(chat, 'user#id'..ci_user, ok_cb, true)
end
end
end
end
end
local function kick_inactive(chat_id, num, receiver)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
-- Get user info
for i = 1, #users do
local user_id = users[i]
local user_info = user_msgs(user_id, chat_id)
local nmsg = user_info
if tonumber(nmsg) < tonumber(num) then
if not is_momod2(user_id, chat_id) then
chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true)
end
end
end
return chat_info(receiver, kick_zero, {chat_id = chat_id})
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local name_log = user_print_name(msg.from)
local group = msg.to.id
if msg.media then
if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then
load_photo(msg.id, set_group_photo, msg)
end
end
if matches[1] == 'اضافه' and not matches[2] then
if is_realm(msg) then
return 'خطا : از قبل ریلیم بوده'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'اضافه' and matches[2] == 'ریلیم' then
if is_group(msg) then
return 'خطا : اینجا یک گروه است'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'حذف' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'حذف' and matches[2] == 'ریلیم' then
print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm")
return realmrem(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then
return automodadd(msg)
end
if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then
return autorealmadd(msg)
end
if msg.to.id and data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if matches[1] == 'chat_add_user' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_member_lock = settings.lock_member
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then
chat_del_user(chat, user, ok_cb, true)
elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then
return nil
elseif group_member_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_del_user' then
if not msg.service then
-- return "Are you trying to troll me?"
end
local user = 'user#id'..msg.action.user.id
local chat = 'chat#id'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user)
end
if matches[1] == 'chat_delete_photo' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then
if not msg.service then
return "Are you trying to troll me?"
end
local group_photo_lock = settings.lock_photo
if group_photo_lock == 'yes' then
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:incr(picturehash)
---
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
local picprotectionredis = redis:get(picturehash)
if picprotectionredis then
if tonumber(picprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(picprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id
redis:set(picturehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ")
chat_set_photo(receiver, settings.set_photo, ok_cb, false)
elseif group_photo_lock == 'no' then
return nil
end
end
if matches[1] == 'chat_rename' then
if not msg.service then
return "Are you trying to troll me?"
end
local group_name_set = settings.set_name
local group_name_lock = settings.lock_name
local to_rename = 'chat#id'..msg.to.id
if group_name_lock == 'yes' then
if group_name_set ~= tostring(msg.to.print_name) then
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:incr(namehash)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
local nameprotectionredis = redis:get(namehash)
if nameprotectionredis then
if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)
end
if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)
local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id
redis:set(namehash, 0)
end
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
elseif group_name_lock == 'no' then
return nil
end
end
if matches[1] == 'تنظیم نام' and is_momod(msg) then
local new_name = string.gsub(matches[2], '_', ' ')
data[tostring(msg.to.id)]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(msg.to.id)]['settings']['set_name']
local to_rename = 'chat#id'..msg.to.id
rename_chat(to_rename, group_name_set, ok_cb, false)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'تنظیم عکس' and is_momod(msg) then
data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting'
save_data(_config.moderation.data, data)
return 'لطفا عکس جدید گروه را ارسال کنید'
end
if matches[1] == 'ترفیع' and not matches[2] then
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'ترفیع' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'ترفیع',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'تنزل' and not matches[2] then
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'تنزل' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "فقط توسط صاحب گروه"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "شما نمیتوانید مقام خود را حذف کنید"
end
local member = matches[2]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member)
local cbres_extra = {
chat_id = msg.to.id,
mod_cmd = 'تنزل',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
return res_user(username, promote_demote_res, cbres_extra)
end
if matches[1] == 'لیست مدیران' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'توضیحات' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'قوانین' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'تنظیم' then
if matches[2] == 'قوانین' then
rules = matches[3]
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rulesmod(msg, data, target)
end
if matches[2] == 'توضیحات' then
local data = load_data(_config.moderation.data)
local target = msg.to.id
local about = matches[3]
savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_descriptionmod(msg, data, target, about)
end
end
if matches[1] == 'قفل' then
local target = msg.to.id
if matches[2] == 'نام' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'اسپم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'ربات ها' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link🔒 ")
return lock_group_link(msg, data, target)
end
if matches[2] == 'تگ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag🔒 ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw🔒 ")
return lock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english🔒 ")
return lock_group_english(msg, data, target)
end
if matches[2] == 'خروج' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'بازکردن' then
local target = msg.to.id
if matches[2] == 'نام' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'عکس' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'اسپم' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'ربات ها' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link🔓 ")
return unlock_group_link(msg, data, target)
end
if matches[2] == 'تگ' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag🔓 ")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw🔓 ")
return unlock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english🔓 ")
return unlock_group_english(msg, data, target)
end
if matches[2] == 'خروج' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'settings' or matches[1] == 'تنظیمات' then
local target = msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ")
return show_group_settingsmod(msg, data, target)
end
--[[if matches[1] == 'public' then
local target = msg.to.id
if matches[2] == 'yes' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public")
return set_public_membermod(msg, data, target)
end
if matches[2] == 'no' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public")
return unset_public_membermod(msg, data, target)
end
end]]
if matches[1] == 'لینک جدید' and not is_realm(msg) then
if not is_momod(msg) then
return "فقط برای مدیران"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*خطا : \nربات سازنده گروه نیست')
end
send_large_msg(receiver, "لینک جدید ساخته شد")
data[tostring(msg.to.id)]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
end
local receiver = 'chat#'..msg.to.id
savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ")
return export_chat_link(receiver, callback, true)
end
if matches[1] == 'لینک' then
if not is_momod(msg) then
return "فقط مدیران"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "اول با لینک جدید یک لینک جدید بسازید"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link
end
if matches[1] == 'لینک خصوصی' then
if not is_momod(msg) then
return "فقط برای مدیران"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "اول با لینک جدید یک لینک جدید بسازید"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
send_large_msg('user#id'..msg.from.id, "لینک گروه:\n🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷🤖🇮🇷\n"..group_link)
end
if matches[1] == 'دارنده' and matches[2] then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
data[tostring(msg.to.id)]['set_owner'] = matches[2]
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as leader")
local text = matches[2].." added as leader"
return text
end
if matches[1] == 'دارنده' and not matches[2] then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setleader_by_reply, false)
end
end
if matches[1] == 'صاحب گروه' then
local group_leader = data[tostring(msg.to.id)]['set_owner']
if not group_leader then
return "no leader,ask admins in support groups to set leader for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /leader")
return "آیدی صاحب گروه : ["..group_leader..']'
end
if matches[1] == 'صاحب' then
local receiver = "chat#id"..matches[2]
if not is_admin(msg) then
return "For admins only!"
end
data[tostring(matches[2])]['set_owner'] = matches[3]
save_data(_config.moderation.data, data)
local text = matches[3].." added as leader"
send_large_msg(receiver, text)
return
end
if matches[1] == 'حساسیت' then
if not is_momod(msg) then
return "شما مجاز نیستید"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "عددی از بین 5 و 20 انتخاب کنید"
end
local flood_max = matches[2]
data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]")
return 'حساسیت اسپم تغییر یافت به '..matches[2]
end
if matches[1] == 'پاک کردن' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
if matches[2] == 'اعضا' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'مدیران' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'مدیری در گروه نیست'
end
local message = '\nلیست مدیران گروه ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n'
for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do
data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist")
end
if matches[2] == 'rules' and matches[2] == 'قوانین' then
local data_cat = 'قوانین'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules")
end
if matches[2] == 'توضیحات' then
local data_cat = 'توضیحات'
data[tostring(msg.to.id)][data_cat] = nil
save_data(_config.moderation.data, data)
savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about")
end
end
if matches[1] == 'kill' and matches[2] == 'chat' then
if not is_admin(msg) then
return nil
end
if not is_realm(msg) then
local receiver = get_receiver(msg)
return modrem(msg),
print("Closing Group..."),
chat_info(receiver, killchat, {receiver=receiver})
else
return 'This is a realm'
end
end
if matches[1] == 'kill' and matches[2] == 'realm' then
if not is_admin(msg) then
return nil
end
if not is_group(msg) then
local receiver = get_receiver(msg)
return realmrem(msg),
print("Closing Realm..."),
chat_info(receiver, killrealm, {receiver=receiver})
else
return 'This is a group'
end
end
if matches[1] == 'راهنما' then
if not is_momod(msg) or is_realm(msg) then
return
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help")
return help()
end
if matches[1] == 'کد' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
if matches[1] == 'kickinactive' then
--send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]')
if not is_momod(msg) then
return 'Only a moderator can kick inactive users'
end
local num = 1
if matches[2] then
num = matches[2]
end
local chat_id = msg.to.id
local receiver = get_receiver(msg)
return kick_inactive(chat_id, num, receiver)
end
end
end
return {
patterns = {
"^(اضافه)$",
"^(اضافه) (ریلیم)$",
"^(حذف)$",
"^(حذف) (ریلیم)$",
"^(قوانین)$",
"^(توضیحات)$",
"^(تنظیم نام) (.*)$",
"^(تنظیم عکس)$",
"^(ترفیع) (.*)$",
"^(ترفیع)",
"^(راهنما)$",
"^(پاک کردن) (.*)$",
"^(kill) (chat)$",
"^(kill) (realm)$",
"^(تنزل) (.*)$",
"^(تنزل)",
"^(تنظیم) ([^%s]+) (.*)$",
"^(قفل) (.*)$",
"^(دارنده) (%d+)$",
"^(دارنده)",
"^(صاحب گروه)$",
"^(کد) (.*)$",
"^(صاحب) (%d+) (%d+)$",-- (group id) (leader id)
"^(بازکردن) (.*)$",
"^(حساسیت) (%d+)$",
"^(تنظیمات)$",
-- "^(public) (.*)$",
"^(لیست مدیران)$",
"^(لینک جدید)$",
"^(لینک)$",
"^(kickinactive)$",
"^(kickinactive) (%d+)$",
"^(لینک خصوصی)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
roboxt/ss | plugins/spam.lua | 34 | 1560 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
--------------------------------------------------
local function kick_user(msg)
local chat = 'chat#id'..msg.to.id
local channel = 'channel#id'..msg.to.id
local user = msg.from.id
if msg.to.type == 'chat' then
chat_del_user(chat, 'user#id'..user, ok_cb, true)
elseif msg.to.type == 'channel' then
channel_kick_user(channel, 'user#id'..user, ok_cb, true)
end
end
local function run(msg, matches)
if not permissions(msg.from.id, msg.to.id, "settings") then
local hash = 'spam:'..msg.to.id
if redis:get(hash) then
kick_user(msg)
delete_msg(msg.id, ok_cb, false)
send_report(msg)
end
end
end
return {
patterns = {
-- You can add much as patterns you want to stop all spam traffic
"[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm]%.[Mm][Ee]",
"[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm]%.[Oo][Rr][Gg]",
"[Aa][Dd][Ff]%.[Ll][Yy]",
"[Bb][Ii][Tt]%.[Ll][Yy]",
"[Gg][Oo][Oo]%.[Gg][Ll]"
}, run = run}
| gpl-2.0 |
emoses/hammerspoon | extensions/base64/init.lua | 18 | 1412 | --- === hs.base64 ===
---
--- Base64 encoding and decoding
---
--- Portions sourced from (https://gist.github.com/shpakovski/1902994).
local module = require("hs.base64.internal")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
--- hs.base64.encode(val[,width]) -> str
--- Function
--- Encodes a given string to base64
---
--- Parameters:
--- * val - A string to encode as base64
--- * width - Optional line width to split the string into (usually 64 or 76)
---
--- Returns:
--- * A string containing the base64 representation of the input string
module.encode = function(data, width)
local _data = module._encode(data)
if width then
local _hold, i, j = _data, 1, width
_data = ""
repeat
_data = _data.._hold:sub(i,j).."\n"
i = i + width
j = j + width
until i > #_hold
return _data:sub(1,#_data - 1)
else
return _data
end
end
--- hs.base64.decode(str) -> val
--- Function
--- Decodes a given base64 string
---
--- Parameters:
--- * str - A base64 encoded string
---
--- Returns:
--- * A string containing the decoded data
module.decode = function(data)
return module._decode(data:gsub("[\r\n]+",""))
end
-- Return Module Object --------------------------------------------------
return module
| mit |
kidaa/FFXIOrgins | scripts/zones/Aht_Urhgan_Whitegate/npcs/Ratihb.lua | 2 | 3224 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Ratihb
-- Standard Info NPC
-- @pos 75.225 -6.000 -137.203 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/settings");
require("scripts/globals/status");
require("scripts/globals/titles");
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 LuckOfTheDraw = player:getQuestStatus(AHT_URHGAN,LUCK_OF_THE_DRAW);
local EquipedforAllOccasions = player:getQuestStatus(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
if(LuckOfTheDraw == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL) then -- corsair job quest
player:startEvent(0x0223);
player:setVar("LuckOfTheDraw",1);
player:addQuest(AHT_URHGAN,LUCK_OF_THE_DRAW);
elseif(player:getQuestStatus(AHT_URHGAN,LUCK_OF_THE_DRAW) == QUEST_COMPLETED and player:getVar("LuckOfTheDraw") ==5) then -- Ending CS for Corsair Optional
player:startEvent(0x0228);
player:setVar("LuckOfTheDraw",6);
elseif(player:getVar("EquipedforAllOccasions") ==4 and player:getVar("LuckOfTheDraw") ==6) then --Af1 Final CS
player:startEvent(0x0304);
player:setVar("EquipedforAllOccasions",5);
player:setVar("LuckOfTheDraw",0);
elseif(player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_COMPLETED and player:getMainJob() == JOB_COR and mLvl >= AF1_QUEST_LEVEL)then
player:startEvent(0x031D);
elseif(player:getQuestStatus(AHT_URHGAN,LUCK_OF_THE_DRAW) == QUEST_COMPLETED and player:getQuestStatus(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS) == QUEST_COMPLETED) then
player:setVar("EquipedforAllOccasions",0);
else
player:startEvent(0x025B); -- 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 == 0x0304) then
local AFgun = 18702;
if(player:getFreeSlotsCount() >= 1) then
player:addItem(AFgun) -- Receive Af1 Trump Gun
player:messageSpecial(ITEM_OBTAINED,AFgun);
player:completeQuest(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
player:setVar("EquipedforAllOccasions",0);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,AFgun);
end
elseif(csid == 0x031D) then
player:setVar("AgainstAllOdds",1); -- Set For Corsair BCNM
player:setVar("AgainstAllOddsSideQuests",1); -- Set For Corsair Side Quests
player:addQuest(AHT_URHGAN,AGAINST_ALL_ODDS); -- Start of af 3 not completed yet
player:addKeyItem(LIFE_FLOAT); -- BCNM KEY ITEM TO ENTER BCNM
player:messageSpecial(KEYITEM_OBTAINED, LIFE_FLOAT);
end
end;
| gpl-3.0 |
aurelien-defossez/ecusson | game/lib/ecusson/DeferredTaskHandler.lua | 3 | 3036 | -----------------------------------------------------------------------------------------
--
-- Author: Aurélien Defossez
-- (c) 2014 Tabemasu Games (www.tabemasu.com)
--
-- DeferredTaskHandler.lua
--
-- An event handler that piles events for a deferred resolution
--
-----------------------------------------------------------------------------------------
local utils = require("lib.ecusson.Utils")
-----------------------------------------------------------------------------------------
local Class = {}
-----------------------------------------------------------------------------------------
-- Initialization and Destruction
-----------------------------------------------------------------------------------------
-- Create the deferred event handler
--
-- Parameters:
-- target: The target object that will receive final events
function Class.create(options)
local self = utils.extend(Class)
-- Initialize attributes
self.target = options.target
self.listeners = {}
self.deferreds = {}
return self
end
-- Destroy the handler
function Class:destroy()
utils.deleteObject(self)
end
-----------------------------------------------------------------------------------------
-- Methods
-----------------------------------------------------------------------------------------
-- Add an event listener that will add a task when triggered
--
-- Parameters:
-- source: The object to bind the event on
-- eventName: The event name to listen to
function Class:addEventListener(source, eventName)
if self.listeners[eventName] then
utils.softError("Event listener already attached to this deferred handler "..eventName)
else
local function handler(event)
self:addTask(eventName, event)
end
source:addEventListener(eventName, handler)
self.listeners[eventName] = handler
end
end
-- Remove an event listener previously bound with addEventListener
--
-- Parameters:
-- source: The bound object
-- eventName: The event name
function Class:removeEventListener(source, eventName)
source:removeEventListener(eventName, self.listeners[eventName])
self.listeners[eventName] = nil
end
-- Add a task to the pile
--
-- Parameters:
-- taskName: The name of the task, which will be used to call a method with the same name on the target object
-- options: A userdata array directly passed to the deferred call
function Class:addTask(taskName, options)
self.deferreds[#self.deferreds + 1] = {
name = taskName,
options = options
}
end
-- Resolve all the tasks in the pile
function Class:resolveTasks()
-- Immediately create a new deferred stack if some arrive while resolving the current ones
local currentDeferreds = self.deferreds
self.deferreds = {}
-- Call deferred methods
for _, deferred in pairs(currentDeferreds) do
self.target[deferred.name](self.target, deferred.options)
end
-- Execute new tasks recursively if any
if #self.deferreds > 0 then
self:resolveTasks()
end
end
-----------------------------------------------------------------------------------------
return Class
| lgpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/weaponskills/shoulder_tackle.lua | 4 | 1376 | -----------------------------------
-- Shoulder Tackle
-- Hand-to-Hand weapon skill
-- Skill Level: 40
-- Stuns target. Chance of stunning varies with TP.
-- Will stack with Sneak Attack.
-- Aligned with the Aqua Gorget & Thunder Gorget.
-- Aligned with the Aqua Belt & Thunder Belt.
-- Element: None
-- Modifiers: VIT:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 2;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.3; 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;
local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params);
local chance = player:getTP()-100 > math.random()*150;
if(damage > 0 and target:hasStatusEffect(EFFECT_STUN) == false) then
target:addStatusEffect(EFFECT_STUN, 1, 0, 4);
end
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Riverne-Site_A01/Zone.lua | 1 | 1818 | -----------------------------------
--
-- Zone: Riverne-Site_A01
--
-----------------------------------
package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Riverne-Site_A01/TextIDs");
require("scripts/globals/status");
require("scripts/globals/settings");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
SetServerVariable("Heliodromos_ToD", (os.time() + math.random((43200), (54000))));
end;
-----------------------------------
-- onConquestUpdate
-----------------------------------
function onConquestUpdate(zone, updatetype)
local players = zone:getPlayers();
for name, player in pairs(players) do
conquestUpdate(zone, player, updatetype, CONQUEST_BASE);
end
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
local cs = -1;
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
player:setPos(732.55,-32.5,-506.544,90); -- {R}
end
-- ZONE LEVEL RESTRICTION
if(ENABLE_COP_ZONE_CAP == 1)then
player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,40,0,0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
MarcoQin/AyrLand | scripts/behaviourtree/test.lua | 1 | 1631 | local t = 0
math.random()
math.random()
math.random()
math.random()
function GetTime()
return t
-- return os.time()
end
local test1root = SequenceNode(
{
ActionNode(
function() print("Looking") end,
"LookNode"
),
ConditionWaitNode(
function() return GetTime() > 10 end,
"Waiting"
)
}
)
local test0root = PriorityNode(
{
IfNode(
function() return GetTime() % 2 == 0 end,
"Time Test",
ActionNode(
function() print("test0root Action emit!") end,
"Action Test"
)
),
WhileNode(
function() return GetTime() % 3 == 0 end,
"no name",
ActionNode(
function() print("whileNode Action emit") end,
"Action Test2"
)
),
ParallelNodeAny {
WaitNode(math.random(1, 10)),
PriorityNode {
IfNode(
function () return GetTime() % 5 == 0 end,
"pna.pn.ifn",
ActionNode(
function () print("PNA-Action emit") end,
"PNA-Action"
)
)
}
},
test1root,
}, .25
)
local bt = BT(test0root)
for i = 0, 20, 1 do
t = t + 1
bt:update()
print(tostring(bt))
end
bt:stop()
-- local bt = BT(test1root)
-- for i = 0, 20, 1 do
-- t = t + 1
-- bt:update()
-- print(tostring(bt))
-- end
-- bt:stop()
| mit |
kidaa/FFXIOrgins | scripts/zones/Arrapago_Reef/npcs/qm10.lua | 4 | 2891 | -----------------------------------
-- Area: Arrapago Reef
-- NPC: ???
-- Starts: Corsair Af1 ,AF2 ,AF3
-- @pos 457.128 -8.249 60.795 54
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/quests");
require("scripts/globals/titles");
require("scripts/zones/Arrapago_Reef/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local mJob = player:getMainJob();
local mLvl = player:getMainLvl();
local equipedForAll = player:getQuestStatus(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
local NoStringsAttached = player:getQuestStatus(AHT_URHGAN,NO_STRINGS_ATTACHED);
local NoStringsAttachedProgress = player:getVar("NoStringsAttachedProgress");
if (equipedForAll == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF1_QUEST_LEVEL) then
player:startEvent(0x0E4);
elseif(equipedForAll == QUEST_ACCEPTED and player:getVar("EquipedforAllOccasions") ==3) then
player:startEvent(0x0E7);
player:delKeyItem(WHEEL_LOCK_TRIGGER);
elseif(equipedForAll == QUEST_COMPLETED and player:getQuestStatus(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS) == QUEST_AVAILABLE and mJob == JOB_COR and mLvl >= AF2_QUEST_LEVEL) then
player:startEvent(0x0E8);
elseif(player:getVar("NavigatingtheUnfriendlySeas") ==4) then
player:startEvent(0x0E9);
elseif(NoStringsAttachedProgress == 3) then
player:startEvent(0x00d6); -- "You see an old, dented automaton..."
else
player:messageSpecial(8327); -- "There is nothing else of interest here."
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 == 0x0E4) then
player:addQuest(AHT_URHGAN,EQUIPED_FOR_ALL_OCCASIONS);
player:setVar("EquipedforAllOccasions",1);
elseif(csid== 0x0E7) then
player:setVar("EquipedforAllOccasions",4);
elseif(csid == 0x0E8) then
player:addQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",1);
elseif(csid == 0x0E9) then
player:addItem(15601) -- Receive item Corsairs culottes
player:messageSpecial(ITEM_OBTAINED,15601);
player:completeQuest(AHT_URHGAN,NAVIGATING_THE_UNFRIENDLY_SEAS);
player:setVar("NavigatingtheUnfriendlySeas",0);
player:setVar("HydrogauageTimer",0);
elseif(csid == 0x00d6) then
player:addKeyItem(798);
player:messageSpecial(KEYITEM_OBTAINED,ANTIQUE_AUTOMATON);
player:setVar("NoStringsAttachedProgress",4);
end
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/mobskills/Havoc_Spiral.lua | 10 | 1098 | ---------------------------------------------
-- Havoc Spiral
--
-- Description: Deals damage to players in an area of effect. Additional effect: Sleep
-- Type: Physical
-- 2-3 Shadows
-- Range: Unknown
-- Special weaponskill unique to Ark Angel MR. Deals ~100-300 damage.
---------------------------------------------
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;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_2_SHADOW);
-- Witnessed 280 to a melee, 400 to a BRD, and 500 to a wyvern, so...
target:delHP(dmg);
MobStatusEffectMove(mob, target, EFFECT_SLEEP_I, 1, 0, math.random(30, 60));
return dmg;
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Northern_San_dOria/npcs/Calovour.lua | 36 | 1427 | -----------------------------------
-- Area: Northern San d'Oria
-- NPC: Calovour
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/zones/Northern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0279);
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 |
MOSAVI17/Security1 | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
lordporya/lord-dark | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
RockySeven3161/Unknown. | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
Clavus/LD32 | engine/classes/sprite/sprite.lua | 2 | 2649 | ------------------------
-- Sprite class.
-- Your standard animated sprite class.
--
-- Derived from @{Object}.
-- @cl Sprite
local Sprite = class("Sprite")
function Sprite:initialize( sData )
self._image = sData.image
self._offset = sData.offset or Vector(0,0)
self._size = sData.size or Vector(self._image:getWidth(), self._image:getHeight())
self._origin_pos = sData.origin_pos or Vector(0,0)
if (sData.origin_relative) then
self._origin_pos = sData.origin_relative * self._size
end
self._num_frames = sData.num_frames or 1
self._fps = sData.fps or 0
self._loops = sData.should_loop or false
self._cur_frame = 1
self._ended = false
self._speed = 1
self.visible = true
local quads = {}
local col = 0
local row = 0
local fw, fh = self._size.x, self._size.y
local img = self._image
local offset = self._offset
local num_columns = sData.num_columns or 1
for i = 1, self._num_frames do
table.insert(quads, love.graphics.newQuad(offset.x + col*fw, offset.y + row*fh, fw, fh, img:getWidth(), img:getHeight()))
col = col + 1
if (col >= num_columns) then
col = 0
row = row + 1
end
end
self._frames = quads
end
function Sprite:update( dt )
if (not self._ended and self._num_frames > 1 and self._fps * self._speed ~= 0) then
self._cur_frame = self._cur_frame + (dt * self._fps * self._speed)
if (self._cur_frame >= self._num_frames + 1) then
if (self._loops) then
self._cur_frame = self._cur_frame - self._num_frames
else
self._cur_frame = self._num_frames
self._ended = true
end
elseif (self._cur_frame < 1) then
if (self._loops) then
self._cur_frame = self._num_frames + 1 + self._cur_frame
else
self._cur_frame = self._num_frames
self._ended = true
end
end
end
end
function Sprite:setSpeed( scalar )
self._speed = scalar
end
function Sprite:getSpeed( scalar )
return self._speed
end
function Sprite:draw(x, y, r, sx, sy)
if not self.visible then return end
r = r or 0
sx = sx or 1
sy = sy or sx
local frame = self._frames[math.floor(self._cur_frame)] or self._frames[1]
local origin = self._origin_pos
love.graphics.draw(self._image, frame, x, y, r, sx, sy, origin.x, origin.y)
end
function Sprite:reset()
self._cur_frame = 1
self._speed = 1
self._ended = false
end
function Sprite:getWidth()
return self._size.x
end
function Sprite:getHeight()
return self._size.y
end
function Sprite:setFrame( frame )
self._cur_frame = frame
end
function Sprite:getCurrentFrame()
return math.floor(self._cur_frame)
end
function Sprite:getFrameCount()
return self._num_frames
end
function Sprite:hasEnded()
return self._ended
end
return Sprite
| mit |
kidaa/FFXIOrgins | scripts/zones/Tavnazian_Safehold/npcs/Pradiulot.lua | 4 | 2321 | -----------------------------------
-- Area: Tavnazian Safehold
-- NPC: Pradiulot
-- Involved in Quest: Unforgiven
-- @zone 26
-- @pos -20.814 -22 8.399
-----------------------------------
package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Tavnazian_Safehold/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- For those who don't know
-- at the end of if(player:getQuestStatus(REGION,QUEST_NAME)
-- == 0 means QUEST_AVAILABLE
-- == 1 means QUEST_ACCEPTED
-- == 2 means QUEST_COMPLETED
-- e.g. if(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 0
-- means if(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == QUEST AVAILABLE
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 2 and trade:getGil() == 1 == true) then
player:startEvent(0x00CE); -- Dialogue after completing quest (optional)
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local Unforgiven = player:getQuestStatus(OTHER_AREAS,UNFORGIVEN);
if (Unforgiven == 1 and player:getVar("UnforgivenVar") == 1) then
player:startEvent(0x00CC); -- Dialogue for final stage of Unforgiven Quest
elseif(player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 2 and player:getVar("UnforgivenVar") == 2) then
player:startEvent(0x00CE); -- Dialogue after completing quest (optional)
else
player:startEvent(0x0173); -- Default Dialogue
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 == 0x00CC) then
player:setVar("UnforgivenVar",2);
player:addKeyItem(440)
player:messageSpecial(KEYITEM_OBTAINED,440); -- Map of Tavnazia
player:completeQuest(OTHER_AREAS,UNFORGIVEN);
player:addFame(OTHER_AREAS,30);
elseif (csid == 0x00CE) then
player:setVar("UnforgivenVar",0);
end
end;
| gpl-3.0 |
BTAxis/naev | dat/ai/include/atk_fighter.lua | 9 | 4835 | --[[This file contains the attack profiles by ship type.
--commonly used range and condition-based attack patterns are found in another file
--Think functions for determining who to attack are found in another file
--]]
-- Initializes the fighter
function atk_fighter_init ()
mem.atk_think = atk_fighter_think
mem.atk = atk_fighter
end
--[[
-- Mainly targets small fighters.
--]]
function atk_fighter_think ()
local target = ai.target()
-- Stop attacking if it doesn't exist
if not target:exists() then
ai.poptask()
return
end
local enemy = ai.getenemy_size(0, 200)
local nearest_enemy = ai.getenemy()
local dist = ai.dist(target)
local range = ai.getweaprange(3, 0)
-- Get new target if it's closer
--prioritize targets within the size limit
if enemy ~= target and enemy ~= nil then
-- Shouldn't switch targets if close
if dist > range * mem.atk_changetarget then
ai.pushtask("attack", enemy )
end
elseif nearest_enemy ~= target and nearest_enemy ~= nil then
-- Shouldn't switch targets if close
if dist > range * mem.atk_changetarget then
ai.pushtask("attack", nearest_enemy )
end
end
end
--[[
-- Main control function for fighter behavior.
--]]
function atk_fighter ()
local target = _atk_com_think()
if target == nil then return end
-- Targetting stuff
ai.hostile(target) -- Mark as hostile
ai.settarget(target)
-- Get stats about enemy
local dist = ai.dist( target ) -- get distance
local range = ai.getweaprange(3, 0)
-- We first bias towards range
if dist > range * mem.atk_approach then
_atk_g_ranged( target, dist ) -- Use generic ranged function
-- Otherwise melee
else
if target:stats().mass < 200 then
_atk_f_space_sup( target, dist )
else
_atk_f_flyby( target, dist )
end
end
end
--[[
-- Execute a sequence of close-in flyby attacks
-- Uses a combination of facing and distance to determine what action to take
-- This version is slightly less aggressive and cruises by the target
--]]
function _atk_f_flyby( target, dist )
local range = ai.getweaprange(3)
local dir = 0
ai.weapset( 3 ) -- Forward/turrets
-- Far away, must approach
if dist > (3 * range) then
dir = ai.idir(target)
if dir < 10 and dir > -10 then
_atk_keep_distance()
ai.accel()
else
dir = ai.iface(target)
end
-- Midrange
elseif dist > (0.75 * range) then
dir = ai.idir(target)
--test if we're facing the target. If we are, keep approaching
if dir <= 30 and dir > -30 then
ai.iface(target)
if dir < 10 and dir > -10 then
ai.accel()
end
elseif dir > 30 and dir < 180 then
ai.turn(1)
ai.accel()
else
ai.turn(-1)
ai.accel()
end
--otherwise we're close to the target and should attack until we start to zip away
else
dir = ai.aim(target)
--not accellerating here is the only difference between the aggression levels. This can probably be an aggression AI parameter
if mem.aggressive == true then
ai.accel()
end
-- Shoot if should be shooting.
if dir < 10 then
ai.shoot()
end
ai.shoot(true)
end
end
--[[
-- Attack Profile for a maneuverable ship engaging a maneuverable target
--
--This is designed for fighters engaging other fighters
--]]
function _atk_f_space_sup( target, dist )
local range = ai.getweaprange(3)
local dir = 0
ai.weapset( 3 ) -- Forward/turrets
--if we're far away from the target, then turn and approach
if dist > (range) then
dir = ai.idir(target)
if dir < 10 and dir > -10 then
_atk_keep_distance()
ai.accel()
else
dir = ai.iface(target)
end
elseif dist > 0.8* range then
--drifting away from target, so emphasize intercept
--course facing and accelerate to close
dir = ai.iface(target)
if dir < 10 and dir > -10 then
ai.accel()
end
--within close range; aim and blast away with everything
elseif dist > 0.4*range then
dir = ai.aim(target)
local dir2 = ai.idir(target)
--accelerate and try to close
--but only accel if it will be productive
if dir2 < 15 and dir2 > -15 and ai.relvel(target) > -10 then
ai.accel()
end
-- Shoot if should be shooting.
if dir < 10 then
ai.shoot()
end
ai.shoot(true)
--within close range; aim and blast away with everything
else
dir = ai.aim(target)
-- Shoot if should be shooting.
if dir < 10 then
ai.shoot()
end
ai.shoot(true)
end
end
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/bunch_of_gysahl_greens.lua | 18 | 1506 | -----------------------------------------
-- ID: 4545
-- Item: Bunch of Gysahl Greens
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Agility +3
-- Vitality -5
-- Additional Effect with Chocobo Shirt
-- Agility +10
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,ChocoboShirt(target),0,300,4545);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
local power = effect:getPower();
if(power == 1) then
chocoboShirt = 1;
target:addMod(MOD_AGI, 13);
target:addMod(MOD_VIT, -5);
else
target:addMod(MOD_AGI, 3);
target:addMod(MOD_VIT, -5);
end
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
local power = effect:getPower();
if(power == 1) then
target:delMod(MOD_AGI, 13);
target:delMod(MOD_VIT, -5);
else
target:delMod(MOD_AGI, 3);
target:delMod(MOD_VIT, -5);
end
end; | gpl-3.0 |
ChaosForge/doomrl | bin/lua/klass.lua | 2 | 8777 | function DoomRL.load_klasses()
register_klass "marine"
{
name = "Marine",
char = "M",
traits = {
{ id = "ironman", max = 3, max_12 = 5 },
{ id = "finesse", max = 2, max_12 = 3 },
{ id = "hellrunner", max = 2, max_12 = 3 },
{ id = "nails", max = 2, max_12 = 3 },
{ id = "bitch", max = 3, max_12 = 5 },
{ id = "gun", max = 3, max_12 = 5 },
{ id = "reloader", max = 2, max_12 = 3 },
{ id = "eagle", max = 3, max_12 = 5 },
{ id = "brute", max = 3, max_12 = 5 },
{ id = "badass", max = 2 },
{ id = "juggler", requires = {{ "finesse", 1 }}, },
{ id = "berserker", requires = {{ "brute", 2 }}, },
{ id = "dualgunner", requires = {{ "gun", 2 }}, },
{ id = "dodgemaster", requires = {{ "hellrunner", 2 }}, },
{ id = "intuition", requires = {{ "eagle", 2 }}, max = 2 },
{ id = "shottyman", requires = {{ "reloader", 2 }}, },
{ id = "triggerhappy", requires = {{ "bitch", 2 }}, max = 2 },
{ id = "whizkid", requires = {{ "finesse", 2 }}, max = 2 },
{ id = "vampyre", requires = {{ "berserker", 1 }, { "badass", 1 }, }, blocks = { "eagle", "bitch", "hellrunner", }, reqlevel = 6, master = true },
{ id = "bulletdance", requires = {{ "dualgunner", 1 }, { "triggerhappy", 1 }, }, blocks = { "hellrunner", "eagle", "brute", }, master = true },
{ id = "armydead", requires = {{ "shottyman", 1 }, { "badass", 1 }, }, blocks = { "finesse", "eagle", "hellrunner", }, reqlevel = 6, master = true },
{ id = "ammochain", requires = {{ "triggerhappy", 2 }, { "reloader", 2 }, }, blocks = { "nails", "gun", "eagle", }, master = true },
{ id = "survivalist", requires = {{ "badass", 1 }, { "ironman", 3 }, {"nails", 2}, }, blocks = { "hellrunner", "berserker", "bitch", }, master = true },
},
desc = "Marines are the backbone of the UAC, resilient and hardy. They start with 10 more health points and powerups they use have a +50% duration bonus (+25% on Nightmare).",
OnPick = function( being )
being.flags[ BF_POWERBONUS ] = true
being.hpmax = being.hpmax + 10
being.hp = being.hp + 10
being.eq.weapon = "pistol"
being.inv:add( "ammo", { ammo = 40 } )
being.inv:add( "smed" )
being.inv:add( "smed" )
end
}
register_klass "scout"
{
name = "Scout",
char = "S",
traits = {
{ id = "ironman", max = 3, max_12 = 5 },
{ id = "finesse", max = 2, max_12 = 3 },
{ id = "hellrunner", max = 2, max_12 = 3 },
{ id = "nails", max = 2, max_12 = 3 },
{ id = "bitch", max = 3, max_12 = 5 },
{ id = "gun", max = 3, max_12 = 5 },
{ id = "reloader", max = 2, max_12 = 3 },
{ id = "eagle", max = 3, max_12 = 5 },
{ id = "brute", max = 3, max_12 = 5 },
{ id = "intuition", max = 2, },
{ id = "juggler", requires = {{ "finesse", 1 }}, },
{ id = "berserker", requires = {{ "brute", 2 }}, },
{ id = "dualgunner", requires = {{ "gun", 2 }}, },
{ id = "dodgemaster", requires = {{ "hellrunner", 2 }}, },
{ id = "badass", requires = {{ "nails", 2 }}, max = 2 },
{ id = "shottyman", requires = {{ "reloader", 2 }}, },
{ id = "triggerhappy", requires = {{ "bitch", 2 }}, max = 2 },
{ id = "whizkid", requires = {{ "finesse", 2 }}, max = 2 },
{ id = "blademaster", requires = {{ "berserker", 1 }, { "brute", 3}, { "hellrunner", 2 }, }, blocks = { "nails", "bitch", "gun", }, master = true },
{ id = "gunkata", requires = {{ "dualgunner", 1 }, { "dodgemaster", 1}, }, blocks = { "nails", "bitch", "brute", }, master = true },
{ id = "shottyhead", requires = {{ "juggler", 1 }, { "shottyman", 1}, { "hellrunner", 1 }, }, blocks = { "nails", "bitch", "eagle", }, master = true },
{ id = "cateye", requires = {{ "triggerhappy", 1 }, { "intuition", 1}, }, blocks = { "reloader", "brute", "nails", }, reqlevel = 6, master = true },
{ id = "gunrunner", requires = {{ "dodgemaster", 1 }, { "juggler", 1}, }, blocks = { "bitch", "nails", "whizkid", }, master = true },
},
desc = "Scouts are agile and have the best intel. They are generally 10% faster and inherently know the location of stairs on any given level.",
OnPick = function( being )
being.flags[ BF_STAIRSENSE ] = true
being.speed = being.speed + 10
being.eq.weapon = "pistol"
being.inv:add( "ammo", { ammo = 20 } )
being.inv:add( "smed" )
being.inv:add( "smed" )
end
}
register_klass "technician"
{
name = "Technician",
char = "T",
traits = {
{ id = "ironman", max = 3, max_12 = 5 },
{ id = "finesse", max = 2, max_12 = 3 },
{ id = "hellrunner", max = 2, max_12 = 3 },
{ id = "nails", max = 2, max_12 = 3 },
{ id = "bitch", max = 3, max_12 = 5 },
{ id = "gun", max = 3, max_12 = 5 },
{ id = "reloader", max = 2, max_12 = 3 },
{ id = "eagle", max = 3, max_12 = 5 },
{ id = "brute", max = 3, max_12 = 5 },
{ id = "whizkid", max = 2 },
{ id = "juggler", requires = {{ "finesse", 1 }}, },
{ id = "berserker", requires = {{ "brute", 2 }}, },
{ id = "dualgunner", requires = {{ "gun", 2 }}, },
{ id = "dodgemaster", requires = {{ "hellrunner", 2 }}, },
{ id = "intuition", requires = {{ "eagle", 2 }}, max = 2 },
{ id = "badass", requires = {{ "nails", 2 }}, max = 2 },
{ id = "shottyman", requires = {{ "reloader", 2 }}, },
{ id = "triggerhappy", requires = {{ "bitch", 2 }}, max = 2 },
{ id = "malicious", requires = {{ "dodgemaster", 1 }, { "brute", 2 }, { "finesse", 1 }, }, blocks = { "berserker", "nails", "eagle", }, master = true },
{ id = "sharpshooter", requires = {{ "gun", 3 }, { "eagle", 3 }, }, blocks = { "dualgunner", "nails", "bitch", }, master = true },
{ id = "fireangel", requires = {{ "dodgemaster", 1 }, { "shottyman", 1 }, }, blocks = { "gun", "bitch", "eagle", }, master = true },
{ id = "entrenchment", requires = {{ "triggerhappy", 1 }, { "badass", 1 }, }, blocks = { "finesse", "reloader", "gun", }, master = true },
{ id = "scavenger", requires = {{ "whizkid", 2 }, { "intuition", 1 }, }, blocks = { "triggerhappy", "berserker", "dualgunner", }, reqlevel = 6, master = true },
},
desc = "Technicians are masters of equipment and tinkering. They use consumables almost instantly and can hack computer maps for tracking data.",
OnPick = function( being )
being.flags[ BF_INSTAUSE ] = true
being.flags[ BF_MAPEXPERT ] = true
being.flags[ BF_MODEXPERT ] = true
being.eq.weapon = "pistol"
being.inv:add( "ammo", { ammo = 20 } )
being.inv:add( "smed" )
being.inv:add( "smed" )
being.inv:add( "mod_tech" )
end
}
register_klass "soldat"
{
name = "Soldier",
char = "S",
hidden = true,
traits = {
{ id = "ironman", max = 5 },
{ id = "finesse", max = 3 },
{ id = "hellrunner", max = 3 },
{ id = "nails", max = 3 },
{ id = "bitch", max = 5 },
{ id = "gun", max = 5 },
{ id = "reloader", max = 3 },
{ id = "eagle", max = 5 },
{ id = "brute", max = 5 },
{ id = "juggler", requires = {{ "finesse", 1 }}, },
{ id = "berserker", requires = {{ "brute", 2 }}, },
{ id = "dualgunner", requires = {{ "gun", 2 }}, },
{ id = "dodgemaster", requires = {{ "hellrunner", 2 }}, },
{ id = "intuition", requires = {{ "eagle", 2 }}, max = 2 },
{ id = "shottyman", requires = {{ "reloader", 2 }}, },
{ id = "triggerhappy", requires = {{ "bitch", 2 }}, max = 2 },
{ id = "badass", requires = {{ "nails", 2 }}, max = 2 },
},
desc = "Soldiers are unnamed and unknown. You don't choose to be a soldier, you just are...",
OnPick = function( being )
being.eq.weapon = "pistol"
being.inv:add( "ammo", { ammo = 40 } )
being.inv:add( "smed" )
being.inv:add( "smed" )
end
}
end
| gpl-2.0 |
oralius/gto | plugins/welcome.lua | 5 | 5348 | ------------------------------------------
-- DBTeam DBTeam DBTeam DBTeam DBTeam ---
-- Welcome by @xxdamage ---
-- multilanguage and fix by@Jarriz ---
------------------------------------------
function chat_new_user(msg)
local name = msg.action.user.first_name:gsub('_', ' ')
local id = msg.action.user.id
if msg.action.user.username then
name = name
end
local chat = msg.to.print_name:gsub('_', ' ')
local receiver = get_receiver(msg)
local message = redis:get('welcome:'..msg.to.id)
local custom_message = message:gsub('$id', msg.action.user.id):gsub('$name', msg.action.user.first_name):gsub('$user', '@'..msg.action.user.username)
if not message then
return '😀 ' ..lang_text(msg.to.id, 'welcome1') ..name.. '! ' ..lang_text(msg.to.id, 'welcome2') ..chat..'!\n🆔 ' ..id
end
send_msg(receiver, custom_message, ok_cb, false)
end
local function wlc_enabled(msg)
local var = true
local hash = 'wlcstatus:'..msg.to.id
local cstatus = redis:get(hash)
if cstatus == 'off' then
var = false
end
return var
end
local function bye_enabled(msg)
local var = true
local hash = 'byestatus:'..msg.to.id
local cstatus = redis:get(hash)
if cstatus == 'off' then
var = false
end
return var
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == "chat_add_user" then
if not wlc_enabled(msg) then
return
end
return chat_new_user(msg)
elseif matches[1] == "chat_add_user_link" then
if not wlc_enabled(msg) then
return
end
local name = msg.from.first_name:gsub('_', ' ')
local chat = msg.to.print_name:gsub('_', ' ')
local message
if msg.from.username then
name = name
end
message = redis:get('welcome:'..msg.to.id)
if not message then
return '😀' ..lang_text(msg.to.id, 'welcome1') ..name.. '!' ..lang_text(msg.to.id, 'welcome2') ..chat..'!\n🆔 ' ..id
end
send_msg(receiver, message, ok_cb, false)
elseif matches[1] == "chat_del_user" then
if not bye_enabled(msg) then
return
end
local name = msg.action.user.first_name:gsub('_', ' ')
if msg.action.user.username then
name = name
end
local message = redis:get('bye:'..msg.to.id)
if not message then
return '😀 ' ..lang_text(msg.to.id, 'bye1') ..name.. '!' ..lang_text(msg.to.id, 'bye2')
end
send_msg(receiver, message, ok_cb, false)
elseif matches[1] == 'setwelcome' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
print(msg.to.id)
local hash = 'welcome:'..msg.to.id
redis:set(hash, matches[2])
return '✅ ' ..lang_text(msg.to.id, 'welnew') .. ': \n' ..matches[2]
elseif matches[1] == 'getwelcome' then
print(msg.to.id)
local hash = 'welcome:'..msg.to.id
local wel = redis:get(hash)
if not wel then
return 'ℹ️ ' ..lang_text(msg.to.id, 'weldefault')
end
return wel
elseif matches[1] == 'setbye' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return ' 🚫'..lang_text(msg.to.id, 'require_mod')
end
print(msg.to.id)
local hash = 'bye:'..msg.to.id
redis:set(hash, matches[2])
return '✅ ' ..lang_text(msg.to.id, 'newbye') .. ':\n'..matches[2]
elseif matches[1] == 'getbye' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return ' 🚫'..lang_text(msg.to.id, 'require_mod')
end
print(msg.to.id)
local hash = 'bye:'..msg.to.id
local wel = redis:get(hash)
if not wel then
return 'ℹ️ ' ..lang_text(msg.to.id, 'byedefault')
end
return wel
elseif matches[1] == 'welcome on' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return ' 🚫'..lang_text(msg.to.id, 'require_mod')
end
local hash = 'wlcstatus:'..msg.to.id
redis:set(hash, 'on')
return 'ℹ️ '..lang_text(msg.to.id, 'welon')
elseif matches[1] == 'welcome off' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return '🚫 '..lang_text(msg.to.id, 'require_mod')
end
local hash = 'wlcstatus:'..msg.to.id
redis:set(hash, 'off')
return 'ℹ️ '..lang_text(msg.to.id, 'weloff')
elseif matches[1] == 'bye on' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return ' 🚫'..lang_text(msg.to.id, 'require_mod')
end
local hash = 'byestatus:'..msg.to.id
redis:set(hash, 'on')
return 'ℹ️ '..lang_text(msg.to.id, 'byeon')
elseif matches[1] == 'bye off' then
if not permissions(msg.from.id, msg.to.id, "welcome") then
return ' 🚫'..lang_text(msg.to.id, 'require_mod')
end
local hash = 'byestatus:'..msg.to.id
redis:set(hash, 'off')
return 'ℹ️ '..lang_text(msg.to.id, 'byeoff')
end
end
return {
description = "Service plugin that sends a custom message when an user enters a chat.",
usage = "",
patterns = {
"^!!tgservice (chat_add_user)$",
"^!!tgservice (chat_del_user)$",
"^!!tgservice (chat_add_user_link)$",
"^[!/#](setwelcome) (.*)",
"^[!/#](getwelcome)",
"^[!/#](setbye) (.*)",
"^[!/#](getbye)",
"^[!/#](welcome on)",
"^[!/#](welcome off)",
"^[!/#](bye on)",
"^[!/#](bye off)"
},
run = run
}
| gpl-2.0 |
ForgedAddons/StayFocused_AutoShot | Config.lua | 1 | 2609 | local frame = CreateFrame("Frame", nil, InterfaceOptionsFramePanelContainer)
frame.name = "Auto Shot (plugin)"
frame.parent = "Stay Focused!"
frame:Hide()
local title, subtitle = LibStub("tekKonfig-Heading").new(frame, "|cffa0a0f0Stay Focused!|r Auto Shot", "Options for auto shot bar.")
local ICONSIZE, ICONGAP, GAP, EDGEGAP, BIGGAP = 32, 3, 8, 16, 16
local tekcheck = LibStub("tekKonfig-Checkbox")
local tekslide = LibStub("tekKonfig-Slider")
local show_text = tekcheck.new(frame, nil, "Show text", "TOPLEFT", subtitle, "BOTTOMLEFT", 0, -GAP)
local checksound = show_text:GetScript("OnClick")
show_text:SetScript("OnClick", function(self)
checksound(self);
StayFocusedAutoShot.db.show_text = not StayFocusedAutoShot.db.show_text
StayFocusedAutoShot:ApplyOptions()
end)
local frame_width, frame_width_l, frame_width_c = tekslide.new(frame, "Width", 50, 500, "TOPLEFT", show_text, "BOTTOMLEFT", 0, -BIGGAP)
frame_width:SetValueStep(5)
frame_width:SetScript("OnValueChanged", function(self, newvalue)
frame_width_l:SetText(string.format("Width: %d", newvalue))
StayFocusedAutoShot.db.width = newvalue
StayFocusedAutoShot:ApplyOptions()
end)
local frame_height, frame_height_l, frame_height_c = tekslide.new(frame, "Height", 1, 100, "TOPLEFT", frame_width_c, "TOPRIGHT", 4*GAP, 0)
frame_height:SetValueStep(1)
frame_height:SetScript("OnValueChanged", function(self, newvalue)
frame_height_l:SetText(string.format("Height: %d", newvalue))
StayFocusedAutoShot.db.height = newvalue
StayFocusedAutoShot:ApplyOptions()
end)
local font_size, font_size_l, font_size_c = tekslide.new(frame, "Font size", 6, 32, "TOPLEFT", frame_width_c, "BOTTOMLEFT", 0, -BIGGAP)
font_size:SetValueStep(1)
font_size:SetScript("OnValueChanged", function(self, newvalue)
font_size_l:SetText(string.format("Font size: %d", newvalue))
StayFocusedAutoShot.db.font_size = newvalue
StayFocusedAutoShot:ApplyOptions()
end)
local font_outline = tekcheck.new(frame, nil, "Font Outline", "TOPLEFT", font_size_c, "TOPRIGHT", 4*GAP, 0)
font_outline:SetScript("OnClick", function(self)
checksound(self);
StayFocusedAutoShot.db.font_outline = not StayFocusedAutoShot.db.font_outline
StayFocusedAutoShot:ApplyOptions()
end)
frame:SetScript("OnShow", function(frame)
show_text:SetChecked(StayFocusedAutoShot.db.show_text)
font_size:SetValue(StayFocusedAutoShot.db.font_size)
font_outline:SetChecked(StayFocusedAutoShot.db.font_outline)
frame_width:SetValue(StayFocusedAutoShot.db.width)
frame_height:SetValue(StayFocusedAutoShot.db.height)
end)
StayFocusedAutoShot.configframe = frame
InterfaceOptions_AddCategory(frame) | apache-2.0 |
samueljackson92/scripts | love/roguelike/gui/gui.lua | 1 | 1075 | GUI =
{
fonts =
{
DEFAULT = love.graphics.getFont(),
MAIN_HEADING = love.graphics.newFont("images/GODOFWAR.TTF", 50),
MENU_LARGE = love.graphics.newFont("images/GODOFWAR.TTF", 20),
MAIN_SUBHEADING = love.graphics.newFont("images/MORPHEUS.TTF", 20),
},
}
-- Basic UI Components
require "gui/guicomponent.lua"
require "gui/panel.lua"
require "gui/label.lua"
require "gui/button.lua"
--Complex UI Components
require "gui/menus/mainmenu.lua"
require "gui/menus/hud.lua"
require "gui/menus/inventory.lua"
function GUI:init()
MainMenu:init()
HUD:init()
Inventory:init()
end
function GUI:draw()
if Game.MAIN_MENU then
MainMenu:drawComponents()
else
HUD:drawComponents()
Inventory:drawComponents()
end
end
function GUI:doEvents(e)
if Game.MAIN_MENU then
MainMenu:doEvents(e)
else
if e == "i" then
Inventory:toggleVisible()
end
HUD:doEvents(e)
Inventory:doEvents(e)
end
end
function GUI:setColour(tbl)
love.graphics.setColor(tbl[1], tbl[2], tbl[3], tbl[4])
end
function GUI:clearColour()
love.graphics.setColor(255, 255, 255, 255)
end
| mit |
raziel-carvajal/splay-daemon | src/lua/modules/splay/urpc.lua | 2 | 13616 | --[[
Splay ### v1.3 ###
Copyright 2006-2011
http://www.splay-project.org
]]
--[[
This file is part of Splay.
Splay 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.
Splay 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 Splayd. If not, see <http://www.gnu.org/licenses/>.
]]
--[[
UDP based RPC
-------------
Pros:
- Faster than TCP
- Only one socket used, both for receiving and sending
Cons:
- Limited size of RPC (8k)
- Limited fault tolerance (we include a timeout and retry system)
- Adaptative retry
- Response caching
- Host to IP resolution
- Detect and report call size problem (max 8k)
DATAGRAM
--------
=>
key (~ 30 octets)
type = call || ping
[call] = array with function call
[source_ip]
[source_port]
<=
reply
key
type = call || ping
[call] = array with function call results
[error] = size error...
(try to free memory before timeout, 1 more packet but less CPU computation)
=>
free
key
NOTE:
First, we set a default socket that will permit us to send RPC (and receive
the replies). This default server will always run once with have done an RPC
call (but no one will use it to contact us since it is on a random unknown
port). Then, calling server(port), we will setup an additionnal server, on a
specific port this time. The default socket, will still be used to send and
receive RPC done by this host.
setsockname must be called (in server()) before sending any UDP messages.
If not, a free port will be taken and it will not be possible to bind it
anymore on the choosen port (or use 2 socket).
When re-sending an UDP RPC, we will keep the same key. The server will cache
the response it send for a key the first time and reuse that value. Old reply
values will be cleaned. That way, we avoid calling again a function.
Once we have received the reply, we will fire en event with the reply key: or
is the first reply and the function is still waiting for it, or this is not
the first and nobody wait for that event.
The fact that we run a local server if no server is defined, will generate a
warning "receivefrom(): nil refused" when we launch another local server
because the previous socket waiting is closed.
]]
local math = require"math"
local string = require"string"
local crypto = require"crypto"
local events = require"splay.events"
local socket = require"splay.socket"
--local enc = require"json"
local enc = require"splay.benc"
local misc = require"splay.misc"
local log = require"splay.log"
local error = error
local pairs = pairs
local pcall = pcall
local print = print
local setmetatable = setmetatable
local tostring = tostring
local type = type
local unpack = unpack
local tonumber = tonumber
--module("splay.urpc")
local _M = {}
_M._COPYRIGHT = "Copyright 2006 - 2011"
_M._DESCRIPTION = "UDP RPC"
_M._VERSION = 1.0
_M._NAME = "splay.urpc"
--[[ DEBUG ]]--
_M.l_o = log.new(3, "[".._M._NAME.."]")
_M.settings = {
max = nil, -- max outgoing RPCs
default_timeout = 40,
retry_number = 2,
cleaning_after = 120, -- max timeout = 0.9 * cleaning_after
cleaning_interval = 5,
try_free = true -- send an aditional message to free the cache
}
_M.mode = "urpc"
local number = 0
local call_s = nil
local sockets = {}
local replied = {} -- store reply and their values (server)
local messages = {} -- messages to send or resend (still not replied)
local server_run = false
local server_port = nil --assigned when unconnected->connected
local base_key = nil
local c = 0
function _M.get_key(seed)
if not base_key then
base_key = crypto.evp.new("sha1"):digest(math.random()..tostring(seed))
end
c = c + 1
return base_key..c
end
function _M.stats()
return number
end
function _M.infos()
return "Number of RPCs: "..number
end
local function clean_replied()
local now = misc.time()
for key, d in pairs(replied) do
-- If we clean the entry too soon, we will maybe still receive a msg for
-- that function call. If the entry is cleaned, we need to call the
-- function again, that in most cases is not wanted.
if _M.settings.cleaning_after and d.time + _M.settings.cleaning_after < now then
--l_o:debug("CLEANING", key)
replied[key] = nil
end
end
end
-- server function
local function reply(s, data, ip, port)
local reply_s
-- could permit a special routing, normally data.source_* is not set
if data.source_ip and data.source_port then
ip, port = data.source_ip, data.source_port
data.source_ip, data.source_port = nil, nil
end
data.reply = true
-- For type "ping", nothing more to do
if data.type == "call" then
if not replied[data.key] then
--l_o:debug("call()", data.key)
local val = misc.call(data.call)
-- TODO good error report
if val == nil then val = {nil} end
replied[data.key] = {val = val, time = misc.time()}
end
data.call = replied[data.key].val
reply_s = enc.encode(data)
local length = #reply_s
if length > 8192 then
data.call = nil
data.error = "reply length ("..length..")"
-- we were optimistic, we need to reencode now...
reply_s = enc.encode(data)
_M.l_o:warning("reply(): too much data")
end
else
reply_s = enc.encode(data)
end
local ok, err = s:sendto(reply_s, ip, port)
if not ok then
_M.l_o:warn("sendto(): "..err)
end
end
local function process_one_msg(s, data, ip, port)
local ok, data = pcall(function() return enc.decode(data) end)
if ok then
if data.reply then -- we have received a reply
messages[data.key] = nil
if _M.settings.try_free then
s:sendto(enc.encode({free = true, key = data.key}), ip, port)
end
return events.fire("urpc:"..data.key, data)
elseif data.free then -- we have received a free packet
replied[data.key] = nil
else
return reply(s, data, ip, port)
end
else
_M.l_o:warn("corrupted message")
end
end
--[[ Thread that will send or resend RPC ]]--
local function sender(s)
while true do
--_M.l_o:debug("sender() loop")
local q = {}
local now, next_wakeup = misc.time()
for key, data in pairs(messages) do
if data.next_try <= now then
--_M.l_o:debug("try", data.nb_try, data.key)
-- add to the send queue
q[#q + 1] = misc.dup(data)
data.nb_try = data.nb_try + 1
data.next_try = now + (data.timeout / (_M.settings.retry_number + 1))
if data.nb_try >= _M.settings.retry_number then
messages[key] = nil
else
if not next_wakeup or data.next_try < next_wakeup then
next_wakeup = data.next_try
end
end
else
if not next_wakeup or data.next_try < next_wakeup then
next_wakeup = data.next_try
end
end
end
if #q > 0 then
for _, data in pairs(q) do
-- sending
s:sendto(data.enc, data.ip, data.port)
-- unconnected->connected
local ip,port = s:getsockname()
server_port=port
sockets[server_port]=s -- to be able to close it later
end
q = {}
end
if next_wakeup then
--_M.l_o:debug("wait", next_wakeup - now)
events.wait("urpc:sender", next_wakeup - now)
else
--_M.l_o:debug("wait")
events.wait("urpc:sender")
end
end
end
local function receiver(s)
while true do
local data, ip, port = s:receivefrom()
if data then
events.thread(function()
process_one_msg(s, data, ip, port)
end)
else
if ip == "timeout" then
_M.l_o:warn("receivefrom(): "..ip)
else
_M.l_o:notice("receivefrom(): server closed")
break
end
end
end
end
-- To enable an additional RPC server on a specific port
function _M.server(port)
local ip="*" --bind on all IPs on this machine
if type(port) == 'table' and port.port then
if port.ip then ip=port.ip end
port = port.port
end
--verify conflicts with default_server's port
local default_to_restart=false
if port==server_port then
server_run=false
default_to_restart=true
sockets[server_port]:close()
sockets[server_port]=nil
end
local s, err = socket.udp()
if not s then
_M.l_o:warn("udp():"..err)
return nil, err
end
_M.l_o:notice("URPC server bound on port "..port)
local r, err = s:setsockname(ip, port)
if not r then
_M.l_o:warn("setsockname("..port.."): "..err)
return nil, err
end
sockets[port] = s -- to be able to close it later
events.thread(function() receiver(s) end)
--if the default server was stopped due to port conflict, restart it
if default_to_restart then _M.default_server() end
return true
end
function _M.stop_server(port)
if sockets[port] then
sockets[port]:close()
sockets[port] = nil
end
end
--[[ To enable our local RPC UDP server ]]--
function _M.default_server()
local s, err = socket.udp()
if not s then
_M.l_o:warn("udp():"..err)
return nil, err
end
events.thread(function() sender(s) end)
events.thread(function() receiver(s) end)
events.periodic(_M.settings.cleaning_interval, clean_replied)
server_run = true
end
-- return: true|false, array of responses
local function do_call(ip, port, typ, call, timeout)
-- If no server runs, we need a default server (binded on a port choosen by
-- the system to be able to receive replies for our rpcs)
if not server_run then _M.default_server() end
if _M.settings.max and not call_s then
call_s = events.semaphore(_M.settings.max)
end
timeout = timeout or _M.settings.default_timeout
if (timeout and _M.settings.cleaning_after and
timeout > _M.settings.cleaning_after * 0.9) or
(not timeout and _M.settings.cleaning_after) then
_M.l_o:warn("do_call adjusted timeout", timeout)
timeout = _M.settings.cleaning_after * 0.9
end
local datac = {key = _M.get_key()}
if typ == "ping" then
datac.type = "ping"
else
datac.type = "call"
datac.call = call
end
local edatac = enc.encode(datac)
local l = #edatac
if l > 8192 then
_M.l_o:warn("RPC UDP too big to be sent: "..l)
return nil, "call length ("..l..")"
end
local data = {
enc = edatac,
key = datac.key,
type = datac.type,
next_try = misc.time(),
nb_try = 0,
ip = ip,
port = port,
timeout = timeout,
}
datac = nil
local start_time = misc.time()
if call_s then
if not call_s:lock(timeout) then
return false, "local timeout"
end
-- update timeout
if timeout then
timeout = timeout - (misc.time() - start_time)
-- normally not possible here since lock() don't returns on timeout
if timeout <= 0 then
return false, "local timeout"
end
end
end
number = number + 1
-- we store our new message in the send queue
messages[data.key] = data
-- wake up sender thread
events.fire("urpc:sender")
local ok, reply
if timeout then
ok, reply = events.wait("urpc:"..data.key, timeout)
else
ok = true
reply = events.wait("urpc:"..data.key, timeout)
end
if call_s then call_s:unlock() end
if not ok then
return false, "timeout"
elseif reply.error then
return false, reply.error
elseif reply.type == "ping" then
return true, {true}
else
return true, reply.call
end
end
--------------------[[ HIGH LEVEL FUNCTIONS ]]--------------------
-- return: true|false, array of responses
function _M.acall(ip, port, call, timeout)
-- support for a node array with ip and port
if type(ip) == "table" then
if not ip.ip or not ip.port then
_M.l_o:warn("parameter array without ip or port")
return false, "parameter array without ip or port"
else
timeout = call
call = port
port = ip.port
ip = ip.ip
end
end
if timeout ~=nil and tonumber(timeout)==nil then
_M.l_o:warn("invalid timeout value: ",timeout)
return false, "invalid timeout value: "..timeout
end
if type(call) ~= "table" then
call = {call}
end
return do_call(ip, port, "call", call, timeout)
end
-- DEPRECATED
--function a_call(...) return acall(...) end
function _M.ecall(ip, port, func, timeout)
local ok, r = _M.acall(ip, port, func, timeout)
if ok then
return unpack(r)
else
error(r)
end
end
-- To be used when we are sure that all the rpc reply return something other
-- than nil, then nil will indicate and error. The best way to do is to use
-- acall() and then unpack the second return values or use it as an array.
function _M.call(ip, port, func, timeout)
local ok, r = _M.acall(ip, port, func, timeout)
if ok then
return unpack(r)
else
return nil, r
end
end
-- RPC ping
function _M.ping(ip, port, timeout)
-- support for a node array with ip and port
if type(ip) == "table" and ip.ip and ip.port then
timeout = port
port = ip.port
ip = ip.ip
end
local t = misc.time()
local ok, r = do_call(ip, port, "ping", nil, timeout)
if ok then
return misc.time() - t
else
return nil, r
end
end
--[[ Create an RPC proxy object
You can then call functions on that object with the classical notation:
o = rpc.proxy(node)
o:remote_function(arg1, arg2)
]]
function _M.proxy(ip, port)
local p = {}
if type(ip) == "table" then
p.port = ip.port
p.ip = ip.ip
else
p.port = port
p.ip = ip
end
p.timeout = _M.settings.default_timeout
p.ping = function(self)
return _M.ping(self, self.timeout)
end
setmetatable(p,
{__index = function(t, func)
-- if __index is called, timeout == nil
if func == "timeout" then return nil end
return function(self, ...)
return _M.ecall(self, {func, unpack(arg)}, self.timeout)
end
end})
return p
end
return _M | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Dynamis-Xarcabard/mobs/Icon_Prototype.lua | 2 | 1391 | -----------------------------------
-- Area: Dynamis Xarcabard
-- NPC: Icon Prototype
-----------------------------------
package.loaded["scripts/zones/Dynamis-Xarcabard/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/dynamis");
require("scripts/zones/Dynamis-Xarcabard/TextIDs");
-----------------------------------
-- onMobInitialize Action
-----------------------------------
function onMobInitialize(mob,target)
end;
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
-- Time Bonus: 043
if(mobID == 17330814 and mob:isInBattlefieldList() == false) then
killer:addTimeToDynamis(30);
mob:addInBattlefieldList();
-- HP Bonus: 052
elseif(mobID == 17330533) then
killer:restoreHP(2000);
killer:messageBasic(024,(killer:getMaxHP()-killer:getHP()));
-- HP Bonus: 073
elseif(mobID == 17330843) then
killer:restoreMP(2000);
killer:messageBasic(025,(killer:getMaxMP()-killer:getMP()));
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/globals/items/bowl_of_pea_soup.lua | 1 | 1338 | -----------------------------------------
-- ID: 4416
-- Item: bowl_of_pea_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- Vitality -1
-- Agility 1
-- Ranged Accuracy 5
-- HP Recovered While Healing 3
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,4416);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 1);
target:addMod(MOD_RACC, 5);
target:addMod(MOD_HPHEAL, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 1);
target:delMod(MOD_RACC, 5);
target:delMod(MOD_HPHEAL, 3);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Kazham/Zone.lua | 4 | 1292 | -----------------------------------
--
-- Zone: Kazham (250)
--
-----------------------------------
-----------------------------------
-- 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
if (prevZone == 226) then
cs = 0x2712;
end
player:setPos(-4.000, -3.000, 14.000, 66);
end
return cs;
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
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 (csid == 0x2710) then
player:setPos(0,0,0,0,226);
end
end;
| gpl-3.0 |
mohammadjkh/PowerTeam | plugins/extra.lua | 1 | 4021 | local action = function(msg, blocks, ln)
if msg.chat.type == 'private' then return end
if blocks[1] == 'extra' then
if not is_mod(msg) then return end
if not blocks[2] then return end
if not blocks[3] and not msg.reply then return end
if msg.reply and not blocks[3] then
local file_id, media_with_special_method = get_media_id(msg.reply)
if not file_id then
return
else
local to_save
if media_with_special_method then --photo, voices, video need their method to be sent by file_id
to_save = '###file_id!'..media_with_special_method..'###:'..file_id
else
to_save = '###file_id###:'..file_id
end
db:hset('chat:'..msg.chat.id..':extra', blocks[2], to_save)
api.sendReply(msg, 'This media has been saved as response to '..blocks[2])
end
else
local hash = 'chat:'..msg.chat.id..':extra'
local res, code = api.sendReply(msg, blocks[3], true)
if not res then
if code == 118 then
api.sendMessage(msg.chat.id, lang[ln].bonus.too_long)
else
api.sendMessage(msg.chat.id, lang[ln].breaks_markdown, true)
end
else
db:hset(hash, blocks[2], blocks[3])
local msg_id = res.result.message_id
api.editMessageText(msg.chat.id, msg_id, make_text(lang[ln].extra.setted, blocks[2]), false)
end
end
mystat('!extra')
elseif blocks[1] == 'extra list' then
if not is_mod(msg) then return end
local hash = 'chat:'..msg.chat.id..':extra'
local commands = db:hkeys(hash)
local text = ''
if commands[1] == nil then
api.sendReply(msg, lang[ln].extra.no_commands)
else
for k,v in pairs(commands) do
text = text..v..'\n'
end
local out = make_text(lang[ln].extra.commands_list, text)
api.sendReply(msg, out, true)
end
mystat('!extra list')
elseif blocks[1] == 'extra del' then
if not is_mod(msg) then return end
local hash = 'chat:'..msg.chat.id..':extra'
local success = db:hdel(hash, blocks[2])
if success == 1 then
local out = make_text(lang[ln].extra.command_deleted, blocks[2])
api.sendReply(msg, out)
else
local out = make_text(lang[ln].extra.command_empty, blocks[2])
api.sendReply(msg, out)
end
mystat('!extra del')
else
local hash = 'chat:'..msg.chat.id..':extra'
local text = db:hget(hash, blocks[1])
if not text then return end
local file_id = text:match('^###.+###:(.*)')
local special_method = text:match('^###file_id!(.*)###') --photo, voices, video need their method to be sent by file_id
if is_locked(msg, 'Extra') and not is_mod(msg) then --send it in private
if not file_id then
api.sendMessage(msg.from.id, text, true)
else
if special_method then
api.sendMediaId(msg.from.id, file_id, special_method) --photo, voices, video need their method to be sent by file_id
else
api.sendDocumentId(msg.from.id, file_id)
end
end
else
local msg_to_reply
if msg.reply then
msg_to_reply = msg.reply.message_id
else
msg_to_reply = msg.message_id
end
if file_id then
if special_method then
api.sendMediaId(msg.chat.id, file_id, special_method, msg_to_reply) --photo, voices, video need their method to be sent by file_id
else
api.sendDocumentId(msg.chat.id, file_id, msg_to_reply)
end
else
api.sendMessage(msg.chat.id, text, true, msg_to_reply) --if the mod replies to an user, the bot will reply to the user too
end
end
mystat('!extra command')
end
end
return {
action = action,
triggers = {
'^!(extra)$',
'^!(extra) (#[%w_]*)%s(.*)$',
'^!(extra) (#[%w_]*)',
'^!(extra del) (#[%w_]*)$',
'^!(extra list)$',
'^(#[%w_]*)$'
}
} | gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Sauromugue_Champaign/npcs/qm3.lua | 4 | 1464 | -----------------------------------
-- Area: Sauromugue Champaign
-- NPC: qm3 (Tower 3)
-- Type: Standard NPC
--
-- THF Quest "As Thick As Thieves"
-- @zone: 120
-- @where x414, y16, z-131
-----------------------------------
package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/quests");
require("scripts/globals/keyitems");
require("scripts/zones/Sauromugue_Champaign/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
thickAsThieves = player:getQuestStatus(WINDURST,AS_THICK_AS_THIEVES);
thickAsThievesGrapplingCS = player:getVar("thickAsThievesGrapplingCS");
if(thickAsThievesGrapplingCS == 3) then
SpawnMob(17269107,120):updateEnmity(player); -- Climbpix Highrise
setMobPos(17269107,414,16,-131,0);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
-- printf("CSID: %u",csid);
-- printf("RESULT: %u",option);
end; | gpl-3.0 |
xia-lixun/libvsthostm | Trunk/hetero/Release/host.lua | 1 | 6674 | --#!/bin/lua
--configurations for simple vst host
--lixun.2016
---------------------------------------
-- OBS! DON'T TOUCH SECTION BELOW! --
---------------------------------------
GlobalModuleCount = 0 --13
InputModuleSize = 0 --2
OutputModuleSize = 0 --2
PluginModuleSize = 0 --9
InputModule = {} --module index {1, 2}
OutputModule = {} --module index {12, 13}
PluginModule = {} --moudle index {3, 4, 5, 6, 7, 8, 9, 10, 11}
InputModuleFile = {} --{1={"L-1.wav","L-2.wav"...}, 2={"R-1.wav", "R-2.wav"...}}
OutputModuleFile = {} --{12={"A-1.wav","A-2.wav"...}, 13={"B-1.wav","B-2.wav"...}}
OutputModuleBitsPerSample = {} --{12=24, 13=32}
PluginModuleDLL = {} --{3="biquad-1.dll", 4="biquad-2.dll" ... 11="AEC.dll"}
PluginModuleParam = {} --{3={...}, 4={...}, ... 11={...}}
ModuleNumInputs = {} --{0, 0, 2, 2, 2, 2, 8, 7, 9, 8, 2, 2, 4}
ModuleNumOutputs = {} --{8, 8, 2, 2, 2, 2, 21, 8, 9, 21, 2, 0, 0}
TotalConnectionCount = 0;
FromModule = {}
ToModule = {}
FromPin = {}
ToPin = {}
function TableLength(T)
local count = 0
for _ in pairs(T) do count = count + 1 end
return count
end
function Module(t)
GlobalModuleCount = GlobalModuleCount + 1
if t.numInputs == 0 then --case of input module
InputModuleSize = InputModuleSize + 1
table.insert(InputModule, GlobalModuleCount)
InputModuleFile[GlobalModuleCount] = {}
for i,v in ipairs(t) do
table.insert(InputModuleFile[GlobalModuleCount], v)
end
elseif t.numOutputs == 0 then --case of output module
OutputModuleSize = OutputModuleSize + 1
table.insert(OutputModule, GlobalModuleCount)
OutputModuleFile[GlobalModuleCount] = {}
for i,v in ipairs(t) do
table.insert(OutputModuleFile[GlobalModuleCount], v)
end
OutputModuleBitsPerSample[GlobalModuleCount] = t.bitsPerSample
else --case of vst plugin module
PluginModuleSize = PluginModuleSize + 1
table.insert(PluginModule, GlobalModuleCount)
PluginModuleDLL[GlobalModuleCount] = t.location
PluginModuleParam[GlobalModuleCount] = t.params
end
table.insert(ModuleNumInputs, t.numInputs)
table.insert(ModuleNumOutputs, t.numOutputs)
end
function Map(t)
for i,v in ipairs(t) do
table.insert(FromModule, v[1][1])
table.insert(ToModule, v[2][1])
table.insert(FromPin, v[1][2])
table.insert(ToPin, v[2][2])
TotalConnectionCount = TotalConnectionCount + 1
end
end
---------------------------------------
-- section for host configurations --
---------------------------------------
--[1] plugin 1 is always the input
--[2] plugin[#plugin] is always the output
--[3] the rest plugins are arranged in sequence
Host={
HostSampleRate = 44100,
BlockSize = 64
}
-------------------------------------
-- section for input wav vectors --
-- only one input module allowed --
-------------------------------------
--1
Module{
numInputs = 0,
numOutputs = 8,
--put all input vectors here
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-L.wav",
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-L.wav"
}
--2
Module{
numInputs = 0,
numOutputs = 8,
--put all input vectors here
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-R.wav",
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-R.wav"
}
-------------------------------------
-- section for signal processing --
-------------------------------------
--3
Module{
location = "Biquad-1.dll",
numInputs = 2,
numOutputs = 2,
params = {0.369, 0.5, 0.091, 0.118}
}
--4
Module{
location = "Biquad-2.dll",
numInputs = 2,
numOutputs = 2,
params = {0.369, 0.5, 0.091, 0.118}
}
--5
Module{
location = "Biquad-3.dll",
numInputs = 2,
numOutputs = 2,
params = {0.369, 0.5, 0.091, 0.118}
}
--6
Module{
location = "Biquad-4.dll",
numInputs = 2,
numOutputs = 2,
params = {0.369, 0.5, 0.091, 0.118}
}
--7
Module{
location = "Aec.dll",
numInputs = 8,
numOutputs = 21,
params = {0.0, 0.50485438108444, 0.02912621386349, 0.39823007583618, 0.49599999189377, 0.00999999977648, 0.31000000238419, 1.0, 1.0, 0.30000001192093, 0.13203883171082, 0.89999997615814}
}
--8
Module{
location = "FixedBeamFormer.dll",
numInputs = 7,
numOutputs = 8,
params = {0.0, 0.89657139778137, 0.45800003409386}
}
--9
Module{
location = "BeamSteering.dll",
numInputs = 9,
numOutputs = 9,
params = {0.0, 0.22599999606609, 0.82792788743973, 0.54981982707977, 0.07199999690056, 0.48800000548363, 0.33329999446869, 0.5, 1.0, 0.10300000011921, 0.5}
}
--10
Module{
location = "AecPlus.dll",
numInputs = 8,
numOutputs = 21,
params = {0.0, 0.50485438108444, 0.02912621386349, 0.39823007583618, 0.49599999189377, 0.00999999977648, 0.31000000238419, 1.0, 1.0, 0.30000001192093, 0.13203883171082, 0.89999997615814}
}
--11
Module{
location = "AdaptiveBeamFormer.dll",
numInputs = 2,
numOutputs = 2,
params = {0.0, 1.0, 0.00999999977648, 0.5, 0.89099997282028, 0.86900001764297, 0.82899999618530, 0.69999998807907, 0.89999997615814}
}
------------------------------------
-- section for signal recording --
------------------------------------
--12
Module{
numInputs = 2,
numOutputs = 0,
bitsPerSample = 32,
--put all resultant files here
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-Out-1.wav",
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-Out-2.wav"
}
--13
Module{
numInputs = 8,
numOutputs = 0,
bitsPerSample = 24,
--put all resultant files here
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-Dbg-1.wav",
"D:/Git/libvsthostm/Trunk/hetero/Release/MicIn5min-Dbg-2.wav"
}
----------------------------------
-- section for signal routing --
----------------------------------
Map{
--{{module,portout}, {module,portin}}
--wavplay to biquad
{{1,1}, {3,1}},
{{1,2}, {3,2}},
{{1,3}, {4,1}},
{{1,4}, {4,2}},
{{2,5}, {5,1}},
{{2,6}, {5,2}},
{{2,7}, {6,1}},
{{2,8}, {6,2}},
--biquad to aec
{{3,1}, {7,1}},
{{3,2}, {7,2}},
{{4,1}, {7,3}},
{{4,2}, {7,4}},
{{5,1}, {7,5}},
{{5,2}, {7,6}},
{{6,1}, {7,7}},
{{6,2}, {7,8}},
--aec to fixed beam former
{{7,8}, {8,1}},
{{7,9}, {8,2}},
{{7,10}, {8,3}},
{{7,11}, {8,4}},
{{7,12}, {8,5}},
{{7,13}, {8,6}},
{{7,14}, {8,7}},
--fixed beam former to beam steering
{{8,1}, {9,1}},
{{8,2}, {9,2}},
{{8,3}, {9,3}},
{{8,4}, {9,4}},
{{8,5}, {9,5}},
{{8,6}, {9,6}},
{{8,7}, {9,7}},
{{8,8}, {9,8}},
{{9,3}, {10,2}},
{{1,1}, {10,1}},
{{10,8}, {11,1}},
{{9,4}, {11,2}},
{{11,1}, {12,1}},
{{11,2}, {12,2}},
--inspection channels
{{8,1}, {13,1}},
{{8,2}, {13,2}},
{{8,3}, {13,3}},
{{8,4}, {13,4}},
{{8,5}, {13,5}},
{{8,6}, {13,6}},
{{8,7}, {13,7}},
{{8,8}, {13,8}}
}
| mit |
sinaw1/igroup | plugins/owners.lua | 284 | 12473 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
alikineh/ali_kineh | plugins/boobs.lua | 731 | 1601 | 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
| gpl-2.0 |
Fatalerror66/ffxi-a | scripts/zones/Dynamis-Windurst/npcs/qm1.lua | 2 | 1228 | -----------------------------------
-- Area: Dynamis Windurst
-- NPC: ??? (Spawn when mega is defeated)
-----------------------------------
package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/keyitems");
require("scripts/zones/Dynamis-Windurst/TextIDs");
-----------------------------------
-- onTrade
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger
-----------------------------------
function onTrigger(player,npc)
if(player:hasKeyItem(HYDRA_CORPS_LANTERN) == false)then
player:setVar("DynaWindurst_Win",1);
player:addKeyItem(HYDRA_CORPS_LANTERN);
player:messageSpecial(KEYITEM_OBTAINED,HYDRA_CORPS_LANTERN);
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/globals/weaponskills/backhand_blow.lua | 6 | 1226 | -----------------------------------
-- Backhand Blow
-- Hand-to-Hand weapon skill
-- Skill Level: 100
-- Deals params.critical damage. Chance of params.critical hit varies with TP.
-- Aligned with the Breeze Gorget.
-- Aligned with the Breeze Belt.
-- Element: None
-- Modifiers: STR:30% ; DEX:30%
-- 100%TP 200%TP 300%TP
-- 1.00 1.00 1.00
-----------------------------------
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function OnUseWeaponSkill(player, target, wsID)
local params = {};
params.numHits = 1;
params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1;
params.str_wsc = 0.3; params.dex_wsc = 0.3; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.crit100 = 0.4; params.crit200 = 0.6; params.crit300 = 0.8;
params.canCrit = true;
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/Port_Jeuno/npcs/_6u8.lua | 4 | 1512 | -----------------------------------
-- Area: Port Jeuno
-- NPC: Door: Departures Exit (for Kahzam)
-- @zone 246
-- @pos -12 8 54
-----------------------------------
package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Port_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
KazhPass = player:hasKeyItem(AIRSHIP_PASS_FOR_KAZHAM);
Gil = player:getGil();
if(KazhPass == false) then
player:startEvent(0x0023); -- without pass
elseif(KazhPass == true and Gil < 200) then
player:startEvent(0x002d); -- Pass without money
elseif(KazhPass == true) then
player:startEvent(0x0025); -- Pass with money
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);
if(csid == 0x0025) then
Z = player:getZPos();
if(Z >= 58 and Z <= 61) then
player:delGil(200);
end
end
end; | gpl-3.0 |
FilthyPeasantDEV/PokeBot | BizHawk-1.11.6/Lua/SNES/Contra 3.lua | 7 | 3522 | ----------------------------------------------
-----Contra III hitbox viewer script SNES-----
----------------------------------------------
--Player Colors:
--Gold = Invuln
--Blue = Vulnerable
--Enemy colors:
--Red = Can be touched and hit with projectiles
--Green = Can be hit with projectiles but has no collision
--Yellow = Can touch you, cannot be hit with player projectiles
--White Axis in middle of box = Box is invulnerable
local xm
local ym
function findbit(p)
return 2 ^ (p - 1)
end
function hasbit(x, p)
return x % (p + p) >= p
end
local function check_offscreen(pos,val)
if val ~= 0 then
if val == 1 then
pos = 255 + pos
elseif val == 255 then
pos = 0 -(255 - pos)
end
end
return pos
end
local function draw_invuln(x,y,xrad,yrad)
gui.drawLine(x + (xrad / 2), y, x + (xrad / 2), y + yrad,0xFFFFFFFF)
gui.drawLine(x, y + (yrad / 2), x + xrad, y + (yrad / 2),0xFFFFFFFF)
end
local function Player()
local pbase = 0x200
for i = 0,1,1 do
pbase = pbase + (i * 0x40)
local x = mainmemory.read_u8(pbase + 6)
local y = mainmemory.read_u8(pbase + 0x10)
local x2 = mainmemory.read_u8(pbase + 0x28)
local y2 = mainmemory.read_u8(pbase + 0x2A)
local x_offscreen = mainmemory.read_u8(pbase + 0x7)
local y_offscreen = mainmemory.read_u8(pbase + 0x11)
local x2_offscreen = mainmemory.read_u8(pbase + 0x29)
local y2_offscreen = mainmemory.read_u8(pbase + 0x2B)
local active = mainmemory.read_u8(pbase + 0x16)
-- Checks if the box went off screen and adjusts
x = check_offscreen(x,x_offscreen)
x2 = check_offscreen(x2,x2_offscreen)
y = check_offscreen(y,y_offscreen)
y2 = check_offscreen(y2,y2_offscreen)
if active > 0 then
if hasbit(active,findbit(2)) == true or mainmemory.read_u16_le(0x1F88 + (i * 0x40)) > 0 then
gui.drawBox(x,y,x2,y2,0xFFFDD017,0x35FDD017)
else
gui.drawBox(x,y,x2,y2,0xFF0000FF,0x350000FF)
end
end
end
end
local function Enemies()
local start = 0x280
local base = 0
local oend = 32
local x
local x_offscreen
local y
local y_offscreen
local xrad
local yrad
local active
local touch
local projectile
local invuln
local hp
for i = 0,oend,1 do
base = start + (i * 0x40)
active = mainmemory.read_u8(base + 0x16)
hp = mainmemory.read_s16_le(base + 6)
if active > 0 then
touch = hasbit(active,findbit(4))
projectile = hasbit(active,findbit(5))
invuln = hasbit(active,findbit(6))
x = mainmemory.read_u8(base + 0xa)
x_offscreen = mainmemory.read_u8(base + 0xb)
y = mainmemory.read_u8(base + 0xe)
y_offscreen = mainmemory.read_u8(base + 0xf)
xrad = mainmemory.read_s16_le(base+0x28)
yrad = mainmemory.read_s16_le(base+0x2A)
-- Checks if the box went off screen and adjusts
x = check_offscreen(x,x_offscreen)
y = check_offscreen(y,y_offscreen)
if projectile and touch then
gui.drawBox(x,y,x+ xrad,y+yrad,0xFFFF0000,0x35FF0000)
elseif projectile then
gui.drawBox(x,y,x + xrad,y+yrad,0xFF00FF00,0x3500FF00)
elseif touch then
gui.drawBox(x,y,x + xrad,y + yrad,0xFFFFFF00,0x35FFFF00)
end
if hp > 0 and invuln == false then
gui.text((x-5) * xm,(y-5) * ym,"HP: " .. hp)
end
if invuln then
draw_invuln(x,y,xrad,yrad)
end
end
end
end
local function scaler()
xm = client.screenwidth() / 256
ym = client.screenheight() / 224
end
while true do
scaler()
local stage = mainmemory.read_u8(0x7E0086)
if stage ~= 2 and stage ~= 5 then
Player()
Enemies()
end
emu.frameadvance()
end | mit |
Fatalerror66/ffxi-a | scripts/zones/Windurst_Woods/npcs/Mheca_Khetashipah.lua | 5 | 1047 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Mheca Khetashipah
-- Type: Standard NPC
-- @zone: 241
-- @pos: 66.881 -6.249 185.752
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x01aa);
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/bowl_of_riverfin_soup.lua | 36 | 1822 | -----------------------------------------
-- ID: 6069
-- Item: Bowl of Riverfin Soup
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- Accuracy % 14 Cap 90
-- Ranged Accuracy % 14 Cap 90
-- Attack % 18 Cap 80
-- Ranged Attack % 18 Cap 80
-- Amorph Killer 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,10800,6069);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_ACCP, 14);
target:addMod(MOD_FOOD_ACC_CAP, 90);
target:addMod(MOD_FOOD_RACCP, 14);
target:addMod(MOD_FOOD_RACC_CAP, 90);
target:addMod(MOD_FOOD_ATTP, 18);
target:addMod(MOD_FOOD_ATT_CAP, 80);
target:addMod(MOD_FOOD_RATTP, 18);
target:addMod(MOD_FOOD_RATT_CAP, 80);
target:addMod(MOD_AMORPH_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_ACCP, 14);
target:delMod(MOD_FOOD_ACC_CAP, 90);
target:delMod(MOD_FOOD_RACCP, 14);
target:delMod(MOD_FOOD_RACC_CAP, 90);
target:delMod(MOD_FOOD_ATTP, 18);
target:delMod(MOD_FOOD_ATT_CAP, 80);
target:delMod(MOD_FOOD_RATTP, 18);
target:delMod(MOD_FOOD_RATT_CAP, 80);
target:delMod(MOD_AMORPH_KILLER, 5);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Bastok-Jeuno_Airship/Zone.lua | 7 | 1324 | -----------------------------------
--
-- Zone: Bastok-Jeuno_Airship
--
-----------------------------------
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
if ((player:getXPos() ~= 0) or (player:getYPos() ~= 0) or (player:getZPos() ~= 0)) then
player:setPos(0,0,0,224);
end
return cs;
end;
-----------------------------------
-- onTransportEvent
-----------------------------------
function onTransportEvent(player,transport)
player:startEvent(0x0064);
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
prevzone = player:getPreviousZone();
if (prevzone == 246) then
player:setPos(0,0,0,0,236);
elseif (prevzone == 236) then
player:setPos(0,0,0,0,246);
end
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/globals/items/bowl_of_whitefish_stew.lua | 2 | 1484 | -----------------------------------------
-- ID: 4440
-- Item: Bowl of Whitefish Stew
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Health 10
-- Dexterity 3
-- Mind -3
-- Accuracy 3
-- Ranged ACC % 7
-- Ranged ACC Cap 10
-----------------------------------------
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,4440);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 10);
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -3);
target:addMod(MOD_ACC, 3);
target:addMod(MOD_FOOD_RACCP, 7);
target:addMod(MOD_FOOD_RACC_CAP, 10);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 10);
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -3);
target:delMod(MOD_ACC, 3);
target:delMod(MOD_FOOD_RACCP, 7);
target:delMod(MOD_FOOD_RACC_CAP, 10);
end;
| gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Lower_Jeuno/npcs/Kurou-Morou.lua | 2 | 5247 | -----------------------------------
-- Area: Lower Jeuno
-- Starts and Finishes Quest: Your
-- Crystal Ball & Never to return
-- @zone 245
-- @pos -4 -6 -28
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Lower_Jeuno/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if(player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL) == QUEST_ACCEPTED and trade:getItemCount() == 1) then
if(trade:hasItemQty(557,1) == true) then
player:startEvent(0x00C0); -- CS for ahriman lens trade; Trading the lens to Kurou-Morou is optional
elseif(trade:hasItemQty(556,1) == true) then
player:startEvent(0x00C4); -- Trade divination sphere, finish quest
end
elseif(player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_ACCEPTED and trade:hasItemQty(12507,1) == true and trade:getItemCount() == 1) then
player:startEvent(0x00Cb); -- Finish "Never to return" quest
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
printf("Ontrigger completed");
local YourCrystalBall = player:getQuestStatus(JEUNO,YOUR_CRYSTAL_BALL);
local SearchingForTheRightWords = player:getQuestStatus(JEUNO,SEARCHING_FOR_THE_RIGHT_WORDS);
local ACandlelightVigil = player:getQuestStatus(JEUNO,A_CANDLELIGHT_VIGIL);
local RubbishDay = player:getQuestStatus(JEUNO,RUBBISH_DAY);
local NeverToReturn = player:getQuestStatus(JEUNO,NEVER_TO_RETURN);
local JFame = player:getFameLevel(JEUNO);
local SearchingForWords_prereq = player:getVar("QuestSearchRightWords_prereq");
if (JFame >= 2 and YourCrystalBall == QUEST_AVAILABLE) then
player:startEvent(0x00C2); -- Start "Your Crystal Ball" quest
elseif(JFame >= 5 and YourCrystalBall == QUEST_COMPLETED and player:getQuestStatus(JEUNO,NEVER_TO_RETURN) == QUEST_AVAILABLE and player:getVar("QuestNeverToReturn_day") ~= VanadielDayOfTheYear()) then
prog = player:getVar("QuestNeverToReturn_prog");
if(prog <= 2) then
fortune = math.random(1,99);
player:startEvent(0x00Cc,fortune); -- Required to get fortune read 3x on 3 diff game days before quest is kicked off
elseif(prog == 3) then
player:startEvent(0x00Ca); -- Start "Never to return" quest
end
--if searching for right words *prereq* CS has been activated
elseif(SearchingForWords_prereq == 1) then
player:startEvent(0x0026);
elseif(player:getVar("QuestSearchRightWords_denied") == 1) then
player:startEvent(0x0024);
elseif(SearchingForTheRightWords == QUEST_ACCEPTED) then
player:startEvent(0x0027);
elseif(player:getVar("SearchingForRightWords_postcs") == -2) then
player:startEvent(0x009a);
elseif(SearchingForTheRightWords == QUEST_COMPLETED) then --final state, after all quests complete
player:startEvent(0x0025);
--conditions for searching for the right words
elseif(JFame >= 7 and ACandlelightVigil == QUEST_COMPLETED and RubbishDay == QUEST_COMPLETED and
NeverToReturn == QUEST_COMPLETED and SearchingForTheRightWords == QUEST_AVAILABLE) then
player:startEvent(0x0011);
else
player:startEvent(0x00C1); -- 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 == 0x00C2 and option == 0) then
player:addQuest(JEUNO,YOUR_CRYSTAL_BALL);
elseif(csid == 0x00C4) then
player:addTitle(FORTUNETELLER_IN_TRAINING);
player:addFame(JEUNO,30);
player:tradeComplete(trade);
player:completeQuest(JEUNO,YOUR_CRYSTAL_BALL);
elseif(csid == 0x00Cc and option == 0) then
player:setVar("QuestNeverToReturn_prog", player:getVar("QuestNeverToReturn_prog") + 1); -- Keep track of how many times the players fortune has been read
player:setVar("QuestNeverToReturn_day", VanadielDayOfTheYear()); -- new vanadiel day
elseif(csid == 0x00Ca and option == 0) then
player:addQuest(JEUNO,NEVER_TO_RETURN);
player:setVar("QuestNeverToReturn_prog", 0);
player:setVar("QuestNeverToReturn_day", 0);
elseif(csid == 0x00Cb) then
if (player:getFreeSlotsCount() == 0) then
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13477);
else
player:addGil(GIL_RATE*1200);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*1200);
player:addItem(13477);
player:messageSpecial(ITEM_OBTAINED,13477);
player:addFame(JEUNO,30);
player:tradeComplete(trade);
player:completeQuest(JEUNO,NEVER_TO_RETURN);
end
elseif(csid == 0x0011) then
player:setVar("QuestSearchRightWords_prereq", 1);
elseif(csid == 0x009a) then
player:setVar("SearchingForRightWords_postcs", -1);
end
end; | gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/Port_San_dOria/npcs/Arminibit.lua | 4 | 1536 | -----------------------------------
-- Area: Port San d'Oria
-- NPC: Arminibit
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/zones/Port_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if(FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if(MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getMainLvl() >= 30 and player:getQuestStatus(SANDORIA,THE_HOLY_CREST) == QUEST_AVAILABLE) then
player:startEvent(0x0018);
else
player:startEvent(0x024b);
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 == 0x0018) then
player:setVar("TheHolyCrest_Event",1);
end
end; | gpl-3.0 |
Fatalerror66/ffxi-a | scripts/zones/Balgas_Dais/npcs/Armoury_Crate.lua | 36 | 1024 | -----------------------------------
-- Area: Balgas Dais
-- NPC: Armoury Crate
-- Balgas Dais Burning Cicrcle Armoury Crate
-----------------------------------
package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/zones/Balgas_Dais/TextIDs");
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:getBCNMloot();
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
end;
| gpl-3.0 |
kidaa/FFXIOrgins | scripts/zones/FeiYin/npcs/Underground_Pool.lua | 2 | 2233 | -----------------------------------
-- Area: FeiYin
-- NPC: Underground Pool
-- Involved In Quest: Scattered into Shadow
-- @pos 7 0 32 204 (H-8)
-- @pos 7 0 247 204 (H-5)
-- @pos -168 0 247 204 (F-5)
-----------------------------------
package.loaded["scripts/zones/FeiYin/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/FeiYin/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(JEUNO,SCATTERED_INTO_SHADOW) == QUEST_ACCEPTED) then
local npcID = npc:getID();
local aquaKI1 = player:hasKeyItem(AQUAFLORA1);
local aquaKI2 = player:hasKeyItem(AQUAFLORA2);
local aquaKI3 = player:hasKeyItem(AQUAFLORA3);
local Z = player:getZPos();
local X = player:getXPos();
if((Z > 20 and Z < 40) and (X > -.3 and X < 19.7) and (aquaKI1)) then
player:startEvent(0x0015);
elseif((Z > 242 and Z < 256) and (X > -2 and X < 16) and (aquaKI2)) then
player:startEvent(0x0014);
elseif((Z > 239 and Z < 259) and (X > -180 and X < -160) and (aquaKI3)) then
if(player:getVar("DabotzKilled") == 1) then
player:startEvent(0x0012);
else
SpawnMob(17613129,300):updateEnmity(player);
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x0015) then
player:delKeyItem(AQUAFLORA1);
elseif(csid == 0x0014) then
player:delKeyItem(AQUAFLORA2);
elseif(csid == 0x0012) then
player:delKeyItem(AQUAFLORA3);
player:setVar("DabotzKilled",0);
end
end; | gpl-3.0 |
wizawu/meeci-worker | worker.lua | 1 | 7111 | #!/usr/bin/luajit
local io = require("io")
local os = require("os")
local string = require("string")
local http = require("socket.http")
local json = require("dkjson")
local memcache = require("memcached")
local nonblock = require("nonblock")
-- check effective uid
if io.popen("whoami"):read("*l") ~= "root" then
print("Need to be root.")
os.exit(1)
end
-- retrieve url from environment
local meeci_host = os.getenv("MEECI_HOST")
if not meeci_host then
print("MEECI_HOST is not defined.")
os.exit(2)
end
local meeci_http = "http://" .. meeci_host .. ":80"
local meeci_ftp = "ftp://" .. meeci_host .. "/meeci"
local mc = memcache.connect(meeci_host, 11211)
--<< function definitions
local strformat = string.format
function fwrite(fmt, ...)
return io.write(strformat(fmt, ...))
end
function sleep(n)
os.execute("sleep " .. tonumber(n))
end
-- luajit os.execute returns only the exit status
function execute(cmd)
print(cmd)
if _G.jit then
return os.execute(cmd) == 0
else
return os.execute(cmd)
end
end
-- return content of a file
function cat(file)
local stream = io.popen("cat " .. file)
local result = stream:read("*a")
stream:close()
return result
end
-- receive a task from meeci-web
function receive()
local body, code = http.request(meeci_http .. "/task")
if code == 200 then
return json.decode(body)
end
end
function log(task)
fwrite("[%s] %s %s: ", os.date(), task.type, task.strid)
if task.type == "build" then
io.write(task.url .. '\n')
else
fwrite("%s@%s\n", task.container, task.user)
end
end
-- download files in /meeci/container
function wget(file)
local cmd = "wget -N " .. meeci_ftp .. "/containers/" .. file
return execute(cmd)
end
-- extract a container into 'container' directory
-- [args] container: container name with suffix .tgz
function tarx(container)
execute("rm -rf container")
return execute("tar xf " .. container)
end
-- download a shallow repository and its build script
function gitclone(task)
local dir = "container/opt/" .. task.repository
if not execute("mkdir -p " .. dir) then
return false
end
local cmd = "git clone --depth 30 -b %s %s %s"
local https_url = "https://github.com/" .. task.owner ..
"/" .. task.repository .. ".git"
cmd = strformat(cmd, task.branch, https_url, dir)
if not execute(cmd) then
return false
end
cmd = "cd " .. dir .. "; git checkout " .. task.commit
if not execute(cmd) then
return false
end
local url = meeci_http .. strformat(
"/scripts/%s/%s/%s/%d",
task.user, task.repository, task.owner, task.host
)
cmd = "wget -O " .. dir .. "/meeci_build.sh " .. url
return execute(cmd)
end
-- inform meeci-web the result
function report(task, start, stop, code)
local cmd = strformat(
"wput /var/lib/meeci/worker/logs/%s/%s.log " ..
meeci_ftp .. "/logs/%s/%s.log",
task.type, task.strid, task.type, task.strid
)
execute(cmd);
local str = json.encode({
user = task.user,
start = start,
stop = stop,
exit = code,
container = task.container
})
mc:set(task.type:sub(1, 1) .. ":" .. task.strid, str)
local url = meeci_http .. strformat(
"/finish/%s/%s", task.type, task.strid
)
print("Exit status " .. code)
http.request(url, tostring(code))
print("POST " .. url)
end
-- compress and upload a new container
-- [args] container: container name with suffix .tgz
function upload(container)
execute("rm -f container/meeci_exit_status")
-- TODO: file changed as we read it
execute("tar zcf container.tgz container")
local url = meeci_ftp .. "/containers/" .. container
if execute("wput container.tgz " .. url) then
os.remove("container.tgz")
return true
end
end
-- run a build task or create a container
function build(task)
local dir, script
if task.type == "build" then
dir = "/opt/" .. task.repository
script = "meeci_build.sh"
else
dir = "/root"
script = task.container .. ".sh"
end
local cmd = "cd %s; bash %s; echo -n $? > /meeci_exit_status"
cmd = strformat(cmd, dir, script)
cmd = strformat("systemd-nspawn -D ./container bash -c '%s'", cmd)
-- file log
local logdir = "/var/lib/meeci/worker/logs"
local log = strformat("%s/%s/%s.log", logdir, task.type, task.strid)
log = io.open(log, 'a')
-- memcache log
local key = task.type:sub(1, 1) .. "#" .. tostring(task.strid)
mc:set(key, "")
local start = os.time()
local stream, fd = nonblock:popen(cmd)
while true do
local n, line = nonblock:read(fd)
if n == 0 then break end
log:write(line)
mc:append(key, line)
if n < 1000 then sleep(1) end
-- TODO: 10min and 60min limit
end
log:close()
nonblock:pclose(stream)
local stop = os.time()
local code = tonumber(cat("container/meeci_exit_status"))
if task.type == "container" then
if not upload(task.user .. "/" .. task.container .. ".tgz") then
code = 21
end
end
report(task, start, stop, code)
return code == 0
end
-->>
if not wget("meeci-minbase.tgz") then
print("Cannot wget meeci-minbase.tgz")
os.exit(3)
end
-- main loop --
local failure = 0
local sleep_intv = 10
local idle = os.time()
while not test do
local done = false
local task = receive()
if task then
log(task)
if task.type == "build" then
if not wget(task.user .. "/" .. task.container .. ".tgz") then
goto END_TASK
end
if not tarx(task.container .. ".tgz") then
goto END_TASK
end
os.remove(task.container .. ".tgz")
if not gitclone(task) then
goto END_TASK
end
else
if not tarx("meeci-minbase.tgz") then
goto END_TASK
end
local script = task.container .. ".sh"
if not wget(task.user .. "/" .. script) then
goto END_TASK
end
os.rename(script, "container/root/" .. script)
end
done = build(task)
::END_TASK::
execute("rm -rf container")
if done then
fwrite("[%s] SUCCESS\n", os.date())
if failure > 0 then
failure = failure - 1
end
else
fwrite("[%s] ERROR\n", os.date())
failure = failure + 1
if failure == 10 then
fwrite("Worker stopped because of too many failures.\n")
os.exit(10)
end
end
idle = os.time()
else
-- while there is no task
sleep(sleep_intv)
end
if (os.time() - idle) % 600 < sleep_intv then
local m = math.floor((os.time() - idle) / 60)
fwrite("[%s] idle for %d min\n", os.date(), m)
end
end
| mit |
droid4control/esp8266-luasdp | init.lua | 1 | 1266 | local function start(nextfile)
-- This code is based on https://github.com/marcoskirsch/nodemcu-httpserver
local compileAndRemoveIfNeeded = function(f)
if file.open(f) then
file.close()
print('Compiling:', f)
node.compile(f)
file.remove(f)
print('Compiled:', f)
collectgarbage()
return 1
end
return 0
end
local serverFiles = { 'droidcontroller.lua', 'sdp.lua', 'sdppacket.lua', 'udpcomm.lua', 'waitip.lua' }
local compiledfiles = 0
for i, f in ipairs(serverFiles) do
compiledfiles = compiledfiles + compileAndRemoveIfNeeded(f)
end
if (compiledfiles > 0) then
print("Cleanup reboot after compiled ", compiledfiles, " files")
return node.restart()
end
-- end of nodemcu-httpserver code
return dofile(nextfile)
end
local pin_sdp_tx = 2
local pin_sdp_rx = 5
gpio.mode(pin_sdp_rx, gpio.OUTPUT)
gpio.mode(pin_sdp_tx, gpio.OUTPUT)
gpio.write(pin_sdp_rx, gpio.HIGH)
gpio.write(pin_sdp_tx, gpio.LOW)
led = function (name, status)
local pin = nil
if name == "RX" then pin = pin_sdp_rx end
if name == "TX" then pin = pin_sdp_tx end
if not pin then return end
if status then
gpio.write(pin, gpio.HIGH)
else
gpio.write(pin, gpio.LOW)
end
end
tmr.alarm(0, 1000, 0, function() return start("droidcontroller.lc") end)
| mit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.