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 |
|---|---|---|---|---|---|
OpenRA/OpenRA | mods/d2k/maps/harkonnen-03b/harkonnen03b.lua | 7 | 6559 | --[[
Copyright 2007-2022 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you under the terms of the GNU General Public License
as published by the Free Software Foundation, either version 3 of
the License, or (at your option) any later version. For more
information, see COPYING.
]]
AtreidesBase = { ABarracks, AWindTrap1, AWindTrap2, AWindTrap3, ALightFactory, AOutpost, AConyard, ARefinery, ASilo1, ASilo2, ASilo3, ASilo4 }
AtreidesBaseAreaTriggers =
{
{ CPos.New(10, 53), CPos.New(11, 53), CPos.New(12, 53), CPos.New(13, 53), CPos.New(14, 53), CPos.New(15, 53), CPos.New(16, 53), CPos.New(17, 53), CPos.New(17, 52), CPos.New(17, 51), CPos.New(17, 50), CPos.New(17, 49), CPos.New(17, 48), CPos.New(17, 47), CPos.New(17, 46), CPos.New(17, 45), CPos.New(17, 44), CPos.New(17, 43), CPos.New(17, 42), CPos.New(17, 41), CPos.New(17, 40), CPos.New(17, 39), CPos.New(17, 38), CPos.New(2, 35), CPos.New(3, 35), CPos.New(4, 35), CPos.New(5, 35), CPos.New(6, 35), CPos.New(7, 35), CPos.New(8, 35), CPos.New(9, 35), CPos.New(10, 35), CPos.New(11, 35), CPos.New(12, 35) },
{ CPos.New(49, 25), CPos.New(50, 25), CPos.New(51, 25), CPos.New(52, 25), CPos.New(53, 25), CPos.New(54, 25), CPos.New(54, 26), CPos.New(54, 27), CPos.New(54, 28), CPos.New(54, 29) },
{ CPos.New(19, 2), CPos.New(19, 3), CPos.New(19, 4), CPos.New(41, 2), CPos.New(41, 3), CPos.New(41, 4), CPos.New(41, 5), CPos.New(41, 6), CPos.New(41, 7), CPos.New(41, 8), CPos.New(41, 9), CPos.New(41, 10), CPos.New(41, 11) },
{ CPos.New(2, 16), CPos.New(3, 16), CPos.New(4, 16), CPos.New(5, 16), CPos.New(19, 2), CPos.New(19, 3), CPos.New(19, 4) }
}
AtreidesReinforcements =
{
easy =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" }
},
normal =
{
{ "light_inf", "trike", "trooper" },
{ "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trike", "trike", "quad" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "light_inf", "light_inf", "light_inf", "light_inf" },
{ "light_inf", "trike", "quad", "quad" }
},
hard =
{
{ "trike", "trike", "quad" },
{ "light_inf", "trike", "trike" },
{ "trooper", "trooper", "light_inf", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "light_inf", "trooper", "trooper" },
{ "trike", "trike", "quad", "quad", "quad", "trike" },
{ "light_inf", "light_inf", "light_inf", "trike", "trike" },
{ "light_inf", "trike", "light_inf", "trooper", "trooper", "quad" },
{ "trike", "trike", "quad", "quad", "quad", "trike" }
}
}
AtreidesAttackDelay =
{
easy = DateTime.Minutes(5),
normal = DateTime.Minutes(2) + DateTime.Seconds(40),
hard = DateTime.Minutes(1) + DateTime.Seconds(20)
}
AtreidesAttackWaves =
{
easy = 3,
normal = 6,
hard = 9
}
AtreidesHunters =
{
{ "trooper", "trooper", "trooper" },
{ "trike", "light_inf", "light_inf", "light_inf", "light_inf" },
{ "trooper", "trooper", "trooper", "trike", "trike" },
{ "light_inf", "light_inf", "light_inf", "light_inf", "light_inf", "trooper", "trooper", "trooper", "trooper", "trooper" }
}
AtreidesPaths =
{
{ AtreidesEntry4.Location, AtreidesRally4.Location },
{ AtreidesEntry7.Location, AtreidesRally7.Location },
{ AtreidesEntry8.Location, AtreidesRally8.Location }
}
AtreidesHunterPaths =
{
{ AtreidesEntry6.Location, AtreidesRally6.Location },
{ AtreidesEntry5.Location, AtreidesRally5.Location },
{ AtreidesEntry3.Location, AtreidesRally3.Location },
{ AtreidesEntry1.Location, AtreidesRally1.Location }
}
AtreidesInitialPath = { AtreidesEntry2.Location, AtreidesRally2.Location }
AtreidesInitialReinforcements = { "light_inf", "light_inf", "quad", "quad", "trike", "trike", "trooper", "trooper" }
HarkonnenReinforcements = { "quad", "quad" }
HarkonnenPath = { HarkonnenEntry.Location, HarkonnenRally.Location }
HarkonnenBaseBuildings = { "barracks", "light_factory" }
HarkonnenUpgrades = { "upgrade.barracks", "upgrade.light" }
MessageCheck = function(index)
return #player.GetActorsByType(HarkonnenBaseBuildings[index]) > 0 and not player.HasPrerequisites({ HarkonnenUpgrades[index] })
end
Tick = function()
if player.HasNoRequiredUnits() then
atreides.MarkCompletedObjective(KillHarkonnen)
end
if atreides.HasNoRequiredUnits() and not player.IsObjectiveCompleted(KillAtreides) then
Media.DisplayMessage("The Atreides have been annihilated!", "Mentat")
player.MarkCompletedObjective(KillAtreides)
end
if DateTime.GameTime % DateTime.Seconds(10) == 0 and LastHarvesterEaten[atreides] then
local units = atreides.GetActorsByType("harvester")
if #units > 0 then
LastHarvesterEaten[atreides] = false
ProtectHarvester(units[1], atreides, AttackGroupSize[Difficulty])
end
end
if DateTime.GameTime % DateTime.Seconds(32) == 0 and (MessageCheck(1) or MessageCheck(2)) then
Media.DisplayMessage("Upgrade barracks and light factory to produce more advanced units.", "Mentat")
end
end
WorldLoaded = function()
atreides = Player.GetPlayer("Atreides")
player = Player.GetPlayer("Harkonnen")
InitObjectives(player)
KillHarkonnen = atreides.AddPrimaryObjective("Kill all Harkonnen units.")
KillAtreides = player.AddPrimaryObjective("Eliminate all Atreides units and reinforcements\nin the area.")
Camera.Position = HConyard.CenterPosition
Trigger.OnAllKilled(AtreidesBase, function()
Utils.Do(atreides.GetGroundAttackers(), IdleHunt)
end)
local path = function() return Utils.Random(AtreidesPaths) end
local waveCondition = function() return player.IsObjectiveCompleted(KillAtreides) end
SendCarryallReinforcements(atreides, 0, AtreidesAttackWaves[Difficulty], AtreidesAttackDelay[Difficulty], path, AtreidesReinforcements[Difficulty], waveCondition)
ActivateAI()
Trigger.AfterDelay(DateTime.Minutes(2) + DateTime.Seconds(30), function()
Reinforcements.ReinforceWithTransport(player, "carryall.reinforce", HarkonnenReinforcements, HarkonnenPath, { HarkonnenPath[1] })
end)
TriggerCarryallReinforcements(player, atreides, AtreidesBaseAreaTriggers[1], AtreidesHunters[1], AtreidesHunterPaths[1])
TriggerCarryallReinforcements(player, atreides, AtreidesBaseAreaTriggers[2], AtreidesHunters[2], AtreidesHunterPaths[2])
TriggerCarryallReinforcements(player, atreides, AtreidesBaseAreaTriggers[3], AtreidesHunters[3], AtreidesHunterPaths[3])
TriggerCarryallReinforcements(player, atreides, AtreidesBaseAreaTriggers[4], AtreidesHunters[4], AtreidesHunterPaths[4])
end
| gpl-3.0 |
upsoft/nginx-openresty-windows | luajit-root-x64/luajit/share/luajit-2.1.0-alpha/jit/v.lua | 17 | 5620 | ----------------------------------------------------------------------------
-- Verbose mode of the LuaJIT compiler.
--
-- Copyright (C) 2005-2013 Mike Pall. All rights reserved.
-- Released under the MIT license. See Copyright Notice in luajit.h
----------------------------------------------------------------------------
--
-- This module shows verbose information about the progress of the
-- JIT compiler. It prints one line for each generated trace. This module
-- is useful to see which code has been compiled or where the compiler
-- punts and falls back to the interpreter.
--
-- Example usage:
--
-- luajit -jv -e "for i=1,1000 do for j=1,1000 do end end"
-- luajit -jv=myapp.out myapp.lua
--
-- Default output is to stderr. To redirect the output to a file, pass a
-- filename as an argument (use '-' for stdout) or set the environment
-- variable LUAJIT_VERBOSEFILE. The file is overwritten every time the
-- module is started.
--
-- The output from the first example should look like this:
--
-- [TRACE 1 (command line):1 loop]
-- [TRACE 2 (1/3) (command line):1 -> 1]
--
-- The first number in each line is the internal trace number. Next are
-- the file name ('(command line)') and the line number (':1') where the
-- trace has started. Side traces also show the parent trace number and
-- the exit number where they are attached to in parentheses ('(1/3)').
-- An arrow at the end shows where the trace links to ('-> 1'), unless
-- it loops to itself.
--
-- In this case the inner loop gets hot and is traced first, generating
-- a root trace. Then the last exit from the 1st trace gets hot, too,
-- and triggers generation of the 2nd trace. The side trace follows the
-- path along the outer loop and *around* the inner loop, back to its
-- start, and then links to the 1st trace. Yes, this may seem unusual,
-- if you know how traditional compilers work. Trace compilers are full
-- of surprises like this -- have fun! :-)
--
-- Aborted traces are shown like this:
--
-- [TRACE --- foo.lua:44 -- leaving loop in root trace at foo:lua:50]
--
-- Don't worry -- trace aborts are quite common, even in programs which
-- can be fully compiled. The compiler may retry several times until it
-- finds a suitable trace.
--
-- Of course this doesn't work with features that are not-yet-implemented
-- (NYI error messages). The VM simply falls back to the interpreter. This
-- may not matter at all if the particular trace is not very high up in
-- the CPU usage profile. Oh, and the interpreter is quite fast, too.
--
-- Also check out the -jdump module, which prints all the gory details.
--
------------------------------------------------------------------------------
-- Cache some library functions and objects.
local jit = require("jit")
assert(jit.version_num == 20100, "LuaJIT core/library version mismatch")
local jutil = require("jit.util")
local vmdef = require("jit.vmdef")
local funcinfo, traceinfo = jutil.funcinfo, jutil.traceinfo
local type, format = type, string.format
local stdout, stderr = io.stdout, io.stderr
-- Active flag and output file handle.
local active, out
------------------------------------------------------------------------------
local startloc, startex
local function fmtfunc(func, pc)
local fi = funcinfo(func, pc)
if fi.loc then
return fi.loc
elseif fi.ffid then
return vmdef.ffnames[fi.ffid]
elseif fi.addr then
return format("C:%x", fi.addr)
else
return "(?)"
end
end
-- Format trace error message.
local function fmterr(err, info)
if type(err) == "number" then
if type(info) == "function" then info = fmtfunc(info) end
err = format(vmdef.traceerr[err], info)
end
return err
end
-- Dump trace states.
local function dump_trace(what, tr, func, pc, otr, oex)
if what == "start" then
startloc = fmtfunc(func, pc)
startex = otr and "("..otr.."/"..oex..") " or ""
else
if what == "abort" then
local loc = fmtfunc(func, pc)
if loc ~= startloc then
out:write(format("[TRACE --- %s%s -- %s at %s]\n",
startex, startloc, fmterr(otr, oex), loc))
else
out:write(format("[TRACE --- %s%s -- %s]\n",
startex, startloc, fmterr(otr, oex)))
end
elseif what == "stop" then
local info = traceinfo(tr)
local link, ltype = info.link, info.linktype
if ltype == "interpreter" then
out:write(format("[TRACE %3s %s%s -- fallback to interpreter]\n",
tr, startex, startloc))
elseif link == tr or link == 0 then
out:write(format("[TRACE %3s %s%s %s]\n",
tr, startex, startloc, ltype))
elseif ltype == "root" then
out:write(format("[TRACE %3s %s%s -> %d]\n",
tr, startex, startloc, link))
else
out:write(format("[TRACE %3s %s%s -> %d %s]\n",
tr, startex, startloc, link, ltype))
end
else
out:write(format("[TRACE %s]\n", what))
end
out:flush()
end
end
------------------------------------------------------------------------------
-- Detach dump handlers.
local function dumpoff()
if active then
active = false
jit.attach(dump_trace)
if out and out ~= stdout and out ~= stderr then out:close() end
out = nil
end
end
-- Open the output file and attach dump handlers.
local function dumpon(outfile)
if active then dumpoff() end
if not outfile then outfile = os.getenv("LUAJIT_VERBOSEFILE") end
if outfile then
out = outfile == "-" and stdout or assert(io.open(outfile, "w"))
else
out = stderr
end
jit.attach(dump_trace, "trace")
active = true
end
-- Public module functions.
return {
on = dumpon,
off = dumpoff,
start = dumpon -- For -j command line option.
}
| bsd-2-clause |
pydsigner/naev | dat/events/tutorial/tutorial.lua | 11 | 3115 | -- Master tutorial script.
-- This script allows the player to choose a tutorial module to run, or return to the main menu.
-- localization stuff, translators would work here
lang = naev.lang()
if lang == "es" then
else -- default english
menutitle = "Tutorial Menu"
menutext = "Welcome to the Naev tutorial menu. Please select a tutorial module from the list below:"
menuall = "Play All"
menubasic = "Tutorial: Basic Operation"
menudiscover = "Tutorial: Exploration and Discovery"
menuinterstellar = "Tutorial: Interstellar Flight"
menubasiccombat = "Tutorial: Basic Combat"
menumisscombat = "Tutorial: Missile Combat"
menuheat = "Tutorial: Heat"
menuaoutfits = "Tutorial: Activated Outfits"
menudisable = "Tutorial: Disabling"
menuplanet = "Tutorial: The Planetary Screen"
menutrade = "Tutorial: Trade"
menumissions = "Tutorial: Missions and Events"
menucomms = "Tutorial: Communications"
menux = "Quit to Main Menu"
end
function create()
-- Set defaults just in case.
local pp = player.pilot()
player.teleport("Mohawk")
player.msgClear()
player.swapShip("Llama", "Tutorial Llama", "Paul 2", true, true)
player.rmOutfit("all")
pp = player.pilot()
pp:rmOutfit("all")
pp:addOutfit("Milspec Orion 2301 Core System", 1, true)
pp:addOutfit("Nexus Dart 300 Engine", 1, true)
pp:addOutfit("S&K Light Combat Plating", 1, true)
pp:setEnergy(100)
pp:setHealth(100, 100)
player.refuel()
player.cinematics(true, { no2x = true })
pp:setPos(vec2.new(0, 0))
pp:setVel(vec2.new(0, 0))
pp:setHealth(100, 100)
pp:control(false)
pp:setNoLand(false)
pp:setNoJump(false)
system.get("Mohawk"):setKnown(false, true)
system.get("Cherokee"):setKnown(false, true)
system.get("Iroquois"):setKnown(false, true)
system.get("Navajo"):setKnown(false, true)
system.get("Sioux"):setKnown(false, true)
-- List of all tutorial modules, in order of appearance.
-- HACK: Add "menux" to the end of this table, because the unpack() function has to be at the end of the tk.choice call.
local modules = {menubasic, menudiscover, menuinterstellar, menucomms, menubasiccombat, menumisscombat, menuheat, menuaoutfits, menudisable, menuplanet, menumissions, menux}
if var.peek("tut_next") then
if var.peek("tut_next") == #modules-1 then
var.pop("tut_next")
else
var.push("tut_next", var.peek("tut_next") + 1)
startModule(modules[var.peek("tut_next")])
end
end
-- Create menu.
_, selection = tk.choice(menutitle, menutext, menuall, unpack(modules))
startModule(selection)
end
-- Helper function for starting the tutorial modules
function startModule(module)
if selection == menux then -- Quit to main menu
tut.main_menu()
elseif selection == menuall then
var.push("tut_next", 1)
module = menubasic
end
player.cinematics(false)
naev.eventStart(module)
evt.finish(true) -- While the module is running, this event should not.
end
| gpl-3.0 |
badboyam/crazy_bot | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
emadni/launcherlord | plugins/google.lua | 722 | 1037 | local function googlethat(query)
local api = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&"
local parameters = "q=".. (URL.escape(query) or "")
-- Do the request
local res, code = https.request(api..parameters)
if code ~=200 then return nil end
local data = json:decode(res)
local results = {}
for key,result in ipairs(data.responseData.results) do
table.insert(results, {
result.titleNoFormatting,
result.unescapedUrl or result.url
})
end
return results
end
local function stringlinks(results)
local stringresults=""
for key,val in ipairs(results) do
stringresults=stringresults..val[1].." - "..val[2].."\n"
end
return stringresults
end
local function run(msg, matches)
local results = googlethat(matches[1])
return stringlinks(results)
end
return {
description = "Searches Google and send results",
usage = "!google [terms]: Searches Google and send results",
patterns = {
"^!google (.*)$",
"^%.[g|G]oogle (.*)$"
},
run = run
}
| gpl-2.0 |
amirkingred/telejian | plugins/btc.lua | 289 | 1375 | -- See https://bitcoinaverage.com/api
local function getBTCX(amount,currency)
local base_url = 'https://api.bitcoinaverage.com/ticker/global/'
-- Do request on bitcoinaverage, the final / is critical!
local res,code = https.request(base_url..currency.."/")
if code ~= 200 then return nil end
local data = json:decode(res)
-- Easy, it's right there
text = "BTC/"..currency..'\n'..'Buy: '..data.ask..'\n'..'Sell: '..data.bid
-- If we have a number as second parameter, calculate the bitcoin amount
if amount~=nil then
btc = tonumber(amount) / tonumber(data.ask)
text = text.."\n "..currency .." "..amount.." = BTC "..btc
end
return text
end
local function run(msg, matches)
local cur = 'EUR'
local amt = nil
-- Get the global match out of the way
if matches[1] == "!btc" then
return getBTCX(amt,cur)
end
if matches[2] ~= nil then
-- There is a second match
amt = matches[2]
cur = string.upper(matches[1])
else
-- Just a EUR or USD param
cur = string.upper(matches[1])
end
return getBTCX(amt,cur)
end
return {
description = "Bitcoin global average market value (in EUR or USD)",
usage = "!btc [EUR|USD] [amount]",
patterns = {
"^!btc$",
"^!btc ([Ee][Uu][Rr])$",
"^!btc ([Uu][Ss][Dd])$",
"^!btc (EUR) (%d+[%d%.]*)$",
"^!btc (USD) (%d+[%d%.]*)$"
},
run = run
}
| gpl-2.0 |
szym/turbo | turbo/httpserver.lua | 8 | 18590 | --- Turbo.lua HTTP Server module
-- A non-blocking HTTPS Server based on the TCPServer class.
-- Supports HTTP/1.0 and HTTP/1.1.
-- Includes SSL support.
-- Copyright 2011, 2012, 2013 John Abrahamsen
--
-- Licensed under the Apache License, Version 2.0 (the "License");
-- you may not use this file except in compliance with the License.
-- You may obtain a copy of the License at
--
-- http://www.apache.org/licenses/LICENSE-2.0
--
-- Unless required by applicable law or agreed to in writing, software
-- distributed under the License is distributed on an "AS IS" BASIS,
-- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-- See the License for the specific language governing permissions and
-- limitations under the License.
local tcpserver = require "turbo.tcpserver"
local httputil = require "turbo.httputil"
local ioloop = require "turbo.ioloop"
local iostream = require "turbo.iostream"
local util = require "turbo.util"
local log = require "turbo.log"
require('turbo.3rdparty.middleclass')
local httpserver = {} -- httpserver namespace
-- HTTPServer based on TCPServer, IOStream and IOLoop classes.
-- This class is used by the Application class to serve its RequestHandlers.
-- The server itself is only responsible for handling incoming requests, no
-- response to the request is produced, that is the purpose of the request
-- callback given as argument on initialization. The callback recieves the
-- HTTPRequest class instance produced for the incoming request and can
-- by data provided in that instance decide on how it want to respond to
-- the client. The callback must produce a valid HTTP response header and
-- optionally a response body and use the HTTPRequest:write method.
-- The server supports SSL, HTTP/1.1 Keep-Alive and optionally HTTP/1.0
-- Keep-Alive if the header field is specified.
-- Example usage of HTTPServer:
-- local httpserver = require('turbo.httpserver')
-- local ioloop = require('turbo.ioloop')
-- local ioloop_instance = ioloop.instance()
-- function handle_request(request)
-- local message = "You requested: " .. request.path
-- request:write("HTTP/1.1 200 OK\r\nContent-Length:" .. message:len() ..
-- "\r\n\r\n")
-- request:write(message)
-- request:finish()
-- end
-- http_server = httpserver.HTTPServer:new(handle_request)
-- http_server:listen(8888)
-- ioloop_instance:start()
httpserver.HTTPServer = class('HTTPServer', tcpserver.TCPServer)
--- Create a new HTTPServer class instance.
-- @param request_callback (Function) Callback when requests are recieved by
-- the server.
-- @param no_keep_alive (Boolean) If clients request use Keep-Alive it is to be
-- ignored.
-- @param io_loop (IOLoop instance) The IOLoop instance you want to use.
-- @param xheaders (Boolean) Care about X-* header fields or not.
-- @param kwargs (Table) Key word arguments.
-- Key word arguments supported:
-- "read_body" = Automatically read, and parse any request body. Default is
-- true. If set to false, the user must read the body from the connection
-- himself. Not reading a body in the case of a keep-alive request may
-- lead to undefined behaviour. The body should be read or connection
-- closed.
-- "max_header_size" = The maximum amount of bytes a header can be.
-- If exceeded, request is dropped.
-- "max_body_size" = The maxium amount of bytes a request body can be.
-- If exceeded, request is dropped. HAS NO EFFECT IF read_body IS FALSE.
-- "ssl_options" =
-- "key_file" = SSL key file if a SSL enabled server is wanted.
-- "cert_file" = Certificate file. key_file must also be set.
function httpserver.HTTPServer:initialize(request_callback,
no_keep_alive,
io_loop,
xheaders,
kwargs)
self.request_callback = request_callback
self.no_keep_alive = no_keep_alive
self.xheaders = xheaders
self.kwargs = kwargs
tcpserver.TCPServer.initialize(self,
io_loop,
kwargs and kwargs.ssl_options)
end
--- Internal handle_stream method to be called by super class TCPServer on new
-- connection.
-- @param stream (IOStream instance) Stream for the newly connected client.
-- @param address (String) IP address of newly connected client.
function httpserver.HTTPServer:handle_stream(stream, address)
local http_conn = httpserver.HTTPConnection(
stream,
address,
self.request_callback,
self.no_keep_alive,
self.xheaders,
self.kwargs)
end
--- HTTPConnection class.
-- Represents a live connection to the server. Basically a helper class to
-- HTTPServer. It uses the IOStream class's callbacks to handle the different
-- sections of a HTTP request.
httpserver.HTTPConnection = class('HTTPConnection')
function httpserver.HTTPConnection:initialize(stream, address,
request_callback, no_keep_alive, xheaders, kwargs)
self.stream = stream
self.address = address
self.request_callback = request_callback
self.no_keep_alive = no_keep_alive or false
self.xheaders = xheaders or false
self._request_finished = false
self._header_callback = self._on_headers
self.kwargs = kwargs or {}
self.stream:set_maxed_buffer_callback(self._on_max_buffer, self)
-- 18K max header size by default.
self.stream:set_max_buffer_size(self.kwargs.max_header_size or 1024*18)
self.stream:read_until("\r\n\r\n", self._header_callback, self)
end
function httpserver.HTTPConnection:_set_write_callback(callback, arg)
self._write_callback = callback
self._write_callback_arg = arg
end
function httpserver.HTTPConnection:_clear_write_callback()
self._write_callback = nil
self._write_callback_arg = nil
end
--- Writes a chunk of output to the underlying stream.
-- @param chunk (String) Data chunk to write to underlying IOStream.
-- @param callback (Function) Optional function called when buffer is fully
-- flushed.
-- @param arg Optional first argument for callback.
function httpserver.HTTPConnection:write(chunk, callback, arg)
if not self._request then
error("Request closed.")
end
if not self.stream:closed() then
self:_set_write_callback(callback, arg)
self.stream:write(chunk, self._on_write_complete, self)
end
end
--- Write the given ``turbo.structs.buffer`` to the underlying stream.
-- @param buf (Buffer class instance)
-- @param callback (Function) Optional function called when buffer is fully
-- flushed.
-- @param arg Optional first argument for callback.
function httpserver.HTTPConnection:write_buffer(buf, callback, arg)
if not self._request then
error("Request closed.")
end
if not self.stream:closed() then
self:_set_write_callback(callback, arg)
self.stream:write_buffer(buf, self._on_write_complete, self)
end
end
--- Write a Buffer class instance without copying it into the IOStream internal
-- buffer. Some considerations has to be done when using this. Any prior calls
-- to HTTPConnection:write or HTTPConnection:write_buffer must have completed
-- before this method can be used. The zero copy write must complete before any
-- other writes may be done. Also the buffer class should not be modified
-- while the write is being completed. Failure to follow these advice will lead
-- to undefined behaviour.
-- @param buf (Buffer class instance)
-- @param callback (Function) Optional function called when buffer is fully
-- flushed.
-- @param arg Optional first argument for callback.
function httpserver.HTTPConnection:write_zero_copy(buf, callback, arg)
if not self._request then
error("Request closed.")
end
if not self.stream:closed() then
self:_set_write_callback(callback, arg)
self.stream:write_zero_copy(buf, self._on_write_complete, self)
else
log.devel("[httpserver.lua] Trying to do zero copy operation on closed stream.")
end
end
--- Finishes the request.
function httpserver.HTTPConnection:finish()
assert(self._request, "Request closed")
self._request_finished = true
if not self.stream:writing() then
self:_clear_write_callback()
self:_finish_request()
end
end
local function _on_headers_error_handler(err)
log.error(string.format("[httpserver.lua] Invalid request. %s", err))
end
--- Handles incoming headers. The HTTPHeaders class is used to parse
-- request headers.
function httpserver.HTTPConnection:_on_headers(data)
local headers
local status, headers = xpcall(httputil.HTTPParser,
_on_headers_error_handler, data, httputil.hdr_t["HTTP_REQUEST"])
if status == false then
-- Invalid headers. Close stream.
-- Log line is printed by error handler describing the reason.
self.stream:close()
return
end
self._headers_read = true
self._request = httpserver.HTTPRequest:new(headers:get_method(),
headers:get_url(), {
version = headers.version,
connection = self,
headers = headers,
remote_ip = self.address
})
if self.kwargs.read_body ~= false then
local content_length = headers:get("Content-Length")
if content_length then
content_length = tonumber(content_length)
-- Set max buffer size to 128MB.
self.stream:set_max_buffer_size(
self.kwargs.max_body_size or math.max(content_length, 1024*18))
if content_length > self.stream.max_buffer_size then
log.error(
"[httpserver.lua] Content-Length too long \
compared to current max body size.")
self.stream:close()
end
if headers:get("Expect") == "100-continue" then
self.stream:write("HTTP/1.1 100 (Continue)\r\n\r\n")
end
self.stream:read_bytes(content_length, self._on_request_body, self)
return
end
end
self.request_callback(self._request)
end
--- Handles incoming request body.
function httpserver.HTTPConnection:_on_request_body(data)
self._request.body = data
local content_type = self._request.headers:get("Content-Type")
if content_type then
if content_type:find("x-www-form-urlencoded", 1, true) then
self.arguments =
httputil.parse_post_arguments(self._request.body) or {}
elseif content_type:find("multipart/form-data", 1, true) then
-- Valid boundary must only be max 70 characters not
-- ending in space.
-- Valid characters from RFC2046 are:
-- bchar := DIGIT / ALPHA / "'" / "(" / ")" /
-- "+" / "_" / "," / "-" / "." /
-- "/" / ":" / "=" / "?" / " "
-- Boundary string is permitted to be quoted.
local boundary =
content_type:match(
"boundary=[\"]?([0-9a-zA-Z'()+_,-./:=? ]*[0-9a-zA-Z'()+_,-./:=?])")
self.arguments =
httputil.parse_multipart_data(self._request.body, boundary)
or {}
end
end
self.request_callback(self._request)
end
--- Finish request.
function httpserver.HTTPConnection:_finish_request()
local disconnect = false
if self.no_keep_alive then
disconnect = true
else
local connection_header = self._request.headers:get("Connection")
if connection_header then
connection_header = connection_header:lower()
end
if self._request:supports_http_1_1() then
disconnect = connection_header == "close"
elseif self._request.headers:get("Content-Length") or
self._request.headers.method == "HEAD" or
self._request.method == "GET" then
disconnect = connection_header ~= "keep-alive"
else
disconnect = true
end
end
self._max_buf = false
self._request_finished = false
if disconnect then
self.stream:close()
return
end
self.arguments = nil -- Reset table in case of keep-alive.
if not self.stream:closed() then
self.stream:set_max_buffer_size(self.kwargs.max_header_size or 1024*18)
self.stream:read_until("\r\n\r\n", self._header_callback, self)
else
log.debug("[httpserver.lua] Client hang up. End Keep-Alive session.")
self = nil
return
end
end
--- Callback for on complete event.
function httpserver.HTTPConnection:_on_write_complete()
if self._write_callback then
local callback = self._write_callback
local argument = self._write_callback_arg
self:_clear_write_callback()
callback(argument)
end
if self._request_finished and not self.stream:writing() then
self:_finish_request()
end
end
--- Callback for maxed out buffer.
function httpserver.HTTPConnection:_on_max_buffer()
if self._max_buf then
-- Allow one iteration of buffer at max. In case headers
-- and body arrive in one chunk.
if not self._headers_read then
log.error(
string.format("[httpserver.lua] Headers too large for limit %dB.",
self.kwargs.max_header_size or 1024*18))
else
log.error(
string.format("[httpserver.lua] Request body too large for limit %dB.",
self.kwargs.max_header_size or 1024*18))
end
self.stream:close()
return
end
self._max_buf = true
end
--- HTTPRequest class.
-- Represents a HTTP request to the server.
-- HTTP headers are parsed magically if headers are supplied with kwargs table.
httpserver.HTTPRequest = class('HTTPRequest')
--- Create a new HTTPRequest class instance.
-- @param method (String) HTTP request method, e.g "POST".
-- @param uri (String) The URI requested.
-- @param args (Table) Table or optional arguments:
-- Arguments available:
-- headers,
-- body,
-- remote_ip,
-- protocol,
-- host,
-- files,
-- connection
function httpserver.HTTPRequest:initialize(method, uri, args)
local headers, body, remote_ip, protocol, host, files, version, connection
= nil, nil, nil, nil, nil, nil, "HTTP/1.0", nil
-- Find arguments sent.
if type(args) == "table" then
version = args.version or version
headers = args.headers
body = args.body
remote_ip = args.remote_ip
protocol = args.protocol
host = args.host
files = args.files
connection = args.connection
end
self.method = method
self.uri = uri
self.version = args.version or version
self.headers = headers or httputil.HTTPHeaders:new()
self.body = body or ""
if connection and connection.xheaders then
self.remote_ip = self.headers:get("X-Real-Ip") or
self.headers:get("X-Forwarded-For")
if not self:_valid_ip(self.remote_ip) then
self.remote_ip = remote_ip
end
self.protocol = self.headers:get("X-Scheme") or
self.headers:get("X-Forwarded-Proto")
if self.protocol ~= "http" or self.protocol ~= "https" then
self.protocol = "http"
end
else
self.remote_ip = remote_ip
if protocol then
self.protocol = protocol
elseif connection and
instanceOf(iostream.SSLIOStream, connection.stream) then
self.protocol = "https"
else
self.protocol = "http"
end
end
self.host = host or self.headers:get("Host") or "127.0.0.1"
self.files = files or {}
self.connection = connection
self._start_time = util.gettimemonotonic()
self._finish_time = nil
self.path = self.headers:get_url_field(httputil.UF.PATH)
self.arguments = self.headers:get_arguments()
end
--- Returns true if requester supports HTTP 1.1.
-- @return (Boolean)
function httpserver.HTTPRequest:supports_http_1_1()
return self.version == "HTTP/1.1"
end
--- Writes a chunk of output to the stream.
-- @param chunk (String) Data chunk to write to underlying IOStream.
-- @param callback (Function) Optional callback called when socket is flushed.
function httpserver.HTTPRequest:write(chunk, callback, arg)
self.connection:write(chunk, callback, arg)
end
--- Write a Buffer class instance to the stream.
-- @param buf (Buffer class instance)
-- @param callback Optional callback when socket is flushed.
-- @param arg Optional first argument for callback.
function httpserver.HTTPRequest:write_buffer(buf, callback, arg)
self.connection:write_buffer(buf, callback, arg)
end
--- Write a Buffer class instance without copying it into the IOStream internal
-- buffer. Some considerations has to be done when using this. Any prior calls
-- to HTTPConnection:write or HTTPConnection:write_buffer must have completed
-- before this method can be used. The zero copy write must complete before any
-- other writes may be done. Also the buffer class should not be modified
-- while the write is being completed. Failure to follow these advice will lead
-- to undefined behaviour.
-- @param buf (Buffer class instance)
-- @param callback Optional callback when socket is flushed.
-- @param arg Optional first argument for callback.
function httpserver.HTTPRequest:write_zero_copy(buf, callback, arg)
self.connection:write_zero_copy(buf, callback, arg)
end
--- Finish the request. Close connection.
function httpserver.HTTPRequest:finish()
self.connection:finish()
self._finish_time = util.gettimemonotonic()
end
--- Return the full URL that the user requested.
function httpserver.HTTPRequest:full_url()
return self.protocol .. "://" .. self.host .. self.uri
end
--- Return the time used to handle the request or the
-- time up to now if request not finished.
-- @return (Number) Ms the request took to finish, or up until now if not yet
-- completed.
function httpserver.HTTPRequest:request_time()
if not self._finish_time then
return util.gettimemonotonic() - self._start_time
else
return self._finish_time - self._start_time
end
end
function httpserver.HTTPRequest:_valid_ip(ip)
--FIXME: This IP validation is broken!
local ip = ip or ''
return ip:find("[%d+%.]+") or nil
end
return httpserver
| apache-2.0 |
salorium/awesome | lib/awful/widget/tasklist.lua | 2 | 14226 | ---------------------------------------------------------------------------
--- Tasklist widget module for awful
--
-- @author Julien Danjou <julien@danjou.info>
-- @copyright 2008-2009 Julien Danjou
-- @release @AWESOME_VERSION@
-- @classmod awful.widget.tasklist
---------------------------------------------------------------------------
-- Grab environment we need
local capi = { screen = screen,
client = client }
local ipairs = ipairs
local setmetatable = setmetatable
local table = table
local common = require("awful.widget.common")
local beautiful = require("beautiful")
local util = require("awful.util")
local tag = require("awful.tag")
local flex = require("wibox.layout.flex")
local timer = require("gears.timer")
local function get_screen(s)
return s and screen[s]
end
local tasklist = { mt = {} }
local instances
-- Public structures
tasklist.filter = {}
local function tasklist_label(c, args, tb)
if not args then args = {} end
local theme = beautiful.get()
local fg_normal = util.ensure_pango_color(args.fg_normal or theme.tasklist_fg_normal or theme.fg_normal, "white")
local bg_normal = args.bg_normal or theme.tasklist_bg_normal or theme.bg_normal or "#000000"
local fg_focus = util.ensure_pango_color(args.fg_focus or theme.tasklist_fg_focus or theme.fg_focus, fg_normal)
local bg_focus = args.bg_focus or theme.tasklist_bg_focus or theme.bg_focus or bg_normal
local fg_urgent = util.ensure_pango_color(args.fg_urgent or theme.tasklist_fg_urgent or theme.fg_urgent, fg_normal)
local bg_urgent = args.bg_urgent or theme.tasklist_bg_urgent or theme.bg_urgent or bg_normal
local fg_minimize = util.ensure_pango_color(args.fg_minimize or theme.tasklist_fg_minimize or theme.fg_minimize, fg_normal)
local bg_minimize = args.bg_minimize or theme.tasklist_bg_minimize or theme.bg_minimize or bg_normal
local bg_image_normal = args.bg_image_normal or theme.bg_image_normal
local bg_image_focus = args.bg_image_focus or theme.bg_image_focus
local bg_image_urgent = args.bg_image_urgent or theme.bg_image_urgent
local bg_image_minimize = args.bg_image_minimize or theme.bg_image_minimize
local tasklist_disable_icon = args.tasklist_disable_icon or theme.tasklist_disable_icon or false
local font = args.font or theme.tasklist_font or theme.font or ""
local font_focus = args.font_focus or theme.tasklist_font_focus or theme.font_focus or font or ""
local font_minimized = args.font_minimized or theme.tasklist_font_minimized or theme.font_minimized or font or ""
local font_urgent = args.font_urgent or theme.tasklist_font_urgent or theme.font_urgent or font or ""
local text = ""
local name = ""
local bg
local bg_image
-- symbol to use to indicate certain client properties
local sticky = args.sticky or theme.tasklist_sticky or "▪"
local ontop = args.ontop or theme.tasklist_ontop or '⌃'
local above = args.above or theme.tasklist_above or '▴'
local below = args.below or theme.tasklist_below or '▾'
local floating = args.floating or theme.tasklist_floating or '✈'
local maximized = args.maximized or theme.tasklist_maximized or '<b>+</b>'
local maximized_horizontal = args.maximized_horizontal or theme.tasklist_maximized_horizontal or '⬌'
local maximized_vertical = args.maximized_vertical or theme.tasklist_maximized_vertical or '⬍'
if not theme.tasklist_plain_task_name then
if c.sticky then name = name .. sticky end
if c.ontop then name = name .. ontop
elseif c.above then name = name .. above
elseif c.below then name = name .. below end
if c.maximized then
name = name .. maximized
else
if c.maximized_horizontal then name = name .. maximized_horizontal end
if c.maximized_vertical then name = name .. maximized_vertical end
if c.floating then name = name .. floating end
end
end
if c.minimized then
name = name .. (util.escape(c.icon_name) or util.escape(c.name) or util.escape("<untitled>"))
else
name = name .. (util.escape(c.name) or util.escape("<untitled>"))
end
local focused = capi.client.focus == c
-- Handle transient_for: the first parent that does not skip the taskbar
-- is considered to be focused, if the real client has skip_taskbar.
if not focused and capi.client.focus and capi.client.focus.skip_taskbar
and capi.client.focus:get_transient_for_matching(function(cl)
return not cl.skip_taskbar
end) == c then
focused = true
end
if focused then
bg = bg_focus
text = text .. "<span color='"..fg_focus.."'>"..name.."</span>"
bg_image = bg_image_focus
font = font_focus
elseif c.urgent then
bg = bg_urgent
text = text .. "<span color='"..fg_urgent.."'>"..name.."</span>"
bg_image = bg_image_urgent
font = font_urgent
elseif c.minimized then
bg = bg_minimize
text = text .. "<span color='"..fg_minimize.."'>"..name.."</span>"
bg_image = bg_image_minimize
font = font_minimized
else
bg = bg_normal
text = text .. "<span color='"..fg_normal.."'>"..name.."</span>"
bg_image = bg_image_normal
end
tb:set_font(font)
return text, bg, bg_image, not tasklist_disable_icon and c.icon or nil
end
local function tasklist_update(s, w, buttons, filter, data, style, update_function)
local clients = {}
for _, c in ipairs(capi.client.get()) do
if not (c.skip_taskbar or c.hidden
or c.type == "splash" or c.type == "dock" or c.type == "desktop")
and filter(c, s) then
table.insert(clients, c)
end
end
local function label(c, tb) return tasklist_label(c, style, tb) end
update_function(w, buttons, label, data, clients)
end
--- Create a new tasklist widget. The last two arguments (update_function
-- and base_widget) serve to customize the layout of the tasklist (eg. to
-- make it vertical). For that, you will need to copy the
-- awful.widget.common.list_update function, make your changes to it
-- and pass it as update_function here. Also change the base_widget if the
-- default is not what you want.
-- @param screen The screen to draw tasklist for.
-- @param filter Filter function to define what clients will be listed.
-- @param buttons A table with buttons binding to set.
-- @param style The style overrides default theme.
-- @param[opt] update_function Function to create a tag widget on each
-- update. See `awful.widget.common.list_update`.
-- @tparam[opt] table base_widget Container widget for tag widgets. Default
-- is `wibox.layout.flex.horizontal`.
-- @param base_widget.bg_normal The background color for unfocused client.
-- @param base_widget.bg_normal The background color for unfocused client.
-- @param base_widget.fg_normal The foreground color for unfocused client.
-- @param base_widget.bg_focus The background color for focused client.
-- @param base_widget.fg_focus The foreground color for focused client.
-- @param base_widget.bg_urgent The background color for urgent clients.
-- @param base_widget.fg_urgent The foreground color for urgent clients.
-- @param base_widget.bg_minimize The background color for minimized clients.
-- @param base_widget.fg_minimize The foreground color for minimized clients.
-- @param base_widget.floating Symbol to use for floating clients.
-- @param base_widget.ontop Symbol to use for ontop clients.
-- @param base_widget.above Symbol to use for clients kept above others.
-- @param base_widget.below Symbol to use for clients kept below others.
-- @param base_widget.maximized Symbol to use for clients that have been maximized (vertically and horizontally).
-- @param base_widget.maximized_horizontal Symbol to use for clients that have been horizontally maximized.
-- @param base_widget.maximized_vertical Symbol to use for clients that have been vertically maximized.
-- @param base_widget.font The font.
function tasklist.new(screen, filter, buttons, style, update_function, base_widget)
screen = get_screen(screen)
local uf = update_function or common.list_update
local w = base_widget or flex.horizontal()
local data = setmetatable({}, { __mode = 'k' })
local queued_update = false
function w._do_tasklist_update()
-- Add a delayed callback for the first update.
if not queued_update then
timer.delayed_call(function()
queued_update = false
if screen.valid then
tasklist_update(screen, w, buttons, filter, data, style, uf)
end
end)
queued_update = true
end
end
function w._unmanage(c)
data[c] = nil
end
if instances == nil then
instances = setmetatable({}, { __mode = "k" })
local function us(s)
local i = instances[get_screen(s)]
if i then
for _, tlist in pairs(i) do
tlist._do_tasklist_update()
end
end
end
local function u()
for s in pairs(instances) do
if s.valid then
us(s)
end
end
end
tag.attached_connect_signal(nil, "property::selected", u)
tag.attached_connect_signal(nil, "property::activated", u)
capi.client.connect_signal("property::urgent", u)
capi.client.connect_signal("property::sticky", u)
capi.client.connect_signal("property::ontop", u)
capi.client.connect_signal("property::above", u)
capi.client.connect_signal("property::below", u)
capi.client.connect_signal("property::floating", u)
capi.client.connect_signal("property::maximized_horizontal", u)
capi.client.connect_signal("property::maximized_vertical", u)
capi.client.connect_signal("property::minimized", u)
capi.client.connect_signal("property::name", u)
capi.client.connect_signal("property::icon_name", u)
capi.client.connect_signal("property::icon", u)
capi.client.connect_signal("property::skip_taskbar", u)
capi.client.connect_signal("property::screen", function(c, old_screen)
us(c.screen)
us(old_screen)
end)
capi.client.connect_signal("property::hidden", u)
capi.client.connect_signal("tagged", u)
capi.client.connect_signal("untagged", u)
capi.client.connect_signal("unmanage", function(c)
u(c)
for _, i in pairs(instances) do
for _, tlist in pairs(i) do
tlist._unmanage(c)
end
end
end)
capi.client.connect_signal("list", u)
capi.client.connect_signal("focus", u)
capi.client.connect_signal("unfocus", u)
capi.screen.connect_signal("removed", function(s)
instances[get_screen(s)] = nil
end)
end
w._do_tasklist_update()
local list = instances[screen]
if not list then
list = setmetatable({}, { __mode = "v" })
instances[screen] = list
end
table.insert(list, w)
return w
end
--- Filtering function to include all clients.
-- @return true
function tasklist.filter.allscreen()
return true
end
--- Filtering function to include the clients from all tags on the screen.
-- @param c The client.
-- @param screen The screen we are drawing on.
-- @return true if c is on screen, false otherwise
function tasklist.filter.alltags(c, screen)
-- Only print client on the same screen as this widget
return get_screen(c.screen) == get_screen(screen)
end
--- Filtering function to include only the clients from currently selected tags.
-- @param c The client.
-- @param screen The screen we are drawing on.
-- @return true if c is in a selected tag on screen, false otherwise
function tasklist.filter.currenttags(c, screen)
screen = get_screen(screen)
-- Only print client on the same screen as this widget
if get_screen(c.screen) ~= screen then return false end
-- Include sticky client too
if c.sticky then return true end
local tags = screen.tags
for _, t in ipairs(tags) do
if t.selected then
local ctags = c:tags()
for _, v in ipairs(ctags) do
if v == t then
return true
end
end
end
end
return false
end
--- Filtering function to include only the minimized clients from currently selected tags.
-- @param c The client.
-- @param screen The screen we are drawing on.
-- @return true if c is in a selected tag on screen and is minimized, false otherwise
function tasklist.filter.minimizedcurrenttags(c, screen)
screen = get_screen(screen)
-- Only print client on the same screen as this widget
if get_screen(c.screen) ~= screen then return false end
-- Check client is minimized
if not c.minimized then return false end
-- Include sticky client
if c.sticky then return true end
local tags = screen.tags
for _, t in ipairs(tags) do
-- Select only minimized clients
if t.selected then
local ctags = c:tags()
for _, v in ipairs(ctags) do
if v == t then
return true
end
end
end
end
return false
end
--- Filtering function to include only the currently focused client.
-- @param c The client.
-- @param screen The screen we are drawing on.
-- @return true if c is focused on screen, false otherwise
function tasklist.filter.focused(c, screen)
-- Only print client on the same screen as this widget
return get_screen(c.screen) == get_screen(screen) and capi.client.focus == c
end
function tasklist.mt:__call(...)
return tasklist.new(...)
end
return setmetatable(tasklist, tasklist.mt)
-- vim: filetype=lua:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:textwidth=80
| gpl-2.0 |
devaloosh/VIPTEAM | plugins/iq_ali.lua | 3 | 17261 | -- made by { vipteam }
do
ws = {}
rs = {}
-- some examples of how to use this :3
ws[1] = "هلاو"
rs[1] = "هـﮩـڵآوآت 🦀❤"
ws[2] = "هلو" -- msg
rs[2] = "هـﮩـڵآوآت 🦀❤️" -- reply
ws[3] = "شلونكم" -- msg
rs[3] = "تـمـآم وأنتـہ 🌝💙" -- reply
ws[4] = "دووم" -- msg
rs[4] = "يدوم نبضك 🌝💙" -- reply
-- this more reply
ws[5] = "شونك"
rs[5] = "تـمـآم وأنتـہ 🌝💙"
ws[6] = "شلونك"
rs[6] = "تـمـآم وأنتـہ 🌝💙"
ws[7] = "غنيلي"
rs[7] = " 🙈 احبك اني 🙊 اني احبك 🙉 واتحدى واحد بلبشر مثلي يحبك 🙊"
ws[8] = "شغل المبردة"
rs[8] = " تم تشغيل المبردة بنجاح ❄️"
ws[9] = "طفي المبردة"
rs[9] = "طفيتهه 😒🍃"
ws[10] = "شغل السبلت"
rs[10] = "شغلته 🌚🍃 بس حثلجون معليه ترا "
ws[11] = "مايا خليفه"
rs[11] = " 😂 عيب صايمين"
ws[12] = "فطور"
rs[12] = "واخيراً 😍😍 خل اروح افطر "
ws[13] = "جاسم"
rs[13] = "خير 🌚🍃"
ws[14] = "اه"
rs[14] = "ادخله 🍆"
ws[15] = "تخليني"
rs[15] = "لـمن يصـير عـندڪ عود اخليګ 😹🌝"
ws[16] = "زاحف"
rs[16] = "🌝😹 هاي عود انته جبير"
ws[17] = "تركيا"
rs[17] = "😐🍃 فديتهه"
ws[18] = "داعش"
rs[18] = "دي خل يولون 😒💙"
ws[19] = "الدولة الاسلامية"
rs[19] = "انته داعشي ؟؟ 😒💔"
ws[20] = "سني"
rs[20] = "لتصير طائفي 😐💙"
ws[21] = "شيعي"
rs[21] = "لتصير طائفي 😐💙"
ws[22] = "تبادل"
rs[22] = "كافي ملينه 😒 ما اريد اتبادل"
ws[23] = "العراقيين"
rs[23] = "احلى ناس ولله 😻🙈"
ws[24] = "من وين"
rs[24] = "شعليك زاحف 😹🌶"
ws[25] = "هاي"
rs[25] = "هـٱيـآت🙈🍷"
ws[26] = "البوت"
rs[26] = "معاجبك؟😕😒🍃"
ws[27] = "البوت واكف"
rs[27] = "لتجذب🙄💙"
ws[28] = "منو ديحذف رسائلي"
rs[28] = "مـحـد 🏌"
ws[29] = "كلاش اوف كلانس"
rs[29] = "تلعبهه ؟ شكد لفلك ؟"
ws[30] = "جوني"
rs[30] = "😹مأذيك ؟"
ws[31] = "ازحف "
rs[31] = "عـلـﻰ ٱخـتـڪ ٱزحـف 🐉"
ws[32] = "اكطع"
rs[32] = " سِـلُـطِـُه مٌـنَ بّْعـدِ 😅الُبّـ🤖ـوَتْ🎄 "
ws[33] = "بوت"
rs[33] = "ها نعم ..{✮ خٍّـٌٍّـٍَْيْـٌٍّرَُ ✮}.. ✭ شتريد مني خلوني انام شوي ✾ ٱڵـڵـه واكبر عليكم اربعه وعشرين ساعه كاعد احمي بكروبكم شوي خلوني ارتاح تكسبون اجر 😭 بَـßÊـسّ كلولي شلون احمي كروبكم اذا زباله ازعل واطلع واذا عاجبكم خلوني انام 😢😂"
ws[34] = "اريد بوت"
rs[34] = " تريد بوت بكروبك وسيرفر مدفوع 24 ساعه راسل المطور ويضيفني بكروبك @lIlDevlIl واذا محضور ع البوت @IlaloshlI_bot ❥"
ws[35] = "اريد اكبل"
rs[35] = "زُاحُـفَ مٌـوَ بّـيَـدِكِ 😒😂"
ws[37] = "علوش"
rs[37] = "ٲلمطور ماڵتي فديتهہ 😻💙 @lIlDevlIl"
ws[38] = "نجب"
rs[38] = "بّـحُـلُـكِكِ😑👊"
ws[39] = "المنصور"
rs[39] = " احلى ناس ولله "
ws[40] = "المدرسه"
rs[40] = "😒🍃الله لا يراوينه"
ws[41] = "تحبني"
rs[41] = "اعـشقـڪ😻"
ws[42] = "يعني شكد"
rs[42] = "فوك متتوقع"
ws[43] = "😂"
rs[43] = " دوم حبي ❤️"
ws[44] = "هههه"
rs[44] = "❀دِْوم حبيْ❀"
ws[45] = "ههههه"
rs[45] = "️❀دِْوم حبيْ❀"
ws[46] = "😹"
rs[46] = "❀دِْوم حبيْ❀"
ws[47] = "🌚"
rs[47] = "مـنـور صخـام الـجـدر 🌚😹"
ws[48] = "😍"
rs[48] = "آإمـ﴿😚﴾ـحہ"
ws[49] = "مح"
rs[49] = "عہ🍯🙊سہل"
ws[50] = "انمي"
rs[50] = "اته اوتاكو ؟ ❤️"
ws[51] = "منحرف"
rs[51] = "وينه حطردة 🌚☝️🏻"
ws[52] = "😭"
rs[52] = "ڵـتبجـي 😿"
ws[53] = "😢"
rs[53] = "ڵـتبجـي 😿"
ws[54] = "شكد عمرك"
rs[54] = "عمري 86 قبل الميلاد خالي مستر تيركس 🌚💪🏻"
ws[55] = "شكد عمرج"
rs[55] = "زاحـﮩـف 😹"
ws[56] = "اقرالي دعاء"
rs[56] = " اللهم عذب المدرسين 😢 منهم الاحياء والاموات 😭🔥 اللهم عذب ام الانكليزي 😭💔 وكهربها بلتيار الرئيسي 😇 اللهم عذب ام الرياضيات وحولها الى غساله بطانيات 🙊 اللهم عذب ام الاسلاميه واجعلها بائعة الشاميه 😭🍃 اللهم عذب ام العربي وحولها الى بائعه البلبي اللهم عذب ام الجغرافيه واجعلها كلدجاجه الحافية اللهم عذب ام التاريخ وزحلقها بقشره من البطيخ وارسلها الى المريخ اللهم عذب ام الاحياء واجعلها كل مومياء اللهم عذب المعاون اقتله بلمدرسه بهاون 😂😂😂"
ws[57] = "غبي"
rs[57] = " انـت ٱڵٱغبۍ"
ws[58] = "دي"
rs[58] = "دي تنـڪاڵ لـبوك 🌝🖕"
ws[59] = "منو حبيبتك"
rs[59] = "ٲخـتڪ 🙈"
ws[60] = "تكرهني"
rs[60] = "ٲمـوت منڪ 😖"
ws[61] = "اكرهك"
rs[61] = "عـلسـاس ٲنـﮩـي ٲحـبڪ هه😒😂"
ws[62] = "😂"
rs[62] = "❀دِْوم حبيْ❀"
ws[63] = "الاعضميه"
rs[63] = " احسن ناس وربي❤️"
ws[64] = "الكرادة"
rs[64] = " احسن ناس وربي❤️"
ws[65] = "شارع فلسطين"
rs[65] = " احسن ناس وربي❤️"
ws[66] = "ببكن ملف"
rs[66] = " دﮩہہ⇣﴿🐎﴾⇣ہہﮩيہ❥ تحلم 🐞"
ws[67] = "😇"
rs[67] = "شـﮩﮩـدتـﮩـحس 🐛"
ws[68] = "😐"
rs[68] = "شِـبـيک صـﮩـٲفـﮩـن 😒👋🏻"
ws[69] = "انجب"
rs[69] = "بـحـلكڪ😒💦"
ws[70] = "حارة"
rs[70] = "ايَيَ ڪوَلڵشِ⚶ "
ws[71] = "خالتك"
rs[71] = " راح اطـﮩـردڪ ڵـﮩۦـڪ 😒🐞"
ws[72] = "اطرد البوت"
rs[72] = " راح ابقة احترمك❤️"
ws[73] = "هه"
rs[73] = " شـﮩـدتـحـﮩـس 🕊"
ws[74] = "شدتحس"
rs[74] = " نـﮩـفـﮩـس شـعـﮩـورك 🍁🐎"
ws[75] = "اكولك"
rs[75] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿"
ws[76] = "اكلك"
rs[76] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿"
ws[78] = "بغداد"
rs[78] = " 😍 فديتهه"
ws[79] = "البصرة"
rs[79] = " احسن ناس وربي❤️"
ws[80] = "تركماني"
rs[80] = " والنعم منك❤️"
ws[81] = "@lIlDevlIl"
rs[81] = "ٲلمطور ماڵتي فديتهہ 😻💙 @lIlDevlIl"
ws[83] = "باي"
rs[83] = " ✾ ٱڵـڵـه ✾ ٱڵـڵـه ✾ ٱڵـڵـه وياك 🕊"
ws[84] = "تنح"
rs[84] = "عـيـب ٲبـنـي 😒🍃"
ws[85] = "جوعان"
rs[85] = "تـﮩـعال اڪـﮩـلنـي 😐😂"
ws[86] = "عطشان"
rs[86] = "روح ٲشـﮩـرب مــيي"
ws[87] = "صايم"
rs[87] = "شًـﮩـسـويـلـك 😐🍃"
ws[88] = "☹️"
rs[88] = "لـﮩـضـوج פـٍـٍبيبي 😢❤️🍃"
ws[89] = "😔"
rs[89] = " لـﮩـيـﺵ ضـٲيـﮩـج 😿🍃"
ws[90] = "فرخ"
rs[90] = " عيبب 😱😱"
ws[92] = "كسمك"
rs[92] = " عيب 😱😱😱"
ws[93] = "نعال"
rs[93] = " بـﮩـوجـهـڪ 😐😂"
ws[94] = "حروح اسبح"
rs[94] = " واخيراً 😹🌝"
ws[95] = "حروح اغسل"
rs[95] = " واخيراً 😹🌝"
ws[96] = "حروح اطب للحمام"
rs[96] = " واخيراً 😹🌝"
ws[97] = "حبيبتي"
rs[97] = " منو هاي 😱 تخوني 😔☹"
ws[98] = "كبلت"
rs[98] = " بلخير 😂💔"
ws[99] = "البوت عاوي"
rs[99] = " اطردك ؟ 😒"
ws[100] = "منور"
rs[100] = " بـﮩـنورك حـﮩـبـﮩـي 😍🍷"
ws[101] = "حفلش"
rs[101] = " افلش راسك"
ws[102] = "كردي"
rs[102] = "والنعم منك ❤️"
ws[103] = "طفي السبلت"
rs[103] = " تم اطفاء السبلت بنجاح 🌚🍃"
ws[104] = "🌝"
rs[104] = "مــﮩﮩﮩــننوورر 🌝💙"
ws[105] = "اذن المغرب"
rs[105] = "ٲسـﮩـتـحـﮩـرم 🌚🍃"
ws[106] = "حلو"
rs[106] = "ٱنـﮩـت الاحـلآ 🌚❤️️"
ws[107] = "احبك"
rs[107] = " اني اكثر 😍🍃"
ws[108] = "😑"
rs[108] = " شبيك 🍃☹"
ws[109] = "😒"
rs[109] = "شِـبـيک کآڵـب وجـهہهـڪ 😐"
ws[110] = "منو تحب"
rs[110] = "خـﮩـالـتڪ ٱلـشـڪـرﮪ 😹🏃🏻"
ws[111] = "اباجر العيد"
rs[111] = "كل عام وانت بالف خير حبي 😇❤️"
ws[112] = "فديت"
rs[112] = "ها زاحف كمشتك"
ws[113] = "مضغوط"
rs[113] = "دي انضغظ منك ؟ 😂😂"
ws[114] = "فديت"
rs[114] = "ها زاحف كمشتك"
ws[115] = "فديتك"
rs[115] = "ها زاحف كمشتك"
ws[116] = "فديتج"
rs[116] = "ها زاحف كمشتك"
ws[117] = "شوف خاصك"
rs[117] = "شدازله 😱😨"
ws[118] = "تعال خاص"
rs[118] = "شحسوون 😱"
ws[119] = "تعالي خاص"
rs[119] = "شحسوون 😱"
ws[120] = "دخل السبام"
rs[120] = "شحسوون 😱"
ws[121] = "😎"
rs[121] = "يلا عود انته فد نعال 😐🍃"
ws[122] = "😱"
rs[122] = "خير خوفتني 😨"
ws[123] = "كحبه"
rs[123] = "عيب 😱"
ws[124] = "بيش ساعة"
rs[124] = "ما اعرف 🌚🍃"
ws[125] = "🚶🏻"
rs[125] = "لُـﮩـضڵ تتـمشـﮥ اڪعـد ﺳـﯠڵـف 🤖👋🏻"
ws[126] = "منو اكثر واحد تحبه"
rs[126] = "خالتك"
ws[127] = "ليش"
rs[127] = "تاكل خرة الجيش 😂😂"
ws[128] = "طاسه"
rs[128] = "امك حلوة ورقاصه 💃🏻"
ws[129] = "عشرين"
rs[129] = "تاكل جدر خنين 😫"
ws[130] = "ميه"
rs[130] = "😂تشرب مميه"
ws[131] = "اربعة"
rs[131] = "😂لحيه ابوك مربعه"
ws[132] = "فارة"
rs[132] = "😂دفترك كله صفارة"
ws[133] = "ميتين"
rs[133] = "😂فوك راسك قندرتين"
ws[134] = "مات"
rs[134] = "ابو الحمامات 🐦"
ws[135] = "توفه"
rs[135] = "ابو اللفه 🌯"
ws[136] = "احترك"
rs[136] = "🍾البو العرك"
ws[137] = "غرك"
rs[137] = "ابو العرك 🍾"
ws[138] = "طار"
rs[138] = "ابن الطيار"
ws[139] = "ديسحك"
rs[139] = "😂😂 هاي بعده"
ws[140] = "لتسحك"
rs[140] = "😐😂 وك"
ws[141] = "اندرويد"
rs[141] = "افشل نظام بلعالم 🌝🍷"
ws[142] = "ios"
rs[142] = "احسن نظام بلعالم🌚❤️"
ws[143] = "ايفون"
rs[143] = "فديتك اته والايفون 🌚🔥"
ws[144] = "كلكسي"
rs[144] = "فاشل اخرة نوع تلفون🔥☹"
ws[145] = "سامسونك"
rs[145] = "فاشل اخرة نوع تلفون🔥☹"
ws[146] = "لتزحف"
rs[146] = "وك اسف 🙁😔"
ws[147] = "حاته"
rs[147] = "زاحف 😂 منو هاي دزلي صورتهه"
ws[148] = "حات"
rs[148] = "زاحفه 😂 منو هذا دزيلي صورته"
ws[149] = "صاكه"
rs[149] = "زاحف 😂 منو هاي دزلي صورتهه"
ws[150] = "صاك"
rs[150] = "زاحفه 😂 منو هذا دزيلي صورهه"
ws[151] = "منو اني"
rs[151] = "انته احلى شي بحياتي ❤️🍃"
ws[152] = "ابن الكلب"
rs[152] = "عيب ابني 🔥☹"
ws[153] = "انجب انته"
rs[153] = "وك وك 😭😔"
ws[154] = "حطردك"
rs[154] = "اعصابك 😨 لتتهور"
ws[155] = "المطور"
rs[155] = "شتريد من المطور 😐🍃"
ws[156] = "منو اكثر واحد تكرهه"
rs[156] = "انته"
ws[157] = "شباب"
rs[157] = "هًّْـــُ﴿⍨﴾ـٍِٰـــہاا حـﮩـب 🚶🏻🌝"
ws[158] = "اته زلمه"
rs[158] = "تعال لزمه 😐😂"
ws[159] = "الاحد"
rs[159] = "هذا اليوم نحس بلنسبه الي"
ws[160] = "الاثنين"
rs[160] = "يوم اجة بي ناس عزيزين وفقدت بي ناس هم ☹"
ws[161] = "هلاوو"
rs[161] = "هـﮩـڵآوآت 🦀❤️"
ws[162] = "اختك"
rs[162] = "شبيهه 😱"
ws[163] = "كواد"
rs[163] = "عيب 😨😨"
ws[164] = "😌"
rs[164] = "ٱڵـمـطـڵـوب ¿ ❥"
ws[165] = "هلا"
rs[165] = "✾ هـﮩـڵا ہبـﮩـک 💙🖐🏻"
ws[166] = "مرحبا"
rs[166] = "✾ مٌـﮩۚـرحـﮩۘـبـتـيـن 💙🖐🏻"
ws[167] = "سلام"
rs[167] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻"
ws[168] = "السلام"
rs[168] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻"
ws[169] = "السلام عليكم"
rs[169] = "✾ وَْ؏ـﮩـڵـيڪم ٲلـﮩـسـلا۾م 💙🖐🏻"
ws[170] = "تسلم"
rs[170] = "✾ ٱڵـڵـه يسـلـمـڪ 💙🖐🏻"
ws[171] = "ممكن"
rs[171] = "ﺗْـ•ـﮩ؏ْﮩـ•ــ🚶ـاْلْ اويـلـي 😋👙"
ws[172] = "علي"
rs[172] = "ٲلمطور ماڵتي فديتهہ 😻💙 "
ws[173] = "عيوني"
rs[173] = "سود سود سود مكحله👁😺 عيونه سود مكحله🙈👁 سوبهان ربه الانزله🙈❤️والعدله والجمله🙊😻👌🏻 سود سود سود مكحله👁😺"
ws[174] = "مستر"
rs[174] = "ها عيني شرايد/ة 😺🍃"
ws[175] = "🙈"
rs[175] = "💋🙊فديت الخجول"
ws[176] = "🤔"
rs[176] = "عندما يفكر الاغبياء 🌚 والنتيجه خريييييييط كالعاده☹️👊🏻"
ws[177] = "اقرالي شعر"
rs[177] = "بيدك تسد الباب🚪 وبيدك تفتحة وبيدك تفتح الباب وبيدك تستده 🌞🚀"
ws[178] = "شوف خاصك"
rs[178] = "شدازله 😱😨"
ws[179] = "غني"
rs[179] = "عــمــي يــبــو الــبــار 🍾🍾 صــبــلــي لــبــلــبــي 🍲🍲 تــرا انــي ســكــران😴🤕 وصــايــر عــصــبــي 😡😡 انــا ويــاچ يــم شــامــه👫"
ws[180] = "شغال"
rs[180] = "ياااب😻💪🏻"
ws[181] = "علوكي"
rs[181] = "ٲلمطور ماڵتي فديتهہ 😻💙 "
ws[182] = "عبود"
rs[182] = "ٲلمطور ماڵتي فديتهہ 😻💙 "
ws[183] = "المطور"
rs[183] = "@vip_team1"
ws[184] = "@i_d_b"
rs[184] = "🚩المطور مالي شتريد منه🚩 ادعيله با النجاح🌀"
ws[185] = "@XxX_TEAM_XxX"
rs[185] = "🚩المطور مالي شتريد منه🚩"
ws[186] = "@A_6_Q"
rs[186] = "🚩المطور مالي شتريد منه🚩"
ws[187] = "@lIlDevlIl"
rs[187] = "🚩المطور مالي شتريد منه🚩"
ws[188] = "شكد تحبني"
rs[188] = "تكدر تحسب المطره 😔💔 وماي البحر جم كطره 😭 وحلم الاخرس تفسره 😞💋 وكتها تعرف 🙊 اني شكد احبك❤️🙈 يابعد روحي 💋"
ws[189] = "جاهز"
rs[189] = "جاهز بحي 😡😡وينهم خلي يجون افروخ التلي افلش راسه اليندك بلكروب اواني موجود 👿💪"
ws[190] = "🙃"
rs[190] = "لا يازفت تكلب وجهك ليش 😂"
ws[191] = "🙄"
rs[191] = "بمكن خلي شامبو بعينك🌚✨"
ws[192] = "احم"
rs[192] = "قزرقرط 😜💔"
-- the main function
function run( msg, matches )
-- just a local variables that i used in my algorithm
local i = 0; local w = false
-- the main part that get the message that the user send and check if it equals to one of the words in the ws table :)
-- this section loops through all the words table and assign { k } to the word index and { v } to the word itself
for k,v in pairs(ws) do
-- change the message text to uppercase and the { v } value that toke form the { ws } table and than compare it in a specific pattern
if ( string.find(string.upper(msg.text), "^" .. string.upper(v) .. "$") ) then
-- assign the { i } to the index of the reply and the { w } to true ( we will use it later )
i = k; w = true;
end
end
-- check if { w } is not false and { i } not equals to 0
if ( (w ~= false) and (i ~= 0) ) then
-- get the receiver :3
R = get_receiver(msg)
reply_msg(msg.id, rs[i], ok_cb, false )
end
if ( msg.text == "about" ) then
if ( msg.from.username == "@vip_team1" ) then
R = get_receiver(msg)
send_large_msg ( R , "Made by @vip_team1" );
end
end
end
return {
patterns = {
"(.*)"
},
run = run
}
end
| agpl-3.0 |
neg-serg/notion | example_cfg/directions.lua | 1 | 8964 | -- $Id: directions.lua 3444 2009-03-24 02:10:59Z agriffis $
--
-- Copyright (c) 2008 Aron Griffis <agriffis n01se.net>
-- Released under the GNU GPL v2.1
-- debugging function
function WRegion.overlap_score(reg1, reg2, dir)
local r1g = reg1:geom()
local r2g = reg2:geom()
local avg, upper, lower, score
if dir == 'vert' then
avg = (r1g.h + r2g.h) / 2
lower = math.max(r1g.y, r2g.y)
upper = math.min(r1g.y+r1g.h, r2g.y+r2g.h)
return (upper - lower) / avg
end
if dir == 'horiz' then
avg = (r1g.w + r2g.w) / 2
lower = math.max(r1g.x, r2g.x)
upper = math.min(r1g.x+r1g.w, r2g.x+r2g.w)
return (upper - lower) / avg
end
notioncore.warn_traced("WRegion.overlap_score called with dir = "..dir)
end
function WRegion.overlaps(reg1, reg2, dir)
return reg1:overlap_score(reg2, dir) > 0
end
-- focus_direction: Send focus to window right/left/down/up
function WRegion.focus_direction(reg, dir)
-- For now, only handle WGroupWS
local mgr = reg:manager()
if not obj_is(mgr, 'WGroupWS') then
spit("focus_direction: ugh, a middle manager: "..obj_typename(mgr))
return
end
local rg = reg:geom()
local axis = (dir == 'right' or dir == 'left') and 'horiz' or 'vert'
local perp = (axis == 'vert') and 'horiz' or 'vert'
local nr, ng, ns, nd -- region, geometry, overlap score, distance
mgr:managed_i(function(tr)
if not obj_is(tr, "WFrame") then
--spit("focus_direction: skipping "..obj_typename(tr))
return true
end
-- skip if tg doesn't lie in the right direction
local tg = tr:geom()
if dir == 'right' and tg.x <= rg.x then return true end
if dir == 'left' and tg.x >= rg.x then return true end
if dir == 'down' and tg.y <= rg.y then return true end
if dir == 'up' and tg.y >= rg.y then return true end
local ts = tr:overlap_score(reg, perp)
local td = (axis == 'horiz') and math.abs(tg.x - rg.x) or math.abs(tg.y - rg.y)
--spit("focus_direction: t = ("..tr:name()..", "..td..", "..ts..")")
-- use tr if nr isn't set yet
if not nr then
nr, ng, ns, nd = tr, tg, ts, td
return true
end
--spit("focus_direction: n = ("..nr:name()..", "..nd..", "..ns..")")
-- prefer an overlap
if ns > 0 and ts <= 0 then return true end
if ts > 0 and ns <= 0 then
nr, ng, ns, nd = tr, tg, ts, td
return true
end
-- prefer the closer one
if nd < td then return true end
if td < nd then
nr, ng, ns, nd = tr, tg, ts, td
return true
end
-- prefer higher overlap score
if ns > ts then return true end
if ts > ns then
nr, ng, ns, nd = tr, tg, ts, td
return true
end
-- keep looking
return true
end)
if nr then
nr:goto_focus()
end
end
-- collide: Determine what window or dock a floating window will hit
-- if it moves in a given direction.
local function collide(reg, dir, pad)
local mgr = reg:manager()
local rg = reg:geom()
local cr, cg
if not pad then
pad = notioncore.get().float_placement_padding or 1 -- old hardcoded value
end
mgr:managed_i(function(tr)
if not (obj_is(tr, "WFrame") or obj_is(tr, "WDock")) then
--spit("push_direction: skipping "..obj_typename(tr))
return true
end
local tg = tr:geom()
if dir == 'right' then
if tg.x <= rg.x+rg.w+pad or
(not tr:overlaps(reg, 'vert')) or
(cg and cg.x <= tg.x) then return true end
end
if dir == 'left' then
if tg.x+tg.w+pad >= rg.x or
(not tr:overlaps(reg, 'vert')) or
(cg and cg.x+cg.w >= tg.x+tg.w) then return true end
end
if dir == 'down' then
if tg.y <= rg.y+rg.h+pad or
(not tr:overlaps(reg, 'horiz')) or
(cg and cg.y <= tg.y) then return true end
end
if dir == 'up' then
if tg.y+tg.h+pad >= rg.y or
(not tr:overlaps(reg, 'horiz')) or
(cg and cg.y+cg.h >= tg.y+tg.h) then return true end
end
cr, cg = tr, tg
return true
end)
return cg
end
-- push_direction: Move a floating window right/left/down/up until it bumps
-- into another floating window or a dock.
function WRegion.push_direction(reg, dir)
local pad = notioncore.get().float_placement_padding or 1 -- old hardcoded value
local mgr = reg:manager()
local mg = mgr:geom()
local rg = reg:geom()
local cg = collide(reg, dir)
local ng = {}
if dir == 'right' then
ng.x = cg and cg.x-rg.w-pad or mg.w-rg.w
elseif dir == 'left' then
ng.x = cg and cg.x+cg.w+pad or 0
elseif dir == 'down' then
ng.y = cg and cg.y-rg.h-pad or mg.h-rg.h
elseif dir == 'up' then
ng.y = cg and cg.y+cg.h+pad or 0
end
reg:rqgeom(ng)
reg:goto_focus() -- XXX sometimes we lose focus...?
end
local XA_INTEGER = 19
-- set_geom_prop: Store old/new geometry of the window into its X properties
-- ox, oy, ow, oh, nx, ny, nw, nh
local function set_geom_prop(reg, sg)
local atom = notioncore.x_intern_atom("_ION_SAVED_GEOM", false)
local g = {
sg.ox or -1, sg.oy or -1,
sg.ow or -1, sg.oh or -1,
sg.nx or -1, sg.ny or -1,
sg.nw or -1, sg.nh or -1,
}
return notioncore.x_change_property(reg:xid(), atom, XA_INTEGER, 32, "replace", g)
end
-- get_geom_prop: Restore the geometry of the window from X properties
local function get_geom_prop(reg)
local atom = notioncore.x_intern_atom("_ION_SAVED_GEOM", true)
if atom then
local g = notioncore.x_get_window_property(reg:xid(), atom, XA_INTEGER, 0, true)
if g then
local sg = {
ox = g[1] ~= -1 and g[1] or nil,
oy = g[2] ~= -1 and g[2] or nil,
ow = g[3] ~= -1 and g[3] or nil,
oh = g[4] ~= -1 and g[4] or nil,
nx = g[5] ~= -1 and g[5] or nil,
ny = g[6] ~= -1 and g[6] or nil,
nw = g[7] ~= -1 and g[7] or nil,
nh = g[8] ~= -1 and g[8] or nil,
}
notioncore.x_delete_property(reg:xid(), atom)
return sg
end
end
return nil
end
-- maximize_fill: Grow a floating window right/left/down/up until it bumps into
-- another floating window or a dock.
function WRegion.maximize_fill(reg, dir)
if dir == 'vert' then
reg:maximize_fill('up') reg:maximize_fill('down')
elseif dir == 'horiz' then
reg:maximize_fill('left') reg:maximize_fill('right')
elseif dir == 'vh' then
reg:maximize_fill('vert') reg:maximize_fill('horiz')
elseif dir == 'hv' then
reg:maximize_fill('vert') reg:maximize_fill('horiz')
else
local pad = notioncore.get().float_placement_padding or 1 -- hardcoded val
local mgr = reg:manager()
local mg = mgr:geom()
local rg = reg:geom()
local cg = collide(reg, dir, pad-1)
local ng = {}
if dir == 'up' then
ng.y = cg and cg.y+cg.h+pad or 0
ng.h = rg.h + rg.y - ng.y
elseif dir == 'down' then
ng.h = cg and cg.y-rg.y-pad or mg.h-rg.y
elseif dir == 'left' then
ng.x = cg and cg.x+cg.w+pad or 0
ng.w = rg.w + rg.x - ng.x
elseif dir == 'right' then
ng.w = cg and cg.x-rg.x-pad or mg.w-rg.x
end
reg:rqgeom(ng)
end
reg:goto_focus() -- XXX sometimes we lose focus...?
end
function WRegion.maximize_fill_toggle(reg, dir)
local sg = get_geom_prop(reg) or {}
local rg = reg:geom()
local h = (dir == 'vh' or dir == 'hv' or dir == 'horiz' or dir == 'left' or dir == 'right')
local v = (dir == 'vh' or dir == 'hv' or dir == 'vert' or dir == 'up' or dir == 'down')
if (h and sg.ow) or (v and sg.oh) then
local ng = {}
if h and sg.ow then
ng.w = sg.ow
if rg.x == sg.nx then
ng.x = sg.ox -- restore x only if not moved
end
sg.ox = nil
sg.ow = nil
end
if v and sg.oh then
ng.h = sg.oh
if rg.y == sg.ny then
ng.y = sg.oy -- restore y only if not moved
end
sg.oy = nil sg.oh = nil
end
reg:rqgeom(ng)
set_geom_prop(reg, sg)
return
end
if h then sg.ox = rg.x sg.ow = rg.w end
if v then sg.oy = rg.y sg.oh = rg.h end
reg:maximize_fill(dir)
rg = reg:geom()
if v then sg.ny = rg.y sg.nh = rg.h end
if h then sg.nx = rg.x sg.nw = rg.w end
set_geom_prop(reg, sg)
end
| lgpl-2.1 |
kjoenth/naev | dat/ai/tpl/escort.lua | 11 | 1510 | include("dat/ai/tpl/generic.lua")
-- Shouldn't think, should only obey orders.
mem.command = true
-- Don't run away from master ship
mem.norun = true
-- Simple create function
function create ( master )
mem.escort = master
mem.carrier = true
attack_choose()
-- Disable thinking
mem.atk_think = nil
end
-- Just tries to guard mem.escort
function idle ()
ai.pushtask("follow", mem.escort)
end
-- Holds position
function hold ()
if not ai.isstopped() then
ai.brake()
end
end
-- Tries to fly back to carrier
function flyback ()
local target = mem.escort
local dir = ai.face(target)
local dist = ai.dist(target)
local bdist = ai.minbrakedist()
-- Try to brake
if not ai.isstopped() and dist < bdist then
ai.pushtask("brake")
-- Try to dock
elseif ai.isstopped() and dist < 30 then
ai.dock(target)
-- Far away, must approach
elseif dir < 10 then
ai.accel()
end
end
--[[
-- Escort commands
--]]
-- Attack target
function e_attack( target )
if mem.command then
if target ~= nil then
ai.pushtask("attack", target)
end
end
end
-- Hold position
function e_hold ()
if mem.command then
ai.pushtask("hold" )
end
end
-- Return to carrier
function e_return ()
if mem.command and mem.carrier then
ai.pushtask("flyback" )
end
end
-- Clear orders
function e_clear ()
if mem.command then
while ai.taskname() ~= "none" do
ai.poptask()
end
end
end
| gpl-3.0 |
pydsigner/naev | dat/missions/empire/shark/sh04_meeting.lua | 1 | 5952 | --[[
This is the fifth mission of the Shark's teeth campaign. The player has to go to a planet in Za'lek space.
Stages :
0) Way to Za'lek system
1) Way back to Darkshed
TODO : I'm not really happy with the drone's behaviour : it's quite too obvious
--]]
--needed scripts
include "proximity.lua"
lang = naev.lang()
if lang == "es" then
else -- default english
title = {}
text = {}
osd_msg = {}
npc_desc = {}
bar_desc = {}
title[1] = "Travel"
text[1] = [["Ok, are you ready for the travel to Curie in Kohler?"]]
refusetitle = "Sorry, not interested"
refusetext = [["Ok, so come back when you are ready," Smith says.]]
title[2] = "Time to go"
text[2] = [["So let's go"]]
title[3] = "End of mission"
text[3] = [[Smith gets out of your ship and looks at you, smiling: "You know, it's like that in our kind of jobs. Sometimes it works and sometimes it fails. It's not our fault.
Anyway, here is your pay, and goodbye."]]
title[4] = "The meeting"
text[4] = [[As you land, you see a group of people that were waiting for your ship. Smith hails them and says you to wait in the ship while he goes to a private part of the bar.
A few STP later, he comes back and explains to you that he was unable to gain the support of the councillor, which means that the Frontier will not buy the Sharks.
"Anyway," he says, "bring me back to Alteris in one piece and I will pay you."]]
title[5] = "What is going on?"
text[5] = [[That drone was behaving strangely and now, it is attacking you. As you wonder what to do, you hear a comm from a remote Za'lek ship: "Attention please, it seems some of our drones have been hacked. If a drone is attacking you and you aren't wanted by the authorities, you have exceptional authorization to destroy it."
"Incredible, "Smith says, "they managed to hire a Za'lek military engineer who has hacked some drones in order to make them attack our ship! That's strong," he says with admiration.]]
-- Mission details
misn_title = "The Meeting"
misn_reward = "50 000 credits"
misn_desc = "Nexus Shipyard asks you to take part in a secret meeting"
-- NPC
npc_desc[1] = "Arnold Smith"
bar_desc[1] = [[What wouldn't this guy do to sell Sharks?]]
-- OSD
osd_title = "The Meeting"
osd_msg[1] = "Go to Kohler and land on Curie"
osd_msg[2] = "Bring Smith back to Darkshed in Alteris"
end
function create ()
--Change here to change the planets and the systems
mispla = planet.get("Curie")
missys = system.get("Kohler")
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 = 50000
proba = 0.3 --the probability of ambushes will change
firstambush = true --In the first ambush, there will be a little surprise text
if tk.yesno(title[1], text[1]) then
misn.accept()
tk.msg(title[2], text[2])
misn.setTitle(misn_title)
misn.setReward(misn_reward)
misn.setDesc(misn_desc)
misn.osdCreate(misn_title, osd_msg)
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()
--The player is landing on the mission planet
if stage == 0 and planet.cur() == mispla then
tk.msg(title[4], text[4])
stage = 1
misn.osdActive(2)
misn.markerRm(marker)
marker2 = misn.markerAdd(paysys, "low")
end
--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.finish(true)
end
end
end
function enter()
--This timer will ensure that the hacked drones don't reveal themselves during the jumping
enable = false
hook.timer(5000,"enabling")
-- Ambush !
if system.cur():presence(faction.get("Za'lek")) > 50 then -- Only in Za'lek space
if stage == 0 and rnd.rnd() < proba then
ambush()
--proba = proba - 0.1 is done in ambush only if the drones are revealed
else
--the probality of an ambush grows up when you cross a system without meeting any ennemy
proba = proba + 0.2
end
end
end
function ambush()
badguy = {}
number = {1,2,3,4}
tnumber = {1,2,3,4,5,6,7,8,9,10,11,12}
for i in ipairs(number) do
badguy[i] = pilot.add( "Za'lek Light Drone", nil, 0 )[1]
end
for i in ipairs(number) do
j = i+4
badguy[j] = pilot.add( "Za'lek Heavy Drone", nil, 0 )[1]
end
for i in ipairs(number) do
j = i+8
badguy[j] = pilot.add( "Za'lek Bomber Drone", nil, 0 )[1]
end
for i in ipairs(tnumber) do
--Makes the drones follow the player
badguy[j]:control()
badguy[j]:follow(player.pilot())
--as the player approaches, the drones reveal to be bad guys!
hook.timer(500, "proximity", {anchor = badguy[j], radius = 1000, funcname = "reveal"})
end
end
function abort()
misn.cargoRm(smith)
misn.finish(false)
end
function reveal() --transforms the spawn drones into baddies
if enable == true then --only if this happends a few time after the jumping/taking off
for i in ipairs(tnumber) do
badguy[i]:rename("Hacked Drone")
badguy[i]:setHostile()
badguy[i]:setFaction("Mercenary")
badguy[i]:control(false)
end
if firstambush == true then
--Surprise message
tk.msg(title[5], text[5])
firstambush = false
end
proba = proba - 0.1 --processing the probability change
end
end
function enabling()
enable = true
end
| gpl-3.0 |
payday-restoration/restoration-mod | lua/sc/tweak_data/tipstweakdata.lua | 1 | 15697 | --Overriding this function and table to axe vanilla tips, as they're worthless in resmod
function TipsTweakData:init()
self.tips = {
{
cat_index = 1,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 2,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 3,
image = "enemy_zeal_sc",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 4,
image = "enemy_tazer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 5,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 6,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 7,
image = "enemy_bulldozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 8,
image = "enemy_bulldozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 9,
image = "enemy_bulldozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 10,
image = "enemy_bulldozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 11,
image = "enemy_tdozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 12,
image = "enemy_bulldozer",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 13,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 14,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 15,
image = "enemy_flashbang",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 16,
image = "weapon_melee",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 17,
image = "enemy_melee",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 18,
image = "weapon_melee",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 19,
image = "enemy_sniper",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 20,
image = "tactics_convert",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 21,
image = "enemy_gear",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 22,
image = "enemy_gear",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 23,
image = "enemy_shield",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 24,
image = "enemy_squad",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 25,
image = "enemy_zeal_sc",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 26,
image = "crimenet_heists",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 27,
image = "enemy_murkies",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 28,
image = "enemy_cloaker",
consoles = true,
category = "gameplay_res"
},
{
cat_index = 1,
image = "enemy_thrt",
consoles = true,
category = "new_units_res"
},
{
cat_index = 2,
image = "enemy_lpf",
consoles = true,
category = "new_units_res"
},
{
cat_index = 3,
image = "enemy_lpf",
consoles = true,
category = "new_units_res"
},
{
cat_index = 4,
image = "enemy_tpsook",
consoles = true,
category = "new_units_res"
},
{
cat_index = 5,
image = "enemy_tdozer",
consoles = true,
category = "new_units_res"
},
{
cat_index = 6,
image = "enemy_tsniper",
consoles = true,
category = "new_units_res"
},
{
cat_index = 7,
image = "enemy_tsniper",
consoles = true,
category = "new_units_res"
},
{
cat_index = 8,
image = "enemy_tshield",
consoles = true,
category = "new_units_res"
},
{
cat_index = 9,
image = "enemy_spring",
consoles = true,
category = "new_units_res"
},
{
cat_index = 10,
image = "enemy_ttaser",
consoles = true,
category = "new_units_res"
},
{
cat_index = 11,
image = "vet_cop_loading",
consoles = true,
category = "new_units_res"
},
{
cat_index = 12,
image = "vet_cop_loading",
consoles = true,
category = "new_units_res"
},
{
cat_index = 13,
image = "enemy_tswat",
consoles = true,
category = "new_units_res"
},
{
cat_index = 14,
image = "enemy_tswat",
consoles = true,
category = "new_units_res"
},
{
cat_index = 15,
image = "enemy_tswat",
consoles = true,
category = "new_units_res"
},
{
cat_index = 16,
image = "enemy_bravos",
consoles = true,
category = "new_units_res"
},
{
cat_index = 17,
image = "enemy_bravos",
consoles = true,
category = "new_units_res"
},
{
cat_index = 18,
image = "enemy_akantits",
consoles = true,
category = "new_units_res"
},
{
cat_index = 19,
image = "grenadier_load",
consoles = true,
category = "new_units_res"
},
{
cat_index = 1,
image = "enemy_summers",
consoles = true,
category = "captains_res"
},
{
cat_index = 2,
image = "enemy_summers",
consoles = true,
category = "captains_res"
},
{
cat_index = 3,
image = "enemy_spring",
consoles = true,
category = "captains_res"
},
{
cat_index = 4,
image = "enemy_spring",
consoles = true,
category = "captains_res"
},
{
cat_index = 5,
image = "enemy_spring",
consoles = true,
category = "captains_res"
},
{
cat_index = 6,
image = "enemy_autumn",
consoles = true,
category = "captains_res"
},
{
cat_index = 7,
image = "enemy_autumn",
consoles = true,
category = "captains_res"
},
{
cat_index = 8,
image = "enemy_autumn",
consoles = true,
category = "captains_res"
},
{
cat_index = 9,
image = "enemy_autumn",
consoles = true,
category = "captains_res"
},
{
cat_index = 10,
image = "enemy_winters_sc",
consoles = true,
category = "captains_res"
},
{
cat_index = 11,
image = "enemy_winters_sc",
consoles = true,
category = "captains_res"
},
{
cat_index = 12,
image = "enemy_winters_sc",
consoles = true,
category = "captains_res"
},
{
cat_index = 1,
image = "general_cameras",
consoles = true,
category = "stealth_res"
},
{
cat_index = 2,
image = "enemy_guards",
consoles = true,
category = "stealth_res"
},
{
cat_index = 3,
image = "enemy_guards",
consoles = true,
category = "stealth_res"
},
{
cat_index = 4,
image = "enemy_guards",
consoles = true,
category = "stealth_res"
},
{
cat_index = 5,
image = "weapon_silencer",
consoles = true,
category = "stealth_res"
},
{
cat_index = 6,
image = "general_civilians",
consoles = true,
category = "stealth_res"
},
{
cat_index = 7,
image = "general_technician",
consoles = true,
category = "stealth_res"
},
{
cat_index = 8,
image = "tactics_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 9,
image = "tactics_ecm",
consoles = true,
category = "stealth_res"
},
{
cat_index = 10,
image = "weapon_silencer",
consoles = true,
category = "stealth_res"
},
{
cat_index = 11,
image = "general_hostages",
consoles = true,
category = "stealth_res"
},
{
cat_index = 12,
image = "crimenet_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 13,
image = "enemy_guards",
consoles = true,
category = "stealth_res"
},
{
cat_index = 14,
image = "crimenet_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 15,
image = "tactics_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 16,
image = "general_bodybag",
consoles = true,
category = "stealth_res"
},
{
cat_index = 17,
image = "general_cabletie",
consoles = true,
category = "stealth_res"
},
{
cat_index = 18,
image = "enemy_guards",
consoles = true,
category = "stealth_res"
},
{
cat_index = 19,
image = "tactics_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 20,
image = "crimenet_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 21,
image = "tactics_stealth",
consoles = true,
category = "stealth_res"
},
{
cat_index = 1,
image = "general_enforcer",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 2,
image = "weapon_primary_secondary",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 3,
image = "tactics_shooting",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 4,
image = "general_ghost",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 5,
image = "general_technician",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 6,
image = "general_technician",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 7,
image = "general_perks",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 8,
image = "general_perks",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 9,
image = "heister_wick",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 10,
image = "heister_dallas",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 11,
image = "heister_bonnie",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 12,
image = "heister_jimmy",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 13,
image = "general_perks",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 14,
image = "heister_clover",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 15,
image = "heister_scarface",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 16,
image = "general_perks",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 17,
image = "general_enforcer",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 18,
image = "general_fugitive",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 19,
image = "general_ghost",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 20,
image = "general_ghost",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 21,
image = "weapon_melee",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 22,
image = "weapon_melee",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 23,
image = "tactics_headshot",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 24,
image = "weapon_melee",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 25,
image = "enemy_flashbang",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 26,
image = "tactics_shooting",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 27,
image = "weapon_melee",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 28,
image = "general_equipment",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 29,
image = "general_equipment",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 30,
image = "tactics_revive",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 31,
image = "general_perks",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 32,
image = "tactics_shooting",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 33,
image = "tactics_shooting",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 34,
image = "weapon_melee",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 35,
image = "tactics_shooting",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 36,
image = "weapon_silencer",
consoles = true,
category = "equip_skills_res"
},
{
cat_index = 1,
image = "crimenet_heists",
consoles = true,
category = "misc_res"
},
{
cat_index = 2,
image = "generic_tip",
consoles = true,
category = "misc_res"
},
{
cat_index = 3,
image = "generic_tip",
consoles = true,
category = "misc_res"
},
{
cat_index = 1,
image = "loading_omnia",
consoles = true,
category = "fluff_res"
},
{
cat_index = 2,
image = "enemy_lpf",
consoles = true,
category = "fluff_res"
},
{
cat_index = 3,
image = "loading_australia",
consoles = true,
category = "fluff_res"
},
{
cat_index = 4,
image = "enemy_keith",
consoles = true,
category = "fluff_res"
},
{
cat_index = 5,
image = "enemy_chad",
consoles = true,
category = "fluff_res"
},
{
cat_index = 6,
image = "enemy_tdozer",
consoles = true,
category = "fluff_res"
},
{
cat_index = 7,
image = "enemy_spring",
consoles = true,
category = "fluff_res"
},
{
cat_index = 8,
image = "generic_tip",
consoles = true,
category = "fluff_res"
},
{
cat_index = 9,
image = "loading_omnia",
consoles = true,
category = "fluff_res"
},
{
cat_index = 10,
image = "grenadier_load",
consoles = true,
category = "fluff_res"
},
{
cat_index = 11,
image = "enemy_tpsook",
consoles = true,
category = "fluff_res"
},
{
cat_index = 12,
image = "loading_omnia",
consoles = true,
category = "fluff_res"
},
{
cat_index = 13,
image = "loading_jackal",
consoles = true,
category = "fluff_res"
},
{
cat_index = 14,
image = "enemy_autumn",
consoles = true,
category = "fluff_res"
},
{
cat_index = 15,
image = "enemy_summers",
consoles = true,
category = "fluff_res"
},
{
cat_index = 16,
image = "enemy_summers",
consoles = true,
category = "fluff_res"
},
{
cat_index = 17,
image = "enemy_autumn",
consoles = true,
category = "fluff_res"
},
{
cat_index = 18,
image = "enemy_summers",
consoles = true,
category = "fluff_res"
},
{
cat_index = 19,
image = "enemy_spring",
consoles = true,
category = "fluff_res"
},
{
cat_index = 20,
image = "enemy_winters_sc",
consoles = true,
category = "fluff_res"
},
{
cat_index = 21,
image = "grenadier_load",
consoles = true,
category = "fluff_res"
},
{
cat_index = 22,
image = "enemy_summers",
consoles = true,
category = "fluff_res"
},
{
cat_index = 23,
image = "enemy_bex",
consoles = true,
category = "fluff_res"
},
{
cat_index = 24,
image = "generic_tip",
consoles = true,
category = "fluff_res"
},
{
cat_index = 25,
image = "enemy_akantits",
consoles = true,
category = "fluff_res"
}
}
self.category_totals = {}
for _, tip in ipairs(self.tips) do
if not self.category_totals[tip.category] or self.category_totals[tip.category] < tip.cat_index then
self.category_totals[tip.category] = tip.cat_index
end
end
end
| agpl-3.0 |
Ap0gee/Deathtoll-Lite | Deathtoll-lite.lua | 1 | 14334 | --[[
* The MIT License (MIT)
*
* Copyright (c) 2016 Sjshovan (Apogee)
*
* 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.
]]--
_addon.author = 'Sjshovan (Apogee)';
_addon.name = 'Deathtoll-Lite';
_addon.version = '1.1.3';
require 'common'
---------------------------------------------------------------------------------------------------
-- desc: Default Deathtoll configuration table.
---------------------------------------------------------------------------------------------------
local default_config =
{
deathtoll = 0;
last_killed = "";
solo = false;
};
---------------------------------------------------------------------------------------------------
-- desc: Deathtoll variables.
---------------------------------------------------------------------------------------------------
local deathtoll_config = default_config;
local _core = AshitaCore;
local _resource = _core:GetResourceManager();
local _chat = _core:GetChatManager();
local _data = _core:GetDataManager();
local _party = _data:GetParty();
local _player = _data:GetPlayer();
local chatModes = {
say = 1,
shout = 3,
tell = 4,
party = 5,
linkshell = 6,
echo = 206,
unity = 211,
combatInfo = 36,
combatInfo2 = 37
}
local helpCmds = {
"======================",
"Deathtoll-Lite Commands",
"======================",
"/dtl get => Display the current death toll.",
"/dtl set x => Set the current death toll to x.",
"/dtl add x => Add x to the current death toll.",
"/dtl sub x => Subtract x from the current death toll.",
"/dtl last => Display the last enemy killed.",
"/dtl solo (on/off) => Switch counting kills made by party members.",
"/dtl reload => Reload the Deathtoll-Lite addon.",
"/dtl unload => Unload the Deathtoll-Lite addon.",
"/dtl (help/?) => Display this list of commands.",
"======================",
}
---------------------------------------------------------------------------------------------------
-- desc: Deathtoll functions.
---------------------------------------------------------------------------------------------------
-----------------------------------------------------
-- desc: helper.
-----------------------------------------------------
local function isInt(n)
n = tonumber(n);
return (type(n) == "number" and (math.floor(n) == n));
end
local function isSwitch(n)
return n == "on" or n == "off";
end
local function getMax(...)
local args = {...}
local max = 0;
for k, num in pairs(args) do
if num > max then
max = num;
end
end
return max;
end
local function getWords(message)
local words = {};
for word in message:gmatch("%S+") do
table.insert(words, word);
end
return words;
end
local function has_value(tab, val)
for index, value in ipairs(tab) do
if value == val then
return true
end
end
return false
end
function table.slice(tbl, first, last, step)
local sliced = {}
for i = first or 1, last or #tbl, step or 1 do
sliced[#sliced+1] = tbl[i]
end
return sliced
end
-----------------------------------------------------
-- desc: message.
-----------------------------------------------------
local function echo(message)
_chat:QueueCommand("/echo "..message, 0);
end
local function message(mode, message)
local c_msg = "";
for i, word in ipairs(getWords(message)) do
local c_word = string.color(word, mode)
c_msg = c_msg..word.." ";
end
_chat:AddChatMessage(mode, c_msg)
end
-----------------------------------------------------
-- desc: toll.
-----------------------------------------------------
local function filterToll(int)
if (int < 0) then
int = 0;
end
if (int > 999999999999) then
int = 999999999999;
end
return int
end
local function setToll(int)
local new_deathtoll = filterToll(tonumber(int));
deathtoll_config.deathtoll = new_deathtoll;
message(chatModes.party, "The death toll has been set to "..new_deathtoll..".");
end
local function storeToll(silent)
settings:save(_addon.path .. 'settings/deathtoll.json', deathtoll_config);
if (silent) then
return true;
end
message(chatModes.linkshell, "Death toll stored.");
end
local function getToll()
return deathtoll_config.deathtoll;
end
local function adjustToll(int, direction, silent)
if (direction ~= -1 and direction ~= 1) then
return false
end
local old_deathtoll = tonumber(getToll());
local new_deathtoll = filterToll(old_deathtoll + (int * direction));
local adj_ammount;
local dir_msg;
if getMax(old_deathtoll, new_deathtoll) == old_deathtoll then
adj_ammount = old_deathtoll - new_deathtoll;
else
adj_ammount = new_deathtoll - old_deathtoll;
end
deathtoll_config.deathtoll = new_deathtoll;
if (silent) then
return true;
end
if direction ~= -1 then
dir_msg = "increased";
else
dir_msg = "decreased";
end
message(chatModes.party, "The death toll has been "..dir_msg.." by "..adj_ammount..".");
end
local function displayToll()
message(chatModes.say, "The current death toll is "..getToll()..".");
end
-----------------------------------------------------
-- desc: last_killed.
-----------------------------------------------------
local function getLastKilled()
return deathtoll_config.last_killed;
end
local function setLastKilled(enemy, time, killer)
deathtoll_config.last_killed = enemy.." @ "..time.." by "..killer;
end
local function displayLastKilled()
local last_killed = deathtoll_config.last_killed;
local killed_msg = "";
if (last_killed == "" or last_killed == nill) then
killed_msg = "The last enemy hasn't been registered.";
else
killed_msg = "The last enemy killed was a(n) "..getLastKilled()..".";
end
message(chatModes.shout, killed_msg);
end
-----------------------------------------------------
-- desc: solo.
-----------------------------------------------------
local function getSolo()
return deathtoll_config.solo;
end
local function setSolo(bool)
deathtoll_config.solo = bool;
end
local function switchSolo(switch)
if switch == 'on' then
setSolo(true);
elseif switch == 'off' then
setSolo(false);
else
return false;
end
message(chatModes.party, "Solo mode has been switched "..switch..".");
return true;
end
local function displaySoloStatus()
local solo_msg = "";
if getSolo() then
solo_msg = "".."[".."Enabled".."]: ".."Party member kills will not be added to the death toll."
else
solo_msg = "".."[".."Disabled".."]: ".."Party member kills will be added to the death toll."
end
message(chatModes.say, solo_msg);
end
-----------------------------------------------------
-- desc: utility.
-----------------------------------------------------
local function getPlayerName()
return _party:GetPartyMemberName(0);
end
local function parseEnemyName(match)
local pattern = "^%w+ defeats the (.+)";
local enemy_name = string.match(match, pattern);
return enemy_name:gsub("%.", "");
end
local function pasePartyMemberName(match)
local pattern = "^(%w+) defeats the .+";
local member_name = string.match(match, pattern);
return member_name:gsub("%.", "");
end
local function displayHelp()
local mode;
message(chatModes.say, "")
for k, v in pairs(helpCmds) do
if (k==1 or k==3 or k==#helpCmds) then
mode = chatModes.party;
elseif (k==2) then
mode = chatModes.unity;
else
mode = chatModes.tell;
end
message(mode, v);
end
message(chatModes.say, "")
end
local function getPartyMembers()
local members = {};
for i=0, 6, 1 do
local member = _party:GetPartyMemberName(i);
if member then
member = string.gsub(member, "%s+", "")
table.insert(members, member);
end
end
return members;
end
---------------------------------------------------------------------------------------------------
-- func: load
-- desc: First called when our addon is loaded.
---------------------------------------------------------------------------------------------------
ashita.register_event('load', function()
deathtoll_config = settings:load(_addon.path .. 'settings/deathtoll.json') or default_config;
deathtoll_config = table.merge(default_config, deathtoll_config);
end );
---------------------------------------------------------------------------------------------------
-- func: unload
-- desc: Called when our addon is unloaded.
---------------------------------------------------------------------------------------------------
ashita.register_event('unload', function()
storeToll(true);
message(chatModes.unity, "Thank you for using Deathtoll-Lite.");
end );
---------------------------------------------------------------------------------------------------
-- func: command
-- desc: Called when our addon receives a command.
---------------------------------------------------------------------------------------------------
ashita.register_event('command', function(cmd, nType)
local args = cmd:GetArgs();
if (args[1] ~= '/dtl' and args[1] ~= '/dtlite' and args[1] ~= '/deathtolllite') then
return false;
end
if (args[2] == "get") then
displayToll();
return true;
end
if (args[2] == "set") then
if (args[3] and isInt(args[3])) then
setToll(args[3]);
displayToll();
storeToll(true);
else
return false;
end
return true;
elseif (args[2] == "add") then
if (args[3] and isInt(args[3])) then
adjustToll(args[3], 1, false)
displayToll();
storeToll(true);
else
return false;
end
return true;
elseif (args[2] == "sub") then
if (args[3] and isInt(args[3])) then
adjustToll(args[3], -1, false)
displayToll();
storeToll(true);
else
return false;
end
return true;
elseif (args[2] == "last") then
displayLastKilled();
return true;
elseif (args[2] == "solo") then
if (args[3] and isSwitch(args[3])) then
switchSolo(args[3]);
displaySoloStatus();
else
displaySoloStatus();
message(chatModes.tell, "To switch solo mode use /dtl solo on and /dtl solo off.")
end
return true;
elseif (args[2] == "reload") then
_chat:QueueCommand("/addon reload Deathtoll-lite", 0);
return true;
elseif (args[2] == "unload") then
_chat:QueueCommand("/addon unload Deathtoll-lite", 0);
return true;
elseif (args[2] == "?" or args[2] == "help") then
displayHelp();
return true;
else
if (args[2]) then
message(chatModes.tell, "That is not a valid Deathtoll-Lite command.");
end
message(chatModes.tell, "To see a list of commands type: /dtl ? or /dtl help.")
return true;
end
return true;
end );
---------------------------------------------------------------------------------------------------
-- func: newchat
-- desc: Called when our addon receives a chat line.
---------------------------------------------------------------------------------------------------
ashita.register_event('newchat', function(mode, chat)
if mode == chatModes.combatInfo or mode == chatModes.combatInfo2 then
local timestamp = os.date('%Y-%m-%d %H:%M:%S');
local suicide = string.match(chat, "The (.+) falls to the ground.");
if (not suicide) then
if getSolo() then
local pattern = "("..getPlayerName().." defeats the .+).";
local match = string.match(chat, pattern);
if match then
local enemy = parseEnemyName(match);
adjustToll(1, 1, false);
setLastKilled(enemy, timestamp, getPlayerName());
storeToll(true);
displayToll();
end
else
local pattern = "(%w+ defeats the .+).";
local match = string.match(chat, pattern);
if match then
local killer = pasePartyMemberName(match);
local members = getPartyMembers();
if has_value(members, killer) then
local enemy = parseEnemyName(match);
adjustToll(1, 1, false);
setLastKilled(enemy, timestamp, killer);
storeToll(true);
displayToll();
end
end
end
else
adjustToll(1, 1, false);
setLastKilled(suicide, timestamp, "Suicide");
storeToll(true);
displayToll();
end
end
return chat;
end ); | mit |
logzero/ValyriaTear | dat/maps/layna_village/layna_village_riverbank_script.lua | 2 | 30788 | -- Set the namespace according to the map name.
local ns = {};
setmetatable(ns, {__index = _G});
layna_village_riverbank_script = ns;
setfenv(1, ns);
-- The map name, subname and location image
map_name = "Mountain Village of Layna"
map_image_filename = "img/menus/locations/mountain_village.png"
map_subname = "Riverbank"
-- The music file used as default background music on this map.
-- Other musics will have to handled through scripting.
music_filename = "mus/Caketown_1-OGA-mat-pablo.ogg"
-- c++ objects instances
local Map = {};
local ObjectManager = {};
local DialogueManager = {};
local EventManager = {};
local bronann = {};
local kalya = {};
local orlinn = {};
local orlinn_dialogue_npc = {};
local lilly = {};
-- the main map loading code
function Load(m)
Map = m;
ObjectManager = Map.object_supervisor;
DialogueManager = Map.dialogue_supervisor;
EventManager = Map.event_supervisor;
Map.unlimited_stamina = true;
_CreateCharacters();
-- Set the camera focus on Bronann
Map:SetCamera(bronann);
_CreateNPCs();
_CreateObjects();
_CreateEvents();
_CreateZones();
-- Add clouds overlay
Map:GetEffectSupervisor():EnableAmbientOverlay("img/ambient/clouds.png", 5.0, 5.0, true);
_HandleCredits();
-- Once everything is created, we set up Orlinn and Lilly behaviour
_SetOrlinnState();
_SetLillyState();
end
-- Handle the display of the new game credits
function _HandleCredits()
-- Handle small credits triggering
if (GlobalManager:DoesEventExist("game", "Start_Credits") == false) then
-- Triggers the small credits display
GlobalManager:SetEventValue("game", "Start_Credits", 1);
end
if (GlobalManager:DoesEventExist("game", "Credits_shown") == false) then
Map:GetScriptSupervisor():AddScript("dat/credits/episode1_credits.lua");
end
end
function Update()
-- Check whether the character is in one of the zones
_CheckZones();
end
-- Character creation
function _CreateCharacters()
bronann = CreateSprite(Map, "Bronann", 97, 4);
bronann:SetDirection(vt_map.MapMode.SOUTH);
bronann:SetMovementSpeed(vt_map.MapMode.NORMAL_SPEED);
-- set up the position according to the previous map and location
if (GlobalManager:GetPreviousLocation() == "from_village_south") then
bronann:SetPosition(117, 18);
bronann:SetDirection(vt_map.MapMode.WEST);
end
if (GlobalManager:GetPreviousLocation() == "from_secret_path") then
bronann:SetPosition(65, 4);
bronann:SetDirection(vt_map.MapMode.SOUTH);
end
if (GlobalManager:GetPreviousLocation() == "from_riverbank_house") then
bronann:SetPosition(98, 48);
bronann:SetDirection(vt_map.MapMode.SOUTH);
AudioManager:PlaySound("snd/door_close.wav");
end
Map:AddGroundObject(bronann);
end
function _CreateNPCs()
local text = {}
local dialogue = {}
local event = {}
lilly = CreateNPCSprite(Map, "Woman3", "Lilly", 67, 40);
Map:AddGroundObject(lilly);
object = CreateObject(Map, "Dog1", 66, 42);
Map:AddGroundObject(object);
event = vt_map.SoundEvent("Lilly's dog barks", "snd/dog_barking.wav");
EventManager:RegisterEvent(event);
object:SetEventWhenTalking("Lilly's dog barks");
kalya = CreateSprite(Map, "Kalya", 2, 2);
kalya:SetDirection(vt_map.MapMode.SOUTH);
kalya:SetMovementSpeed(vt_map.MapMode.NORMAL_SPEED);
kalya:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
kalya:SetVisible(false);
Map:AddGroundObject(kalya);
orlinn = CreateSprite(Map, "Orlinn", 82, 5);
orlinn:SetDirection(vt_map.MapMode.SOUTH);
orlinn:SetMovementSpeed(vt_map.MapMode.VERY_FAST_SPEED);
Map:AddGroundObject(orlinn);
-- Create an invisible doppelg\E4nger to permit triggering dialogues when the kid is on the cliff.
orlinn_dialogue_npc = CreateSprite(Map, "Orlinn", 82, 8);
orlinn_dialogue_npc:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
orlinn_dialogue_npc:SetVisible(false);
Map:AddGroundObject(orlinn_dialogue_npc);
end
function _CreateObjects()
local object = {}
object = CreateObject(Map, "Tree Big2", 70, 6);
if (object ~= nil) then Map:AddGroundObject(object) end;
-- Add hill treasure chest
local hill_chest = CreateTreasure(Map, "riverbank_secret_hill_chest", "Wood_Chest1", 72, 5);
if (hill_chest ~= nil) then
hill_chest:AddObject(1, 1);
Map:AddGroundObject(hill_chest);
end
-- trees around the house
object = CreateObject(Map, "Tree Big2", 92, 10);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Tree Small1", 82, 17);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Tree Big1", 75, 20);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Tree Big2", 72, 35);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Tree Big1", 74, 48);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Tree Big2", 76, 50);
if (object ~= nil) then Map:AddGroundObject(object) end;
object = CreateObject(Map, "Barrel1", 56.3, 56.5);
if (object ~= nil) then Map:AddGroundObject(object) end;
-- grass array, used to hide defects
local map_grass = {
{ "Grass Clump1", 111, 7 },
{ "Grass Clump1", 108, 6 },
{ "Grass Clump1", 64, 15 },
{ "Grass Clump1", 62, 13 },
{ "Grass Clump1", 61, 6.2 },
{ "Grass Clump1", 65, 7 },
{ "Grass Clump1", 68, 10 },
{ "Grass Clump1", 72, 8.2 },
{ "Grass Clump1", 76, 8 },
}
-- Loads the trees according to the array
for my_index, my_array in pairs(map_grass) do
--print(my_array[1], my_array[2], my_array[3]);
object = CreateObject(Map, my_array[1], my_array[2], my_array[3]);
object:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
Map:AddGroundObject(object);
end
-- Lights
-- big round windows light flares
Map:AddLight("img/misc/lights/sun_flare_light_main.lua",
"img/misc/lights/sun_flare_light_secondary.lua",
94.0, 40.0,
vt_video.Color(1.0, 1.0, 1.0, 0.6),
vt_video.Color(1.0, 1.0, 0.85, 0.3));
Map:AddLight("img/misc/lights/sun_flare_light_main.lua",
"img/misc/lights/sun_flare_light_secondary.lua",
102.0, 40.0,
vt_video.Color(1.0, 1.0, 1.0, 0.6),
vt_video.Color(1.0, 1.0, 0.85, 0.3));
-- Small door lights
Map:AddLight("img/misc/lights/sun_flare_light_small_main.lua",
"img/misc/lights/sun_flare_light_small_secondary.lua",
98.0, 43.5,
vt_video.Color(1.0, 1.0, 1.0, 0.6),
vt_video.Color(1.0, 1.0, 0.85, 0.3));
object = vt_map.SoundObject("snd/gentle_stream.ogg", 61.0, 27.0, 20.0);
Map:AddAmbientSoundObject(object);
object = vt_map.SoundObject("snd/gentle_stream.ogg", 61.0, 47.0, 20.0);
Map:AddAmbientSoundObject(object);
object = vt_map.SoundObject("snd/gentle_stream.ogg", 61.0, 67.0, 20.0);
Map:AddAmbientSoundObject(object);
object = vt_map.SoundObject("snd/gentle_stream.ogg", 81.0, 67.0, 20.0);
Map:AddAmbientSoundObject(object);
object = vt_map.SoundObject("snd/gentle_stream.ogg", 101.0, 67.0, 20.0);
Map:AddAmbientSoundObject(object);
end
-- Creates all events and sets up the entire event sequence chain
function _CreateEvents()
local event = {};
local dialogue = {};
local text = {};
-- Map change Events
event = vt_map.MapTransitionEvent("to Village center", "dat/maps/layna_village/layna_village_center_map.lua",
"dat/maps/layna_village/layna_village_center_script.lua", "from_riverbank");
EventManager:RegisterEvent(event);
event = vt_map.MapTransitionEvent("to Village south entrance", "dat/maps/layna_village/layna_village_south_entrance_map.lua",
"dat/maps/layna_village/layna_village_south_entrance_script.lua", "from_riverbank");
EventManager:RegisterEvent(event);
event = vt_map.MapTransitionEvent("to Riverbank house", "dat/maps/layna_village/layna_village_riverbank_house_map.lua",
"dat/maps/layna_village/layna_village_riverbank_house_script.lua", "from_riverbank");
EventManager:RegisterEvent(event);
event = vt_map.MapTransitionEvent("to secret path entrance", "dat/maps/layna_village/layna_village_center_map.lua",
"dat/maps/layna_village/layna_village_center_script.lua", "from_secret_path");
EventManager:RegisterEvent(event);
-- Quest events - Hide and seek 2
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Wow! You found me!");
dialogue:AddLineEmote(text, orlinn, "exclamation");
text = vt_system.Translate("But I'm not done yet!");
dialogue:AddLine(text, orlinn);
text = vt_system.Translate("You'll never find me hiding behind the...");
dialogue:AddLine(text, orlinn);
text = vt_system.Translate("Hey, why would I tell you my hiding spots?!");
dialogue:AddLineEmote(text, orlinn, "exclamation");
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Orlinn starts hide and seek3 speech", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Quest1: Hide and seek2: Make Orlinn run");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and seek2: Make Orlinn run", orlinn, 72, 2, true);
event:AddEventLinkAtEnd("Quest1: Hide and seek2: Make Orlinn disappear");
EventManager:RegisterEvent(event);
event = vt_map.ScriptedSpriteEvent("Quest1: Hide and seek2: Make Orlinn disappear", orlinn, "MakeInvisible", "");
event:AddEventLinkAtEnd("Quest1: Hide and seek2: Bronann end speech");
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("That kid is pretty quick. This is going to take all day...");
dialogue:AddLineEmote(text, bronann, "sweat drop");
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Hide and seek2: Bronann end speech", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Map:PopState()");
EventManager:RegisterEvent(event);
event = vt_map.ScriptedEvent("Map:PopState()", "Map_PopState", "");
EventManager:RegisterEvent(event);
-- Final hide and seek (3)
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Orlinn goes top-right", orlinn, 70, 42, false);
event:AddEventLinkAtEnd("Hide n Seek3: Orlinn looks south");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Hide n Seek3: Orlinn looks south", orlinn, vt_map.MapMode.SOUTH);
event:AddEventLinkAtEnd("Hide n Seek3: Orlinn looks north", 800);
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Hide n Seek3: Orlinn looks north", orlinn, vt_map.MapMode.NORTH);
event:AddEventLinkAtEnd("Hide n Seek3: Orlinn goes bottom-left", 800);
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Hide n Seek3: Orlinn goes bottom-left", orlinn, 74, 43.8, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn goes top-right", 8000); -- finish the event loop.
EventManager:RegisterEvent(event);
-- Before Kalya's arrival
event = vt_map.ScriptedEvent("Quest1: Hide and Seek3: Orlinn starts to go away", "Prepare_orlinn_kalya_scene", "");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn tries go to away");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Orlinn tries go to away", orlinn, 76, 38, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Bronann follows him");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Bronann follows him", bronann, 76, 40, true);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Bronann turns to Orlinn");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn turns to him");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Hide and Seek3: Bronann turns to Orlinn", bronann, vt_map.MapMode.NORTH);
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Hide and Seek3: Orlinn turns to him", orlinn, vt_map.MapMode.SOUTH);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Bronann and kalya first speech");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Lilly turns to them");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Hide and Seek3: Lilly turns to them", lilly, vt_map.MapMode.EAST);
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Please no! Wait!");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Orlinn! Stop this!");
dialogue:AddLineEvent(text, kalya, "", "Quest1: Hide and Seek3: Kalya comes to Orlinn");
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Hide and Seek3: Bronann and kalya first speech", dialogue);
event:SetStopCameraMovement(true);
EventManager:RegisterEvent(event);
-- Kalya's arrival
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Kalya comes to Orlinn", kalya, 76, 36, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Kalya's speech");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn turns to Kalya");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Hide and Seek3: Orlinn turns to Kalya", orlinn, vt_map.MapMode.NORTH);
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Orlinn! How many times did I tell you not to bother other people?");
dialogue:AddLine(text, kalya);
text = vt_system.Translate("But sis! I...");
dialogue:AddLineEmote(text, orlinn, "sweat drop");
text = vt_system.Translate("I don't want to hear it! Now, come!");
dialogue:AddLine(text, kalya);
text = vt_system.Translate("Don't blame him, Kalya. Actually, it was...");
dialogue:AddLineEmote(text, bronann, "sweat drop");
text = vt_system.Translate("I don't think I was talking to you, now was I?");
dialogue:AddLine(text, kalya);
text = vt_system.Translate("Come Orlinn!");
dialogue:AddLine(text, kalya);
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Hide and Seek3: Kalya's speech", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Kalya is going away.");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn is going away.", 2000);
EventManager:RegisterEvent(event);
-- Kalya and Orlinn going away
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Kalya is going away.", kalya, 95, 2, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Kalya disappears.");
EventManager:RegisterEvent(event);
event = vt_map.ScriptedSpriteEvent("Quest1: Hide and Seek3: Kalya disappears.", kalya, "MakeInvisible", "");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Orlinn is going away.", orlinn, 76, 32, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn comes back to Bronann", 1000);
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Orlinn comes back to Bronann", orlinn, 76, 38, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn tells Bronann where the pen was");
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("I found that pen near the tree behind you. I just wanted to play...");
dialogue:AddLineEmote(text, orlinn, "sweat drop");
text = vt_system.Translate("Don't worry about that...");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Take it... Thanks.");
dialogue:AddLine(text, orlinn);
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Hide and Seek3: Orlinn tells Bronann where the pen was", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn gives the pen to Bronann");
EventManager:RegisterEvent(event);
event = vt_map.TreasureEvent("Quest1: Hide and Seek3: Orlinn gives the pen to Bronann");
event:AddObject(70001, 1); -- The ink key item
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn is going away for real");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Lilly tells Bronann a bit about Kalya", 2000);
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Hide and Seek3: Orlinn is going away for real", orlinn, 95, 2, false);
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: Orlinn disappears.");
EventManager:RegisterEvent(event);
event = vt_map.ScriptedSpriteEvent("Quest1: Hide and Seek3: Orlinn disappears.", orlinn, "MakeInvisible", "");
EventManager:RegisterEvent(event);
event = vt_map.AnimateSpriteEvent("Quest1: Bronann is sad", bronann, "hero_stance", 2000);
EventManager:RegisterEvent(event);
-- Lilly tells Bronann about Kalya
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Bronann?");
dialogue:AddLineEvent(text, lilly, "", "Quest1: Hide and Seek3: Bronann turns to Lilly");
text = vt_system.Translate("Er, yes?");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Don't blame Kalya. She was having a hard time along with her brother before living here, you know?");
dialogue:AddLineEvent(text, lilly, "", "Quest1: Bronann is sad");
text = vt_system.Translate("Well anyway, she's been ignoring me since the first day I saw her...");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Eh? You really know nothing about women, do you?");
dialogue:AddLine(text, lilly);
text = vt_system.Translate("... Huh?");
dialogue:AddLineEmote(text, bronann, "interrogation");
text = vt_system.Translate("Heh heh, don't worry about it. It will come in time.");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Hide and Seek3: Lilly tells Bronann a bit about Kalya", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Map:PopState()");
event:AddEventLinkAtEnd("Quest1: Hide and Seek3: done");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Hide and Seek3: Bronann turns to Lilly", bronann, vt_map.MapMode.WEST);
EventManager:RegisterEvent(event);
event = vt_map.ScriptedEvent("Quest1: Hide and Seek3: done", "Set_Hide_And_Seek3_Done", "");
EventManager:RegisterEvent(event);
-- Lilly goes and bring back barley meal
event = vt_map.ScriptedEvent("Quest1: Prepare Lilly for a walk", "Prepare_lilly_walk", "");
event:AddEventLinkAtEnd("Quest1: Lilly goes in her house");
event:AddEventLinkAtEnd("Quest1: Bronann moves to his wait place");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Bronann moves to his wait place", bronann, 70, 40, false);
event:AddEventLinkAtEnd("Quest1: Barley Meal: Bronann stares at Lilly");
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Barley Meal: Bronann stares at Lilly", bronann, vt_map.MapMode.SOUTH);
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Lilly goes in her house", lilly, 90, 60, false);
event:AddEventLinkAtEnd("Quest1: Lilly comes back");
EventManager:RegisterEvent(event);
event = vt_map.PathMoveSpriteEvent("Quest1: Lilly comes back", lilly, 67, 40, false);
event:AddEventLinkAtEnd("Quest1: Barley Meal: Lilly turns to Bronann");
event:AddEventLinkAtEnd("Quest1: Barley Meal: Bronann turns to Lilly");
event:AddEventLinkAtEnd("Quest1: Barley Meal: Lilly tells Bronann about the barley meal");
EventManager:RegisterEvent(event);
event = vt_map.LookAtSpriteEvent("Quest1: Barley Meal: Lilly turns to Bronann", lilly, bronann);
EventManager:RegisterEvent(event);
event = vt_map.ChangeDirectionSpriteEvent("Quest1: Barley Meal: Bronann turns to Lilly", bronann, vt_map.MapMode.WEST);
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Here it is, Bronann.");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Barley Meal: Lilly tells Bronann about the barley meal", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Quest1: Barley Meal: Lilly give the barley meal to bronann");
EventManager:RegisterEvent(event);
event = vt_map.TreasureEvent("Quest1: Barley Meal: Lilly give the barley meal to bronann");
event:AddEventLinkAtEnd("Quest1: Barley meal is given.");
event:AddObject(70002, 1); -- The barley meal key item
EventManager:RegisterEvent(event);
event = vt_map.ScriptedEvent("Quest1: Barley meal is given.", "GiveBarleyMeal", "");
event:AddEventLinkAtEnd("Quest1: Barley Meal: Lilly tells Bronann about the restrictions");
EventManager:RegisterEvent(event);
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Thanks, Lilly.");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("We're having a shortage of food lately. And I've been taking... special measures to make sure that everyone has enough food.");
dialogue:AddLine(text, lilly);
text = vt_system.Translate("Try to enjoy this day, Bronann.");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
event = vt_map.DialogueEvent("Quest1: Barley Meal: Lilly tells Bronann about the restrictions", dialogue);
event:SetStopCameraMovement(true);
event:AddEventLinkAtEnd("Quest1: Reset Lilly dialogue");
EventManager:RegisterEvent(event);
event = vt_map.ScriptedEvent("Quest1: Reset Lilly dialogue", "Reset_lilly_dialogue", "");
event:AddEventLinkAtEnd("Map:PopState()");
EventManager:RegisterEvent(event);
end
-- zones
local village_center_zone = {};
local to_village_entrance_zone = {};
local to_riverbank_house_entrance_zone = {};
local to_secret_path_entrance_zone = {};
local orlinn_hide_n_seek2_zone = {};
function _CreateZones()
-- N.B.: left, right, top, bottom
village_center_zone = vt_map.CameraZone(89, 105, 0, 2);
Map:AddZone(village_center_zone);
to_village_entrance_zone = vt_map.CameraZone(118, 119, 10, 27);
Map:AddZone(to_village_entrance_zone);
to_riverbank_house_entrance_zone = vt_map.CameraZone(96, 100, 46, 47);
Map:AddZone(to_riverbank_house_entrance_zone);
to_secret_path_entrance_zone = vt_map.CameraZone(60, 72, 0, 2);
Map:AddZone(to_secret_path_entrance_zone);
orlinn_hide_n_seek2_zone = vt_map.CameraZone(75, 80, 0, 7);
Map:AddZone(orlinn_hide_n_seek2_zone);
end
function _CheckZones()
if (village_center_zone:IsCameraEntering() == true) then
bronann:SetMoving(false);
EventManager:StartEvent("to Village center");
end
if (to_village_entrance_zone:IsCameraEntering() == true) then
bronann:SetMoving(false);
EventManager:StartEvent("to Village south entrance");
end
if (to_riverbank_house_entrance_zone:IsCameraEntering() == true) then
bronann:SetMoving(false);
AudioManager:PlaySound("snd/door_open2.wav");
EventManager:StartEvent("to Riverbank house");
end
if (to_secret_path_entrance_zone:IsCameraEntering() == true) then
bronann:SetMoving(false);
EventManager:StartEvent("to secret path entrance");
end
-- zone based story events
if (GlobalManager:DoesEventExist("layna_south_entrance", "quest1_orlinn_hide_n_seek1_done") == true) then
if (orlinn_hide_n_seek2_zone:IsCameraEntering() == true) then
-- Updates the story state
if (GlobalManager:DoesEventExist("layna_riverbank", "quest1_orlinn_hide_n_seek2_done") == false) then
GlobalManager:SetEventValue("layna_riverbank", "quest1_orlinn_hide_n_seek2_done", 1);
-- Orlinn speaks and flee
Map:PushState(vt_map.MapMode.STATE_SCENE);
orlinn:SetDirection(vt_map.MapMode.WEST);
EventManager:StartEvent("Quest1: Orlinn starts hide and seek3 speech");
end
end
end
end
-- Custom inner map functions
function _SetLillyState()
lilly:SetDirection(vt_map.MapMode.WEST);
lilly:ClearDialogueReferences();
if (GlobalManager:DoesEventExist("story", "kalya_has_joined") == true) then
-- Once they can go into the forest
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("We're counting on you.");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
lilly :AddDialogueReference(dialogue);
elseif (GlobalManager:DoesEventExist("story", "quest1_barley_meal_done") == true) then
dialogue = vt_map.SpriteDialogue("ep1_layna_village_lilly_go_home");
text = vt_system.Translate("You should go back home. Your mom must be waiting for you.");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
lilly :AddDialogueReference(dialogue);
elseif (GlobalManager:DoesEventExist("layna_center", "quest1_pen_given_done") == true) then
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("What a nice day, isn't it?");
dialogue:AddLine(text, lilly);
text = vt_system.Translate("Yes, Lilly. But I have something I have to ask you.");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Sure, just ask.");
dialogue:AddLine(text, lilly);
text = vt_system.Translate("Have you still got any barley meal left for my parents and I? My mother asked me to get some and I...");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("Unfortunately, I gave it all to Kalya...");
dialogue:AddLine(text, lilly);
text = vt_system.Translate("What?!");
dialogue:AddLineEmote(text, bronann, "sweat drop");
text = vt_system.Translate("Ah hah! I just wanted to see your reaction. I still have some. Let me go grab it and bring it back to you.");
dialogue:AddLineEvent(text, lilly, "", "Quest1: Prepare Lilly for a walk");
DialogueManager:AddDialogue(dialogue);
lilly :AddDialogueReference(dialogue);
else
dialogue = vt_map.SpriteDialogue("ep1_layna_village_lilly_default");
text = vt_system.Translate("What a nice day, isn't it?");
dialogue:AddLine(text, lilly);
DialogueManager:AddDialogue(dialogue);
lilly :AddDialogueReference(dialogue);
end
end
function _SetOrlinnState()
local text = {}
local dialogue = {}
orlinn_dialogue_npc:ClearDialogueReferences();
orlinn:ClearDialogueReferences();
if (GlobalManager:DoesEventExist("layna_riverbank", "quest1_orlinn_hide_n_seek3_done") == true) then
orlinn:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
orlinn:SetVisible(false);
return;
elseif (GlobalManager:DoesEventExist("layna_riverbank", "quest1_orlinn_hide_n_seek2_done") == true) then
orlinn:SetPosition(74, 44);
orlinn:SetDirection(vt_map.MapMode.WEST);
-- Final hide and seek dialogue
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("You'll never get me!");
dialogue:AddLineEvent(text, orlinn, "", "Quest1: Hide and Seek3: Orlinn starts to go away");
DialogueManager:AddDialogue(dialogue);
orlinn:AddDialogueReference(dialogue);
EventManager:StartEvent("Quest1: Hide and Seek3: Orlinn goes top-right", 8000);
return;
elseif (GlobalManager:DoesEventExist("layna_south_entrance", "quest1_orlinn_hide_n_seek1_done") == true) then
-- Orlinn is on the cliff and is mocking Bronann.
dialogue = vt_map.SpriteDialogue();
text = vt_system.Translate("Hee hee hee!");
dialogue:AddLine(text, orlinn_dialogue_npc);
text = vt_system.Translate("Orlinn, how did you get there?");
dialogue:AddLine(text, bronann);
text = vt_system.Translate("(giggle) I won't tell you!");
dialogue:AddLine(text, orlinn_dialogue_npc);
DialogueManager:AddDialogue(dialogue);
orlinn_dialogue_npc:AddDialogueReference(dialogue);
return;
end
-- Orlinn default behaviour
orlinn:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
orlinn:SetVisible(false);
end
-- Map Custom functions
map_functions = {
Map_PopState = function()
Map:PopState();
end,
MakeInvisible = function(sprite)
if (sprite ~= nil) then
sprite:SetVisible(false);
sprite:SetCollisionMask(vt_map.MapMode.NO_COLLISION);
end
end,
Prepare_orlinn_kalya_scene = function()
Map:PushState(vt_map.MapMode.STATE_SCENE);
-- Prepare Kalya
kalya:SetPosition(78, 25);
kalya:SetCollisionMask(vt_map.MapMode.ALL_COLLISION);
kalya:SetVisible(true);
-- Stop Orlinn event loop and prepare him for the next events
orlinn:SetMoving(false); -- in case he's moving
orlinn:SetDirection(vt_map.MapMode.NORTH);
orlinn:SetMovementSpeed(vt_map.MapMode.NORMAL_SPEED);
orlinn:ClearDialogueReferences();
EventManager:TerminateAllEvents(orlinn);
end,
Set_Hide_And_Seek3_Done = function()
GlobalManager:SetEventValue("layna_riverbank", "quest1_orlinn_hide_n_seek3_done", 1);
-- Also reset Lilly direction
lilly:SetDirection(vt_map.MapMode.WEST);
end,
Prepare_lilly_walk = function()
Map:PushState(vt_map.MapMode.STATE_SCENE);
-- Stop Lilly dialogue and prepare her for the next events
lilly:SetMoving(false); -- in case he's moving
lilly:ClearDialogueReferences();
EventManager:TerminateAllEvents(lilly);
end,
GiveBarleyMeal = function()
GlobalManager:SetEventValue("story", "quest1_barley_meal_done", 1);
end,
Reset_lilly_dialogue = function()
_SetLillyState();
end
}
| gpl-2.0 |
pydsigner/naev | dat/missions/neutral/cargo.lua | 8 | 4208 | --[[
-- These are regular cargo delivery missions. Pay is low, but so is difficulty.
-- Most of these missions require BULK ships. Not for small ships!
--]]
include "dat/scripts/cargo_common.lua"
include "dat/scripts/numstring.lua"
lang = naev.lang()
if lang == "es" then
else -- default english
misn_desc = "%s in the %s system needs a delivery of %d tons of %s."
misn_reward = "%s credits"
cargosize = {}
cargosize[0] = "Small" -- Note: indexed from 0, to match mission tiers.
cargosize[1] = "Medium"
cargosize[2] = "Sizeable"
cargosize[3] = "Large"
cargosize[4] = "Bulk"
title_p1 = {}
title_p1[1] = " cargo delivery to %s in the %s system"
title_p1[2] = " freight delivery to %s in the %s system"
title_p1[3] = " transport to %s in the %s system"
title_p1[4] = " delivery to %s in the %s system"
-- Note: please leave the trailing space on the line below! Needed to make the newline show up.
title_p2 = [[
Cargo: %s (%d tons)
Jumps: %d
Travel distance: %d]]
full = {}
full[1] = "No room in ship"
full[2] = "You don't have enough cargo space to accept this mission. You need %d tons of free space (you need %d more)."
--=Landing=--
cargo_land_title = "Delivery success!"
cargo_land_p1 = {}
cargo_land_p1[1] = "The crates of "
cargo_land_p1[2] = "The drums of "
cargo_land_p1[3] = "The containers of "
cargo_land_p2 = {}
cargo_land_p2[1] = " are carried out of your ship by a sullen group of workers. The job takes inordinately long to complete, and the leader pays you without speaking a word."
cargo_land_p2[2] = " are rushed out of your vessel by a team shortly after you land. Before you can even collect your thoughts, one of them presses a credit chip in your hand and departs."
cargo_land_p2[3] = " are unloaded by an exhausted-looking bunch of dockworkers. Still, they make fairly good time, delivering your pay upon completion of the job."
cargo_land_p2[4] = " are unloaded by a team of robotic drones supervised by a human overseer, who hands you your pay when they finish."
accept_title = "Mission Accepted"
osd_title = "Cargo mission"
osd_msg = "Fly to %s in the %s system."
end
-- Create the mission
function create()
-- Note: this mission does not make any system claims.
-- Calculate the route, distance, jumps and cargo to take
destplanet, destsys, numjumps, traveldist, cargo, tier = cargo_calculateRoute()
if destplanet == nil then
misn.finish(false)
end
-- Choose amount of cargo and mission reward. This depends on the mission tier.
-- Note: Pay is independent from amount by design! Not all deals are equally attractive!
finished_mod = 2.0 -- Modifier that should tend towards 1.0 as naev is finished as a game
amount = rnd.rnd(5 + 25 * tier, 20 + 60 * tier)
jumpreward = 200
distreward = 0.09
reward = 1.5^tier * (numjumps * jumpreward + traveldist * distreward) * finished_mod * (1. + 0.05*rnd.twosigma())
misn.setTitle(buildCargoMissionDescription( nil, amount, cargo, destplanet, destsys ))
misn.markerAdd(destsys, "computer")
misn.setDesc(cargosize[tier] .. title_p1[rnd.rnd(1, #title_p1)]:format(destplanet:name(), destsys:name()) .. title_p2:format(cargo, amount, numjumps, traveldist))
misn.setReward(misn_reward:format(numstring(reward)))
end
-- Mission is accepted
function accept()
if player.pilot():cargoFree() < amount then
tk.msg(full[1], full[2]:format(amount, amount - player.pilot():cargoFree()))
misn.finish()
end
misn.accept()
misn.cargoAdd(cargo, amount) -- TODO: change to jettisonable cargo once custom commodities are in. For piracy purposes.
misn.osdCreate(osd_title, {osd_msg:format(destplanet:name(), destsys:name())})
hook.land("land")
end
-- Land hook
function land()
if planet.cur() == destplanet then
-- Semi-random message.
tk.msg(cargo_land_title, cargo_land_p1[rnd.rnd(1, #cargo_land_p1)] .. cargo .. cargo_land_p2[rnd.rnd(1, #cargo_land_p2)])
player.pay(reward)
misn.finish(true)
end
end
function abort ()
misn.finish(false)
end
| gpl-3.0 |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/nssm/mobs/ant_worker.lua | 1 | 1149 | mobs:register_mob("nssm:ant_worker", {
type = "monster",
passive = true,
hp_max = 24,
hp_min = 18,
collisionbox = {-0.4, 0.00, -0.4, 0.4, 0.5, 0.4},
visual = "mesh",
mesh = "ant_worker.x",
textures = {
{"ant_worker.png"}
},
visual_size = {x = 2, y = 2},
makes_footstep_sound = true,
view_range = 20,
fear_height = 4,
walk_velocity = 0.5,
run_velocity = 2,
rotate = 270,
sounds = {
random = "ant",
},
damage = 2,
reach = 2,
jump = true,
drops = {
{name = "nssm:life_energy", chance = 2, min = 1, max = 1},
{name = "nssm:ant_leg", chance = 2, min = 1, max = 6},
{name = "nssm:ant_mandible", chance = 3, min = 1, max = 2},
{name = "nssm:ant_hard_skin", chance = 3, min = 1, max = 2},
},
armor = 70,
drawtype = "front",
water_damage = 2,
lava_damage = 7,
light_damage = 0,
group_attack = true,
knock_back = 4,
attack_animals = false,
blood_texture = "nssm_blood_blue.png",
attack_type = "dogfight",
animation = {
speed_normal = 20,
speed_run = 25,
stand_start = 1,
stand_end = 50,
walk_start = 120,
walk_end = 160,
run_start = 120,
run_end = 160,
punch_start = 50,
punch_end = 70,
}
})
| gpl-3.0 |
haider1984/-1 | libs/fakeredis.lua | 650 | 40405 | local unpack = table.unpack or unpack
--- Bit operations
local ok,bit
if _VERSION == "Lua 5.3" then
bit = (load [[ return {
band = function(x, y) return x & y end,
bor = function(x, y) return x | y end,
bxor = function(x, y) return x ~ y end,
bnot = function(x) return ~x end,
rshift = function(x, n) return x >> n end,
lshift = function(x, n) return x << n end,
} ]])()
else
ok,bit = pcall(require,"bit")
if not ok then bit = bit32 end
end
assert(type(bit) == "table", "module for bitops not found")
--- default sleep
local default_sleep
do
local ok, mod = pcall(require, "socket")
if ok and type(mod) == "table" then
default_sleep = mod.sleep
else
default_sleep = function(n)
local t0 = os.clock()
while true do
local delta = os.clock() - t0
if (delta < 0) or (delta > n) then break end
end
end
end
end
--- Helpers
local xdefv = function(ktype)
if ktype == "list" then
return {head = 0, tail = 0}
elseif ktype == "zset" then
return {
list = {},
set = {},
}
else return {} end
end
local xgetr = function(self, k, ktype)
if self.data[k] then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
assert(self.data[k].value)
return self.data[k].value
else return xdefv(ktype) end
end
local xgetw = function(self, k, ktype)
if self.data[k] and self.data[k].value then
assert(
(self.data[k].ktype == ktype),
"ERR Operation against a key holding the wrong kind of value"
)
else
self.data[k] = {ktype = ktype, value = xdefv(ktype)}
end
return self.data[k].value
end
local empty = function(self, k)
local v, t = self.data[k].value, self.data[k].ktype
if t == nil then
return true
elseif t == "string" then
return not v[1]
elseif (t == "hash") or (t == "set") then
for _,_ in pairs(v) do return false end
return true
elseif t == "list" then
return v.head == v.tail
elseif t == "zset" then
if #v.list == 0 then
for _,_ in pairs(v.set) do error("incoherent") end
return true
else
for _,_ in pairs(v.set) do return(false) end
error("incoherent")
end
else error("unsupported") end
end
local cleanup = function(self, k)
if empty(self, k) then self.data[k] = nil end
end
local is_integer = function(x)
return (type(x) == "number") and (math.floor(x) == x)
end
local overflows = function(n)
return (n > 2^53-1) or (n < -2^53+1)
end
local is_bounded_integer = function(x)
return (is_integer(x) and (not overflows(x)))
end
local is_finite_number = function(x)
return (type(x) == "number") and (x > -math.huge) and (x < math.huge)
end
local toint = function(x)
if type(x) == "string" then x = tonumber(x) end
return is_bounded_integer(x) and x or nil
end
local tofloat = function(x)
if type(x) == "number" then return x end
if type(x) ~= "string" then return nil end
local r = tonumber(x)
if r then return r end
if x == "inf" or x == "+inf" then
return math.huge
elseif x == "-inf" then
return -math.huge
else return nil end
end
local tostr = function(x)
if is_bounded_integer(x) then
return string.format("%d", x)
else return tostring(x) end
end
local char_bitcount = function(x)
assert(
(type(x) == "number") and
(math.floor(x) == x) and
(x >= 0) and (x < 256)
)
local n = 0
while x ~= 0 do
x = bit.band(x, x-1)
n = n+1
end
return n
end
local chkarg = function(x)
if type(x) == "number" then x = tostr(x) end
assert(type(x) == "string")
return x
end
local chkargs = function(n, ...)
local arg = {...}
assert(#arg == n)
for i=1,n do arg[i] = chkarg(arg[i]) end
return unpack(arg)
end
local getargs = function(...)
local arg = {...}
local n = #arg; assert(n > 0)
for i=1,n do arg[i] = chkarg(arg[i]) end
return arg
end
local getargs_as_map = function(...)
local arg, r = getargs(...), {}
assert(#arg%2 == 0)
for i=1,#arg,2 do r[arg[i]] = arg[i+1] end
return r
end
local chkargs_wrap = function(f, n)
assert( (type(f) == "function") and (type(n) == "number") )
return function(self, ...) return f(self, chkargs(n, ...)) end
end
local lset_to_list = function(s)
local r = {}
for v,_ in pairs(s) do r[#r+1] = v end
return r
end
local nkeys = function(x)
local r = 0
for _,_ in pairs(x) do r = r + 1 end
return r
end
--- Commands
-- keys
local del = function(self, ...)
local arg = getargs(...)
local r = 0
for i=1,#arg do
if self.data[arg[i]] then r = r + 1 end
self.data[arg[i]] = nil
end
return r
end
local exists = function(self, k)
return not not self.data[k]
end
local keys = function(self, pattern)
assert(type(pattern) == "string")
-- We want to convert the Redis pattern to a Lua pattern.
-- Start by escaping dashes *outside* character classes.
-- We also need to escape percents here.
local t, p, n = {}, 1, #pattern
local p1, p2
while true do
p1, p2 = pattern:find("%[.+%]", p)
if p1 then
if p1 > p then
t[#t+1] = {true, pattern:sub(p, p1-1)}
end
t[#t+1] = {false, pattern:sub(p1, p2)}
p = p2+1
if p > n then break end
else
t[#t+1] = {true, pattern:sub(p, n)}
break
end
end
for i=1,#t do
if t[i][1] then
t[i] = t[i][2]:gsub("[%%%-]", "%%%0")
else t[i] = t[i][2]:gsub("%%", "%%%%") end
end
-- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]'
-- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is.
-- Wrap in '^$' to enforce bounds.
local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0")
:gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$"
local r = {}
for k,_ in pairs(self.data) do
if k:match(lp) then r[#r+1] = k end
end
return r
end
local _type = function(self, k)
return self.data[k] and self.data[k].ktype or "none"
end
local randomkey = function(self)
local ks = lset_to_list(self.data)
local n = #ks
if n > 0 then
return ks[math.random(1, n)]
else return nil end
end
local rename = function(self, k, k2)
assert((k ~= k2) and self.data[k])
self.data[k2] = self.data[k]
self.data[k] = nil
return true
end
local renamenx = function(self, k, k2)
if self.data[k2] then
return false
else
return rename(self, k, k2)
end
end
-- strings
local getrange, incrby, set
local append = function(self, k, v)
local x = xgetw(self, k, "string")
x[1] = (x[1] or "") .. v
return #x[1]
end
local bitcount = function(self, k, i1, i2)
k = chkarg(k)
local s
if i1 or i2 then
assert(i1 and i2, "ERR syntax error")
s = getrange(self, k, i1, i2)
else
s = xgetr(self, k, "string")[1] or ""
end
local r, bytes = 0,{s:byte(1, -1)}
for i=1,#bytes do
r = r + char_bitcount(bytes[i])
end
return r
end
local bitop = function(self, op, k, ...)
assert(type(op) == "string")
op = op:lower()
assert(
(op == "and") or
(op == "or") or
(op == "xor") or
(op == "not"),
"ERR syntax error"
)
k = chkarg(k)
local arg = {...}
local good_arity = (op == "not") and (#arg == 1) or (#arg > 0)
assert(good_arity, "ERR wrong number of arguments for 'bitop' command")
local l, vals = 0, {}
local s
for i=1,#arg do
s = xgetr(self, arg[i], "string")[1] or ""
if #s > l then l = #s end
vals[i] = s
end
if l == 0 then
del(self, k)
return 0
end
local vector_mt = {__index=function() return 0 end}
for i=1,#vals do
vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt)
end
local r = {}
if op == "not" then
assert(#vals[1] == l)
for i=1,l do
r[i] = bit.band(bit.bnot(vals[1][i]), 0xff)
end
else
local _op = bit["b" .. op]
for i=1,l do
local t = {}
for j=1,#vals do t[j] = vals[j][i] end
r[i] = _op(unpack(t))
end
end
set(self, k, string.char(unpack(r)))
return l
end
local decr = function(self, k)
return incrby(self, k, -1)
end
local decrby = function(self, k, n)
n = toint(n)
assert(n, "ERR value is not an integer or out of range")
return incrby(self, k, -n)
end
local get = function(self, k)
local x = xgetr(self, k, "string")
return x[1]
end
local getbit = function(self, k, offset)
k = chkarg(k)
offset = toint(offset)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
if bytepos >= #s then return 0 end
local char = s:sub(bytepos+1, bytepos+1):byte()
return bit.band(bit.rshift(char, 7-bitpos), 1)
end
getrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetr(self, k, "string")
x = x[1] or ""
if i1 >= 0 then i1 = i1 + 1 end
if i2 >= 0 then i2 = i2 + 1 end
return x:sub(i1, i2)
end
local getset = function(self, k, v)
local r = get(self, k)
set(self, k, v)
return r
end
local incr = function(self, k)
return incrby(self, k, 1)
end
incrby = function(self, k, n)
k, n = chkarg(k), toint(n)
assert(n, "ERR value is not an integer or out of range")
local x = xgetw(self, k, "string")
local i = toint(x[1] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[1] = tostr(i)
return i
end
local incrbyfloat = function(self, k, n)
k, n = chkarg(k), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "string")
local i = tofloat(x[1] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[1] = tostr(i)
return i
end
local mget = function(self, ...)
local arg, r = getargs(...), {}
for i=1,#arg do r[i] = get(self, arg[i]) end
return r
end
local mset = function(self, ...)
local argmap = getargs_as_map(...)
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
local msetnx = function(self, ...)
local argmap = getargs_as_map(...)
for k,_ in pairs(argmap) do
if self.data[k] then return false end
end
for k,v in pairs(argmap) do set(self, k, v) end
return true
end
set = function(self, k, v)
self.data[k] = {ktype = "string", value = {v}}
return true
end
local setbit = function(self, k, offset, b)
k = chkarg(k)
offset, b = toint(offset), toint(b)
assert(
(offset >= 0),
"ERR bit offset is not an integer or out of range"
)
assert(
(b == 0) or (b == 1),
"ERR bit is not an integer or out of range"
)
local bitpos = offset % 8 -- starts at 0
local bytepos = (offset - bitpos) / 8 -- starts at 0
local s = xgetr(self, k, "string")[1] or ""
local pad = {s}
for i=2,bytepos+2-#s do pad[i] = "\0" end
s = table.concat(pad)
assert(#s >= bytepos+1)
local before = s:sub(1, bytepos)
local char = s:sub(bytepos+1, bytepos+1):byte()
local after = s:sub(bytepos+2, -1)
local old = bit.band(bit.rshift(char, 7-bitpos), 1)
if b == 1 then
char = bit.bor(bit.lshift(1, 7-bitpos), char)
else
char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char)
end
local r = before .. string.char(char) .. after
set(self, k, r)
return old
end
local setnx = function(self, k, v)
if self.data[k] then
return false
else
return set(self, k, v)
end
end
local setrange = function(self, k, i, s)
local k, s = chkargs(2, k, s)
i = toint(i)
assert(i and (i >= 0))
local x = xgetw(self, k, "string")
local y = x[1] or ""
local ly, ls = #y, #s
if i > ly then -- zero padding
local t = {}
for i=1, i-ly do t[i] = "\0" end
y = y .. table.concat(t) .. s
else
y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly)
end
x[1] = y
return #y
end
local strlen = function(self, k)
local x = xgetr(self, k, "string")
return x[1] and #x[1] or 0
end
-- hashes
local hdel = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local r = 0
local x = xgetw(self, k, "hash")
for i=1,#arg do
if x[arg[i]] then r = r + 1 end
x[arg[i]] = nil
end
cleanup(self, k)
return r
end
local hget
local hexists = function(self, k, k2)
return not not hget(self, k, k2)
end
hget = function(self, k, k2)
local x = xgetr(self, k, "hash")
return x[k2]
end
local hgetall = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,v in pairs(x) do r[_k] = v end
return r
end
local hincrby = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), toint(n)
assert(n, "ERR value is not an integer or out of range")
assert(type(n) == "number")
local x = xgetw(self, k, "hash")
local i = toint(x[k2] or 0)
assert(i, "ERR value is not an integer or out of range")
i = i+n
assert(
(not overflows(i)),
"ERR increment or decrement would overflow"
)
x[k2] = tostr(i)
return i
end
local hincrbyfloat = function(self, k, k2, n)
k, k2, n = chkarg(k), chkarg(k2), tofloat(n)
assert(n, "ERR value is not a valid float")
local x = xgetw(self, k, "hash")
local i = tofloat(x[k2] or 0)
assert(i, "ERR value is not a valid float")
i = i+n
assert(
is_finite_number(i),
"ERR increment would produce NaN or Infinity"
)
x[k2] = tostr(i)
return i
end
local hkeys = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _k,_ in pairs(x) do r[#r+1] = _k end
return r
end
local hlen = function(self, k)
local x = xgetr(self, k, "hash")
return nkeys(x)
end
local hmget = function(self, k, k2s)
k = chkarg(k)
assert((type(k2s) == "table"))
local r = {}
local x = xgetr(self, k, "hash")
for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end
return r
end
local hmset = function(self, k, ...)
k = chkarg(k)
local arg = {...}
if type(arg[1]) == "table" then
assert(#arg == 1)
local x = xgetw(self, k, "hash")
for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end
else
assert(#arg % 2 == 0)
local x = xgetw(self, k, "hash")
local t = getargs(...)
for i=1,#t,2 do x[t[i]] = t[i+1] end
end
return true
end
local hset = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
local r = not x[k2]
x[k2] = v
return r
end
local hsetnx = function(self, k, k2, v)
local x = xgetw(self, k, "hash")
if x[k2] == nil then
x[k2] = v
return true
else
return false
end
end
local hvals = function(self, k)
local x = xgetr(self, k, "hash")
local r = {}
for _,v in pairs(x) do r[#r+1] = v end
return r
end
-- lists (head = left, tail = right)
local _l_real_i = function(x, i)
if i < 0 then
return x.tail+i+1
else
return x.head+i+1
end
end
local _l_len = function(x)
return x.tail - x.head
end
local _block_for = function(self, timeout)
if timeout > 0 then
local sleep = self.sleep or default_sleep
if type(sleep) == "function" then
sleep(timeout)
else
error("sleep function unavailable", 0)
end
else
error("operation would block", 0)
end
end
local rpoplpush
local blpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpop = function(self, ...)
local arg = {...}
local timeout = toint(arg[#arg])
arg[#arg] = nil
local vs = getargs(...)
local x, l, k, v
for i=1,#vs do
k = vs[i]
x = xgetw(self, k, "list")
l = _l_len(x)
if l > 0 then
v = x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return {k, v}
else self.data[k] = nil end
end
_block_for(self, timeout)
end
local brpoplpush = function(self, k1, k2, timeout)
k1, k2 = chkargs(2, k1, k2)
timeout = toint(timeout)
if not self.data[k1] then _block_for(self, timeout) end
return rpoplpush(self, k1, k2)
end
local lindex = function(self, k, i)
k = chkarg(k)
i = assert(toint(i))
local x = xgetr(self, k, "list")
return x[_l_real_i(x, i)]
end
local linsert = function(self, k, mode, pivot, v)
mode = mode:lower()
assert((mode == "before") or (mode == "after"))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local p = nil
for i=x.head+1, x.tail do
if x[i] == pivot then
p = i
break
end
end
if not p then return -1 end
if mode == "after" then
for i=x.head+1, p do x[i-1] = x[i] end
x.head = x.head - 1
else
for i=x.tail, p, -1 do x[i+1] = x[i] end
x.tail = x.tail + 1
end
x[p] = v
return _l_len(x)
end
local llen = function(self, k)
local x = xgetr(self, k, "list")
return _l_len(x)
end
local lpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.head+1]
if l > 1 then
x.head = x.head + 1
x[x.head] = nil
else self.data[k] = nil end
return r
end
local lpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x[x.head] = vs[i]
x.head = x.head - 1
end
return _l_len(x)
end
local lpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x[x.head] = v
x.head = x.head - 1
return _l_len(x)
end
local lrange = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x, r = xgetr(self, k, "list"), {}
i1 = math.max(_l_real_i(x, i1), x.head+1)
i2 = math.min(_l_real_i(x, i2), x.tail)
for i=i1,i2 do r[#r+1] = x[i] end
return r
end
local _lrem_i = function(x, p)
for i=p,x.tail do
x[i] = x[i+1]
end
x.tail = x.tail - 1
end
local _lrem_l = function(x, v, s)
assert(v)
if not s then s = x.head+1 end
for i=s,x.tail do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local _lrem_r = function(x, v, s)
assert(v)
if not s then s = x.tail end
for i=s,x.head+1,-1 do
if x[i] == v then
_lrem_i(x, i)
return i
end
end
return false
end
local lrem = function(self, k, count, v)
k, v = chkarg(k), chkarg(v)
count = assert(toint(count))
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
local n, last = 0, nil
local op = (count < 0) and _lrem_r or _lrem_l
local limited = (count ~= 0)
count = math.abs(count)
while true do
last = op(x, v, last)
if last then
n = n+1
if limited then
count = count - 1
if count == 0 then break end
end
else break end
end
return n
end
local lset = function(self, k, i, v)
k, v = chkarg(k), chkarg(v)
i = assert(toint(i))
if not self.data[k] then
error("ERR no such key")
end
local x = xgetw(self, k, "list")
local l = _l_len(x)
if i >= l or i < -l then
error("ERR index out of range")
end
x[_l_real_i(x, i)] = v
return true
end
local ltrim = function(self, k, i1, i2)
k = chkarg(k)
i1, i2 = toint(i1), toint(i2)
assert(i1 and i2)
local x = xgetw(self, k, "list")
i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2)
for i=x.head+1,i1-1 do x[i] = nil end
for i=i2+1,x.tail do x[i] = nil end
x.head = math.max(i1-1, x.head)
x.tail = math.min(i2, x.tail)
assert(
(x[x.head] == nil) and
(x[x.tail+1] == nil)
)
cleanup(self, k)
return true
end
local rpop = function(self, k)
local x = xgetw(self, k, "list")
local l, r = _l_len(x), x[x.tail]
if l > 1 then
x[x.tail] = nil
x.tail = x.tail - 1
else self.data[k] = nil end
return r
end
rpoplpush = function(self, k1, k2)
local v = rpop(self, k1)
if not v then return nil end
lpush(self, k2, v)
return v
end
local rpush = function(self, k, ...)
local vs = getargs(...)
local x = xgetw(self, k, "list")
for i=1,#vs do
x.tail = x.tail + 1
x[x.tail] = vs[i]
end
return _l_len(x)
end
local rpushx = function(self, k, v)
if not self.data[k] then return 0 end
local x = xgetw(self, k, "list")
x.tail = x.tail + 1
x[x.tail] = v
return _l_len(x)
end
-- sets
local sadd = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if not x[arg[i]] then
x[arg[i]] = true
r = r + 1
end
end
return r
end
local scard = function(self, k)
local x = xgetr(self, k, "set")
return nkeys(x)
end
local _sdiff = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
for v,_ in pairs(x) do r[v] = true end
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = nil end
end
return r
end
local sdiff = function(self, k, ...)
return lset_to_list(_sdiff(self, k, ...))
end
local sdiffstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sdiff(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local _sinter = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x = xgetr(self, k, "set")
local r = {}
local y
for v,_ in pairs(x) do
r[v] = true
for i=1,#arg do
y = xgetr(self, arg[i], "set")
if not y[v] then r[v] = nil; break end
end
end
return r
end
local sinter = function(self, k, ...)
return lset_to_list(_sinter(self, k, ...))
end
local sinterstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sinter(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
local sismember = function(self, k, v)
local x = xgetr(self, k, "set")
return not not x[v]
end
local smembers = function(self, k)
local x = xgetr(self, k, "set")
return lset_to_list(x)
end
local smove = function(self, k, k2, v)
local x = xgetr(self, k, "set")
if x[v] then
local y = xgetw(self, k2, "set")
x[v] = nil
y[v] = true
return true
else return false end
end
local spop = function(self, k)
local x, r = xgetw(self, k, "set"), nil
local l = lset_to_list(x)
local n = #l
if n > 0 then
r = l[math.random(1, n)]
x[r] = nil
end
cleanup(self, k)
return r
end
local srandmember = function(self, k, count)
k = chkarg(k)
local x = xgetr(self, k, "set")
local l = lset_to_list(x)
local n = #l
if not count then
if n > 0 then
return l[math.random(1, n)]
else return nil end
end
count = toint(count)
if (count == 0) or (n == 0) then return {} end
if count >= n then return l end
local r = {}
if count > 0 then -- distinct elements
for i=0,count-1 do
r[#r+1] = table.remove(l, math.random(1, n-i))
end
else -- allow repetition
for i=1,-count do
r[#r+1] = l[math.random(1, n)]
end
end
return r
end
local srem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "set"), 0
for i=1,#arg do
if x[arg[i]] then
x[arg[i]] = nil
r = r + 1
end
end
cleanup(self, k)
return r
end
local _sunion = function(self, ...)
local arg = getargs(...)
local r = {}
local x
for i=1,#arg do
x = xgetr(self, arg[i], "set")
for v,_ in pairs(x) do r[v] = true end
end
return r
end
local sunion = function(self, k, ...)
return lset_to_list(_sunion(self, k, ...))
end
local sunionstore = function(self, k2, k, ...)
k2 = chkarg(k2)
local x = _sunion(self, k, ...)
self.data[k2] = {ktype = "set", value = x}
return nkeys(x)
end
-- zsets
local _z_p_mt = {
__eq = function(a, b)
if a.v == b.v then
assert(a.s == b.s)
return true
else return false end
end,
__lt = function(a, b)
if a.s == b.s then
return (a.v < b.v)
else
return (a.s < b.s)
end
end,
}
local _z_pair = function(s, v)
assert(
(type(s) == "number") and
(type(v) == "string")
)
local r = {s = s, v = v}
return setmetatable(r, _z_p_mt)
end
local _z_pairs = function(...)
local arg = {...}
assert((#arg > 0) and (#arg % 2 == 0))
local ps = {}
for i=1,#arg,2 do
ps[#ps+1] = _z_pair(
assert(tofloat(arg[i])),
chkarg(arg[i+1])
)
end
return ps
end
local _z_insert = function(x, ix, p)
assert(
(type(x) == "table") and
(type(ix) == "number") and
(type(p) == "table")
)
local l = x.list
table.insert(l, ix, p)
for i=ix+1,#l do
x.set[l[i].v] = x.set[l[i].v] + 1
end
x.set[p.v] = ix
end
local _z_remove = function(x, v)
if not x.set[v] then return false end
local l, ix = x.list, x.set[v]
assert(l[ix].v == v)
table.remove(l, ix)
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - 1
end
x.set[v] = nil
return true
end
local _z_remove_range = function(x, i1, i2)
local l = x.list
i2 = i2 or i1
assert(
(i1 > 0) and
(i2 >= i1) and
(i2 <= #l)
)
local ix, n = i1, i2-i1+1
for i=1,n do
x.set[l[ix].v] = nil
table.remove(l, ix)
end
for i=ix,#l do
x.set[l[i].v] = x.set[l[i].v] - n
end
return n
end
local _z_update = function(x, p)
local l = x.list
local found = _z_remove(x, p.v)
local ix = nil
for i=1,#l do
if l[i] > p then
ix = i; break
end
end
if not ix then ix = #l+1 end
_z_insert(x, ix, p)
return found
end
local _z_coherence = function(x)
local l, s = x.list, x.set
local found, n = {}, 0
for val,pos in pairs(s) do
if found[pos] then return false end
found[pos] = true
n = n + 1
if not (l[pos] and (l[pos].v == val)) then
return false
end
end
if #l ~= n then return false end
for i=1, n-1 do
if l[i].s > l[i+1].s then return false end
end
return true
end
local _z_normrange = function(l, i1, i2)
i1, i2 = assert(toint(i1)), assert(toint(i2))
if i1 < 0 then i1 = #l+i1 end
if i2 < 0 then i2 = #l+i2 end
i1, i2 = math.max(i1+1, 1), i2+1
if (i2 < i1) or (i1 > #l) then return nil end
i2 = math.min(i2, #l)
return i1, i2
end
local _zrbs_opts = function(...)
local arg = {...}
if #arg == 0 then return {} end
local ix, opts = 1, {}
while type(arg[ix]) == "string" do
if arg[ix] == "withscores" then
opts.withscores = true
ix = ix + 1
elseif arg[ix] == "limit" then
opts.limit = {
offset = assert(toint(arg[ix+1])),
count = assert(toint(arg[ix+2])),
}
ix = ix + 3
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.withscores = opts.withscores or _o.withscores
if _o.limit then
opts.limit = {
offset = assert(toint(_o.limit.offset or _o.limit[1])),
count = assert(toint(_o.limit.count or _o.limit[2])),
}
end
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.limit then
assert(
(opts.limit.count >= 0) and
(opts.limit.offset >= 0)
)
end
return opts
end
local _z_store_params = function(dest, numkeys, ...)
dest = chkarg(dest)
numkeys = assert(toint(numkeys))
assert(numkeys > 0)
local arg = {...}
assert(#arg >= numkeys)
local ks = {}
for i=1, numkeys do ks[i] = chkarg(arg[i]) end
local ix, opts = numkeys+1,{}
while type(arg[ix]) == "string" do
if arg[ix] == "weights" then
opts.weights = {}
ix = ix + 1
for i=1, numkeys do
opts.weights[i] = assert(toint(arg[ix]))
ix = ix + 1
end
elseif arg[ix] == "aggregate" then
opts.aggregate = assert(chkarg(arg[ix+1]))
ix = ix + 2
else error("input") end
end
if type(arg[ix]) == "table" then
local _o = arg[ix]
opts.weights = opts.weights or _o.weights
opts.aggregate = opts.aggregate or _o.aggregate
ix = ix + 1
end
assert(arg[ix] == nil)
if opts.aggregate then
assert(
(opts.aggregate == "sum") or
(opts.aggregate == "min") or
(opts.aggregate == "max")
)
else opts.aggregate = "sum" end
if opts.weights then
assert(#opts.weights == numkeys)
for i=1,#opts.weights do
assert(type(opts.weights[i]) == "number")
end
else
opts.weights = {}
for i=1, numkeys do opts.weights[i] = 1 end
end
opts.keys = ks
opts.dest = dest
return opts
end
local _zrbs_limits = function(x, s1, s2, descending)
local s1_incl, s2_incl = true, true
if s1:sub(1, 1) == "(" then
s1, s1_incl = s1:sub(2, -1), false
end
s1 = assert(tofloat(s1))
if s2:sub(1, 1) == "(" then
s2, s2_incl = s2:sub(2, -1), false
end
s2 = assert(tofloat(s2))
if descending then
s1, s2 = s2, s1
s1_incl, s2_incl = s2_incl, s1_incl
end
if s2 < s1 then return nil end
local l = x.list
local i1, i2
local fst, lst = l[1].s, l[#l].s
if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end
if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end
if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end
if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end
for i=1,#l do
if (i1 and i2) then break end
if (not i1) then
if l[i].s > s1 then i1 = i end
if s1_incl and l[i].s == s1 then i1 = i end
end
if (not i2) then
if l[i].s > s2 then i2 = i-1 end
if (not s2_incl) and l[i].s == s2 then i2 = i-1 end
end
end
assert(i1 and i2)
if descending then
return #l-i2, #l-i1
else
return i1-1, i2-1
end
end
local dbg_zcoherence = function(self, k)
local x = xgetr(self, k, "zset")
return _z_coherence(x)
end
local zadd = function(self, k, ...)
k = chkarg(k)
local ps = _z_pairs(...)
local x = xgetw(self, k, "zset")
local n = 0
for i=1,#ps do
if not _z_update(x, ps[i]) then n = n+1 end
end
return n
end
local zcard = function(self, k)
local x = xgetr(self, k, "zset")
return #x.list
end
local zcount = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return i2 - i1 + 1
end
local zincrby = function(self, k, n, v)
k,v = chkargs(2, k, v)
n = assert(tofloat(n))
local x = xgetw(self, k, "zset")
local p = x.list[x.set[v]]
local s = p and (p.s + n) or n
_z_update(x, _z_pair(s, v))
return s
end
local zinterstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local aggregate
if params.aggregate == "sum" then
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
aggregate = math.min
elseif params.aggregate == "max" then
aggregate = math.max
else error() end
local y = xgetr(self, params.keys[1], "zset")
local p1, p2
for j=1,#y.list do
p1 = _z_pair(y.list[j].s, y.list[j].v)
_z_update(x, p1)
end
for i=2,#params.keys do
y = xgetr(self, params.keys[i], "zset")
local to_remove, to_update = {}, {}
for j=1,#x.list do
p1 = x.list[j]
if y.set[p1.v] then
p2 = _z_pair(
aggregate(
p1.s,
params.weights[i] * y.list[y.set[p1.v]].s
),
p1.v
)
to_update[#to_update+1] = p2
else
to_remove[#to_remove+1] = p1.v
end
end
for j=1,#to_remove do _z_remove(x, to_remove[j]) end
for j=1,#to_update do _z_update(x, to_update[j]) end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
local _zranger = function(descending)
return function(self, k, i1, i2, opts)
k = chkarg(k)
local withscores = false
if type(opts) == "table" then
withscores = opts.withscores
elseif type(opts) == "string" then
assert(opts:lower() == "withscores")
withscores = true
else assert(opts == nil) end
local x = xgetr(self, k, "zset")
local l = x.list
i1, i2 = _z_normrange(l, i1, i2)
if not i1 then return {} end
local inc = 1
if descending then
i1 = #l - i1 + 1
i2 = #l - i2 + 1
inc = -1
end
local r = {}
if withscores then
for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end
else
for i=i1, i2, inc do r[#r+1] = l[i].v end
end
return r
end
end
local zrange = _zranger(false)
local zrevrange = _zranger(true)
local _zrangerbyscore = function(descending)
return function(self, k, s1, s2, ...)
k, s1, s2 = chkargs(3, k, s1, s2)
local opts = _zrbs_opts(...)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, descending)
if not (i1 and i2) then return {} end
if opts.limit then
if opts.limit.count == 0 then return {} end
i1 = i1 + opts.limit.offset
if i1 > i2 then return {} end
i2 = math.min(i2, i1+opts.limit.count-1)
end
if descending then
return zrevrange(self, k, i1, i2, opts)
else
return zrange(self, k, i1, i2, opts)
end
end
end
local zrangebyscore = _zrangerbyscore(false)
local zrevrangebyscore = _zrangerbyscore(true)
local zrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return r-1
else return nil end
end
local zrem = function(self, k, ...)
k = chkarg(k)
local arg = getargs(...)
local x, r = xgetw(self, k, "zset"), 0
for i=1,#arg do
if _z_remove(x, arg[i]) then r = r + 1 end
end
cleanup(self, k)
return r
end
local zremrangebyrank = function(self, k, i1, i2)
k = chkarg(k)
local x = xgetw(self, k, "zset")
i1, i2 = _z_normrange(x.list, i1, i2)
if not i1 then
cleanup(self, k)
return 0
end
local n = _z_remove_range(x, i1, i2)
cleanup(self, k)
return n
end
local zremrangebyscore = function(self, k, s1, s2)
local x = xgetr(self, k, "zset")
local i1, i2 = _zrbs_limits(x, s1, s2, false)
if not (i1 and i2) then return 0 end
assert(i2 >= i1)
return zremrangebyrank(self, k, i1, i2)
end
local zrevrank = function(self, k, v)
local x = xgetr(self, k, "zset")
local r = x.set[v]
if r then
return #x.list-r
else return nil end
end
local zscore = function(self, k, v)
local x = xgetr(self, k, "zset")
local p = x.list[x.set[v]]
if p then
return p.s
else return nil end
end
local zunionstore = function(self, ...)
local params = _z_store_params(...)
local x = xdefv("zset")
local default_score, aggregate
if params.aggregate == "sum" then
default_score = 0
aggregate = function(x, y) return x+y end
elseif params.aggregate == "min" then
default_score = math.huge
aggregate = math.min
elseif params.aggregate == "max" then
default_score = -math.huge
aggregate = math.max
else error() end
local y, p1, p2
for i=1,#params.keys do
y = xgetr(self, params.keys[i], "zset")
for j=1,#y.list do
p1 = y.list[j]
p2 = _z_pair(
aggregate(
params.weights[i] * p1.s,
x.set[p1.v] and x.list[x.set[p1.v]].s or default_score
),
p1.v
)
_z_update(x, p2)
end
end
local r = #x.list
if r > 0 then
self.data[params.dest] = {ktype = "zset", value = x}
end
return r
end
-- connection
local echo = function(self, v)
return v
end
local ping = function(self)
return true
end
-- server
local flushdb = function(self)
self.data = {}
return true
end
--- Class
local methods = {
-- keys
del = del, -- (...) -> #removed
exists = chkargs_wrap(exists, 1), -- (k) -> exists?
keys = keys, -- (pattern) -> list of keys
["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none]
randomkey = randomkey, -- () -> [k|nil]
rename = chkargs_wrap(rename, 2), -- (k,k2) -> true
renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2
-- strings
append = chkargs_wrap(append, 2), -- (k,v) -> #new
bitcount = bitcount, -- (k,[start,end]) -> n
bitop = bitop, -- ([and|or|xor|not],k,...)
decr = chkargs_wrap(decr, 1), -- (k) -> new
decrby = decrby, -- (k,n) -> new
get = chkargs_wrap(get, 1), -- (k) -> [v|nil]
getbit = getbit, -- (k,offset) -> b
getrange = getrange, -- (k,start,end) -> string
getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil]
incr = chkargs_wrap(incr, 1), -- (k) -> new
incrby = incrby, -- (k,n) -> new
incrbyfloat = incrbyfloat, -- (k,n) -> new
mget = mget, -- (k1,...) -> {v1,...}
mset = mset, -- (k1,v1,...) -> true
msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k)
set = chkargs_wrap(set, 2), -- (k,v) -> true
setbit = setbit, -- (k,offset,b) -> old
setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?)
setrange = setrange, -- (k,offset,val) -> #new
strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0]
-- hashes
hdel = hdel, -- (k,sk1,...) -> #removed
hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists?
hget = chkargs_wrap(hget,2), -- (k,sk) -> v
hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map
hincrby = hincrby, -- (k,sk,n) -> new
hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new
hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys
hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0]
hmget = hmget, -- (k,{sk1,...}) -> {v1,...}
hmset = hmset, -- (k,{sk1=v1,...}) -> true
hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed?
hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?)
hvals = chkargs_wrap(hvals, 1), -- (k) -> values
-- lists
blpop = blpop, -- (k1,...) -> k,v
brpop = brpop, -- (k1,...) -> k,v
brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v
lindex = lindex, -- (k,i) -> v
linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after)
llen = chkargs_wrap(llen, 1), -- (k) -> #list
lpop = chkargs_wrap(lpop, 1), -- (k) -> v
lpush = lpush, -- (k,v1,...) -> #list (after)
lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after)
lrange = lrange, -- (k,start,stop) -> list
lrem = lrem, -- (k,count,v) -> #removed
lset = lset, -- (k,i,v) -> true
ltrim = ltrim, -- (k,start,stop) -> true
rpop = chkargs_wrap(rpop, 1), -- (k) -> v
rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v
rpush = rpush, -- (k,v1,...) -> #list (after)
rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after)
-- sets
sadd = sadd, -- (k,v1,...) -> #added
scard = chkargs_wrap(scard, 1), -- (k) -> [n|0]
sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...)
sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0
sinter = sinter, -- (k1,...) -> set
sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0
sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member?
smembers = chkargs_wrap(smembers, 1), -- (k) -> set
smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1)
spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil]
srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...]
srem = srem, -- (k,v1,...) -> #removed
sunion = sunion, -- (k1,...) -> set
sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0
-- zsets
zadd = zadd, -- (k,score,member,[score,member,...])
zcard = chkargs_wrap(zcard, 1), -- (k) -> n
zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count
zincrby = zincrby, -- (k,score,v) -> score
zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card
zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts
zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank
zrem = zrem, -- (k,v1,...) -> #removed
zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed
zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed
zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts
zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts
zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank
zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score
zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card
-- connection
echo = chkargs_wrap(echo, 1), -- (v) -> v
ping = ping, -- () -> true
-- server
flushall = flushdb, -- () -> true
flushdb = flushdb, -- () -> true
-- debug
dbg_zcoherence = dbg_zcoherence,
}
local new = function()
local r = {data = {}}
return setmetatable(r,{__index = methods})
end
return {
new = new,
}
| gpl-2.0 |
szym/turbo | turbo/httputil.lua | 5 | 25684 | --- Turbo.lua HTTP Utilities module
-- Contains the HTTPHeaders and HTTPParser classes, which parses request and
-- response headers and also offers utilities to build request headers.
--
-- Also offers a few functions for parsing GET URL parameters, and different
-- POST data types.
--
-- Copyright John Abrahamsen 2011, 2012, 2013
--
-- "Permission is hereby granted, free of charge, to any person obtaining a copy of
-- this software and associated documentation files (the "Software"), to deal in
-- the Software without restriction, including without limitation the rights to
-- use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
-- of the Software, and to permit persons to whom the Software is furnished to do
-- so, subject to the following conditions:
--
-- The above copyright notice and this permission notice shall be included in all
-- copies or substantial portions of the Software.
--
-- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-- SOFTWARE."
local log = require "turbo.log"
local status_codes = require "turbo.http_response_codes"
local deque = require "turbo.structs.deque"
local buffer = require "turbo.structs.buffer"
local escape = require "turbo.escape"
local util = require "turbo.util"
local platform = require "turbo.platform"
local ffi = require "ffi"
local libturbo_parser = util.load_libtffi()
require "turbo.cdef"
require "turbo.3rdparty.middleclass"
local fast_assert = util.fast_assert
local b = string.byte
local httputil = {} -- httputil namespace
--- Must match the enum in http-parser.h!
local method_map = {
[0] = "DELETE",
"GET",
"HEAD",
"POST",
"PUT",
"CONNECT",
"OPTIONS",
"TRACE",
"COPY",
"LOCK",
"MKCOL",
"MOVE",
"PROPFIND",
"PROPPATCH",
"SEARCH",
"UNLOCK",
"REPORT",
"MKACTIVITY",
"CHECKOUT",
"MERGE",
"MSEARCH",
"NOTIFY",
"SUBSCRIBE",
"UNSUBSCRIBE",
"PATCH",
"PURGE"
}
local function MAX(a,b) return a > b and a or b end
--*************** HTTP Header parsing ***************
--- URL Field table.
httputil.UF = {
SCHEMA = 0
, HOST = 1
, PORT = 2
, PATH = 3
, QUERY = 4
, FRAGMENT = 5
, USERINFO = 6
}
--- HTTP header type. Use on HTTPHeaders initialize() to specify
-- header type to parse.
httputil.hdr_t = {
HTTP_REQUEST = 0,
HTTP_RESPONSE = 1,
HTTP_BOTH = 2
}
local javascript_types = {
["application/javascript"] = true,
["application/json"] = true,
["application/x-javascript"] = true,
["text/x-javascript"] = true,
["text/x-json"] = true
}
--- HTTPParser Class
-- Class for creation and parsing of HTTP headers.
httputil.HTTPParser = class("HTTPParser")
--- Pass request headers as parameters to parse them into
-- the returned object.
function httputil.HTTPParser:initialize(hdr_str, hdr_t)
if hdr_str and hdr_t then
if hdr_t == httputil.hdr_t["HTTP_REQUEST"] then
self:parse_request_header(hdr_str)
elseif hdr_t == httputil.hdr_t["HTTP_RESPONSE"] then
self:parse_response_header(hdr_str)
end
end
-- Arguments are only parsed on-demand.
self._arguments_parsed = false
end
--- Parse standalone URL and populate class instance with values.
-- HTTPParser.get_url_field must be used to read out values.
-- @param url (String) URL string.
-- @note Will throw error if URL does not parse correctly.
function httputil.HTTPParser:parse_url(url)
if type(url) ~= "string" then
error("URL parameter is not a string")
end
local htpurl = ffi.C.malloc(ffi.sizeof("struct http_parser_url"))
if htpurl == nil then
error("Could not allocate memory")
end
ffi.gc(htpurl, ffi.C.free)
self.http_parser_url = ffi.cast("struct http_parser_url *", htpurl)
local rc = libturbo_parser.http_parser_parse_url(
url,
url:len(),
0,
self.http_parser_url)
if rc ~= 0 then
error("Could not parse URL")
end
if not self.url then
self.url = url
end
end
--- Get a URL field.
-- @param UF_prop (Number) Available fields described in the httputil.UF table.
-- @return nil if not found, else the string value is returned.
function httputil.HTTPParser:get_url_field(UF_prop)
if not self.url then
self:get_url()
end
if not self.http_parser_url then
self:parse_url(self.url)
end
if libturbo_parser.url_field_is_set(
self.http_parser_url, UF_prop) == true then
local url = ffi.cast("const char *", self.url)
local field = ffi.string(
url+self.http_parser_url.field_data[UF_prop].off,
self.http_parser_url.field_data[UF_prop].len)
return field
end
-- Field is not set.
return nil
end
--- Get URL.
-- @return Currently set URI or nil if not set.
function httputil.HTTPParser:get_url()
if self.url then
return self.url
else
if not self.tpw then
error("No URL or header has been parsed. Can not return URL.")
end
if self.tpw.url_str == nil then
error("No URL available for request headers.")
end
self.url = ffi.string(self.tpw.url_str, self.tpw.url_sz)
end
return self.url
end
--- Get HTTP method
-- @return Current method as string or nil if not set.
function httputil.HTTPParser:get_method()
if not self.tpw then
error("No header has been parsed. Can not return method.")
end
return method_map[self.tpw.parser.method]
end
--- Get the HTTP version.
-- @return Currently set version as string or nil if not set.
function httputil.HTTPParser:get_version()
return string.format(
"HTTP/%d.%d",
self.tpw.parser.http_major,
self.tpw.parser.http_minor)
end
--- Get the status code.
-- @return Status code and status code message if set, else nil.
function httputil.HTTPParser:get_status_code()
if not self.tpw then
error("No header has been parsed. Can not return status code.")
elseif self.hdr_t ~= httputil.hdr_t["HTTP_RESPONSE"] then
error("Parsed header not a HTTP response header.")
end
return self.tpw.parser.status_code, status_codes[self.status_code]
end
local function _unescape(s) return string.char(tonumber(s,16)) end
--- Internal function to parse ? and & separated key value fields.
-- @param uri (String)
local function _parse_arguments(uri)
local arguments = {}
local elements = 0;
for k, v in uri:gmatch("([^&=]+)=([^&]+)") do
elements = elements + 1;
if (elements > 256) then
-- Limit to 256 elements, which "should be enough for everyone".
break
end
v = v:gsub("+", " "):gsub("%%(%w%w)", _unescape);
if not arguments[k] then
arguments[k] = v;
else
if type(arguments[k]) == "string" then
local tmp = arguments[k];
arguments[k] = {tmp};
end
table.insert(arguments[k], v);
end
end
return arguments
end
--- Get URL argument of the header.
-- @param argument Key of argument to get value of.
-- @return If argument exists then the argument is either returned
-- as a table if multiple values is given the same key, or as a string if the
-- key only has one value. If argument does not exist, nil is returned.
function httputil.HTTPParser:get_argument(argument)
if not self._arguments_parsed then
self._arguments = _parse_arguments(self:get_url_field(httputil.UF.QUERY))
self._arguments_parsed = true
end
local arguments = self:get_arguments()
if arguments then
if type(arguments[argument]) == "table" then
return arguments[argument]
elseif type(arguments[argument]) == "string" then
return { arguments[argument] }
end
end
end
--- Get all arguments of the header as a table.
-- @return (Table) Table with keys and values.
function httputil.HTTPParser:get_arguments()
if not self._arguments_parsed then
local query = self:get_url_field(httputil.UF.QUERY)
if query then
self._arguments = _parse_arguments(query)
end
self._arguments_parsed = true
end
return self._arguments
end
--- Get given key from header key value section.
-- @param key (String) The key to get.
-- @param caseinsensitive (Boolean) If true then the key will be matched without
-- regard for case sensitivity.
-- @return The value of the key, or nil if not existing. May return a table if
-- multiple keys are set.
local strncasecmp
if platform.__LINUX__ or platform.__UNIX__ then
strncasecmp = ffi.C.strncasecmp
elseif platform.__WINDOWS__ then
-- Windows does not have strncasecmp, but has strnicmp, which does the
-- thing.
strncasecmp = ffi.C._strnicmp
end
function httputil.HTTPParser:get(key, caseinsensitive)
local value
local c = 0
local hdr_sz = tonumber(self.tpw.hkv_sz)
if hdr_sz <= 0 then
return nil
end
if caseinsensitive then
-- Case insensitive key.
for i = 0, hdr_sz-1 do
local field = self.tpw.hkv[i]
local key_sz = key:len()
if field.key_sz == key_sz then
if strncasecmp(
field.key,
key,
field.key_sz) == 0 then
local str = ffi.string(field.value, field.value_sz)
if c == 0 then
value = str
c = 1
elseif c == 1 then
value = {value, str}
c = 2
else
value[#value+1] = str
c = c + 1
end
end
end
end
else
-- Case sensitive key.
for i = 0, hdr_sz-1 do
local field = self.tpw.hkv[i]
local key_sz = key:len()
if field.key_sz == key_sz then
if ffi.C.memcmp(
field.key,
key,
MAX(field.key_sz, key_sz)) == 0 then
local str = ffi.string(field.value, field.value_sz)
if c == 0 then
value = str
c = 1
elseif c == 1 then
value = {value, str}
c = 2
else
value[#value+1] = str
c = c + 1
end
end
end
end
end
return value, c
end
--- Parse HTTP request or response headers.
-- Populates the class with all data in headers.
-- @param hdr_str (String) HTTP header string.
-- @param hdr_t (Number) A number defined in httputil.hdr_t representing header
-- type.
-- @note Will throw error on parsing failure.
function httputil.HTTPParser:parse_header(hdr_str, hdr_t)
-- Ensure the string is not GCed while we are still using it by keeping a
-- reference to it. There is no way for LuaJIT to know we are still
-- using pointers to it.
self.hdr_str = hdr_str
self.hdr_t = hdr_t
local tpw = libturbo_parser.turbo_parser_wrapper_init(
hdr_str,
hdr_str:len(),
hdr_t)
if tpw ~= nil then
ffi.gc(tpw, libturbo_parser.turbo_parser_wrapper_exit)
else
error("libturbo_parser could not allocate memory for struct.")
end
self.tpw = tpw
if libturbo_parser.turbo_parser_check(self.tpw) ~= true then
error(
string.format(
"libturbo_parser could not parse HTTP header. %s %s",
ffi.string(libturbo_parser.http_errno_name(
self.tpw.parser.http_errno)),
ffi.string(libturbo_parser.http_errno_description(
self.tpw.parser.http_errno))))
end
if self.tpw.headers_complete == false then
error("libturbo_parser could not parse header. Unknown error.")
end
end
--- Parse HTTP response headers.
-- Populates the class with all data in headers.
-- @param raw_headers (String) HTTP header string.
-- @note Will throw error on parsing failure.
function httputil.HTTPParser:parse_response_header(raw_headers)
self:parse_header(raw_headers, httputil.hdr_t["HTTP_RESPONSE"])
end
--- Parse HTTP request headers.
-- Populates the class with all data in headers.
-- @param raw_headers (String) HTTP header string.
-- @note Will throw error on parsing failure.
function httputil.HTTPParser:parse_request_header(raw_headers)
self:parse_header(raw_headers, httputil.hdr_t["HTTP_REQUEST"])
end
--- Parse HTTP post arguments.
function httputil.parse_post_arguments(data)
if type(data) ~= "string" then
error("data argument not a string.")
end
return _parse_arguments(data)
end
local DASH = string.byte('-')
local CR = string.byte'\r'
local LF = string.byte'\n'
-- finds the start of a line
local function find_line_start(str,pos, inc)
if not inc then inc = 1 end
local skipped = -1
-- skip any non-CRLF chars
repeat
b = str:byte(pos)
if b == nil then return nil end
pos = pos + inc
skipped = skipped+1
until (b==CR) or (b==LF)
local b2 = str:byte(pos)
if b2 == nil then return nil end
if (b2 == CR) or (b2 == LF) then
if b ~= b2 then
pos = pos + inc
end
end
return pos, skipped
end
-- @return end position of token, token string
local function getRFC822Atom(str,pos)
local fpos, lpos, token = str:find('([^%c%s()<>@,;:\\"/[%]?=]+)', pos)
return lpos, token
end
--- Parse multipart form data.
function httputil.parse_multipart_data(data, boundary)
local arguments = {}
local p1, p2, b1, b2
boundary = "--" .. boundary
p1, p2 = data:find(boundary, 1, true)
b1 = find_line_start(data,p2+1)
repeat
p1, p2 = data:find(boundary, p2, true)
if p1 == nil then break end
b2 = find_line_start(data,p1-1,-1)
do
local boundary_headers
local h1, h2, v1, skipped
v1 = b1
repeat
h1 = v1
v1 = find_line_start(data,v1)
if v1 == nil then goto next_boundary end
until skipped ~= 0
repeat
h2 = v1-1
v1, skipped = find_line_start(data,v1)
if v1 == nil then goto next_boundary end
until skipped == 0
boundary_headers = data:sub(h1,h2)
boundary_headers = boundary_headers:gsub("([^%c%s:]-):",
function(s) return string.gsub(s,"%u", function(c)
return string.lower(c) end) .. ":"
end)
if not boundary_headers then
goto next_boundary
end
do
local name, ctype
local argument = { }
for fname, fvalue, content_kvs in
boundary_headers:gmatch("([^%c%s:]+):%s*([^;]*);?([^\n\r]*)") do
if fvalue == "form-data" and fname=="content-disposition" then
argument[fname] = {}
local p = 1
repeat
p, key = getRFC822Atom(content_kvs,p)
if p == nil then break end
if content_kvs:byte(p+1) ~= string.byte('=') then
break
end
p=p+2
local _, p2, val = content_kvs:find('^"([^"]+)"',p)
if not p2 then
p2, val = getRFC822Atom(content_kvs,p)
if not p2 then break end
end
p = p2+1
if key=="name" then
name=val
end
argument[fname][key] = val
until false
else
if fname=="content-type" then
ctype = fvalue
fvalue = fvalue:lower()
elseif fname=="charset" or
fname=="content-transfer-encoding" then
fvalue = fvalue:lower()
end
argument[fname] = fvalue
end
end
if not name then
goto next_boundary
end
argument[1] = data:sub(v1, b2)
if argument["content-transfer-encoding"] == "base64" then
argument[1] = escape.base64_decode(argument[1])
end
if javascript_types[argument["content-type"]] then
argument[1] = escape.unescape(argument[1])
end
if arguments[name] then
arguments[name][#arguments[name] +1] = argument
else
arguments[name] = { argument }
end
end
end
::next_boundary::
b1 = find_line_start(data,p2+1)
until (b1+1 > #data) or
(data:byte(p2+1) == DASH and data:byte(p2+2) == DASH)
return arguments
end
--*************** HTTP Header generation ***************
--- HTTPHeaders Class
-- Class for creating HTTP headers in a programmatic fashion.
httputil.HTTPHeaders = class("HTTPHeaders")
function httputil.HTTPHeaders:initialize()
self._fields = {}
end
--- Set URI.
-- @param uri (String)
function httputil.HTTPHeaders:set_uri(uri)
if type(uri) ~= "string" then
error("argument #1 not a string.")
end
self.uri = uri
end
--- Get current URI.
-- @return Currently set URI or nil if not set.
function httputil.HTTPHeaders:get_uri() return self.uri end
--- Set HTTP method.
-- @param method (String) Must be string, or error is raised.
function httputil.HTTPHeaders:set_method(method)
if type(method) ~= "string" then
error("argument #1 not a string.")
end
self.method = method
end
--- Get HTTP method
-- @return Current method as string or nil if not set.
function httputil.HTTPHeaders:get_method() return self.method end
--- Set the HTTP version.
-- Applies when building response headers only.
-- @param version (String) Version in string form, e.g "1.1" or "1.0"
-- Must be string or error is raised.
function httputil.HTTPHeaders:set_version(version)
if type(version) ~= "string" then
error("argument #1 not a string.")
end
self.version = version
end
--- Get the current HTTP version.
-- @return Currently set version as string or nil if not set.
function httputil.HTTPHeaders:get_version() return self.version end
--- Set the status code.
-- Applies when building response headers.
-- @param code (Number) HTTP status code to set. Must be number or
-- error is raised.
function httputil.HTTPHeaders:set_status_code(code)
if type(code) ~= "number" then
error("argument #1 not a number.")
end
if not status_codes[code] then
error(string.format("Invalid HTTP status code given: %d", code))
end
self.status_code = code
end
--- Get the current status code.
-- @return Status code and status code message if set, else nil.
function httputil.HTTPHeaders:get_status_code()
return self.status_code, status_codes[self.status_code]
end
--- Get given key from header key value section.
-- @param key (String) The key to get.
-- @param caseinsensitive (Boolean) If true then the key will be matched without
-- regard for case sensitivity.
-- @return The value of the key, or nil if not existing. May return a table if
-- multiple keys are set.
function httputil.HTTPHeaders:get(key, caseinsensitive)
local value
local cnt = 0
if caseinsensitive == true then
key = key:lower()
for i = 1, #self._fields do
if self._fields[i] and self._fields[i][1]:lower() == key then
if cnt == 0 then
value = self._fields[i][2]
cnt = 1
elseif cnt == 1 then
value = {value, self._fields[i][2]}
cnt = 2
else
value[#value + 1] = self._fields[i][2]
cnt = cnt + 1
end
end
end
else
for i = 1, #self._fields do
if self._fields[i] and self._fields[i][1] == key then
if cnt == 0 then
value = self._fields[i][2]
cnt = 1
elseif cnt == 1 then
value = {value, self._fields[i][2]}
cnt = 2
else
value[#value + 1] = self._fields[i][2]
cnt = cnt + 1
end
end
end
end
return value, cnt
end
--- Add a key with value to the headers. Supports adding multiple values to
-- one key. E.g mutiple "Set-Cookie" header fields.
-- @param key (String) Key to add to headers. Must be string or error is raised.
-- @param value (String or Number) Value to associate with the key.
function httputil.HTTPHeaders:add(key, value)
if type(key) ~= "string" then
error("Key parameter must be a string.")
end
local t = type(value)
if t == "string" then
if value:find("\r\n", 1, true) then
error("String value contain <CR><LF>, not allowed.")
end
elseif t ~= "number" then
error("Value parameter must be a string or number.")
end
self._fields[#self._fields + 1] = {key, value}
end
--- Set a key with value to the headers. Overwiting existing key.
-- @param key (String) Key to set to headers. Must be string or error is raised.
-- @param value (String) Value to associate with the key.
function httputil.HTTPHeaders:set(key, value, caseinsensitive)
if type(key) ~= "string" then
error("Key parameter must be a string.")
end
local t = type(value)
if t == "string" then
if value:find("\r\n", 1, true) then
error("String value contain <CR><LF>, not allowed.")
end
elseif t ~= "number" then
error("Value parameter must be a string or number.")
end
self:remove(key, caseinsensitive)
self:add(key, value)
end
--- Remove key from headers.
-- @param key (String) Key to remove from headers. Must be string or error is raised.
-- @param caseinsensitive (Boolean) If true then the key will be matched without
-- regard for case sensitivity.
function httputil.HTTPHeaders:remove(key, caseinsensitive)
if type(key) ~= "string" then
error("Key parameter must be a string.")
end
if caseinsensitive == false then
for i = 1, #self._fields do
if self._fields[i] and self._fields[i][1] == key then
self._fields[i] = nil
end
end
else
key = key:lower()
for i = 1, #self._fields do
if self._fields[i] and self._fields[i][1]:lower() == key then
self._fields[i] = nil
end
end
end
end
--- Stringify data set in class as a HTTP request header.
-- @return (String) HTTP header string excluding final delimiter.
function httputil.HTTPHeaders:stringify_as_request()
local buffer = buffer:new()
for i = 1, #self._fields do
if self._fields[i] then
buffer:append_luastr_right(string.format("%s: %s\r\n",
self._fields[i][1], self._fields[i][2]));
end
end
return string.format("%s %s %s\r\n%s\r\n",
self.method,
self.uri,
self.version,
tostring(buffer))
end
--- Stringify data set in class as a HTTP response header.
-- If not "Date" field is set, it will be generated automatically.
-- @return (String) HTTP header string excluding final delimiter.
function httputil.HTTPHeaders:stringify_as_response()
local buf = buffer:new()
if not self:get("Date") then
-- Add current time as Date header if not set already.
self:add("Date", util.time_format_http_header(util.gettimeofday()))
end
for i = 1 , #self._fields do
if self._fields[i] then
-- string.format causes trace abort here.
-- Just build keyword values by abuse.
buf:append_luastr_right(self._fields[i][1])
buf:append_luastr_right(": ")
buf:append_luastr_right(tostring(self._fields[i][2]))
buf:append_luastr_right("\r\n")
end
end
return string.format("%s %d %s\r\n%s",
self.version,
self.status_code,
status_codes[self.status_code],
tostring(buf))
end
--- Convinience method to return HTTPHeaders:stringify_as_response on string
-- conversion.
function httputil.HTTPHeaders:__tostring()
return self:stringify_as_response()
end
return httputil
| apache-2.0 |
luvit/luvit | examples/http-server-todo-web.lua | 4 | 1719 | local http = require('http');
local url = require('url');
local items = {};
-- see Node.js_in_action.pdf : page 89 (110 of 417)
http.createServer( function(req, res)
--p(req)
if req.url=='/' then
if req.method=='GET' then
show(res);
elseif req.method=='POST' then
add(req, res);
else
badRequest(res);
end
else
notFound(res);
end
end) :listen(8080)
function map(a, fcn)
local b={}
for i,v in ipairs(a) do
table.insert(b, fcn(v))
end
return b
end
function show(res)
local html = '<html><head><title>Todo List</title></head><body>\n'
.. '<h1>Todo List</h1>\n' -- For simple apps, inlining
.. '<ul>\n' -- the HTML instead of
.. table.concat(map(items, function(item) --using a template engine works well.
return '<li>' .. item .. '</li>'
end),'\n')
.. '</ul>\n'
.. '<form method="post" action="/">\n'
.. '<p><input type="text" name="item" /></p>\n'
.. '<p><input type="submit" value="Add Item" /></p>\n'
.. '</form></body></html>\n';
res:setHeader('Content-Type', 'text/html');
res:setHeader('Content-Length', #html);
res:finish(html);
end
function notFound(res)
res.statusCode = 404;
res:setHeader('Content-Type', 'text/plain');
res:finish('Not Found');
end
function badRequest(res)
res.statusCode = 400;
res:setHeader('Content-Type', 'text/plain');
res:finish('Bad Request');
end
local qs = require('querystring');
function add(req, res)
local body = '';
--req.setEncoding('utf8');
req:on('data', function(chunk) body =body.. chunk end);
req:on('end', function()
local obj = qs.parse(body);
--p(obj)
table.insert(items,obj.item);
show(res);
end);
end
print('Server running at http://127.0.0.1:8080/\n Connect to server using a web browser.')
| apache-2.0 |
xingshuo/frame_sync_model | server/agent/player.lua | 1 | 3666 | local Class = require "lualib.class"
local Debug = require "lualib.debug"
local Skynet = require "lualib.local_skynet"
local TimerObj = import "lualib/object"
local Env = import "agent/env"
local Net = import "lualib/net"
local BCApi = import "broadcast/api"
local Player = Class("Player", "TimerObject")
function Player:__tostring()
return string.format("[id:%s name:%s fd:%s]",self.m_ID,self.m_Name,self.m_FD)
end
function Player:init(id, mArgs)
TimerObj.TimerObject.init(self)
self.m_ID = id
self.m_Name = mArgs.name
self.m_FD = mArgs.fd
self.m_GameModeID = mArgs.game_mode_id
self.m_Color = mArgs.color
self.m_PingSession = 0
self.m_LastPingSession = 0
self.m_PingTime = GetCSecond()
self.m_lRTTValues = {}
self.m_RTT = 0
self.m_OldRTT = 0
end
function Player:login()
Env.set_player(self.m_ID, self)
BCApi.register_fd(self.m_ID, self.m_FD)
Debug.fprint("====player %s==login==",self)
local ti = GGameConfig[self.m_GameModeID]["ping_interval"]
self:AddTimer(ti//10, function () self:check_gs_ping() end, "ServerPing")
end
function Player:quit()
Env.del_player(self.m_ID)
BCApi.unregister_fd(self.m_ID)
Debug.fprint("====player %s==quit===",self)
end
function Player:enterwar()
local mt = skynet_call("SCENE_MGR", "enter_player", self.m_GameModeID, self.m_ID, self:PackData())
self.m_GameID = mt.game_id
self.m_SceneAgent = mt.agent
end
function Player:leavewar()
if self.m_SceneAgent then
skynet_send(self.m_SceneAgent, "leave_player", self.m_GameID, self.m_ID)
end
end
function Player:client_ping(session)
--Debug.fprint("==%s=recv=cs ping resp=%s=gs pingsession %s lastpingsession %s=",self,session,self.m_PingSession,self.m_LastPingSession)
if session ~= self.m_PingSession then
return
end
if self.m_LastPingSession == self.m_PingSession then
return
end
self.m_LastPingSession = self.m_PingSession
self:calc_rtt()
Net.send_to_player(self.m_ID, "gs2c_ping", {session = session, timestamp = GetCSecond(), is_resp = true})
end
function Player:check_gs_ping()
if self.m_PingSession == self.m_LastPingSession then
self.m_PingSession = self.m_PingSession + 1
self.m_PingTime = GetCSecond()
Net.send_to_player(self.m_ID, "gs2c_ping", {session = self.m_PingSession, timestamp = GetCSecond(), is_resp = false})
else
self:calc_rtt()
Net.send_to_player(self.m_ID, "gs2c_ping", {session = self.m_PingSession, timestamp = GetCSecond(), is_resp = false}) --resend
end
end
function Player:calc_rtt()
if #self.m_lRTTValues > 0 then
if self.m_lRTTValues[#self.m_lRTTValues][1] == self.m_PingSession then
self.m_lRTTValues[#self.m_lRTTValues][2] = GetCSecond()-self.m_PingTime
else
table.insert(self.m_lRTTValues, {self.m_PingSession, GetCSecond()-self.m_PingTime})
end
else
table.insert(self.m_lRTTValues, {self.m_PingSession, GetCSecond()-self.m_PingTime})
end
if #self.m_lRTTValues > 5 then
table.remove(self.m_lRTTValues, 1)
end
self.m_RTT = table.list_avg_value2(self.m_lRTTValues, 2)
self.m_RTT = math.floor(self.m_RTT)
if math.abs(self.m_RTT - self.m_OldRTT) >= 5 then
self.m_OldRTT = self.m_RTT
skynet_send(self.m_SceneAgent, "sync_data", self.m_GameID, self.m_ID, {rtt = self.m_RTT})
end
-- print(string.format("----%s: rtt: %s---%s--",self.m_Name,self.m_RTT,table.tostring(self.m_lRTTValues)))
end
function Player:PackData()
local mt = {}
mt.name = self.m_Name
mt.pid = self.m_ID
mt.fd = self.m_FD
mt.color = self.m_Color
return mt
end
function Player:sync_ctrl(data)
if self.m_SceneAgent then
skynet_send(self.m_SceneAgent, "sync_ctrl", self.m_GameID, self.m_ID, data)
end
end
function NewPlayer(pid, mArgs)
local pobj = Player:new(pid, mArgs)
return pobj
end | mit |
fucksooN/tabchi | libs/dkjson.lua | 63 | 26559 | -- Module options:
local always_try_using_lpeg = true
local register_global_module_table = false
local global_module_name = 'json'
--[==[
David Kolf's JSON module for Lua 5.1/5.2
========================================
*Version 2.4*
In the default configuration this module writes no global values, not even
the module table. Import it using
json = require ("dkjson")
In environments where `require` or a similiar function are not available
and you cannot receive the return value of the module, you can set the
option `register_global_module_table` to `true`. The module table will
then be saved in the global variable with the name given by the option
`global_module_name`.
Exported functions and values:
`json.encode (object [, state])`
--------------------------------
Create a string representing the object. `Object` can be a table,
a string, a number, a boolean, `nil`, `json.null` or any object with
a function `__tojson` in its metatable. A table can only use strings
and numbers as keys and its values have to be valid objects as
well. It raises an error for any invalid data types or reference
cycles.
`state` is an optional table with the following fields:
- `indent`
When `indent` (a boolean) is set, the created string will contain
newlines and indentations. Otherwise it will be one long line.
- `keyorder`
`keyorder` is an array to specify the ordering of keys in the
encoded output. If an object has keys which are not in this array
they are written after the sorted keys.
- `level`
This is the initial level of indentation used when `indent` is
set. For each level two spaces are added. When absent it is set
to 0.
- `buffer`
`buffer` is an array to store the strings for the result so they
can be concatenated at once. When it isn't given, the encode
function will create it temporary and will return the
concatenated result.
- `bufferlen`
When `bufferlen` is set, it has to be the index of the last
element of `buffer`.
- `tables`
`tables` is a set to detect reference cycles. It is created
temporary when absent. Every table that is currently processed
is used as key, the value is `true`.
When `state.buffer` was set, the return value will be `true` on
success. Without `state.buffer` the return value will be a string.
`json.decode (string [, position [, null]])`
--------------------------------------------
Decode `string` starting at `position` or at 1 if `position` was
omitted.
`null` is an optional value to be returned for null values. The
default is `nil`, but you could set it to `json.null` or any other
value.
The return values are the object or `nil`, the position of the next
character that doesn't belong to the object, and in case of errors
an error message.
Two metatables are created. Every array or object that is decoded gets
a metatable with the `__jsontype` field set to either `array` or
`object`. If you want to provide your own metatables use the syntax
json.decode (string, position, null, objectmeta, arraymeta)
To prevent the assigning of metatables pass `nil`:
json.decode (string, position, null, nil)
`<metatable>.__jsonorder`
-------------------------
`__jsonorder` can overwrite the `keyorder` for a specific table.
`<metatable>.__jsontype`
------------------------
`__jsontype` can be either `"array"` or `"object"`. This value is only
checked for empty tables. (The default for empty tables is `"array"`).
`<metatable>.__tojson (self, state)`
------------------------------------
You can provide your own `__tojson` function in a metatable. In this
function you can either add directly to the buffer and return true,
or you can return a string. On errors nil and a message should be
returned.
`json.null`
-----------
You can use this value for setting explicit `null` values.
`json.version`
--------------
Set to `"dkjson 2.4"`.
`json.quotestring (string)`
---------------------------
Quote a UTF-8 string and escape critical characters using JSON
escape sequences. This function is only necessary when you build
your own `__tojson` functions.
`json.addnewline (state)`
-------------------------
When `state.indent` is set, add a newline to `state.buffer` and spaces
according to `state.level`.
LPeg support
------------
When the local configuration variable `always_try_using_lpeg` is set,
this module tries to load LPeg to replace the `decode` function. The
speed increase is significant. You can get the LPeg module at
<http://www.inf.puc-rio.br/~roberto/lpeg/>.
When LPeg couldn't be loaded, the pure Lua functions stay active.
In case you don't want this module to require LPeg on its own,
disable the option `always_try_using_lpeg` in the options section at
the top of the module.
In this case you can later load LPeg support using
### `json.use_lpeg ()`
Require the LPeg module and replace the functions `quotestring` and
and `decode` with functions that use LPeg patterns.
This function returns the module table, so you can load the module
using:
json = require "dkjson".use_lpeg()
Alternatively you can use `pcall` so the JSON module still works when
LPeg isn't found.
json = require "dkjson"
pcall (json.use_lpeg)
### `json.using_lpeg`
This variable is set to `true` when LPeg was loaded successfully.
---------------------------------------------------------------------
Contact
-------
You can contact the author by sending an e-mail to 'david' at the
domain 'dkolf.de'.
---------------------------------------------------------------------
*Copyright (C) 2010-2013 David Heiko Kolf*
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.
<!-- This documentation can be parsed using Markdown to generate HTML.
The source code is enclosed in a HTML comment so it won't be displayed
by browsers, but it should be removed from the final HTML file as
it isn't a valid HTML comment (and wastes space).
-->
<!--]==]
-- global dependencies:
local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset =
pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset
local error, require, pcall, select = error, require, pcall, select
local floor, huge = math.floor, math.huge
local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat =
string.rep, string.gsub, string.sub, string.byte, string.char,
string.find, string.len, string.format
local strmatch = string.match
local concat = table.concat
local json = { version = "dkjson 2.4" }
if register_global_module_table then
_G[global_module_name] = json
end
local _ENV = nil -- blocking globals in Lua 5.2
pcall (function()
-- Enable access to blocked metatables.
-- Don't worry, this module doesn't change anything in them.
local debmeta = require "debug".getmetatable
if debmeta then getmetatable = debmeta end
end)
json.null = setmetatable ({}, {
__tojson = function () return "null" end
})
local function isarray (tbl)
local max, n, arraylen = 0, 0, 0
for k,v in pairs (tbl) do
if k == 'n' and type(v) == 'number' then
arraylen = v
if v > max then
max = v
end
else
if type(k) ~= 'number' or k < 1 or floor(k) ~= k then
return false
end
if k > max then
max = k
end
n = n + 1
end
end
if max > 10 and max > arraylen and max > n * 2 then
return false -- don't create an array with too many holes
end
return true, max
end
local escapecodes = {
["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f",
["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t"
}
local function escapeutf8 (uchar)
local value = escapecodes[uchar]
if value then
return value
end
local a, b, c, d = strbyte (uchar, 1, 4)
a, b, c, d = a or 0, b or 0, c or 0, d or 0
if a <= 0x7f then
value = a
elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then
value = (a - 0xc0) * 0x40 + b - 0x80
elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then
value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80
elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then
value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80
else
return ""
end
if value <= 0xffff then
return strformat ("\\u%.4x", value)
elseif value <= 0x10ffff then
-- encode as UTF-16 surrogate pair
value = value - 0x10000
local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400)
return strformat ("\\u%.4x\\u%.4x", highsur, lowsur)
else
return ""
end
end
local function fsub (str, pattern, repl)
-- gsub always builds a new string in a buffer, even when no match
-- exists. First using find should be more efficient when most strings
-- don't contain the pattern.
if strfind (str, pattern) then
return gsub (str, pattern, repl)
else
return str
end
end
local function quotestring (value)
-- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js
value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8)
if strfind (value, "[\194\216\220\225\226\239]") then
value = fsub (value, "\194[\128-\159\173]", escapeutf8)
value = fsub (value, "\216[\128-\132]", escapeutf8)
value = fsub (value, "\220\143", escapeutf8)
value = fsub (value, "\225\158[\180\181]", escapeutf8)
value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8)
value = fsub (value, "\226\129[\160-\175]", escapeutf8)
value = fsub (value, "\239\187\191", escapeutf8)
value = fsub (value, "\239\191[\176-\191]", escapeutf8)
end
return "\"" .. value .. "\""
end
json.quotestring = quotestring
local function replace(str, o, n)
local i, j = strfind (str, o, 1, true)
if i then
return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1)
else
return str
end
end
-- locale independent num2str and str2num functions
local decpoint, numfilter
local function updatedecpoint ()
decpoint = strmatch(tostring(0.5), "([^05+])")
-- build a filter that can be used to remove group separators
numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+"
end
updatedecpoint()
local function num2str (num)
return replace(fsub(tostring(num), numfilter, ""), decpoint, ".")
end
local function str2num (str)
local num = tonumber(replace(str, ".", decpoint))
if not num then
updatedecpoint()
num = tonumber(replace(str, ".", decpoint))
end
return num
end
local function addnewline2 (level, buffer, buflen)
buffer[buflen+1] = "\n"
buffer[buflen+2] = strrep (" ", level)
buflen = buflen + 2
return buflen
end
function json.addnewline (state)
if state.indent then
state.bufferlen = addnewline2 (state.level or 0,
state.buffer, state.bufferlen or #(state.buffer))
end
end
local encode2 -- forward declaration
local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder)
local kt = type (key)
if kt ~= 'string' and kt ~= 'number' then
return nil, "type '" .. kt .. "' is not supported as a key by JSON."
end
if prev then
buflen = buflen + 1
buffer[buflen] = ","
end
if indent then
buflen = addnewline2 (level, buffer, buflen)
end
buffer[buflen+1] = quotestring (key)
buffer[buflen+2] = ":"
return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder)
end
encode2 = function (value, indent, level, buffer, buflen, tables, globalorder)
local valtype = type (value)
local valmeta = getmetatable (value)
valmeta = type (valmeta) == 'table' and valmeta -- only tables
local valtojson = valmeta and valmeta.__tojson
if valtojson then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
local state = {
indent = indent, level = level, buffer = buffer,
bufferlen = buflen, tables = tables, keyorder = globalorder
}
local ret, msg = valtojson (value, state)
if not ret then return nil, msg end
tables[value] = nil
buflen = state.bufferlen
if type (ret) == 'string' then
buflen = buflen + 1
buffer[buflen] = ret
end
elseif value == nil then
buflen = buflen + 1
buffer[buflen] = "null"
elseif valtype == 'number' then
local s
if value ~= value or value >= huge or -value >= huge then
-- This is the behaviour of the original JSON implementation.
s = "null"
else
s = num2str (value)
end
buflen = buflen + 1
buffer[buflen] = s
elseif valtype == 'boolean' then
buflen = buflen + 1
buffer[buflen] = value and "true" or "false"
elseif valtype == 'string' then
buflen = buflen + 1
buffer[buflen] = quotestring (value)
elseif valtype == 'table' then
if tables[value] then
return nil, "reference cycle"
end
tables[value] = true
level = level + 1
local isa, n = isarray (value)
if n == 0 and valmeta and valmeta.__jsontype == 'object' then
isa = false
end
local msg
if isa then -- JSON array
buflen = buflen + 1
buffer[buflen] = "["
for i = 1, n do
buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
if i < n then
buflen = buflen + 1
buffer[buflen] = ","
end
end
buflen = buflen + 1
buffer[buflen] = "]"
else -- JSON object
local prev = false
buflen = buflen + 1
buffer[buflen] = "{"
local order = valmeta and valmeta.__jsonorder or globalorder
if order then
local used = {}
n = #order
for i = 1, n do
local k = order[i]
local v = value[k]
if v then
used[k] = true
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
prev = true -- add a seperator before the next element
end
end
for k,v in pairs (value) do
if not used[k] then
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
else -- unordered
for k,v in pairs (value) do
buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder)
if not buflen then return nil, msg end
prev = true -- add a seperator before the next element
end
end
if indent then
buflen = addnewline2 (level - 1, buffer, buflen)
end
buflen = buflen + 1
buffer[buflen] = "}"
end
tables[value] = nil
else
return nil, "type '" .. valtype .. "' is not supported by JSON."
end
return buflen
end
function json.encode (value, state)
state = state or {}
local oldbuffer = state.buffer
local buffer = oldbuffer or {}
updatedecpoint()
local ret, msg = encode2 (value, state.indent, state.level or 0,
buffer, state.bufferlen or 0, state.tables or {}, state.keyorder)
if not ret then
error (msg, 2)
elseif oldbuffer then
state.bufferlen = ret
return true
else
return concat (buffer)
end
end
local function loc (str, where)
local line, pos, linepos = 1, 1, 0
while true do
pos = strfind (str, "\n", pos, true)
if pos and pos < where then
line = line + 1
linepos = pos
pos = pos + 1
else
break
end
end
return "line " .. line .. ", column " .. (where - linepos)
end
local function unterminated (str, what, where)
return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where)
end
local function scanwhite (str, pos)
while true do
pos = strfind (str, "%S", pos)
if not pos then return nil end
if strsub (str, pos, pos + 2) == "\239\187\191" then
-- UTF-8 Byte Order Mark
pos = pos + 3
else
return pos
end
end
end
local escapechars = {
["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f",
["n"] = "\n", ["r"] = "\r", ["t"] = "\t"
}
local function unichar (value)
if value < 0 then
return nil
elseif value <= 0x007f then
return strchar (value)
elseif value <= 0x07ff then
return strchar (0xc0 + floor(value/0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0xffff then
return strchar (0xe0 + floor(value/0x1000),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
elseif value <= 0x10ffff then
return strchar (0xf0 + floor(value/0x40000),
0x80 + (floor(value/0x1000) % 0x40),
0x80 + (floor(value/0x40) % 0x40),
0x80 + (floor(value) % 0x40))
else
return nil
end
end
local function scanstring (str, pos)
local lastpos = pos + 1
local buffer, n = {}, 0
while true do
local nextpos = strfind (str, "[\"\\]", lastpos)
if not nextpos then
return unterminated (str, "string", pos)
end
if nextpos > lastpos then
n = n + 1
buffer[n] = strsub (str, lastpos, nextpos - 1)
end
if strsub (str, nextpos, nextpos) == "\"" then
lastpos = nextpos + 1
break
else
local escchar = strsub (str, nextpos + 1, nextpos + 1)
local value
if escchar == "u" then
value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16)
if value then
local value2
if 0xD800 <= value and value <= 0xDBff then
-- we have the high surrogate of UTF-16. Check if there is a
-- low surrogate escaped nearby to combine them.
if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then
value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16)
if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then
value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000
else
value2 = nil -- in case it was out of range for a low surrogate
end
end
end
value = value and unichar (value)
if value then
if value2 then
lastpos = nextpos + 12
else
lastpos = nextpos + 6
end
end
end
end
if not value then
value = escapechars[escchar] or escchar
lastpos = nextpos + 2
end
n = n + 1
buffer[n] = value
end
end
if n == 1 then
return buffer[1], lastpos
elseif n > 1 then
return concat (buffer), lastpos
else
return "", lastpos
end
end
local scanvalue -- forward declaration
local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta)
local len = strlen (str)
local tbl, n = {}, 0
local pos = startpos + 1
if what == 'object' then
setmetatable (tbl, objectmeta)
else
setmetatable (tbl, arraymeta)
end
while true do
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
local char = strsub (str, pos, pos)
if char == closechar then
return tbl, pos + 1
end
local val1, err
val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
if char == ":" then
if val1 == nil then
return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")"
end
pos = scanwhite (str, pos + 1)
if not pos then return unterminated (str, what, startpos) end
local val2
val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta)
if err then return nil, pos, err end
tbl[val1] = val2
pos = scanwhite (str, pos)
if not pos then return unterminated (str, what, startpos) end
char = strsub (str, pos, pos)
else
n = n + 1
tbl[n] = val1
end
if char == "," then
pos = pos + 1
end
end
end
scanvalue = function (str, pos, nullval, objectmeta, arraymeta)
pos = pos or 1
pos = scanwhite (str, pos)
if not pos then
return nil, strlen (str) + 1, "no valid JSON value (reached the end)"
end
local char = strsub (str, pos, pos)
if char == "{" then
return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta)
elseif char == "[" then
return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta)
elseif char == "\"" then
return scanstring (str, pos)
else
local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos)
if pstart then
local number = str2num (strsub (str, pstart, pend))
if number then
return number, pend + 1
end
end
pstart, pend = strfind (str, "^%a%w*", pos)
if pstart then
local name = strsub (str, pstart, pend)
if name == "true" then
return true, pend + 1
elseif name == "false" then
return false, pend + 1
elseif name == "null" then
return nullval, pend + 1
end
end
return nil, pos, "no valid JSON value at " .. loc (str, pos)
end
end
local function optionalmetatables(...)
if select("#", ...) > 0 then
return ...
else
return {__jsontype = 'object'}, {__jsontype = 'array'}
end
end
function json.decode (str, pos, nullval, ...)
local objectmeta, arraymeta = optionalmetatables(...)
return scanvalue (str, pos, nullval, objectmeta, arraymeta)
end
function json.use_lpeg ()
local g = require ("lpeg")
if g.version() == "0.11" then
error "due to a bug in LPeg 0.11, it cannot be used for JSON matching"
end
local pegmatch = g.match
local P, S, R = g.P, g.S, g.R
local function ErrorCall (str, pos, msg, state)
if not state.msg then
state.msg = msg .. " at " .. loc (str, pos)
state.pos = pos
end
return false
end
local function Err (msg)
return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall)
end
local Space = (S" \n\r\t" + P"\239\187\191")^0
local PlainChar = 1 - S"\"\\\n\r"
local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars
local HexDigit = R("09", "af", "AF")
local function UTF16Surrogate (match, pos, high, low)
high, low = tonumber (high, 16), tonumber (low, 16)
if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then
return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000)
else
return false
end
end
local function UTF16BMP (hex)
return unichar (tonumber (hex, 16))
end
local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit))
local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP
local Char = UnicodeEscape + EscapeSequence + PlainChar
local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string")
local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0))
local Fractal = P"." * R"09"^0
local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1
local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num
local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1)
local SimpleValue = Number + String + Constant
local ArrayContent, ObjectContent
-- The functions parsearray and parseobject parse only a single value/pair
-- at a time and store them directly to avoid hitting the LPeg limits.
local function parsearray (str, pos, nullval, state)
local obj, cont
local npos
local t, nt = {}, 0
repeat
obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state)
if not npos then break end
pos = npos
nt = nt + 1
t[nt] = obj
until cont == 'last'
return pos, setmetatable (t, state.arraymeta)
end
local function parseobject (str, pos, nullval, state)
local obj, key, cont
local npos
local t = {}
repeat
key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state)
if not npos then break end
pos = npos
t[key] = obj
until cont == 'last'
return pos, setmetatable (t, state.objectmeta)
end
local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected")
local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected")
local Value = Space * (Array + Object + SimpleValue)
local ExpectedValue = Value + Space * Err "value expected"
ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue)
ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp()
local DecodeValue = ExpectedValue * g.Cp ()
function json.decode (str, pos, nullval, ...)
local state = {}
state.objectmeta, state.arraymeta = optionalmetatables(...)
local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state)
if state.msg then
return nil, state.pos, state.msg
else
return obj, retpos
end
end
-- use this function only once:
json.use_lpeg = function () return json end
json.using_lpeg = true
return json -- so you can get the module using json = require "dkjson".use_lpeg()
end
if always_try_using_lpeg then
pcall (json.use_lpeg)
end
return json
-->
| unlicense |
khanasbot/Avatar_Bot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
ahmadreza5251/terojanbot | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
pjanouch/logdiag | share/library/Active/bipolar.lua | 1 | 1302 | -- Symbol names
local names_npn =
{
en = "NPN transistor",
cs = "Tranzistor NPN",
sk = "Tranzistor NPN",
pl = "Tranzystor NPN",
de = "NPN Transistor"
}
local names_pnp =
{
en = "PNP transistor",
cs = "Tranzistor PNP",
sk = "Tranzistor PNP",
pl = "Tranzystor PNP",
de = "PNP Transistor"
}
-- Render area in base units (X1, Y1, X2, Y2)
local area = {-2, -2, 2, 2}
-- Terminal points
local terminals = {{-2, 0}, {2, 2}, {2, -2}}
-- Rendering
local render = function (cr)
-- The terminals
cr:move_to (-2, 0)
cr:line_to (0, 0)
cr:move_to (0, 0.5)
cr:line_to (2, 2)
cr:move_to (0, -0.5)
cr:line_to (2, -2)
-- The ohmic connection
cr:move_to (0, -1)
cr:line_to (0, 1)
cr:stroke ()
end
local render_npn = function (cr)
render (cr)
cr:save ()
cr:translate (0, 0.5)
cr:rotate (math.atan2 (-2, 1.5))
cr:move_to (-0.4, 0.8)
cr:line_to (0, 1.4)
cr:line_to (0.4, 0.8)
cr:stroke ()
cr:restore ()
end
local render_pnp = function (cr)
render (cr)
cr:save ()
cr:translate (2, -2)
cr:rotate (math.atan2 (2, 1.5))
cr:move_to (-0.4, 1.3)
cr:line_to (0, 1.9)
cr:line_to (0.4, 1.3)
cr:stroke ()
cr:restore ()
end
-- Register the symbols
logdiag.register ("NPN", names_npn, area, terminals, render_npn)
logdiag.register ("PNP", names_pnp, area, terminals, render_pnp)
| isc |
MOSAVI17/FreeTG | plugins/ingroup.lua | 527 | 44020 | 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'
}
}
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, 'Welcome to your new realm !')
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'
}
}
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, 'Realm has been added!')
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',
}
}
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, 'You have been promoted as the owner.')
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',
}
}
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, 'Group is added and you have been promoted as the owner ')
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, 'Realm has been removed!')
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, 'Group has been removed')
end
end
end
--End Check Member
local function show_group_settingsmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
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 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.."\nLock group leave : "..leave_ban.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public
return text
end
local function set_descriptionmod(msg, data, target, about)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function 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 lock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'yes' then
return 'Arabic is already locked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'yes'
save_data(_config.moderation.data, data)
return 'Arabic has been locked'
end
end
local function unlock_group_arabic(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic']
if group_arabic_lock == 'no' then
return 'Arabic is already unlocked'
else
data[tostring(target)]['settings']['lock_arabic'] = 'no'
save_data(_config.moderation.data, data)
return 'Arabic has been unlocked'
end
end
local function lock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'yes' then
return 'Bots protection is already enabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'yes'
save_data(_config.moderation.data, data)
return 'Bots protection has been enabled'
end
end
local function unlock_group_bots(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_bots_lock = data[tostring(target)]['settings']['lock_bots']
if group_bots_lock == 'no' then
return 'Bots protection is already disabled'
else
data[tostring(target)]['settings']['lock_bots'] = 'no'
save_data(_config.moderation.data, data)
return 'Bots protection has been disabled'
end
end
local function lock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
if not is_owner(msg) then
return "Only admins can do it for now"
end
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function set_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'yes' then
return 'Group is already public'
else
data[tostring(target)]['settings']['public'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group is now: public'
end
local function unset_public_membermod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_member_lock = data[tostring(target)]['settings']['public']
if group_member_lock == 'no' then
return 'Group is not public'
else
data[tostring(target)]['settings']['public'] = 'no'
save_data(_config.moderation.data, data)
return 'Group is now: not public'
end
end
local function lock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'yes' then
return 'Leaving users will be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Leaving users will be banned'
end
local function unlock_group_leave(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban']
if leave_ban == 'no' then
return 'Leaving users will not be banned'
else
data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no'
save_data(_config.moderation.data, data)
return 'Leaving users will not be banned'
end
end
local function unlock_group_photomod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function set_rulesmod(msg, data, target)
if not is_momod(msg) then
return "For moderators only!"
end
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function modadd(msg)
-- superuser and admins only (because sudo are always has privilege)
if not is_admin(msg) then
return "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_group(msg) then
return 'Group is already added.'
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 "You're not admin"
end
local data = load_data(_config.moderation.data)
if is_realm(msg) then
return 'Realm is already added.'
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 "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_group(msg) then
return 'Group is not added.'
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 "You're not admin"
end
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
return 'Realm is not added.'
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 = '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 = 'Chat 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, 'Photo saved!', 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, 'Group is not added.')
end
if data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is already a moderator.')
end
data[group]['moderators'][tostring(member_id)] = member_username
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been promoted.')
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, 'Group is not added.')
end
if not data[group]['moderators'][tostring(member_id)] then
return send_large_msg(receiver, member_username..' is not a moderator.')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_username..' has been demoted.')
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 setowner_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 owner")
local text = msg.from.print_name:gsub("_", " ").." is the owner now"
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 == 'promote' then
return promote(receiver, member_username, member_id)
elseif mod_cmd == 'demote' 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 'Group is not added.'
end
-- determine if table is empty
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators for ' .. 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] == 'add' and not matches[2] then
if is_realm(msg) then
return 'Error: Already a realm.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added")
return modadd(msg)
end
if matches[1] == 'add' and matches[2] == 'realm' then
if is_group(msg) then
return 'Error: Already a group.'
end
print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm")
return realmadd(msg)
end
if matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'rem' and matches[2] == 'realm' 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] == '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)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
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
if matches[1] == 'promote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can prmote new moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, promote_by_reply, false)
end
end
if matches[1] == 'promote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can promote"
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 = 'promote',
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] == 'demote' and not matches[2] then
if not is_owner(msg) then
return "Only the owner can demote moderators"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, demote_by_reply, false)
end
end
if matches[1] == 'demote' and matches[2] then
if not is_momod(msg) then
return
end
if not is_owner(msg) then
return "Only owner can demote"
end
if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then
return "You can't demote yourself"
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 = 'demote',
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] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'set' then
if matches[2] == 'rules' 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] == 'about' 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] == 'lock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ")
return lock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'arabic' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ")
return unlock_group_arabic(msg, data, target)
end
if matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'leave' 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' 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] == 'newlink' and not is_realm(msg) then
if not is_momod(msg) then
return "For moderators only!"
end
local function callback (extra , success, result)
local receiver = 'chat#'..msg.to.id
if success == 0 then
return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.')
end
send_large_msg(receiver, "Created a new link")
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] == 'link' then
if not is_momod(msg) then
return "For moderators only!"
end
local group_link = data[tostring(msg.to.id)]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
if matches[1] == 'setowner' and matches[2] then
if not is_owner(msg) then
return "For owner only!"
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 owner")
local text = matches[2].." added as owner"
return text
end
if matches[1] == 'setowner' and not matches[2] then
if not is_owner(msg) then
return "only for the owner!"
end
if type(msg.reply_id)~="nil" then
msgr = get_message(msg.reply_id, setowner_by_reply, false)
end
end
if matches[1] == 'owner' then
local group_owner = data[tostring(msg.to.id)]['set_owner']
if not group_owner then
return "no owner,ask admins in support groups to set owner for your group"
end
savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner")
return "Group owner is ["..group_owner..']'
end
if matches[1] == 'setgpowner' 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 owner"
send_large_msg(receiver, text)
return
end
if matches[1] == 'setflood' then
if not is_momod(msg) then
return "For moderators only!"
end
if tonumber(matches[2]) < 5 or tonumber(matches[2]) > 20 then
return "Wrong number,range is [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 'Group flood has been set to '..matches[2]
end
if matches[1] == 'clean' then
if not is_owner(msg) then
return "Only owner can clean"
end
if matches[2] == 'member' then
if not is_owner(msg) then
return "Only admins can clean members"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'modlist' then
if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way
return 'No moderator in this group.'
end
local message = '\nList of moderators for ' .. 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' then
local data_cat = 'rules'
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] == 'about' then
local data_cat = 'description'
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] == 'help' 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] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local username = matches[2]
local username = username:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username)
return res_user(username, callbackres, cbres_extra)
end
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 = {
"^[!/](add)$",
"^[!/](add) (realm)$",
"^[!/](rem)$",
"^[!/](rem) (realm)$",
"^[!/](rules)$",
"^[!/](about)$",
"^[!/](setname) (.*)$",
"^[!/](setphoto)$",
"^[!/](promote) (.*)$",
"^[!/](promote)",
"^[!/](help)$",
"^[!/](clean) (.*)$",
"^[!/](kill) (chat)$",
"^[!/](kill) (realm)$",
"^[!/](demote) (.*)$",
"^[!/](demote)",
"^[!/](set) ([^%s]+) (.*)$",
"^[!/](lock) (.*)$",
"^[!/](setowner) (%d+)$",
"^[!/](setowner)",
"^[!/](owner)$",
"^[!/](res) (.*)$",
"^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id)
"^[!/](unlock) (.*)$",
"^[!/](setflood) (%d+)$",
"^[!/](settings)$",
-- "^[!/](public) (.*)$",
"^[!/](modlist)$",
"^[!/](newlink)$",
"^[!/](link)$",
"^[!/](kickinactive)$",
"^[!/](kickinactive) (%d+)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
Billiam/love-rollbar | luajit-request/init.lua | 1 | 9160 | --[[
LuaJIT-Request
Lucien Greathouse
Wrapper for LuaJIT-cURL for easy HTTP(S) requests.
Copyright (c) 2014 lucien Greathouse
This software is provided 'as-is', without any express
or implied warranty. In no event will the authors be held
liable for any damages arising from the use of this software.
Permission is granted to anyone to use this software for any purpose,
including commercial applications, andto alter it and redistribute it
freely, subject to the following restrictions:
1. The origin of this software must not be misrepresented; you must not
claim that you wrote the original software. If you use this software
in a product, an acknowledgment in the product documentation would be
appreciated but is not required.
2. Altered source versions must be plainly marked as such, and must
not be misrepresented as being the original software.
3. This notice may not be removed or altered from any source distribution.
]]
local path = (...):gsub("%.init$", ""):match("%.?(.-)$") .. "."
local ffi = require("ffi")
local curl = require(path .. "luajit-curl")
local request
local function url_encode(str)
if (str) then
str = str:gsub("\n", "\r\n")
str = str:gsub("([^%w %-%_%.%~])", function(c)
return string.format ("%%%02X", string.byte(c))
end)
str = str:gsub(" ", "%%20")
end
return str
end
local function cookie_encode(str, name)
str = str:gsub("[,;%s]", "")
if (name) then
str = str:gsub("=", "")
end
return str
end
local auth_map = {
BASIC = ffi.cast("long", curl.CURLAUTH_BASIC),
DIGEST = ffi.cast("long", curl.CURLAUTH_DIGEST),
NEGOTIATE = ffi.cast("long", curl.CURLAUTH_NEGOTIATE)
}
request = {
error = {
unknown = 0,
timeout = 1
},
version = "2.2.0",
version_major = 2,
version_minor = 2,
version_patch = 0,
--[[
Send an HTTP(S) request to the URL at 'url' using the HTTP method 'method'.
Use the 'args' parameter to optionally configure the request:
- method: HTTP method to use. Defaults to "GET", but can be any HTTP verb like "POST" or "PUT"
- headers: Dictionary of additional HTTP headers to send with request
- data: Dictionary or string to send as request body
- cookies: Dictionary table of cookies to send
- timeout: How long to wait for the connection to be made before giving up
- allow_redirects: Whether or not to allow redirection. Defaults to true
- body_stream_callback: A method to call with each piece of the response body.
- header_stream_callback: A method to call with each piece of the resulting header.
- transfer_info_callback: A method to call with transfer progress data.
- auth_type: Authentication method to use. Defaults to "none", but can also be "basic", "digest" or "negotiate"
- username: A username to use with authentication. 'auth_type' must also be specified.
- password: A password to use with authentication. 'auth_type' must also be specified.
If both body_stream_callback and header_stream_callback are defined, a boolean true will be returned instead of the following object.
The return object is a dictionary with the following members:
- code: The HTTP status code the response gave. Will not exist if header_stream_callback is defined above.
- body: The body of the response. Will not exist if body_stream_callback is defined above.
- headers: A dictionary of headers and their values. Will not exist if header_stream_callback is defined above.
- headers_raw: A raw string containing the actual headers the server sent back. Will not exist if header_stream_callback is defined above.
- set_cookies: A dictionary of cookies given by the "Set-Cookie" header from the server. Will not exist if the server did not set any cookies.
]]
send = function(url, args)
local handle = curl.curl_easy_init()
local header_chunk
local out_buffer
local headers_buffer
args = args or {}
curl.curl_easy_setopt(handle, curl.CURLOPT_URL, url)
curl.curl_easy_setopt(handle, curl.CURLOPT_SSL_VERIFYPEER, 1)
curl.curl_easy_setopt(handle, curl.CURLOPT_SSL_VERIFYHOST, 2)
if (args.method) then
local method = string.upper(tostring(args.method))
if (method == "GET") then
curl.curl_easy_setopt(handle, curl.CURLOPT_HTTPGET, 1)
elseif (method == "POST") then
curl.curl_easy_setopt(handle, curl.CURLOPT_POST, 1)
else
curl.curl_easy_setopt(handle, curl.CURLOPT_CUSTOMREQUEST, method)
end
end
if (args.headers) then
for key, value in pairs(args.headers) do
header_chunk = curl.curl_slist_append(header_chunk, tostring(key) .. ":" .. tostring(value))
end
curl.curl_easy_setopt(handle, curl.CURLOPT_HTTPHEADER, header_chunk)
end
if (args.auth_type) then
local auth = string.upper(tostring(args.auth_type))
if (auth_map[auth]) then
curl.curl_easy_setopt(handle, curl.CURLOPT_HTTPAUTH, auth_map[auth])
curl.curl_easy_setopt(handle, curl.CURLOPT_USERNAME, tostring(args.username))
curl.curl_easy_setopt(handle, curl.CURLOPT_PASSWORD, tostring(args.password or ""))
elseif (auth ~= "NONE") then
error("Unsupported authentication type '" .. auth .. "'")
end
end
if (args.body_stream_callback) then
curl.curl_easy_setopt(handle, curl.CURLOPT_WRITEFUNCTION, ffi.cast("curl_callback", function(data, size, nmeb, user)
args.body_stream_callback(ffi.string(data, size * nmeb))
return size * nmeb
end))
else
out_buffer = {}
curl.curl_easy_setopt(handle, curl.CURLOPT_WRITEFUNCTION, ffi.cast("curl_callback", function(data, size, nmeb, user)
table.insert(out_buffer, ffi.string(data, size * nmeb))
return size * nmeb
end))
end
if (args.header_stream_callback) then
curl.curl_easy_setopt(handle, curl.CURLOPT_HEADERFUNCTION, ffi.cast("curl_callback", function(data, size, nmeb, user)
args.header_stream_callback(ffi.string(data, size * nmeb))
return size * nmeb
end))
else
headers_buffer = {}
curl.curl_easy_setopt(handle, curl.CURLOPT_HEADERFUNCTION, ffi.cast("curl_callback", function(data, size, nmeb, user)
table.insert(headers_buffer, ffi.string(data, size * nmeb))
return size * nmeb
end))
end
if (args.transfer_info_callback) then
curl.curl_easy_setopt(handle, curl.CURLOPT_NOPROGRESS, 0)
curl.curl_easy_setopt(handle, curl.CURLOPT_XFERINFOFUNCTION, ffi.cast("curl_xferinfo_callback", function(client, dltotal, dlnow, ultotal, ulnow)
args.transfer_info_callback(tonumber(dltotal), tonumber(dlnow), tonumber(ultotal), tonumber(ulnow))
return 0
end))
end
if (args.follow_redirects == nil) then
curl.curl_easy_setopt(handle, curl.CURLOPT_FOLLOWLOCATION, true)
else
curl.curl_easy_setopt(handle, curl.CURLOPT_FOLLOWLOCATION, not not args.follow_redirects)
end
if (args.data) then
if (type(args.data) == "table") then
local buffer = {}
for key, value in pairs(args.data) do
table.insert(buffer, ("%s=%s"):format(url_encode(key), url_encode(value)))
end
curl.curl_easy_setopt(handle, curl.CURLOPT_POSTFIELDS, table.concat(buffer, "&"))
else
curl.curl_easy_setopt(handle, curl.CURLOPT_POSTFIELDS, tostring(args.data))
end
end
if (args.cookies) then
local cookie_out
if (type(args.cookies) == "table") then
local buffer = {}
for key, value in pairs(args.cookies) do
table.insert(buffer, ("%s=%s"):format(cookie_encode(key, true), cookie_encode(value)))
end
cookie_out = table.concat(buffer, "; ")
else
cookie_out = tostring(args.cookies)
end
curl.curl_easy_setopt(handle, curl.CURLOPT_COOKIE, cookie_out)
end
if (tonumber(args.timeout)) then
curl.curl_easy_setopt(handle, curl.CURLOPT_CONNECTTIMEOUT, tonumber(args.timeout))
end
local result = curl.curl_easy_perform(handle)
curl.curl_easy_cleanup(handle)
curl.curl_slist_free_all(header_chunk)
if (result == curl.CURLE_OK) then
if (out_buffer or headers_buffer) then
local headers, status, parsed_headers, set_cookies
if (headers_buffer) then
headers = table.concat(headers_buffer)
status = headers:match("%s+(%d+)%s+")
parsed_headers = {}
for key, value in headers:gmatch("\n([^:]+):%s*([^\r\n]*)") do
parsed_headers[key] = value
end
if (parsed_headers["Set-Cookie"]) then
set_cookies = {}
-- Get unquoted cookie values
for key, value in parsed_headers["Set-Cookie"]:gmatch("%s*([^=]+)=([^;]*)") do
set_cookies[key] = value
end
-- Get quoted cookie values
for key, value in parsed_headers["Set-Cookie"]:gmatch("%s*([^=]+)=(%b\"\")") do
set_cookies[key] = value:sub(2, -2)
end
end
end
return {
body = table.concat(out_buffer),
headers = parsed_headers,
set_cookies = set_cookies,
code = status,
raw_headers = headers
}
else
return true
end
elseif (result == curl.CURLE_OPERATION_TIMEDOUT) then
return false, request.error.timeout, "Connection timed out"
else
return false, request.error.unknown, "Unknown error"
end
end,
init = function()
curl.curl_global_init(curl.CURL_GLOBAL_ALL)
end,
close = function()
curl.curl_global_cleanup()
end
}
request.init()
return request | mit |
xing634325131/Luci-0.11.1 | libs/sgi-luci/luasrc/ttpd/handler/luci.lua | 53 | 1923 | --[[
HTTP server implementation for LuCI - luci handler
(c) 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local dsp = require "luci.dispatcher"
local util = require "luci.util"
local http = require "luci.http"
local ltn12 = require "luci.ltn12"
local mod = require "luci.ttpd.module"
local table = require "table"
local coroutine = require "coroutine"
module "luci.ttpd.handler.luci"
Luci = util.class(mod.Handler)
Response = mod.Response
function Luci.__init__(self, limit)
mod.Handler.__init__(self)
end
function Luci.handle_head(self, ...)
return (self:handle_get(...))
end
function Luci.handle_post(self, ...)
return self:handle_get(...)
end
function Luci.handle_get(self, request, sourcein, sinkerr)
local r = http.Request(
request.env,
sourcein,
sinkerr
)
local res, id, data1, data2 = true, 0, nil, nil
local headers = {}
local status = 200
local active = true
local x = coroutine.create(dsp.httpdispatch)
while not id or id < 3 do
res, id, data1, data2 = coroutine.resume(x, r)
if not res then
status = 500
headers["Content-Type"] = "text/plain"
local err = {id}
return Response( status, headers ), function() return table.remove(err) end
end
if id == 1 then
status = data1
elseif id == 2 then
headers[data1] = data2
end
end
local function iter()
local res, id, data = coroutine.resume(x)
if not res then
return nil, id
elseif not id or not active then
return true
elseif id == 5 then
active = false
while (coroutine.resume(x)) do
end
return nil
elseif id == 4 then
return data
end
if coroutine.status(x) == "dead" then
return nil
end
end
return Response(status, headers), iter
end
| apache-2.0 |
payday-restoration/restoration-mod | lua/sc/units/player/playertased.lua | 1 | 6541 | function PlayerTased:enter(state_data, enter_data)
PlayerTased.super.enter(self, state_data, enter_data)
self._ids_tased_boost = Idstring("tased_boost")
self._ids_tased = Idstring("tased")
self._ids_counter_tase = Idstring("tazer_counter")
self:_start_action_tased(managers.player:player_timer():time(), state_data.non_lethal_electrocution)
if state_data.non_lethal_electrocution then
state_data.non_lethal_electrocution = nil
local recover_time = Application:time() + tweak_data.player.damage.STUN_TIME * managers.player:upgrade_value("player", "electrocution_resistance_multiplier", 1)
self._recover_delayed_clbk = "PlayerTased_recover_delayed_clbk"
managers.enemy:add_delayed_clbk(self._recover_delayed_clbk, callback(self, self, "clbk_exit_to_std"), recover_time)
else
self._fatal_delayed_clbk = "PlayerTased_fatal_delayed_clbk"
local tased_time = tweak_data.player.damage.TASED_TIME
--Taser Overcharge changed to allow for taser aim delays to be changed.
managers.enemy:add_delayed_clbk(self._fatal_delayed_clbk, callback(self, self, "clbk_exit_to_fatal"), TimerManager:game():time() + tased_time)
end
self._next_shock = 0.5
self._taser_value = 1
self._num_shocks = 0
managers.groupai:state():on_criminal_disabled(self._unit, "electrified")
if Network:is_server() then
self:_register_revive_SO()
end
--Removed free reload from being tased.
local projectile_entry = managers.blackmarket:equipped_projectile()
if tweak_data.blackmarket.projectiles[projectile_entry].is_a_grenade then
self:_interupt_action_throw_grenade()
else
self:_interupt_action_throw_projectile()
end
self:_interupt_action_reload()
self:_interupt_action_steelsight()
self:_interupt_action_melee(managers.player:player_timer():time())
self:_interupt_action_ladder(managers.player:player_timer():time())
self:_interupt_action_charging_weapon(managers.player:player_timer():time())
self._rumble_electrified = managers.rumble:play("electrified")
self.tased = true
self._state_data = state_data
CopDamage.register_listener("on_criminal_tased", {
"on_criminal_tased"
}, callback(self, self, "_on_tased_event"))
end
function PlayerTased:_on_tased_event(taser_unit, tased_unit)
if self._unit == tased_unit then
self._taser_unit = taser_unit
if managers.player:has_category_upgrade("player", "taser_malfunction") then
local data = managers.player:upgrade_value("player", "taser_malfunction")
if data then
managers.player:register_message(Message.SendTaserMalfunction, "taser_malfunction", function ()
self:_on_malfunction_to_taser_event()
end)
managers.player:add_coroutine("taser_malfunction", PlayerAction.TaserMalfunction, managers.player, data.interval, data.chance_to_trigger)
end
end
if managers.player:has_category_upgrade("player", "escape_taser") then
local interact_string = managers.localization:text("hud_int_escape_taser", {
BTN_INTERACT = managers.localization:btn_macro("interact", false)
})
managers.hud:show_interact({
icon = "mugshot_electrified",
text = interact_string
})
local target_time = managers.player:upgrade_value("player", "escape_taser", 2)
managers.player:add_coroutine("escape_tase", PlayerAction.EscapeTase, managers.player, managers.hud, Application:time() + target_time)
--Instead directly call give_shock_to_taser().
managers.player:register_message(Message.EscapeTase, "escape_tase", self:give_shock_to_taser())
end
end
end
--Prevent tasers from putting players at downed health, and instead deal flat health damage.
Hooks:PostHook(PlayerTased, "clbk_exit_to_fatal", "ResTaseNoHealthChange", function(self)
self._unit:character_damage():cloak_or_shock_incap(tweak_data.character.taser.shock_damage)
end)
--Adds animation to shockproof ace.
function PlayerTased:call_teammate(line, t, no_gesture, skip_alert)
local voice_type, plural, prime_target = self:_get_unit_intimidation_action(true, false, false, true, false)
local interact_type, queue_name = nil
if voice_type == "stop_cop" or voice_type == "mark_cop" then
local prime_target_tweak = tweak_data.character[prime_target.unit:base()._tweak_table]
local shout_sound = prime_target_tweak.priority_shout
if managers.groupai:state():whisper_mode() then
shout_sound = prime_target_tweak.silent_priority_shout or shout_sound
end
if shout_sound then
interact_type = "cmd_point"
queue_name = "s07x_sin"
if managers.player:has_category_upgrade("player", "special_enemy_highlight") then
prime_target.unit:contour():add(managers.player:get_contour_for_marked_enemy(), true, managers.player:upgrade_value("player", "mark_enemy_time_multiplier", 1))
end
--Play Shockproof Aced Animation
if prime_target.unit:base()._tweak_table == "taser" then
if not self._tase_ended and managers.player:has_category_upgrade("player", "escape_taser") and prime_target.unit:key() == self._unit:character_damage():tase_data().attacker_unit:key() then
self:_start_action_counter_tase(t, prime_target)
end
end
end
end
if interact_type then
self:_do_action_intimidate(t, not no_gesture and interact_type or nil, queue_name, skip_alert)
end
end
function PlayerTased:give_shock_to_taser()
if not alive(self._counter_taser_unit) then
return
end
--Remove return, since we now damage Tasers with Shockproof Ace.
self:_give_shock_to_taser(self._counter_taser_unit)
end
function PlayerTased:_give_shock_to_taser(taser_unit)
--Remove return, since we now damage Tasers with Shockproof Ace.
local action_data = {
variant = "counter_tased",
damage = taser_unit:character_damage()._HEALTH_INIT * (tweak_data.upgrades.counter_taser_damage or 0.2),
damage_effect = taser_unit:character_damage()._HEALTH_INIT * 2,
attacker_unit = self._unit,
attack_dir = -taser_unit:movement()._action_common_data.fwd,
col_ray = {
position = mvector3.copy(taser_unit:movement():m_head_pos()),
body = taser_unit:body("body")
}
}
taser_unit:character_damage():damage_melee(action_data)
self._unit:sound():play("tase_counter_attack") --Add sound
end
function PlayerTased:update(t, dt)
if self._equipped_unit then
local weap_base = self._equipped_unit:base()
local fire_mode = weap_base:fire_mode()
if fire_mode == "volley" then
self:_check_action_weapon_firemode(t, { btn_weapon_firemode_press = true }) --volley currently just DUMPS your ammo anf bypasses refire delays, so force firemode switch to not dump ammo as fast
end
end
PlayerTased.super.update(self, t, dt)
end | agpl-3.0 |
simbiose/escambo | escambo.lua | 1 | 16504 | --
-- Escambo, an HTTP content negotiator, content-type parser and creator for Lua
--
-- @author leite (xico@simbio.se)
-- @license MIT
-- @copyright Simbiose 2015
local string, table, tbx, class =
require [[string]], require [[table]], require [[pl.tablex]], require [[30log]]
local Escambo, find, sub, gmatch, format, len, lower, gsub, match, concat, insert, remove, t_sort,
tonumber, type =
class(), string.find, string.sub, string.gmatch, string.format, string.len, string.lower,
string.gsub, string.match, table.concat, table.insert, table.remove, tbx.sort, tonumber, type
local EMPTY, STAR, COMA, EQUAL, SSS, Q, SLASH, DASH, CONCAT_PARAMS, MIME_PATTERN, LANGUAGE_PATTERN,
CHARSET_PATTERN, PARAM, QUOTE_ESCAPE, QUOTED_PARAM, SUBTYPE_NAME, TYPE_NAME, TYPE, TYPE_SPACE,
TOKEN, TEXT, QUOTE =
'', '*', ',', '=', '*/*', 'q', '/', '-', '%s;%s=%s', '%s*([^/=]+)([/=])([^;,%s]*)[;,]?%s*',
'%s*([^%s-=;,]+)%s*([-=,]?)%s*([^%s;,]*)%s*', '%s*([^%s=;,]+)%s*([=,]?)%s*([^%s;,]*)%s*',
";%s*([%w!#%$%%&'%*%+%-%.%^_`|~]+)%s*=%s*([%w!#%$%%&'%*%+%-%.%^_`|~]+)%s*;", '\\([%z\1-\127])',
';%s*([%w!#%$%%&\'%*%+%-%.%^_`|~]+)%s*=?%s*"(.-[^\\])";?', '^[%w][%w!#%$&%^_%.%+%-]+$',
'^[%w][%w!#%$&%^_%-]+$', '^([%w][%w!#%$&%^_%-]+)/([%w][%w!#%$&%^_%.%+%-]+)$',
'^%s*([%w][%w!#%$&%^_%-]+)/([%w][%w!#%$&%^_%.%+%-]+)%s*;', '^[%w!#%$%%&\'%*%+%-%.%^_`|~]+$',
'^[\32-\126\128-\255]+$', '(["])'
Escambo.__name, string, table, tbx, class = 'Escambo', nil, nil, nil, nil
-- order array with insertation sort and exclude nodes with quality below or equals zero
--
-- @table list
-- @string join
-- @return ordered table
local function order_array(list, join)
local i, result, key = 0, {}
if list[1] and list[1][2] > 0 then
result[1] = (not list[1][3] or list[1][3] == EMPTY) and list[1][1] or
concat{list[1][1], join, list[1][3], list[1][4] or ''}
end
for j = 2, #list do
if list[j][2] <= 0 then
j = j - 1
goto followup
end
key, i = list[j], j - 1
while i > 0 and list[i][2] < key[2] do
list[i + 1] = list[i]
if list[i][2] > 0 then
result[i + 1] = (not list[i][3] or list[i][3] == EMPTY) and list[i][1] or
concat{list[i][1], join, list[i][3], list[i][4] or ''}
end
i = i - 1
end
i = i + 1
list[i] = key
result[i] = (not key[3] or key[3] == EMPTY) and key[1] or
concat{key[1], join, key[3], key[4] or ''}
::followup::
end
return result
end
-- index multidimensional table
--
-- @table index
-- @string prefix
-- @string suffix
-- @string params
-- @number value
local function index_it(index, prefix, suffix, params, value)
if index[prefix] then
if not index[ prefix ][ suffix ] then
index[ prefix ][ suffix ] = {[ params ] = value}
else
index[ prefix ][ suffix ][ params ] = value
end
else
index[ prefix ] = {[ suffix ] = {[ params ] = value}}
end
end
-- get "response"/"request" object content type value
--
-- @table object
-- @return string
local function get_content_type(object)
if not object then
return nil
end
return (object.get_header and object.get_header('content-type')) or
(object.headers and object.headers['content-type']) or nil
end
-- escape quotes and quote string
--
-- @string string
-- @return string
local function quote(string)
if find(string, TOKEN) then
return true, string
end
if len(string) > 0 and not find(string, TEXT) then
return false, 'invalid parameter value'
end
return true, concat {'"', gsub(string, QUOTE, '\\%1'), '"'}
end
-- helps language and mimetype methods to parse accept string in a loop
--
-- @string prefix
-- @string suffix
-- @table selected
-- @table provide
-- @table index
-- @table opts
-- @table last
-- @boolean[opt] language
local function language_parser_helper(prefix, suffix, selected, provide, index, opts, last, language)
if last then
local provide_index = (opts.provided and provide[last[1]] and provide[last[1]][last[3]] and
(language or provide[last[1]][last[3]][last[4]]))
if language and opts.provided then
index_it(index, last[1], STAR, last[4], last[2])
opts.suffix_star = true
end
if not opts.provided or (last[1] == STAR or last[3] == STAR) or provide_index then
if provide_index and not language then
last[4] = provide[ provide[last[1]][last[3]][last[4]] ][3]
end
index_it(index, last[1], last[3], last[4], last[2])
if last[1] == STAR or last[3] == STAR then
opts.starred = last[1] == STAR or opts.starred
opts.suffix_star = last[3] == STAR or opts.suffix_star
else
insert(selected, last)
end
end
last = nil
end
if EMPTY == prefix then return end
opts.last = {prefix, 1, suffix, EMPTY}
end
-- parse provided media
--
-- @param input
-- @table result
-- @return boolean
local function parse_media(input, result)
local acx = {}
for i=1, #input do
for a, b, c in gmatch(input[i] or SSS, MIME_PATTERN) do
if SLASH == b then
insert(result, acx)
acx = {a, c, EMPTY}
if result[a] then
if not result[a][c] then result[a][c] = {} end
else
result[a] = {[c] = {}}
end
else
if acx[3] ~= EMPTY then
result[acx[1]][acx[2]][acx[3]] = i
end
acx[3] = format(CONCAT_PARAMS, acx[3], a, c)
end
end
result[acx[1]][acx[2]][acx[3]] = i
insert(result[acx[1]][acx[2]], acx[3])
end
if #acx > 0 then
remove(result, 1)
insert(result, acx)
end
return #result > 0
end
-- helps charset and encoding methods to parse accept string in a loop
--
-- @string value
-- @table selected
-- @table provide
-- @table index
-- @table opts
local function charset_parser_helper(value, selected, provide, index, opts)
if STAR == value then
opts.starred, opts.quality = true, 0
else
if not opts.provided or (opts.provided and provide[value]) then
opts.last = {value, 1}
insert(selected, opts.last)
else
opts.last = nil
end
end
index[value] = true
end
-- parse accept charset and encoding
--
-- @string accept
-- @table[opt] provided
-- @boolean[opt] is_encoding
-- @return table with sanitized, filtered and ordered charset(s) or encoding(s)
local function parse_charset(accept, provided, is_encoding)
local opts, selected, provide, index =
{provided=false, starred=false, last=nil}, {}, {}, {}
provided, accept = provided or {}, accept or (is_encoding and EMPTY or STAR)
for i=1, #provided do
provide[provided[i]], opts.provided = true, true
end
if is_encoding and (EMPTY == accept and not provide.identity) then
provide.identity, opts.provided = true, true
end
for key, sep, val in gmatch(accept, CHARSET_PATTERN) do
if COMA == sep then
charset_parser_helper(key, selected, provide, index, opts)
charset_parser_helper(val, selected, provide, index, opts)
elseif EQUAL == sep and Q == key then
if not opts.last then
opts.quality = tonumber(val)
else
opts.last[2] = tonumber(val)
if opts.last[2] == 0 then
if opts.provided then provide[opts.last[1]] = nil end
remove(selected, #selected)
end
end
else
charset_parser_helper(key, selected, provide, index, opts)
end
end
if opts.provided and opts.starred then
local x, k = opts.quality and (opts.quality + 0.01) or 0.01, ''
for i = 1, #provided do
k = provided[i]
if provide[k] and not index[k] then
x = x - 0.001
index[k] = true
insert(selected, {k, x})
end
end
end
if is_encoding and ((provide.identity and (not index.identity or not opts.provided)) or
(not opts.provided and not index.identity and (not opts.quality or opts.quality > 0))) then
insert(selected, {'identity', 0.0001})
end
return order_array(selected, DASH)
end
-- parse language(s)
--
-- @table[opt] provided
-- @string[opt] accept
-- @return table with sanitized, filtered and ordered language(s)
function Escambo:languages(provided, accept)
local opts, selected, provide, index, bar =
{provided=false, starred=false, last=nil}, {}, {}, {}, nil
provided, accept = provided or {}, accept or STAR
for i=1, #provided do
bar = find(provided[i], DASH, 0, false)
provide[i] =
bar and {sub(provided[i], 1, bar-1), sub(provided[i], bar+1)} or {provided[i], EMPTY}
if provide[provide[i][1]] then
provide[provide[i][1]][provide[i][2]] = i
else
provide[provide[i][1]] = {[provide[i][2]] = i}
end
opts.provided = true
end
for key, sep, val in gmatch(accept, LANGUAGE_PATTERN) do
if COMA == sep then
language_parser_helper(key, EMPTY, selected, provide, index, opts, opts.last, true)
language_parser_helper(val, EMPTY, selected, provide, index, opts, opts.last, true)
elseif DASH == sep then
language_parser_helper(key, val, selected, provide, index, opts, opts.last, true)
elseif EQUAL == sep and Q == key and opts.last then
opts.last[2] = tonumber(val)
if opts.last[2] == 0 then
if opts.provided then
provide[provide[opts.last[1]][opts.last[3]]] = false
provide[opts.last[1]][opts.last[3]] = nil
end
end
else
language_parser_helper(key, EMPTY, selected, provide, index, opts, opts.last, true)
end
end
language_parser_helper(EMPTY, EMPTY, selected, provide, index, opts, opts.last, true)
if opts.provided then
local x = 0.01
for i=1, #provide do
x = x - 0.001
if provide[i] then
if opts.starred and not index[provide[i][1]] then
index[provide[i][1]] = {[provide[i][2]] = true}
insert(selected, {provide[i][1], x, provide[i][2]})
elseif index[provide[i][1]] and not index[provide[i][1]][provide[i][2]] then
index[provide[i][1]][provide[i][2]] = true
insert(selected, {provide[i][1], x, provide[i][2]})
end
end
end
end
return order_array(selected, DASH)
end
-- parse mimetype
--
-- @table[opt] provided
-- @string[opt] accept
-- @return table with sanitized, filtered and ordered mimetype(s)
function Escambo:media_types(provided, accept)
local opts, selected, provide, index =
{provided=false, starred=false, suffix_star=false, last=nil}, {}, {}, {}
provided, accept = provided or {}, (self.accept or accept or SSS)
opts.provided = parse_media(provided, provide)
for key, sep, val in gmatch(accept, MIME_PATTERN) do
if SLASH == sep then
language_parser_helper(key, val, selected, provide, index, opts, opts.last)
elseif EQUAL == sep and opts.last then
if Q == key then
opts.last[2] = tonumber(val)
else
opts.last[4] = format(CONCAT_PARAMS, opts.last[4], key, val)
end
end
end
language_parser_helper(EMPTY, EMPTY, selected, provide, index, opts, opts.last)
if opts.provided and (#selected > 0 or opts.starred or opts.suffix_star) then
local already, x, prefix, suffix, params, nindex = false, 0.001, '', '', '', nil
for i=1, #provide do
if provide[i] then
x, prefix, suffix, params = (x - 0.0001), provide[i][1], provide[i][2], provide[i][3]
already = (index[prefix] and index[prefix][suffix] and index[prefix][suffix][params])
if not already then
if opts.starred and index[STAR][suffix] then
nindex = (index[STAR][suffix][EMPTY] or index[STAR][suffix][params])
elseif opts.suffix_star and index[prefix] and index[prefix][STAR] then
nindex = (index[prefix][STAR][EMPTY] or index[prefix][STAR][params])
elseif opts.suffix_star and opts.starred then
nindex = (index[STAR][STAR][EMPTY] or index[STAR][STAR][params])
end
end
if nindex and not already then
insert(selected, {prefix, nindex and (nindex - x) or x, suffix, params})
index_it(index, prefix, suffix, params, #selected)
nindex = nil
end
end
end
end
return order_array(selected, SLASH)
end
-- initialize "metaclass"
--
-- @string accept
function Escambo:__init(accept)
self.accept = accept
end
-- parse content-type string
--
-- @string string
-- @boolean[opt] expand
-- @return boolean, string|table
function Escambo.parse(string, expand)
if not string then
return false, 'argument string is required'
end
if 'table' == type(string) then
string = get_content_type(string)
end
if 'string' ~= type(string) then
return false, 'argument string is required to be a string'
end
local opts, string, lenght, start, index = {parameters={}}, string .. ';', len(string), 0, 0
start, index, opts.type, opts.subtype = find(string, TYPE_SPACE)
if not opts.type then
return false, 'invalid media type'
end
if expand then
opts.subtype, opts.suffix = match(lower(opts.subtype), '^([^%+$]+)%+?([^$]*)$')
opts.type, opts.suffix = lower(opts.type), opts.suffix ~= '' and opts.suffix or nil
else
opts.type = lower(format('%s/%s', opts.type, opts.subtype))
opts.subtype = nil
end
if (lenght - index) > 3 then
local key, val, last = '', '', index
while start do
start, index, key, val = find(string, QUOTED_PARAM, last)
if not start then
start, index, key, val = find(string, PARAM, last)
else
val = gsub(val, QUOTE_ESCAPE, '%1')
end
if not start or (start - last) > 3 then
break
end
opts.parameters[lower(key)], last = val, index
end
if last < 2 or (last and (lenght - last) > 3) or (start and (start - last) > 3) then
return false, 'invalid parameter format'
end
else
opts.parameters = nil
end
return true, opts
end
-- format content-type "object"
--
-- @table opts
-- @return boolean, string
function Escambo.format(opts)
if not opts then
return false, 'argument is required'
end
if not opts.type then
return false, 'invalid type'
end
local string, _ = '', false
if find(opts.type, '/', 1, true) then
if not find(opts.type, TYPE) then
return false, 'invalid type'
end
string = opts.type
else
if not find(opts.type, TYPE_NAME) then
return false, 'invalid type'
end
if not opts.subtype or not find(opts.subtype, SUBTYPE_NAME) then
return false, 'invalid subtype'
end
string = format('%s/%s', opts.type, opts.subtype)
end
if opts.suffix then
if not find(opts.suffix, TYPE_NAME) then
return false, 'invalid suffix'
end
string = format('%s+%s', string, opts.suffix)
end
if not opts.parameters then
return true, string
end
for key, val in t_sort(opts.parameters) do
if not find(key, TOKEN) then
return false, 'invalid parameter name'
end
_, val = quote(val)
if not _ then
return _, val
end
string = format('%s; %s=%s', string, key, val)
end
return true, string
end
-- get single charset
--
-- @param available
-- @string[opt] accept
-- @return string
function Escambo:charset(available, accept)
local set = parse_charset(accept or self.accept, available)
return #set > 0 and set[1]
end
-- get list of charset(s)
--
-- @param available
-- @string[opt] accept
-- @return table
function Escambo:charsets(available, accept)
return parse_charset(accept or self.accept, available)
end
-- get single encoding
--
-- @param[opt] available
-- @string[opt] accept
-- @return string
function Escambo:encoding(available, accept)
local set = parse_charset(accept or self.accept, available, true)
return #set > 0 and set[1]
end
-- get list of encoding(s)
--
-- @param[opt] available
-- @string[opt] accept
-- @return table
function Escambo:encodings(available, accept)
return parse_charset(accept or self.accept, available, true)
end
-- get single language
--
-- @param[opt] available
-- @string[opt] accept
-- @return string
function Escambo:language(available, accept)
local set = self:languages(accept or self.accept, available)
return #set > 0 and set[1]
end
-- get single media type
--
-- @param[opt] available
-- @string[opt] accept
-- @return string
function Escambo:media_type(available, accept)
local set = self:media_types(accept or self.accept, available)
return #set > 0 and set[1]
end
return Escambo | mit |
T3hArco/skeyler-gamemodes | Sassilization/gamemode/modules/empire/shared.lua | 1 | 11683 | ----------------------------------------
-- Sassilization
-- http://sassilization.com
-- By Sassafrass / Spacetech / LuaPineapple
----------------------------------------
AccessorFunc( GM.PlayerMeta, "empire", "Empire" )
local AccessorFunc = AccessorFunc
local building = building
local FORCE_NUMBER = FORCE_NUMBER
local CLIENT = CLIENT
local usermessage = usermessage
local net = net
local tostring = tostring
local assert = assert
local Msg = Msg
local MsgN = MsgN
local print = print
local PrintTable = PrintTable
local ErrorNoHalt = ErrorNoHalt
local tonumber = tonumber
local IsValid = IsValid
local SERVER = SERVER
local umsg = umsg
local net = net
local util = util
local table = table
local pairs = pairs
local IsValid = IsValid
local Color = Color
local building
local SA = SA
local setmetatable = setmetatable
local building = _G.building
local debug = debug
local math = math
function ValidEmpire( Empire )
if( Empire and Empire:IsValid() ) then
return true
end
end
module( "sh_empire" )
mt = {}
methods = {}
mt.__index = methods
mt.__tostring = function(self) return "Empire [" .. self:GetID() .. "][" .. self:GetName() .. "]" end
EMPIRES = {}
EMPIRE_IDS = {}
AccessorFunc( methods, "i_ID", "ID", FORCE_NUMBER )
AccessorFunc( methods, "player", "Player" )
VARTYPE_STRING = "String"
VARTYPE_SHORT = "Short"
VARTYPE_LONG = "Long"
VARTYPE_BOOL = "Bool"
VARTYPE_CHAR = "Byte"
methods.NWVars = {}
local function ProfileAccessorFuncNW( tab, varname, name, varDefault, vartype, bPrivate )
if(not tab.NWVars) then return end
tab[ "Get"..name ] = function ( self, default )
return self[ varname ] or default or varDefault
end
--Add to NWVars table for loading newcomers
tab.NWVars[ name ] = vartype
if(CLIENT) then
net.Receive( "empire.NW"..vartype.."_"..name, function( len )
-- UByte
local id = net.ReadUInt( 8 )
local emp = EMPIRES[id]
if(not emp) then return end
emp[ "Set"..name ]( emp, net[ "Read"..vartype ]() )
end )
end
if (SERVER) then util.AddNetworkString( "empire.NW"..vartype.."_"..name ) end
if ( vartype == VARTYPE_STRING ) then
tab[ "Set"..name ] = function ( self, v )
self[varname] = tostring(v)
if (SERVER) then
net.Start( "empire.NW" .. vartype .. "_" .. name )
-- UByte
net.WriteUInt( self:GetID(), 8 )
net[ "Write"..vartype ]( v )
rf = ((bPrivate and IsValid(self:GetPlayer())) and self:GetPlayer() or nil)
if rf then net.Send( rf ) else net.Broadcast() end
end
end
return end
if ( vartype == VARTYPE_SHORT ) then
tab[ "Set"..name ] = function ( self, v )
self[varname] = tonumber(v)
if(SERVER) then
net.Start( "empire.NW"..vartype.."_"..name )
-- UByte
net.WriteUInt( self:GetID(), 8 )
net[ "Write"..vartype ]( v )
rf = ((bPrivate and IsValid(self:GetPlayer())) and self:GetPlayer() or nil)
if rf then net.Send( rf ) else net.Broadcast() end
end
end
return end
if ( vartype == VARTYPE_LONG ) then
tab[ "Set"..name ] = function ( self, v )
self[varname] = tonumber(v)
if(SERVER) then
net.Start( "empire.NW"..vartype.."_"..name )
net.WriteUInt( self:GetID(), 8 )
net[ "Write"..vartype ]( v )
rf = ((bPrivate and IsValid(self:GetPlayer())) and self:GetPlayer() or nil)
if rf then net.Send( rf ) else net.Broadcast() end
end
end
return end
end
local PRIVATE = true
local PUBLIC = false
ProfileAccessorFuncNW(methods, "name", "Name", "Sass Empire", VARTYPE_STRING)
ProfileAccessorFuncNW(methods, "res_food", "Food", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "res_iron", "Iron", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "res_gold", "Gold", 0, VARTYPE_SHORT, PUBLIC)
ProfileAccessorFuncNW(methods, "res_creed", "Creed", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "res_supply", "Supply", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "res_supplied", "Supplied", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "cities", "Cities", 0, VARTYPE_SHORT, PUBLIC)
ProfileAccessorFuncNW(methods, "shrines", "Shrines", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "houses", "Houses", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "mines", "Mines", 0, VARTYPE_SHORT, PRIVATE)
ProfileAccessorFuncNW(methods, "farms", "Farms", 0, VARTYPE_SHORT, PRIVATE)
if (SERVER) then
AccessorFunc(methods, "shields", "Shields", FORCE_NUMBER)
end
local function AccessorIncrDecrFunc( tab, varName, funcName )
tab[ "Incr"..varName ] = function( self )
tab[ "Set"..funcName ]( self, self[ "Get"..funcName ](self) + 1 )
end
tab[ "Decr"..varName ] = function( self )
tab[ "Set"..funcName ]( self, self[ "Get"..funcName ](self) - 1 )
end
end
AccessorIncrDecrFunc( methods, "Mine", "Mines" )
AccessorIncrDecrFunc( methods, "Farm", "Farms" )
AccessorIncrDecrFunc( methods, "City", "Cities" )
AccessorIncrDecrFunc( methods, "House", "Houses" )
AccessorIncrDecrFunc( methods, "Shrine", "Shrines" )
if (SERVER) then
AccessorIncrDecrFunc(methods, "Shields", "Shields")
end
function GetAll()
return EMPIRES
end
function GetByID( nid )
if( not nid ) then return end
for id, empire in pairs( GetAll() ) do
if (id == nid) then
return empire
end
end
end
function GetBySteamID( sid )
if( not sid ) then return end
return GetByID( EMPIRE_IDS[ sid ] )
end
function GetColorByID( cid )
assert( cid )
--Msg( "Color ID ", cid, "\n" )
local c = ColorTable[ cid ]
assert( c )
return c
end
function GetBuildings()
local buildings = {}
for id, empire in pairs( GetAll() ) do
for _, bldg in pairs( empire:GetBuildings() ) do
if( IsValid( bldg ) ) then
table.insert( buildings, bldg )
else
empire:GetBuildings()[ _ ] = nil
end
end
end
return buildings
end
function GetUnits()
local units = {}
for id, emp in pairs( GetAll() ) do
for uid, unit in pairs( emp:GetUnits() ) do
table.insert( units, unit)
end
end
return units
end
function methods:GetGoldIncome()
if( self:GetCities() > 0 ) then
return self:GetCities()
elseif( self:GetGold() < building.GetBuildingKey( "city", "Gold" ) ) then
//Was previously 1, was changed to 7 to make recovering from a loss of all cities actually possible.
return 7
else
return 0
end
end
function methods:GetFoodIncome()
return math.ceil(SA.DEFAULT_INCOME_FOOD + self:GetFarms() *1.2)
end
function methods:GetIronIncome()
return math.ceil(SA.DEFAULT_INCOME_IRON +self:GetMines())
end
function methods:AddGold( value )
if self:GetGold() + value < 0 then
self:SetGold(0)
else
self:SetGold(self:GetGold() +value)
end
end
function methods:AddFood( value )
self:SetFood(self:GetFood() +value)
end
function methods:AddIron( value )
self:SetIron(self:GetIron() +value)
end
function methods:AddSupplied( value )
self:SetSupplied( self:GetSupplied() + value )
end
function methods:AddCreed( value )
self:SetCreed( self:GetCreed() + value )
end
function methods:GetBuildings()
return self.structures
end
function methods:GetUnits()
local units = {}
local count = 1
for id, unit in pairs( self.units ) do
units[ count ] = unit
count = count + 1
end
return units
end
function methods:GetSelectedUnits()
return self.selected.units
end
function methods:NumSelectedUnits()
return self.selected.unitcount
end
function methods:Select(Ent, Select)
if(Ent) then
return Ent:Select(Select)
else
if(not Select) then
local unit = self:GetSelectedUnits()[ Ent ]
if(IsValid(unit)) then
unit:Select(false)
end
end
end
end
function methods:SelectUnit( unit, bSelected )
local wasSelected = self:GetSelectedUnits()[ unit ]
self:GetSelectedUnits()[ unit ] = bSelected or nil
if( bSelected and not wasSelected ) then
self.selected.unitcount = self.selected.unitcount + 1
elseif( not bSelected and wasSelected ) then
self.selected.unitcount = self.selected.unitcount - 1
end
end
function methods:DeselectAllUnits()
assert( self.selected.units )
for unit, selected in pairs( self.selected.units ) do
unit:Select( false )
end
self.selected.units = {}
self.selected.unitcount = 0
end
--[[
No longer using these because some are too similar to eachother.
ColorTable = {
Color(90, 90, 90, 255), -- Grey
Color(200, 0, 0, 255), -- Red
Color(0, 200, 0, 255), -- Green
Color(0, 0, 200, 255), -- Blue
Color(200, 0, 200, 255), -- Magenta
Color(200, 200, 0, 255), -- Yellow
Color(0, 200, 200, 255), -- Cyan
Color(255, 140, 50, 255), -- Orange
Color(100, 0, 200, 255), -- Purple
Color(0, 128, 128, 255), -- Teal
Color(100, 64, 0, 255), -- Brown
Color(128, 200, 0, 255), -- Olive
Color(90, 150, 59, 255), -- Green-Gray
Color(155, 166, 200, 255), -- Light Purple
Color(0, 144, 200, 255), -- Sky blue
Color(200, 150, 160, 255), -- Pink
Color(255, 255, 0, 255), -- Pineapple Yellow (LuaPineapple Only)
}
--]]
ColorTable = {
Color(200, 60, 60, 255), -- Red
Color(90, 90, 90, 255), -- Grey
Color(45, 150, 140, 255), -- Torquise
Color(150, 150, 45, 255), -- Yellow
Color(200, 60, 165, 255), -- Pink
Color(100, 37, 125, 255), -- Purple
Color(60, 77, 201, 255), -- Blue
Color(100, 75, 30, 255), -- Brown
Color(60, 160, 50, 255), -- Green | The ones from this point on are overflow in case someone leaves the game and we need another color for a new player
Color(180, 204, 137, 255), -- Olive | The reason I copy pasted old ones was so that there are colors for people to go to without any problems, this is just temporarily for the dedicated server without the Lobby.
Color(255, 159, 51, 255), -- Orange
Color(93, 255, 77, 255), -- Bright Green
Color(255, 179, 252, 255), -- Bubblegum
Color(128, 42, 42, 255), -- Maroon
Color(237, 237, 66, 255), -- Bright Yellow
Color(200, 0, 200, 255), -- Magenta
Color(200, 200, 0, 255), -- Yellow
Color(0, 200, 200, 255), -- Cyan
Color(255, 140, 50, 255), -- Orange
Color(100, 0, 200, 255), -- Purple
Color(0, 128, 128, 255), -- Teal
Color(100, 64, 0, 255), -- Brown
Color(255, 255, 0, 255) -- Pineapple Yellow (LuaPineapple Only)
}
function methods:HasColor()
return (self.color ~= nil)
end
function methods:SetColorID( cid )
self.colorID = cid
self:SetColor( GetColorByID( cid ) )
end
function methods:GetColorID()
return self.colorID
end
function methods:SetColor( c )
if( not self:HasColor() ) then
self.color = Color( c.r, c.g, c.b, c.a )
return
end
self.color.r = c.r
self.color.g = c.g
self.color.b = c.b
self.color.a = c.a
end
function methods:GetColor()
return self.color
end
function methods:HasOwner( pl )
local owner = self:GetPlayer()
if not (IsValid( owner ) and owner:IsPlayer()) then return end
if not (owner == pl) then return end
return true
end
function methods:IsEmpire()
return true
end
function methods:IsPlayer()
return false
end
function methods:IsValid()
return true
end
function methods:HasBuilding()
end
function methods:Nick()
return self:GetName( "Empire" )
end | bsd-3-clause |
drdownload/prosody-modules | mod_vjud/vcard.lib.lua | 32 | 9198 | -- Copyright (C) 2011-2012 Kim Alvefur
--
-- This project is MIT/X11 licensed. Please see the
-- COPYING file in the source package for more information.
--
-- TODO
-- Fix folding.
local st = require "util.stanza";
local t_insert, t_concat = table.insert, table.concat;
local type = type;
local next, pairs, ipairs = next, pairs, ipairs;
local from_text, to_text, from_xep54, to_xep54;
local line_sep = "\n";
local vCard_dtd; -- See end of file
local function fold_line()
error "Not implemented" --TODO
end
local function unfold_line()
error "Not implemented"
-- gsub("\r?\n[ \t]([^\r\n])", "%1");
end
local function vCard_esc(s)
return s:gsub("[,:;\\]", "\\%1"):gsub("\n","\\n");
end
local function vCard_unesc(s)
return s:gsub("\\?[\\nt:;,]", {
["\\\\"] = "\\",
["\\n"] = "\n",
["\\r"] = "\r",
["\\t"] = "\t",
["\\:"] = ":", -- FIXME Shouldn't need to espace : in values, just params
["\\;"] = ";",
["\\,"] = ",",
[":"] = "\29",
[";"] = "\30",
[","] = "\31",
});
end
local function item_to_xep54(item)
local t = st.stanza(item.name, { xmlns = "vcard-temp" });
local prop_def = vCard_dtd[item.name];
if prop_def == "text" then
t:text(item[1]);
elseif type(prop_def) == "table" then
if prop_def.types and item.TYPE then
if type(item.TYPE) == "table" then
for _,v in pairs(prop_def.types) do
for _,typ in pairs(item.TYPE) do
if typ:upper() == v then
t:tag(v):up();
break;
end
end
end
else
t:tag(item.TYPE:upper()):up();
end
end
if prop_def.props then
for _,v in pairs(prop_def.props) do
if item[v] then
t:tag(v):up();
end
end
end
if prop_def.value then
t:tag(prop_def.value):text(item[1]):up();
elseif prop_def.values then
local prop_def_values = prop_def.values;
local repeat_last = prop_def_values.behaviour == "repeat-last" and prop_def_values[#prop_def_values];
for i=1,#item do
t:tag(prop_def.values[i] or repeat_last):text(item[i]):up();
end
end
end
return t;
end
local function vcard_to_xep54(vCard)
local t = st.stanza("vCard", { xmlns = "vcard-temp" });
for i=1,#vCard do
t:add_child(item_to_xep54(vCard[i]));
end
return t;
end
function to_xep54(vCards)
if not vCards[1] or vCards[1].name then
return vcard_to_xep54(vCards)
else
local t = st.stanza("xCard", { xmlns = "vcard-temp" });
for i=1,#vCards do
t:add_child(vcard_to_xep54(vCards[i]));
end
return t;
end
end
function from_text(data)
data = data -- unfold and remove empty lines
:gsub("\r\n","\n")
:gsub("\n ", "")
:gsub("\n\n+","\n");
local vCards = {};
local c; -- current item
for line in data:gmatch("[^\n]+") do
local line = vCard_unesc(line);
local name, params, value = line:match("^([-%a]+)(\30?[^\29]*)\29(.*)$");
value = value:gsub("\29",":");
if #params > 0 then
local _params = {};
for k,isval,v in params:gmatch("\30([^=]+)(=?)([^\30]*)") do
k = k:upper();
local _vt = {};
for _p in v:gmatch("[^\31]+") do
_vt[#_vt+1]=_p
_vt[_p]=true;
end
if isval == "=" then
_params[k]=_vt;
else
_params[k]=true;
end
end
params = _params;
end
if name == "BEGIN" and value == "VCARD" then
c = {};
vCards[#vCards+1] = c;
elseif name == "END" and value == "VCARD" then
c = nil;
elseif vCard_dtd[name] then
local dtd = vCard_dtd[name];
local p = { name = name };
c[#c+1]=p;
--c[name]=p;
local up = c;
c = p;
if dtd.types then
for _, t in ipairs(dtd.types) do
local t = t:lower();
if ( params.TYPE and params.TYPE[t] == true)
or params[t] == true then
c.TYPE=t;
end
end
end
if dtd.props then
for _, p in ipairs(dtd.props) do
if params[p] then
if params[p] == true then
c[p]=true;
else
for _, prop in ipairs(params[p]) do
c[p]=prop;
end
end
end
end
end
if dtd == "text" or dtd.value then
t_insert(c, value);
elseif dtd.values then
local value = "\30"..value;
for p in value:gmatch("\30([^\30]*)") do
t_insert(c, p);
end
end
c = up;
end
end
return vCards;
end
local function item_to_text(item)
local value = {};
for i=1,#item do
value[i] = vCard_esc(item[i]);
end
value = t_concat(value, ";");
local params = "";
for k,v in pairs(item) do
if type(k) == "string" and k ~= "name" then
params = params .. (";%s=%s"):format(k, type(v) == "table" and t_concat(v,",") or v);
end
end
return ("%s%s:%s"):format(item.name, params, value)
end
local function vcard_to_text(vcard)
local t={};
t_insert(t, "BEGIN:VCARD")
for i=1,#vcard do
t_insert(t, item_to_text(vcard[i]));
end
t_insert(t, "END:VCARD")
return t_concat(t, line_sep);
end
function to_text(vCards)
if vCards[1] and vCards[1].name then
return vcard_to_text(vCards)
else
local t = {};
for i=1,#vCards do
t[i]=vcard_to_text(vCards[i]);
end
return t_concat(t, line_sep);
end
end
local function from_xep54_item(item)
local prop_name = item.name;
local prop_def = vCard_dtd[prop_name];
local prop = { name = prop_name };
if prop_def == "text" then
prop[1] = item:get_text();
elseif type(prop_def) == "table" then
if prop_def.value then --single item
prop[1] = item:get_child_text(prop_def.value) or "";
elseif prop_def.values then --array
local value_names = prop_def.values;
if value_names.behaviour == "repeat-last" then
for i=1,#item.tags do
t_insert(prop, item.tags[i]:get_text() or "");
end
else
for i=1,#value_names do
t_insert(prop, item:get_child_text(value_names[i]) or "");
end
end
elseif prop_def.names then
local names = prop_def.names;
for i=1,#names do
if item:get_child(names[i]) then
prop[1] = names[i];
break;
end
end
end
if prop_def.props_verbatim then
for k,v in pairs(prop_def.props_verbatim) do
prop[k] = v;
end
end
if prop_def.types then
local types = prop_def.types;
prop.TYPE = {};
for i=1,#types do
if item:get_child(types[i]) then
t_insert(prop.TYPE, types[i]:lower());
end
end
if #prop.TYPE == 0 then
prop.TYPE = nil;
end
end
-- A key-value pair, within a key-value pair?
if prop_def.props then
local params = prop_def.props;
for i=1,#params do
local name = params[i]
local data = item:get_child_text(name);
if data then
prop[name] = prop[name] or {};
t_insert(prop[name], data);
end
end
end
else
return nil
end
return prop;
end
local function from_xep54_vCard(vCard)
local tags = vCard.tags;
local t = {};
for i=1,#tags do
t_insert(t, from_xep54_item(tags[i]));
end
return t
end
function from_xep54(vCard)
if vCard.attr.xmlns ~= "vcard-temp" then
return nil, "wrong-xmlns";
end
if vCard.name == "xCard" then -- A collection of vCards
local t = {};
local vCards = vCard.tags;
for i=1,#vCards do
t[i] = from_xep54_vCard(vCards[i]);
end
return t
elseif vCard.name == "vCard" then -- A single vCard
return from_xep54_vCard(vCard)
end
end
-- This was adapted from http://xmpp.org/extensions/xep-0054.html#dtd
vCard_dtd = {
VERSION = "text", --MUST be 3.0, so parsing is redundant
FN = "text",
N = {
values = {
"FAMILY",
"GIVEN",
"MIDDLE",
"PREFIX",
"SUFFIX",
},
},
NICKNAME = "text",
PHOTO = {
props_verbatim = { ENCODING = { "b" } },
props = { "TYPE" },
value = "BINVAL", --{ "EXTVAL", },
},
BDAY = "text",
ADR = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
values = {
"POBOX",
"EXTADD",
"STREET",
"LOCALITY",
"REGION",
"PCODE",
"CTRY",
}
},
LABEL = {
types = {
"HOME",
"WORK",
"POSTAL",
"PARCEL",
"DOM",
"INTL",
"PREF",
},
value = "LINE",
},
TEL = {
types = {
"HOME",
"WORK",
"VOICE",
"FAX",
"PAGER",
"MSG",
"CELL",
"VIDEO",
"BBS",
"MODEM",
"ISDN",
"PCS",
"PREF",
},
value = "NUMBER",
},
EMAIL = {
types = {
"HOME",
"WORK",
"INTERNET",
"PREF",
"X400",
},
value = "USERID",
},
JABBERID = "text",
MAILER = "text",
TZ = "text",
GEO = {
values = {
"LAT",
"LON",
},
},
TITLE = "text",
ROLE = "text",
LOGO = "copy of PHOTO",
AGENT = "text",
ORG = {
values = {
behaviour = "repeat-last",
"ORGNAME",
"ORGUNIT",
}
},
CATEGORIES = {
values = "KEYWORD",
},
NOTE = "text",
PRODID = "text",
REV = "text",
SORTSTRING = "text",
SOUND = "copy of PHOTO",
UID = "text",
URL = "text",
CLASS = {
names = { -- The item.name is the value if it's one of these.
"PUBLIC",
"PRIVATE",
"CONFIDENTIAL",
},
},
KEY = {
props = { "TYPE" },
value = "CRED",
},
DESC = "text",
};
vCard_dtd.LOGO = vCard_dtd.PHOTO;
vCard_dtd.SOUND = vCard_dtd.PHOTO;
return {
from_text = from_text;
to_text = to_text;
from_xep54 = from_xep54;
to_xep54 = to_xep54;
-- COMPAT:
lua_to_text = to_text;
lua_to_xep54 = to_xep54;
text_to_lua = from_text;
text_to_xep54 = function (...) return to_xep54(from_text(...)); end;
xep54_to_lua = from_xep54;
xep54_to_text = function (...) return to_text(from_xep54(...)) end;
};
| mit |
xing634325131/Luci-0.11.1 | libs/px5g/lua/px5g/util.lua | 170 | 1148 | --[[
* px5g - Embedded x509 key and certificate generator based on PolarSSL
*
* Copyright (C) 2009 Steven Barth <steven@midlink.org>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License, version 2.1 as published by the Free Software Foundation.
]]--
local nixio = require "nixio"
local table = require "table"
module "px5g.util"
local preamble = {
key = "-----BEGIN RSA PRIVATE KEY-----",
cert = "-----BEGIN CERTIFICATE-----",
request = "-----BEGIN CERTIFICATE REQUEST-----"
}
local postamble = {
key = "-----END RSA PRIVATE KEY-----",
cert = "-----END CERTIFICATE-----",
request = "-----END CERTIFICATE REQUEST-----"
}
function der2pem(data, type)
local b64 = nixio.bin.b64encode(data)
local outdata = {preamble[type]}
for i = 1, #b64, 64 do
outdata[#outdata + 1] = b64:sub(i, i + 63)
end
outdata[#outdata + 1] = postamble[type]
outdata[#outdata + 1] = ""
return table.concat(outdata, "\n")
end
function pem2der(data)
local b64 = data:gsub({["\n"] = "", ["%-%-%-%-%-.-%-%-%-%-%-"] = ""})
return nixio.bin.b64decode(b64)
end | apache-2.0 |
SLAPaper/MCGC | MCGC/c84130822.lua | 3 | 4914 | -- MC群的摆渡者 玲音
function c84130822.initial_effect(c)
-- 不能特招
local e1 = Effect.CreateEffect(c)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(aux.FALSE)
c:RegisterEffect(e1)
-- 弹回手卡
local e2 = Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE + EFFECT_TYPE_CONTINUOUS)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e2:SetCode(EVENT_SUMMON_SUCCESS)
e2:SetOperation(c84130822.backHandOperation1)
c:RegisterEffect(e2)
local e3 = e2:Clone()
e3:SetCode(EVENT_FLIP)
c:RegisterEffect(e3)
-- 无解放召唤
local e4 = Effect.CreateEffect(c)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_SUMMON_PROC)
e4:SetCondition(c84130822.noTributeCondition)
e4:SetOperation(c84130822.noTributeOperation)
c:RegisterEffect(e4)
local e5 = e4:Clone()
e5:SetCode(EFFECT_SET_PROC)
c:RegisterEffect(e5)
-- 三怪兽解放召唤
local e6 = Effect.CreateEffect(c)
e6:SetProperty(EFFECT_FLAG_CANNOT_DISABLE + EFFECT_FLAG_UNCOPYABLE)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_SUMMON_PROC)
e6:SetCondition(c84130822.threeTributeCondition)
e6:SetOperation(c84130822.threeTributeOperation)
e6:SetValue(SUMMON_TYPE_ADVANCE + 1)
c:RegisterEffect(e6)
local e7 = Effect.CreateEffect(c)
e7:SetCategory(CATEGORY_DESTROY)
e7:SetType(EFFECT_TYPE_SINGLE + EFFECT_TYPE_TRIGGER_F)
e7:SetCode(EVENT_SUMMON_SUCCESS)
e7:SetCondition(c84130822.desdroyCondition)
e7:SetTarget(c84130822.desdroyTarget)
e7:SetOperation(c84130822.desdroyOperation)
c:RegisterEffect(e7)
end
function c84130822.backHandOperation1(e, tp, eg, ep, ev, re, r, rp)
local c = e:GetHandler()
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD + EFFECT_TYPE_TRIGGER_F)
e1:SetCategory(CATEGORY_TOHAND)
e1:SetCode(EVENT_PHASE + PHASE_END)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetReset(RESET_EVENT + 0x1ee0000 + RESET_PHASE + PHASE_END)
e1:SetCondition(c84130822.backHandCondition)
e1:SetTarget(c84130822.backHandTarget)
e1:SetOperation(c84130822.backHandOperation2)
c:RegisterEffect(e1)
local e2 = e1:Clone()
e2:SetType(EFFECT_TYPE_FIELD + EFFECT_TYPE_TRIGGER_O)
c:RegisterEffect(e2)
end
function c84130822.backHandCondition(e, tp, eg, ep, ev, re, r, rp)
local c = e:GetHandler()
if c:IsHasEffect(EFFECT_SPIRIT_DONOT_RETURN) then
return false
end
if e:IsHasType(EFFECT_TYPE_TRIGGER_F) then
return not c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN)
else
return c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN)
end
end
function c84130822.backHandTarget(e, tp, eg, ep, ev, re, r, rp, chk, chkc)
if chk == 0 then
return true
end
Duel.SetTargetCard(e:GetHandler())
Duel.SetOperationInfo(0, CATEGORY_TOHAND, e:GetHandler(), 1, 0, 0)
end
function c84130822.backHandOperation2(e, tp, eg, ep, ev, re, r, rp)
local c = e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
Duel.SendtoHand(c, nil, REASON_EFFECT)
end
end
function c84130822.noTributeCondition(e, c, minc)
if c == nil then
return true
end
return minc == 0 and c:GetLevel() > 4 and Duel.GetLocationCount(c:GetControler(), LOCATION_MZONE) > 0
end
function c84130822.noTributeOperation(e, tp, eg, ep, ev, re, r, rp, c)
local e1 = Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e1:SetRange(LOCATION_MZONE)
e1:SetReset(RESET_EVENT + 0xff0000)
e1:SetCode(EFFECT_SET_BASE_ATTACK)
e1:SetValue(1900)
c:RegisterEffect(e1)
end
function c84130822.threeTributeCondition(e, c, minc)
if c == nil then
return true
end
return Duel.GetTributeCount(c) >= 3
end
function c84130822.threeTributeOperation(e, tp, eg, ep, ev, re, r, rp, c)
Duel.Hint(HINT_SELECTMSG, tp, HINTMSG_RELEASE)
local g = Duel.SelectTribute(tp, c, 3, 3)
c:SetMaterial(g)
Duel.Release(g, REASON_SUMMON + REASON_MATERIAL)
end
function c84130822.desdroyCondition(e, tp, eg, ep, ev, re, r, rp)
return e:GetHandler():GetSummonType() == SUMMON_TYPE_ADVANCE + 1
end
function c84130822.desdroyTarget(e, tp, eg, ep, ev, re, r, rp, chk, chkc)
if chk == 0 then
return true
end
local sg = Duel.GetMatchingGroup(Card.IsDestructable, tp, 0, LOCATION_ONFIELD, nil)
Duel.SetTargetCard(sg)
Duel.SetOperationInfo(0, CATEGORY_DESTROY, sg, sg:GetCount(), 0, 0)
end
function c84130822.desdroyOperation(e, tp, eg, ep, ev, re, r, rp)
local sg = Duel.GetMatchingGroup(Card.IsDestructable, tp, 0, LOCATION_ONFIELD, nil)
Duel.Destroy(sg, REASON_EFFECT)
end | mit |
MrCerealGuy/Stonecraft | games/stonecraft_game/mods/mesecons/mesecons_gates/init.lua | 1 | 5407 | --[[
2017-01-06 modified by MrCerealGuy <mrcerealguy@gmx.de>
exit if mod is deactivated
--]]
if core.skip_mod("mesecons") then return end
local selection_box = {
type = "fixed",
fixed = { -8/16, -8/16, -8/16, 8/16, -6/16, 8/16 }
}
local nodebox = {
type = "fixed",
fixed = {
{ -8/16, -8/16, -8/16, 8/16, -7/16, 8/16 }, -- bottom slab
{ -6/16, -7/16, -6/16, 6/16, -6/16, 6/16 }
},
}
local function gate_rotate_rules(node, rules)
for rotations = 0, node.param2 - 1 do
rules = mesecon.rotate_rules_left(rules)
end
return rules
end
local function gate_get_output_rules(node)
return gate_rotate_rules(node, {{x=1, y=0, z=0}})
end
local function gate_get_input_rules_oneinput(node)
return gate_rotate_rules(node, {{x=-1, y=0, z=0}})
end
local function gate_get_input_rules_twoinputs(node)
return gate_rotate_rules(node, {{x=0, y=0, z=1, name="input1"},
{x=0, y=0, z=-1, name="input2"}})
end
local function set_gate(pos, node, state)
local gate = minetest.registered_nodes[node.name]
if mesecon.do_overheat(pos) then
minetest.remove_node(pos)
mesecon.receptor_off(pos, gate_get_output_rules(node))
minetest.add_item(pos, gate.drop)
elseif state then
minetest.swap_node(pos, {name = gate.onstate, param2=node.param2})
mesecon.receptor_on(pos, gate_get_output_rules(node))
else
minetest.swap_node(pos, {name = gate.offstate, param2=node.param2})
mesecon.receptor_off(pos, gate_get_output_rules(node))
end
end
local function update_gate(pos, node, link, newstate)
local gate = minetest.registered_nodes[node.name]
if gate.inputnumber == 1 then
set_gate(pos, node, gate.assess(newstate == "on"))
elseif gate.inputnumber == 2 then
local meta = minetest.get_meta(pos)
meta:set_int(link.name, newstate == "on" and 1 or 0)
local val1 = meta:get_int("input1") == 1
local val2 = meta:get_int("input2") == 1
set_gate(pos, node, gate.assess(val1, val2))
end
end
local function register_gate(name, inputnumber, assess, recipe, description)
local get_inputrules = inputnumber == 2 and gate_get_input_rules_twoinputs or
gate_get_input_rules_oneinput
description = "Logic Gate: "..name
local basename = "mesecons_gates:"..name
mesecon.register_node(basename, {
description = description,
inventory_image = "jeija_gate_off.png^jeija_gate_"..name..".png",
paramtype = "light",
paramtype2 = "facedir",
is_ground_content = false,
drawtype = "nodebox",
drop = basename.."_off",
selection_box = selection_box,
node_box = nodebox,
walkable = true,
sounds = default.node_sound_stone_defaults(),
assess = assess,
onstate = basename.."_on",
offstate = basename.."_off",
inputnumber = inputnumber,
after_dig_node = mesecon.do_cooldown,
},{
tiles = {
"jeija_microcontroller_bottom.png^".."jeija_gate_off.png^"..
"jeija_gate_output_off.png^".."jeija_gate_"..name..".png",
"jeija_microcontroller_bottom.png^".."jeija_gate_output_off.png^"..
"[transformFY",
"jeija_gate_side.png^".."jeija_gate_side_output_off.png",
"jeija_gate_side.png",
"jeija_gate_side.png",
"jeija_gate_side.png"
},
groups = {dig_immediate = 2, overheat = 1},
mesecons = { receptor = {
state = "off",
rules = gate_get_output_rules
}, effector = {
rules = get_inputrules,
action_change = update_gate
}}
},{
tiles = {
"jeija_microcontroller_bottom.png^".."jeija_gate_on.png^"..
"jeija_gate_output_on.png^".."jeija_gate_"..name..".png",
"jeija_microcontroller_bottom.png^".."jeija_gate_output_on.png^"..
"[transformFY",
"jeija_gate_side.png^".."jeija_gate_side_output_on.png",
"jeija_gate_side.png",
"jeija_gate_side.png",
"jeija_gate_side.png"
},
groups = {dig_immediate = 2, not_in_creative_inventory = 1, overheat = 1},
mesecons = { receptor = {
state = "on",
rules = gate_get_output_rules
}, effector = {
rules = get_inputrules,
action_change = update_gate
}}
})
minetest.register_craft({output = basename.."_off", recipe = recipe})
end
register_gate("diode", 1, function (input) return input end,
{{"mesecons:mesecon", "mesecons_torch:mesecon_torch_on", "mesecons_torch:mesecon_torch_on"}},
"Diode")
register_gate("not", 1, function (input) return not input end,
{{"mesecons:mesecon", "mesecons_torch:mesecon_torch_on", "mesecons:mesecon"}},
"NOT Gate")
register_gate("and", 2, function (val1, val2) return val1 and val2 end,
{{"mesecons:mesecon", "", ""},
{"", "mesecons_materials:silicon", "mesecons:mesecon"},
{"mesecons:mesecon", "", ""}},
"AND Gate")
register_gate("nand", 2, function (val1, val2) return not (val1 and val2) end,
{{"mesecons:mesecon", "", ""},
{"", "mesecons_materials:silicon", "mesecons_torch:mesecon_torch_on"},
{"mesecons:mesecon", "", ""}},
"NAND Gate")
register_gate("xor", 2, function (val1, val2) return (val1 or val2) and not (val1 and val2) end,
{{"mesecons:mesecon", "", ""},
{"", "mesecons_materials:silicon", "mesecons_materials:silicon"},
{"mesecons:mesecon", "", ""}},
"XOR Gate")
register_gate("nor", 2, function (val1, val2) return not (val1 or val2) end,
{{"mesecons:mesecon", "", ""},
{"", "mesecons:mesecon", "mesecons_torch:mesecon_torch_on"},
{"mesecons:mesecon", "", ""}},
"NOR Gate")
register_gate("or", 2, function (val1, val2) return (val1 or val2) end,
{{"mesecons:mesecon", "", ""},
{"", "mesecons:mesecon", "mesecons:mesecon"},
{"mesecons:mesecon", "", ""}},
"OR Gate")
| gpl-3.0 |
Hello23-Ygopro/ygopro-kaijudo | expansions/script/c25003082.lua | 1 | 1515 | --Kronkos, General of Fear
local ka=require "expansions.utility_ktcg"
local scard,sid=ka.GetID()
function scard.initial_effect(c)
ka.EnableCreatureAttribute(c)
--banish replace (banish)
ka.AddBanishReplaceAbility(c,0,scard.reptg,scard.repop,scard.repval)
end
scard.kaijudo_card=true
function scard.repfilter(c,tp)
return c:IsLocation(KA_LOCATION_BATTLE) and c:IsFaceup() and c:IsCreatureType(KA_CREATURE_SHADOW_CHAMPION)
and c:IsControler(tp) and not c:IsReason(REASON_REPLACE)
end
function scard.banfilter(c,tp)
return c:IsControler(tp) and not c:IsStatus(KA_STATUS_BANISH_CONFIRMED+KA_STATUS_BATTLE_BANISHED)
end
function scard.reptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return eg:IsExists(scard.repfilter,1,nil,tp)
and Duel.IsExistingMatchingCard(scard.banfilter,tp,KA_LOCATION_BATTLE,0,1,nil,tp) end
if Duel.SelectYesNo(tp,aux.Stringid(sid,1)) then
Duel.Hint(HINT_CARD,0,sid)
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.Hint(HINT_SELECTMSG,tp,KA_HINTMSG_BANREPLACE)
local tc=Duel.SelectMatchingCard(tp,scard.banfilter,tp,KA_LOCATION_BATTLE,0,1,1,nil,tp):GetFirst()
e:SetLabelObject(tc)
Duel.HintSelection(Group.FromCards(tc))
tc:SetStatus(KA_STATUS_BANISH_CONFIRMED,true)
return true
else return false end
end
function scard.repval(e,c)
return scard.repfilter(c,e:GetHandlerPlayer())
end
function scard.repop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject()
tc:SetStatus(KA_STATUS_BANISH_CONFIRMED,false)
Duel.KABanish(tc,KA_REASON_ABILITY+REASON_REPLACE)
end
| gpl-3.0 |
khanasbot/Avatar_Bot | bot/utils.lua | 356 | 14963 | URL = require "socket.url"
http = require "socket.http"
https = require "ssl.https"
ltn12 = require "ltn12"
serpent = require "serpent"
feedparser = require "feedparser"
json = (loadfile "./libs/JSON.lua")()
mimetype = (loadfile "./libs/mimetype.lua")()
redis = (loadfile "./libs/redis.lua")()
JSON = (loadfile "./libs/dkjson.lua")()
http.TIMEOUT = 10
function get_receiver(msg)
if msg.to.type == 'user' then
return 'user#id'..msg.from.id
end
if msg.to.type == 'chat' then
return 'chat#id'..msg.to.id
end
if msg.to.type == 'encr_chat' then
return msg.to.print_name
end
end
function is_chat_msg( msg )
if msg.to.type == 'chat' then
return true
end
return false
end
function string.random(length)
local str = "";
for i = 1, length do
math.random(97, 122)
str = str..string.char(math.random(97, 122));
end
return str;
end
function string:split(sep)
local sep, fields = sep or ":", {}
local pattern = string.format("([^%s]+)", sep)
self:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
-- DEPRECATED
function string.trim(s)
print("string.trim(s) is DEPRECATED use string:trim() instead")
return s:gsub("^%s*(.-)%s*$", "%1")
end
-- Removes spaces
function string:trim()
return self:gsub("^%s*(.-)%s*$", "%1")
end
function get_http_file_name(url, headers)
-- Eg: foo.var
local file_name = url:match("[^%w]+([%.%w]+)$")
-- Any delimited alphanumeric on the url
file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$")
-- Random name, hope content-type works
file_name = file_name or str:random(5)
local content_type = headers["content-type"]
local extension = nil
if content_type then
extension = mimetype.get_mime_extension(content_type)
end
if extension then
file_name = file_name.."."..extension
end
local disposition = headers["content-disposition"]
if disposition then
-- attachment; filename=CodeCogsEqn.png
file_name = disposition:match('filename=([^;]+)') or file_name
end
return file_name
end
-- Saves file to /tmp/. If file_name isn't provided,
-- will get the text after the last "/" for filename
-- and content-type for extension
function download_to_file(url, file_name)
print("url to download: "..url)
local respbody = {}
local options = {
url = url,
sink = ltn12.sink.table(respbody),
redirect = true
}
-- nil, code, headers, status
local response = nil
if url:starts('https') then
options.redirect = false
response = {https.request(options)}
else
response = {http.request(options)}
end
local code = response[2]
local headers = response[3]
local status = response[4]
if code ~= 200 then return nil end
file_name = file_name or get_http_file_name(url, headers)
local file_path = "/tmp/"..file_name
print("Saved to: "..file_path)
file = io.open(file_path, "w+")
file:write(table.concat(respbody))
file:close()
return file_path
end
function vardump(value)
print(serpent.block(value, {comment=false}))
end
-- taken from http://stackoverflow.com/a/11130774/3163199
function scandir(directory)
local i, t, popen = 0, {}, io.popen
for filename in popen('ls -a "'..directory..'"'):lines() do
i = i + 1
t[i] = filename
end
return t
end
-- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen
function run_command(str)
local cmd = io.popen(str)
local result = cmd:read('*all')
cmd:close()
return result
end
-- User has superuser privileges
function is_sudo(msg)
local var = false
-- Check users id in config
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has admins privileges
function is_admin(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
local admins = 'admins'
if data[tostring(admins)] then
if data[tostring(admins)][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- user has moderator privileges
function is_momod(msg)
local var = false
local data = load_data(_config.moderation.data)
local user = msg.from.id
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['moderators'] then
if data[tostring(msg.to.id)]['moderators'][tostring(user)] then
var = true
end
end
end
if data['admins'] then
if data['admins'][tostring(user)] then
var = true
end
end
for v,user in pairs(_config.sudo_users) do
if user == msg.from.id then
var = true
end
end
return var
end
-- Returns the name of the sender
function get_name(msg)
local name = msg.from.first_name
if name == nil then
name = msg.from.id
end
return name
end
-- Returns at table of lua files inside plugins
function plugins_names( )
local files = {}
for k, v in pairs(scandir("plugins")) do
-- Ends with .lua
if (v:match(".lua$")) then
table.insert(files, v)
end
end
return files
end
-- Function name explains what it does.
function file_exists(name)
local f = io.open(name,"r")
if f ~= nil then
io.close(f)
return true
else
return false
end
end
-- Save into file the data serialized for lua.
-- Set uglify true to minify the file.
function serialize_to_file(data, file, uglify)
file = io.open(file, 'w+')
local serialized
if not uglify then
serialized = serpent.block(data, {
comment = false,
name = '_'
})
else
serialized = serpent.dump(data)
end
file:write(serialized)
file:close()
end
-- Returns true if the string is empty
function string:isempty()
return self == nil or self == ''
end
-- Returns true if the string is blank
function string:isblank()
self = self:trim()
return self:isempty()
end
-- DEPRECATED!!!!!
function string.starts(String, Start)
print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead")
return Start == string.sub(String,1,string.len(Start))
end
-- Returns true if String starts with Start
function string:starts(text)
return text == string.sub(self,1,string.len(text))
end
-- Send image to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_photo(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function,
cb_extra = cb_extra
}
-- Call to remove with optional callback
send_photo(receiver, file_path, cb_function, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_photo_from_url(receiver, url, cb_function, cb_extra)
-- If callback not provided
cb_function = cb_function or ok_cb
cb_extra = cb_extra or false
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, cb_function, cb_extra)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, cb_function, cb_extra)
end
end
-- Same as send_photo_from_url but as callback function
function send_photo_from_url_callback(cb_extra, success, result)
local receiver = cb_extra.receiver
local url = cb_extra.url
local file_path = download_to_file(url, false)
if not file_path then -- Error
local text = 'Error downloading the image'
send_msg(receiver, text, ok_cb, false)
else
print("File path: "..file_path)
_send_photo(receiver, file_path, ok_cb, false)
end
end
-- Send multiple images asynchronous.
-- param urls must be a table.
function send_photos_from_url(receiver, urls)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = nil
}
send_photos_from_url_callback(cb_extra)
end
-- Use send_photos_from_url.
-- This function might be difficult to understand.
function send_photos_from_url_callback(cb_extra, success, result)
-- cb_extra is a table containing receiver, urls and remove_path
local receiver = cb_extra.receiver
local urls = cb_extra.urls
local remove_path = cb_extra.remove_path
-- The previously image to remove
if remove_path ~= nil then
os.remove(remove_path)
print("Deleted: "..remove_path)
end
-- Nil or empty, exit case (no more urls)
if urls == nil or #urls == 0 then
return false
end
-- Take the head and remove from urls table
local head = table.remove(urls, 1)
local file_path = download_to_file(head, false)
local cb_extra = {
receiver = receiver,
urls = urls,
remove_path = file_path
}
-- Send first and postpone the others as callback
send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra)
end
-- Callback to remove a file
function rmtmp_cb(cb_extra, success, result)
local file_path = cb_extra.file_path
local cb_function = cb_extra.cb_function or ok_cb
local cb_extra = cb_extra.cb_extra
if file_path ~= nil then
os.remove(file_path)
print("Deleted: "..file_path)
end
-- Finally call the callback
cb_function(cb_extra, success, result)
end
-- Send document to user and delete it when finished.
-- cb_function and cb_extra are optionals callback
function _send_document(receiver, file_path, cb_function, cb_extra)
local cb_extra = {
file_path = file_path,
cb_function = cb_function or ok_cb,
cb_extra = cb_extra or false
}
-- Call to remove with optional callback
send_document(receiver, file_path, rmtmp_cb, cb_extra)
end
-- Download the image and send to receiver, it will be deleted.
-- cb_function and cb_extra are optionals callback
function send_document_from_url(receiver, url, cb_function, cb_extra)
local file_path = download_to_file(url, false)
print("File path: "..file_path)
_send_document(receiver, file_path, cb_function, cb_extra)
end
-- Parameters in ?a=1&b=2 style
function format_http_params(params, is_get)
local str = ''
-- If is get add ? to the beginning
if is_get then str = '?' end
local first = true -- Frist param
for k,v in pairs (params) do
if v then -- nil value
if first then
first = false
str = str..k.. "="..v
else
str = str.."&"..k.. "="..v
end
end
end
return str
end
-- Check if user can use the plugin and warns user
-- Returns true if user was warned and false if not warned (is allowed)
function warns_user_not_allowed(plugin, msg)
if not user_allowed(plugin, msg) then
local text = 'This plugin requires privileged user'
local receiver = get_receiver(msg)
send_msg(receiver, text, ok_cb, false)
return true
else
return false
end
end
-- Check if user can use the plugin
function user_allowed(plugin, msg)
-- Berfungsi utk mengecek user jika plugin moderated = true
if plugin.moderated and not is_momod(msg) then --Cek apakah user adalah momod
if plugin.moderated and not is_admin(msg) then -- Cek apakah user adalah admin
if plugin.moderated and not is_sudo(msg) then -- Cek apakah user adalah sudoers
return false
end
end
end
-- Berfungsi mengecek user jika plugin privileged = true
if plugin.privileged and not is_sudo(msg) then
return false
end
return true
end
function send_order_msg(destination, msgs)
local cb_extra = {
destination = destination,
msgs = msgs
}
send_order_msg_callback(cb_extra, true)
end
function send_order_msg_callback(cb_extra, success, result)
local destination = cb_extra.destination
local msgs = cb_extra.msgs
local file_path = cb_extra.file_path
if file_path ~= nil then
os.remove(file_path)
print("Deleted: " .. file_path)
end
if type(msgs) == 'string' then
send_large_msg(destination, msgs)
elseif type(msgs) ~= 'table' then
return
end
if #msgs < 1 then
return
end
local msg = table.remove(msgs, 1)
local new_cb_extra = {
destination = destination,
msgs = msgs
}
if type(msg) == 'string' then
send_msg(destination, msg, send_order_msg_callback, new_cb_extra)
elseif type(msg) == 'table' then
local typ = msg[1]
local nmsg = msg[2]
new_cb_extra.file_path = nmsg
if typ == 'document' then
send_document(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'image' or typ == 'photo' then
send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'audio' then
send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra)
elseif typ == 'video' then
send_video(destination, nmsg, send_order_msg_callback, new_cb_extra)
else
send_file(destination, nmsg, send_order_msg_callback, new_cb_extra)
end
end
end
-- Same as send_large_msg_callback but friendly params
function send_large_msg(destination, text)
local cb_extra = {
destination = destination,
text = text
}
send_large_msg_callback(cb_extra, true)
end
-- If text is longer than 4096 chars, send multiple msg.
-- https://core.telegram.org/method/messages.sendMessage
function send_large_msg_callback(cb_extra, success, result)
local text_max = 4096
local destination = cb_extra.destination
local text = cb_extra.text
local text_len = string.len(text)
local num_msg = math.ceil(text_len / text_max)
if num_msg <= 1 then
send_msg(destination, text, ok_cb, false)
else
local my_text = string.sub(text, 1, 4096)
local rest = string.sub(text, 4096, text_len)
local cb_extra = {
destination = destination,
text = rest
}
send_msg(destination, my_text, send_large_msg_callback, cb_extra)
end
end
-- Returns a table with matches or nil
function match_pattern(pattern, text, lower_case)
if text then
local matches = {}
if lower_case then
matches = { string.match(text:lower(), pattern) }
else
matches = { string.match(text, pattern) }
end
if next(matches) then
return matches
end
end
-- nil
end
-- Function to read data from files
function load_from_file(file, default_data)
local f = io.open(file, "r+")
-- If file doesn't exists
if f == nil then
-- Create a new empty table
default_data = default_data or {}
serialize_to_file(default_data, file)
print ('Created file', file)
else
print ('Data loaded from file', file)
f:close()
end
return loadfile (file)()
end
-- See http://stackoverflow.com/a/14899740
function unescape_html(str)
local map = {
["lt"] = "<",
["gt"] = ">",
["amp"] = "&",
["quot"] = '"',
["apos"] = "'"
}
new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s)
var = map[s] or n == "#" and string.char(s)
var = var or n == "#x" and string.char(tonumber(s,16))
var = var or orig
return var
end)
return new
end | gpl-2.0 |
luvit/luvit | tests/test-fs-write-sync.lua | 14 | 1192 | --[[
Copyright 2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License")
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
require('tap')(function(test)
local FS = require('fs')
local Path = require('path')
local Buffer = require('buffer').Buffer
test('fs.writeSync', function()
local fn = Path.join(module.dir, 'write.txt')
local foo = 'foo'
local fd = FS.openSync(fn, 'w')
local written = FS.writeSync(fd, -1, '')
assert(written == 0)
FS.writeSync(fd, -1, foo)
local bar = 'bár'
-- TODO: Support buffer argument
written = FS.writeSync(fd, -1, Buffer:new(bar):toString())
assert(written > 3)
FS.closeSync(fd)
assert(FS.readFileSync(fn) == 'foobár')
end)
end)
| apache-2.0 |
kroepke/luna | luna-tests/src/test/resources/benchmarksgame/knucleotide.lua-2.lua | 1 | 1810 | -- The Computer Language Benchmarks Game
-- http://benchmarksgame.alioth.debian.org/
-- contributed by Mike Pall
local function kfrequency(seq, freq, k, frame)
local sub = string.sub
local k1 = k - 1
for i = frame, string.len(seq) - k1, k do
local c = sub(seq, i, i + k1)
freq[c] = freq[c] + 1
end
end
local function freqdefault()
return 0
end
local function count(seq, frag)
local k = string.len(frag)
local freq = setmetatable({}, { __index = freqdefault })
for frame = 1, k do kfrequency(seq, freq, k, frame) end
io.write(freq[frag] or 0, "\t", frag, "\n")
end
local function frequency(seq, k)
local freq = setmetatable({}, { __index = freqdefault })
for frame = 1, k do kfrequency(seq, freq, k, frame) end
local sfreq, sn = {}, 1
for c, v in pairs(freq) do sfreq[sn] = c; sn = sn + 1 end
table.sort(sfreq, function(a, b)
local fa, fb = freq[a], freq[b]
return fa == fb and a > b or fa > fb
end)
sum = string.len(seq) - k + 1
for _, c in ipairs(sfreq) do
io.write(string.format("%s %0.3f\n", c, (freq[c] * 100) / sum))
end
io.write("\n")
end
local function readseq()
local sub = string.sub
for line in io.lines() do
if sub(line, 1, 1) == ">" and sub(line, 2, 6) == "THREE" then break end
end
local lines, ln = {}, 0
for line in io.lines() do
local c = sub(line, 1, 1)
if c == ">" then
break
elseif c ~= ";" then
ln = ln + 1
lines[ln] = line
end
end
return string.upper(table.concat(lines, "", 1, ln))
end
local seq = readseq()
frequency(seq, 1)
frequency(seq, 2)
count(seq, "GGT")
count(seq, "GGTA")
count(seq, "GGTATT")
count(seq, "GGTATTTTAATT")
count(seq, "GGTATTTTAATTTATAGT")
| apache-2.0 |
mardraze/prosody-modules | mod_component_client/mod_component_client.lua | 31 | 8204 | --[[
mod_component_client.lua
This module turns Prosody hosts into components of other XMPP servers.
Config:
VirtualHost "component.example.com"
component_client = {
host = "localhost";
port = 5347;
secret = "hunter2";
}
]]
local socket = require "socket"
local logger = require "util.logger";
local sha1 = require "util.hashes".sha1;
local st = require "util.stanza";
local jid_split = require "util.jid".split;
local new_xmpp_stream = require "util.xmppstream".new;
local uuid_gen = require "util.uuid".generate;
local core_process_stanza = prosody.core_process_stanza;
local hosts = prosody.hosts;
local log = module._log;
local config = module:get_option("component_client", {});
local server_host = config.host or "localhost";
local server_port = config.port or 5347;
local server_secret = config.secret or error("client_component.secret not provided");
local exit_on_disconnect = config.exit_on_disconnect;
local keepalive_interval = config.keepalive_interval or 3600;
local __conn;
local listener = {};
local session;
local xmlns_component = 'jabber:component:accept';
local stream_callbacks = { default_ns = xmlns_component };
local xmlns_xmpp_streams = "urn:ietf:params:xml:ns:xmpp-streams";
function stream_callbacks.error(session, error, data, data2)
if session.destroyed then return; end
module:log("warn", "Error processing component stream: %s", tostring(error));
if error == "no-stream" then
session:close("invalid-namespace");
elseif error == "parse-error" then
session.log("warn", "External component %s XML parse error: %s", tostring(session.host), tostring(data));
session:close("not-well-formed");
elseif error == "stream-error" then
local condition, text = "undefined-condition";
for child in data:children() do
if child.attr.xmlns == xmlns_xmpp_streams then
if child.name ~= "text" then
condition = child.name;
else
text = child:get_text();
end
if condition ~= "undefined-condition" and text then
break;
end
end
end
text = condition .. (text and (" ("..text..")") or "");
session.log("info", "Session closed by remote with error: %s", text);
session:close(nil, text);
end
end
function stream_callbacks.streamopened(session, attr)
-- TODO check id~=nil, from==module.host
module:log("debug", "Sending handshake");
local handshake = st.stanza("handshake"):text(sha1(attr.id..server_secret, true));
session.send(handshake);
session.notopen = nil;
end
function stream_callbacks.streamclosed(session)
session.log("debug", "Received </stream:stream>");
session:close();
end
module:hook("stanza/jabber:component:accept:handshake", function(event)
session.type = "component";
module:log("debug", "Handshake complete");
module:fire_event("component_client/connected", {});
return true; -- READY!
end);
module:hook("route/remote", function(event)
return session and session.send(event.stanza);
end);
function stream_callbacks.handlestanza(session, stanza)
-- Namespaces are icky.
if not stanza.attr.xmlns and stanza.name == "handshake" then
stanza.attr.xmlns = xmlns_component;
end
if not stanza.attr.xmlns or stanza.attr.xmlns == "jabber:client" then
if not stanza.attr.from then
session.log("warn", "Rejecting stanza with no 'from' address");
session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST get a 'from' address on stanzas"));
return;
end
local _, domain = jid_split(stanza.attr.to);
if not domain then
session.log("warn", "Rejecting stanza with no 'to' address");
session.send(st.error_reply(stanza, "modify", "bad-request", "Components MUST get a 'to' address on stanzas"));
return;
elseif domain ~= session.host then
session.log("warn", "Component received stanza with unknown 'to' address");
session.send(st.error_reply(stanza, "cancel", "not-allowed", "Component doesn't serve this JID"));
return;
end
end
return core_process_stanza(session, stanza);
end
local stream_xmlns_attr = {xmlns='urn:ietf:params:xml:ns:xmpp-streams'};
local default_stream_attr = { ["xmlns:stream"] = "http://etherx.jabber.org/streams", xmlns = stream_callbacks.default_ns, version = "1.0", id = "" };
local function session_close(session, reason)
if session.destroyed then return; end
if session.conn then
if session.notopen then
session.send("<?xml version='1.0'?>");
session.send(st.stanza("stream:stream", default_stream_attr):top_tag());
end
if reason then
if type(reason) == "string" then -- assume stream error
module:log("info", "Disconnecting component, <stream:error> is: %s", reason);
session.send(st.stanza("stream:error"):tag(reason, {xmlns = 'urn:ietf:params:xml:ns:xmpp-streams' }));
elseif type(reason) == "table" then
if reason.condition then
local stanza = st.stanza("stream:error"):tag(reason.condition, stream_xmlns_attr):up();
if reason.text then
stanza:tag("text", stream_xmlns_attr):text(reason.text):up();
end
if reason.extra then
stanza:add_child(reason.extra);
end
module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(stanza));
session.send(stanza);
elseif reason.name then -- a stanza
module:log("info", "Disconnecting component, <stream:error> is: %s", tostring(reason));
session.send(reason);
end
end
end
session.send("</stream:stream>");
session.conn:close();
listener.ondisconnect(session.conn, "stream error");
end
end
function listener.onconnect(conn)
session = { type = "component_unauthed", conn = conn, send = function (data) return conn:write(tostring(data)); end, host = module.host };
-- Logging functions --
local conn_name = "jcp"..tostring(session):match("[a-f0-9]+$");
session.log = logger.init(conn_name);
session.close = session_close;
session.log("info", "Outgoing Jabber component connection");
local stream = new_xmpp_stream(session, stream_callbacks);
session.stream = stream;
function session.data(conn, data)
local ok, err = stream:feed(data);
if ok then return; end
module:log("debug", "Received invalid XML (%s) %d bytes: %s", tostring(err), #data, data:sub(1, 300):gsub("[\r\n]+", " "):gsub("[%z\1-\31]", "_"));
session:close("not-well-formed");
end
session.dispatch_stanza = stream_callbacks.handlestanza;
session.notopen = true;
session.send(st.stanza("stream:stream", {
to = session.host;
["xmlns:stream"] = 'http://etherx.jabber.org/streams';
xmlns = xmlns_component;
}):top_tag());
--sessions[conn] = session;
end
function listener.onincoming(conn, data)
--local session = sessions[conn];
session.data(conn, data);
end
function listener.ondisconnect(conn, err)
--local session = sessions[conn];
if session then
(session.log or log)("info", "component disconnected: %s (%s)", tostring(session.host), tostring(err));
if session.on_destroy then session:on_destroy(err); end
--sessions[conn] = nil;
for k in pairs(session) do
if k ~= "log" and k ~= "close" then
session[k] = nil;
end
end
session.destroyed = true;
session = nil;
end
__conn = nil;
module:log("error", "connection lost");
module:fire_event("component_client/disconnected", { reason = err });
if exit_on_disconnect and not prosody.shutdown_reason then
prosody.shutdown("Shutdown by component_client disconnect");
end
end
-- send whitespace keep-alive one an hour
if keepalive_interval ~= 0 then
module:add_timer(keepalive_interval, function()
if __conn then
__conn:write(" ");
end
return keepalive_interval;
end);
end
function connect()
------------------------
-- Taken from net.http
local conn = socket.tcp ( )
conn:settimeout ( 10 )
local ok, err = conn:connect ( server_host , server_port )
if not ok and err ~= "timeout" then
return nil, err;
end
local handler , conn = server.wrapclient ( conn , server_host , server_port , listener , "*a")
__conn = handler;
------------------------
return true;
end
local s, err = connect();
if not s then
listener.ondisconnect(nil, err);
end
module:hook_global("server-stopping", function(event)
local reason = event.reason;
if session then
session:close{ condition = "system-shutdown", text = reason };
end
end, 1000);
| mit |
ld-test/llui | src/xf86drm_ffi.lua | 4 | 21023 | --xf86drm.lua
local ffi = require("ffi")
local bit = require("bit")
local bor = bit.bor
local drm = require("drm")
local Lib_drm = drm.Lib_drm;
local stat = require("stat")()
ffi.cdef[[
typedef uint32_t gid_t;
typedef uint32_t mode_t;
]]
--[[
DRM_IOCTL_NR(n) _IOC_NR(n)
DRM_IOC_VOID _IOC_NONE
DRM_IOC_READ _IOC_READ
DRM_IOC_WRITE _IOC_WRITE
DRM_IOC_READWRITE _IOC_READ|_IOC_WRITE
DRM_IOC(dir, group, nr, size) _IOC(dir, group, nr, size)
--]]
ffi.cdef[[
typedef unsigned int drmSize, *drmSizePtr; /**< For mapped regions */
typedef void *drmAddress, **drmAddressPtr; /**< For mapped regions */
]]
ffi.cdef[[
typedef struct _drmServerInfo {
int (*debug_print)(const char *format, va_list ap);
int (*load_module)(const char *name);
void (*get_perms)(gid_t *, mode_t *);
} drmServerInfo, *drmServerInfoPtr;
typedef struct drmHashEntry {
int fd;
void (*f)(int, void *, void *);
void *tagTable;
} drmHashEntry;
]]
ffi.cdef[[
extern int drmIoctl(int fd, unsigned long request, void *arg);
extern void *drmGetHashTable(void);
extern drmHashEntry *drmGetEntry(int fd);
]]
ffi.cdef[[
/**
* Driver version information.
*
* \sa drmGetVersion() and drmSetVersion().
*/
typedef struct _drmVersion {
int version_major; /**< Major version */
int version_minor; /**< Minor version */
int version_patchlevel; /**< Patch level */
int name_len; /**< Length of name buffer */
char *name; /**< Name of driver */
int date_len; /**< Length of date buffer */
char *date; /**< User-space buffer to hold date */
int desc_len; /**< Length of desc buffer */
char *desc; /**< User-space buffer to hold desc */
} drmVersion, *drmVersionPtr;
]]
local drmVersion_mt = {
__tostring = function(self)
return string.format([[
Version: %d.%d.%d
Name: %s
Date: %s
Description: %s
]],
self.version_major,
self.version_minor,
self.version_patchlevel,
ffi.string(self.name, self.name_len),
ffi.string(self.date, self.date_len),
ffi.string(self.desc, self.desc_len)
)
end,
__index = {
toLua = function(self)
local tbl = {
Version = string.format("%d.%d.%d", self.version_major, self.version_minor, self.version_patchlevel);
Name = ffi.string(self.name, self.name_len);
Date = ffi.string(self.data, self.date_len);
Description = ffi.string(self.desc, self.desc_len);
}
return tbl;
end,
},
}
ffi.metatype(ffi.typeof("drmVersion"), drmVersion_mt)
ffi.cdef[[
typedef struct _drmStats {
unsigned long count; /**< Number of data */
struct {
unsigned long value; /**< Value from kernel */
const char *long_format; /**< Suggested format for long_name */
const char *long_name; /**< Long name for value */
const char *rate_format; /**< Suggested format for rate_name */
const char *rate_name; /**< Short name for value per second */
int isvalue; /**< True if value (vs. counter) */
const char *mult_names; /**< Multiplier names (e.g., "KGM") */
int mult; /**< Multiplier value (e.g., 1024) */
int verbose; /**< Suggest only in verbose output */
} data[15];
} drmStatsT;
]]
ffi.cdef[[
/* All of these enums *MUST* match with the
kernel implementation -- so do *NOT*
change them! (The drmlib implementation
will just copy the flags instead of
translating them.) */
typedef enum {
DRM_FRAME_BUFFER = 0, /**< WC, no caching, no core dump */
DRM_REGISTERS = 1, /**< no caching, no core dump */
DRM_SHM = 2, /**< shared, cached */
DRM_AGP = 3, /**< AGP/GART */
DRM_SCATTER_GATHER = 4, /**< PCI scatter/gather */
DRM_CONSISTENT = 5 /**< PCI consistent */
} drmMapType;
typedef enum {
DRM_RESTRICTED = 0x0001, /**< Cannot be mapped to client-virtual */
DRM_READ_ONLY = 0x0002, /**< Read-only in client-virtual */
DRM_LOCKED = 0x0004, /**< Physical pages locked */
DRM_KERNEL = 0x0008, /**< Kernel requires access */
DRM_WRITE_COMBINING = 0x0010, /**< Use write-combining, if available */
DRM_CONTAINS_LOCK = 0x0020, /**< SHM page that contains lock */
DRM_REMOVABLE = 0x0040 /**< Removable mapping */
} drmMapFlags;
]]
ffi.cdef[[
/**
* \warning These values *MUST* match drm.h
*/
typedef enum {
/** \name Flags for DMA buffer dispatch */
/*@{*/
DRM_DMA_BLOCK = 0x01, /**<
* Block until buffer dispatched.
*
* \note the buffer may not yet have been
* processed by the hardware -- getting a
* hardware lock with the hardware quiescent
* will ensure that the buffer has been
* processed.
*/
DRM_DMA_WHILE_LOCKED = 0x02, /**< Dispatch while lock held */
DRM_DMA_PRIORITY = 0x04, /**< High priority dispatch */
/*@}*/
/** \name Flags for DMA buffer request */
/*@{*/
DRM_DMA_WAIT = 0x10, /**< Wait for free buffers */
DRM_DMA_SMALLER_OK = 0x20, /**< Smaller-than-requested buffers OK */
DRM_DMA_LARGER_OK = 0x40 /**< Larger-than-requested buffers OK */
/*@}*/
} drmDMAFlags;
typedef enum {
DRM_PAGE_ALIGN = 0x01,
DRM_AGP_BUFFER = 0x02,
DRM_SG_BUFFER = 0x04,
DRM_FB_BUFFER = 0x08,
DRM_PCI_BUFFER_RO = 0x10
} drmBufDescFlags;
typedef enum {
DRM_LOCK_READY = 0x01, /**< Wait until hardware is ready for DMA */
DRM_LOCK_QUIESCENT = 0x02, /**< Wait until hardware quiescent */
DRM_LOCK_FLUSH = 0x04, /**< Flush this context's DMA queue first */
DRM_LOCK_FLUSH_ALL = 0x08, /**< Flush all DMA queues first */
/* These *HALT* flags aren't supported yet
-- they will be used to support the
full-screen DGA-like mode. */
DRM_HALT_ALL_QUEUES = 0x10, /**< Halt all current and future queues */
DRM_HALT_CUR_QUEUES = 0x20 /**< Halt all current queues */
} drmLockFlags;
typedef enum {
DRM_CONTEXT_PRESERVED = 0x01, /**< This context is preserved and
never swapped. */
DRM_CONTEXT_2DONLY = 0x02 /**< This context is for 2D rendering only. */
} drm_context_tFlags, *drm_context_tFlagsPtr;
]]
ffi.cdef[[
typedef struct _drmBufDesc {
int count; /**< Number of buffers of this size */
int size; /**< Size in bytes */
int low_mark; /**< Low water mark */
int high_mark; /**< High water mark */
} drmBufDesc, *drmBufDescPtr;
typedef struct _drmBufInfo {
int count; /**< Number of buffers described in list */
drmBufDescPtr list; /**< List of buffer descriptions */
} drmBufInfo, *drmBufInfoPtr;
typedef struct _drmBuf {
int idx; /**< Index into the master buffer list */
int total; /**< Buffer size */
int used; /**< Amount of buffer in use (for DMA) */
drmAddress address; /**< Address */
} drmBuf, *drmBufPtr;
]]
ffi.cdef[[
/**
* Buffer mapping information.
*
* Used by drmMapBufs() and drmUnmapBufs() to store information about the
* mapped buffers.
*/
typedef struct _drmBufMap {
int count; /**< Number of buffers mapped */
drmBufPtr list; /**< Buffers */
} drmBufMap, *drmBufMapPtr;
typedef struct _drmLock {
volatile unsigned int lock;
char padding[60];
/* This is big enough for most current (and future?) architectures:
DEC Alpha: 32 bytes
Intel Merced: ?
Intel P5/PPro/PII/PIII: 32 bytes
Intel StrongARM: 32 bytes
Intel i386/i486: 16 bytes
MIPS: 32 bytes (?)
Motorola 68k: 16 bytes
Motorola PowerPC: 32 bytes
Sun SPARC: 32 bytes
*/
} drmLock, *drmLockPtr;
]]
ffi.cdef[[
/**
* Indices here refer to the offset into
* list in drmBufInfo
*/
typedef struct _drmDMAReq {
drm_context_t context; /**< Context handle */
int send_count; /**< Number of buffers to send */
int *send_list; /**< List of handles to buffers */
int *send_sizes; /**< Lengths of data to send, in bytes */
drmDMAFlags flags; /**< Flags */
int request_count; /**< Number of buffers requested */
int request_size; /**< Desired size of buffers requested */
int *request_list; /**< Buffer information */
int *request_sizes; /**< Minimum acceptable sizes */
int granted_count; /**< Number of buffers granted at this size */
} drmDMAReq, *drmDMAReqPtr;
typedef struct _drmRegion {
drm_handle_t handle;
unsigned int offset;
drmSize size;
drmAddress map;
} drmRegion, *drmRegionPtr;
typedef struct _drmTextureRegion {
unsigned char next;
unsigned char prev;
unsigned char in_use;
unsigned char padding; /**< Explicitly pad this out */
unsigned int age;
} drmTextureRegion, *drmTextureRegionPtr;
]]
ffi.cdef[[
typedef enum {
DRM_VBLANK_ABSOLUTE = 0x0, /**< Wait for specific vblank sequence number */
DRM_VBLANK_RELATIVE = 0x1, /**< Wait for given number of vblanks */
/* bits 1-6 are reserved for high crtcs */
DRM_VBLANK_HIGH_CRTC_MASK = 0x0000003e,
DRM_VBLANK_EVENT = 0x4000000, /**< Send event instead of blocking */
DRM_VBLANK_FLIP = 0x8000000, /**< Scheduled buffer swap should flip */
DRM_VBLANK_NEXTONMISS = 0x10000000, /**< If missed, wait for next vblank */
DRM_VBLANK_SECONDARY = 0x20000000, /**< Secondary display controller */
DRM_VBLANK_SIGNAL = 0x40000000 /* Send signal instead of blocking */
} drmVBlankSeqType;
]]
ffi.cdef[[
typedef struct _drmVBlankReq {
drmVBlankSeqType type;
unsigned int sequence;
unsigned long signal;
} drmVBlankReq, *drmVBlankReqPtr;
typedef struct _drmVBlankReply {
drmVBlankSeqType type;
unsigned int sequence;
long tval_sec;
long tval_usec;
} drmVBlankReply, *drmVBlankReplyPtr;
typedef union _drmVBlank {
drmVBlankReq request;
drmVBlankReply reply;
} drmVBlank, *drmVBlankPtr;
typedef struct _drmSetVersion {
int drm_di_major;
int drm_di_minor;
int drm_dd_major;
int drm_dd_minor;
} drmSetVersion, *drmSetVersionPtr;
]]
ffi.cdef[[
/* General user-level programmers API: unprivileged */
extern int drmAvailable(void);
extern int drmOpen(const char *name, const char *busid);
]]
ffi.cdef[[
extern int drmOpenWithType(const char *name, const char *busid,
int type);
extern int drmOpenControl(int minor);
extern int drmOpenRender(int minor);
extern int drmClose(int fd);
extern drmVersionPtr drmGetVersion(int fd);
extern drmVersionPtr drmGetLibVersion(int fd);
extern int drmGetCap(int fd, uint64_t capability, uint64_t *value);
extern void drmFreeVersion(drmVersionPtr);
extern int drmGetMagic(int fd, drm_magic_t * magic);
extern char *drmGetBusid(int fd);
extern int drmGetInterruptFromBusID(int fd, int busnum, int devnum,
int funcnum);
extern int drmGetMap(int fd, int idx, drm_handle_t *offset,
drmSize *size, drmMapType *type,
drmMapFlags *flags, drm_handle_t *handle,
int *mtrr);
extern int drmGetClient(int fd, int idx, int *auth, int *pid,
int *uid, unsigned long *magic,
unsigned long *iocs);
extern int drmGetStats(int fd, drmStatsT *stats);
extern int drmSetInterfaceVersion(int fd, drmSetVersion *version);
extern int drmCommandNone(int fd, unsigned long drmCommandIndex);
extern int drmCommandRead(int fd, unsigned long drmCommandIndex,
void *data, unsigned long size);
extern int drmCommandWrite(int fd, unsigned long drmCommandIndex,
void *data, unsigned long size);
extern int drmCommandWriteRead(int fd, unsigned long drmCommandIndex,
void *data, unsigned long size);
]]
ffi.cdef[[
/* General user-level programmer's API: X server (root) only */
extern void drmFreeBusid(const char *busid);
extern int drmSetBusid(int fd, const char *busid);
extern int drmAuthMagic(int fd, drm_magic_t magic);
extern int drmAddMap(int fd,
drm_handle_t offset,
drmSize size,
drmMapType type,
drmMapFlags flags,
drm_handle_t * handle);
extern int drmRmMap(int fd, drm_handle_t handle);
extern int drmAddContextPrivateMapping(int fd, drm_context_t ctx_id,
drm_handle_t handle);
extern int drmAddBufs(int fd, int count, int size,
drmBufDescFlags flags,
int agp_offset);
extern int drmMarkBufs(int fd, double low, double high);
extern int drmCreateContext(int fd, drm_context_t * handle);
extern int drmSetContextFlags(int fd, drm_context_t context,
drm_context_tFlags flags);
extern int drmGetContextFlags(int fd, drm_context_t context,
drm_context_tFlagsPtr flags);
extern int drmAddContextTag(int fd, drm_context_t context, void *tag);
extern int drmDelContextTag(int fd, drm_context_t context);
extern void *drmGetContextTag(int fd, drm_context_t context);
extern drm_context_t * drmGetReservedContextList(int fd, int *count);
extern void drmFreeReservedContextList(drm_context_t *);
extern int drmSwitchToContext(int fd, drm_context_t context);
extern int drmDestroyContext(int fd, drm_context_t handle);
extern int drmCreateDrawable(int fd, drm_drawable_t * handle);
extern int drmDestroyDrawable(int fd, drm_drawable_t handle);
extern int drmUpdateDrawableInfo(int fd, drm_drawable_t handle,
drm_drawable_info_type_t type,
unsigned int num, void *data);
extern int drmCtlInstHandler(int fd, int irq);
extern int drmCtlUninstHandler(int fd);
extern int drmSetClientCap(int fd, uint64_t capability,
uint64_t value);
]]
ffi.cdef[[
/* General user-level programmer's API: authenticated client and/or X */
extern int drmMap(int fd,
drm_handle_t handle,
drmSize size,
drmAddressPtr address);
extern int drmUnmap(drmAddress address, drmSize size);
extern drmBufInfoPtr drmGetBufInfo(int fd);
extern drmBufMapPtr drmMapBufs(int fd);
extern int drmUnmapBufs(drmBufMapPtr bufs);
extern int drmDMA(int fd, drmDMAReqPtr request);
extern int drmFreeBufs(int fd, int count, int *list);
extern int drmGetLock(int fd,
drm_context_t context,
drmLockFlags flags);
extern int drmUnlock(int fd, drm_context_t context);
extern int drmFinish(int fd, int context, drmLockFlags flags);
extern int drmGetContextPrivateMapping(int fd, drm_context_t ctx_id,
drm_handle_t * handle);
]]
ffi.cdef[[
/* AGP/GART support: X server (root) only */
extern int drmAgpAcquire(int fd);
extern int drmAgpRelease(int fd);
extern int drmAgpEnable(int fd, unsigned long mode);
extern int drmAgpAlloc(int fd, unsigned long size,
unsigned long type, unsigned long *address,
drm_handle_t *handle);
extern int drmAgpFree(int fd, drm_handle_t handle);
extern int drmAgpBind(int fd, drm_handle_t handle,
unsigned long offset);
extern int drmAgpUnbind(int fd, drm_handle_t handle);
]]
ffi.cdef[[
/* AGP/GART info: authenticated client and/or X */
extern int drmAgpVersionMajor(int fd);
extern int drmAgpVersionMinor(int fd);
extern unsigned long drmAgpGetMode(int fd);
extern unsigned long drmAgpBase(int fd); /* Physical location */
extern unsigned long drmAgpSize(int fd); /* Bytes */
extern unsigned long drmAgpMemoryUsed(int fd);
extern unsigned long drmAgpMemoryAvail(int fd);
extern unsigned int drmAgpVendorId(int fd);
extern unsigned int drmAgpDeviceId(int fd);
]]
ffi.cdef[[
/* PCI scatter/gather support: X server (root) only */
extern int drmScatterGatherAlloc(int fd, unsigned long size,
drm_handle_t *handle);
extern int drmScatterGatherFree(int fd, drm_handle_t handle);
extern int drmWaitVBlank(int fd, drmVBlankPtr vbl);
]]
ffi.cdef[[
/* Support routines */
extern void drmSetServerInfo(drmServerInfoPtr info);
extern int drmError(int err, const char *label);
extern void *drmMalloc(int size);
extern void drmFree(void *pt);
]]
ffi.cdef[[
/* Hash table routines */
extern void *drmHashCreate(void);
extern int drmHashDestroy(void *t);
extern int drmHashLookup(void *t, unsigned long key, void **value);
extern int drmHashInsert(void *t, unsigned long key, void *value);
extern int drmHashDelete(void *t, unsigned long key);
extern int drmHashFirst(void *t, unsigned long *key, void **value);
extern int drmHashNext(void *t, unsigned long *key, void **value);
]]
ffi.cdef[[
/* PRNG routines */
extern void *drmRandomCreate(unsigned long seed);
extern int drmRandomDestroy(void *state);
extern unsigned long drmRandom(void *state);
extern double drmRandomDouble(void *state);
]]
ffi.cdef[[
/* Skip list routines */
extern void *drmSLCreate(void);
extern int drmSLDestroy(void *l);
extern int drmSLLookup(void *l, unsigned long key, void **value);
extern int drmSLInsert(void *l, unsigned long key, void *value);
extern int drmSLDelete(void *l, unsigned long key);
extern int drmSLNext(void *l, unsigned long *key, void **value);
extern int drmSLFirst(void *l, unsigned long *key, void **value);
extern void drmSLDump(void *l);
extern int drmSLLookupNeighbors(void *l, unsigned long key,
unsigned long *prev_key, void **prev_value,
unsigned long *next_key, void **next_value);
]]
ffi.cdef[[
extern int drmOpenOnce(void *unused, const char *BusID, int *newlyopened);
extern int drmOpenOnceWithType(const char *BusID, int *newlyopened, int type);
extern void drmCloseOnce(int fd);
extern void drmMsg(const char *format, ...);
extern int drmSetMaster(int fd);
extern int drmDropMaster(int fd);
]]
ffi.cdef[[
typedef struct _drmEventContext {
/* This struct is versioned so we can add more pointers if we
* add more events. */
int version;
void (*vblank_handler)(int fd,
unsigned int sequence,
unsigned int tv_sec,
unsigned int tv_usec,
void *user_data);
void (*page_flip_handler)(int fd,
unsigned int sequence,
unsigned int tv_sec,
unsigned int tv_usec,
void *user_data);
} drmEventContext, *drmEventContextPtr;
extern int drmHandleEvent(int fd, drmEventContextPtr evctx);
extern char *drmGetDeviceNameFromFd(int fd);
extern int drmGetNodeTypeFromFd(int fd);
extern int drmPrimeHandleToFD(int fd, uint32_t handle, uint32_t flags, int *prime_fd);
extern int drmPrimeFDToHandle(int fd, int prime_fd, uint32_t *handle);
extern char *drmGetPrimaryDeviceNameFromFd(int fd);
extern char *drmGetRenderDeviceNameFromFd(int fd);
]]
local exports = {
Lib_drm = Lib_drm;
-- constants
DRM_MAX_MINOR = 16;
-- Defaults, if nothing set in xf86config
DRM_DEV_UID =0;
DRM_DEV_GID =0;
-- Default /dev/dri directory permissions 0755
DRM_DEV_DIRMODE = bor(S_IRUSR,S_IWUSR,S_IXUSR,S_IRGRP,S_IXGRP,S_IROTH,S_IXOTH);
DRM_DEV_MODE = bor(S_IRUSR,S_IWUSR,S_IRGRP,S_IWGRP,S_IROTH,S_IWOTH);
DRM_DIR_NAME ="/dev/dri";
DRM_DEV_NAME ="%s/card%d";
DRM_CONTROL_DEV_NAME ="%s/controlD%d";
DRM_RENDER_DEV_NAME ="%s/renderD%d";
-- DRM_PROC_NAME "/proc/dri/" -- For backward Linux compatibility
DRM_ERR_NO_DEVICE = -1001;
DRM_ERR_NO_ACCESS = -1002;
DRM_ERR_NOT_ROOT = -1003;
DRM_ERR_INVALID = -1004;
DRM_ERR_NO_FD = -1005;
DRM_AGP_NO_HANDLE =0;
DRM_VBLANK_HIGH_CRTC_SHIFT = 1;
DRM_NODE_PRIMARY = 0;
DRM_NODE_CONTROL = 1;
DRM_NODE_RENDER = 2;
DRM_EVENT_CONTEXT_VERSION = 2;
-- Library functions
drmAvailable = Lib_drm.drmAvailable;
drmFreeVersion = Lib_drm.drmFreeVersion;
drmGetBusid = Lib_drm.drmGetBusid;
drmGetCap = Lib_drm.drmGetCap;
drmGetLibVersion = Lib_drm.drmGetLibVersion;
drmGetStats = Lib_drm.drmGetStats;
drmGetVersion = Lib_drm.drmGetVersion;
drmIoctl = Lib_drm.drmIoctl;
drmOpen = Lib_drm.drmOpen;
}
setmetatable(exports, {
__call = function(self, tbl)
tbl = tbl or _G
for k,v in pairs(exports) do
tbl[k] = v;
end
drm(tbl);
return self;
end,
})
return exports
| mit |
Sweet-kid/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 |
indexTM/index | plugins/filterworld.lua | 1 | 4170 | local function save_filter(msg, name, value)
local hash = nil
if msg.to.type == 'chat' then
hash = 'chat:'..msg.to.id..':filters'
end
if msg.to.type == 'user' then
return 'فقط در گروه ممکن است'
end
if hash then
redis:hset(hash, name, value)
return "انجام شد"
end
end
local function get_filter_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':filters'
end
end
local function list_filter(msg)
if msg.to.type == 'user' then
return 'فقط در گروه'
end
local hash = get_filter_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = 'لیست کلمات فیلتر شده:\n______________________________\n'
for i=1, #names do
text = text..'> '..names[i]..'\n'
end
return text
end
end
local function get_filter(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'کلمه ی کاربردی شما ممنوع است، در صورت تکرار با شما برخورد خواهد شد'
elseif value == 'kick' then
send_large_msg('chat#id'..msg.to.id, "به دلیل عدم رعایت قوانین گفتاری از ادامه ی گفتوگو محروم میشوید")
chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true)
end
end
end
local function get_filter_act(msg, var_name)
local hash = get_filter_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if value == 'msg' then
return 'اخطار و تذکر به این کلمه'
elseif value == 'kick' then
return 'این کلمه ممنوع است و حذف خواهید شد'
elseif value == 'none' then
return 'این کلمه از فیلتر خارج شده است'
end
end
end
local function run(msg, matches)
local data = load_data(_config.moderation.data)
if matches[1] == "ilterlist" then
return list_filter(msg)
elseif matches[1] == "ilter" and matches[2] == ">" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'msg'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "+" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'kick'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "-" then
if data[tostring(msg.to.id)] then
local settings = data[tostring(msg.to.id)]['settings']
if not is_momod(msg) then
return "َشما دسترسی ندارید"
else
local value = 'none'
local name = string.sub(matches[3]:lower(), 1, 1000)
local text = save_filter(msg, name, value)
return text
end
end
elseif matches[1] == "ilter" and matches[2] == "?" then
return get_filter_act(msg, matches[3]:lower())
else
if is_sudo(msg) then
return
elseif is_admin(msg) then
return
elseif is_momod(msg) then
return
elseif tonumber(msg.from.id) == tonumber(our_id) then
return
else
return get_filter(msg, msg.text:lower())
end
end
end
return {
description = "Set and Get Variables",
usage = {
user = {
"filter ? (word) : مشاهده عکس العمل",
"filterlist : لیست فیلتر شده ها",
},
moderator = {
"filter > (word) : اخطار کردن لغت",
"filter + (word) : ممنوع کردن لغت",
"filter - (word) : حذف از فیلتر",
},
},
patterns = {
"^[/!][Ff](ilter) (.+) (.*)$",
"^[/!][Ff](ilterlist)$",
"(.*)",
},
run = run
}
| gpl-2.0 |
Minefix/MineFix | mods/mfbase/default/mapgen.lua | 4 | 29629 | --
-- Aliases for map generator outputs
--
minetest.register_alias("mapgen_stone", "default:stone")
minetest.register_alias("mapgen_dirt", "default:dirt")
minetest.register_alias("mapgen_dirt_with_grass", "default:dirt_with_grass")
minetest.register_alias("mapgen_sand", "default:sand")
minetest.register_alias("mapgen_water_source", "default:water_source")
minetest.register_alias("mapgen_river_water_source", "default:water_source")
minetest.register_alias("mapgen_lava_source", "default:lava_source")
minetest.register_alias("mapgen_gravel", "default:gravel")
minetest.register_alias("mapgen_dirt_with_snow", "default:dirt_with_snow")
minetest.register_alias("mapgen_snowblock", "default:snowblock")
minetest.register_alias("mapgen_snow", "default:snow")
minetest.register_alias("mapgen_ice", "default:ice")
minetest.register_alias("mapgen_sandstone", "default:sandstone")
-- Flora
minetest.register_alias("mapgen_tree", "default:wood_oak")
minetest.register_alias("mapgen_leaves", "default:leaves_oak")
minetest.register_alias("mapgen_jungletree", "default:wood_jungle")
minetest.register_alias("mapgen_jungleleaves", "default:leaves_jungle")
minetest.register_alias("mapgen_junglegrass", "default:junglegrass")
minetest.register_alias("mapgen_pine_tree", "default:wood_spruce")
minetest.register_alias("mapgen_pine_needles", "default:leaves_spruce")
-- Dungeons
minetest.register_alias("mapgen_cobble", "default:cobblestone")
minetest.register_alias("mapgen_stair_cobble", "stairs:stair_cobble")
minetest.register_alias("mapgen_mossycobble", "default:cobblestone_mossy")
minetest.register_alias("mapgen_sandstonebrick", "default:sandstonebrick")
minetest.register_alias("mapgen_stair_sandstonebrick", "stairs:stair_sandstonebrick")
--
-- Register ores
--
function default.register_ores()
-- Blob ores
-- These first to avoid other ores in blobs
-- Clay
-- This first to avoid clay in sand blobs
minetest.register_ore({
ore_type = "blob",
ore = "default:clayblock",
wherein = {"default:sand"},
clust_scarcity = 16 * 16 * 16,
clust_size = 5,
y_min = -15,
y_max = 0,
noise_threshold = 0.0,
noise_params = {
offset = 0.5,
scale = 0.2,
spread = {x = 5, y = 5, z = 5},
seed = -316,
octaves = 1,
persist = 0.0
},
})
-- Sand
minetest.register_ore({
ore_type = "blob",
ore = "default:sand",
wherein = {"default:stone", "default:sandstone"},
clust_scarcity = 16 * 16 * 16,
clust_size = 5,
y_min = -31,
y_max = 0,
noise_threshold = 0.0,
noise_params = {
offset = 0.5,
scale = 0.2,
spread = {x = 5, y = 5, z = 5},
seed = 2316,
octaves = 1,
persist = 0.0
},
})
-- Dirt
minetest.register_ore({
ore_type = "blob",
ore = "default:dirt",
wherein = {"default:stone"},
clust_scarcity = 16 * 16 * 16,
clust_size = 5,
y_min = -31,
y_max = 31000,
noise_threshold = 0.0,
noise_params = {
offset = 0.5,
scale = 0.2,
spread = {x = 5, y = 5, z = 5},
seed = 17676,
octaves = 1,
persist = 0.0
},
})
-- Gravel
minetest.register_ore({
ore_type = "blob",
ore = "default:gravel",
wherein = {"default:stone"},
clust_scarcity = 16 * 16 * 16,
clust_size = 5,
y_min = -31000,
y_max = 31000,
noise_threshold = 0.0,
noise_params = {
offset = 0.5,
scale = 0.2,
spread = {x = 5, y = 5, z = 5},
seed = 766,
octaves = 1,
persist = 0.0
},
})
-- Scatter ores
-- Coal
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_coal",
wherein = "default:stone",
clust_scarcity = 8 * 8 * 8,
clust_num_ores = 9,
clust_size = 3,
y_min = 1025,
y_max = 31000,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_coal",
wherein = "default:stone",
clust_scarcity = 8 * 8 * 8,
clust_num_ores = 8,
clust_size = 3,
y_min = -31000,
y_max = 64,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_coal",
wherein = "default:stone",
clust_scarcity = 24 * 24 * 24,
clust_num_ores = 27,
clust_size = 6,
y_min = -31000,
y_max = 0,
})
-- Iron
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 9 * 9 * 9,
clust_num_ores = 12,
clust_size = 3,
y_min = 1025,
y_max = 31000,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 7 * 7 * 7,
clust_num_ores = 5,
clust_size = 3,
y_min = -31000,
y_max = 0,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_iron",
wherein = "default:stone",
clust_scarcity = 24 * 24 * 24,
clust_num_ores = 27,
clust_size = 6,
y_min = -31000,
y_max = -64,
})
-- Gold
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_gold",
wherein = "default:stone",
clust_scarcity = 13 * 13 * 13,
clust_num_ores = 5,
clust_size = 3,
y_min = 1025,
y_max = 31000,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_gold",
wherein = "default:stone",
clust_scarcity = 15 * 15 * 15,
clust_num_ores = 3,
clust_size = 2,
y_min = -255,
y_max = -64,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_gold",
wherein = "default:stone",
clust_scarcity = 13 * 13 * 13,
clust_num_ores = 5,
clust_size = 3,
y_min = -31000,
y_max = -256,
})
-- Diamond
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_diamond",
wherein = "default:stone",
clust_scarcity = 15 * 15 * 15,
clust_num_ores = 4,
clust_size = 3,
y_min = 1025,
y_max = 31000,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_diamond",
wherein = "default:stone",
clust_scarcity = 17 * 17 * 17,
clust_num_ores = 4,
clust_size = 3,
y_min = -255,
y_max = -128,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_diamond",
wherein = "default:stone",
clust_scarcity = 15 * 15 * 15,
clust_num_ores = 4,
clust_size = 3,
y_min = -31000,
y_max = -256,
})
-- Lapis
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_lapis",
wherein = "default:stone",
clust_scarcity = 15 * 15 * 15,
clust_num_ores = 5,
clust_size = 3,
y_min = 1025,
y_max = 31000,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_lapis",
wherein = "default:stone",
clust_scarcity = 17 * 17 * 17,
clust_num_ores = 5,
clust_size = 3,
y_min = -31,
y_max = -255,
})
minetest.register_ore({
ore_type = "scatter",
ore = "default:stone_with_lapis",
wherein = "default:stone",
clust_scarcity = 16 * 16 * 16,
clust_num_ores = 5,
clust_size = 3,
y_min = -31000,
y_max = -256,
})
minetest.register_ore({
ore_type = "blob",
ore = "default:andesite",
wherein = {"default:stone"},
clust_scarcity= 16 * 16 * 16,
clust_size = 5,
y_min = -31000,
y_max = 31000,
});
minetest.register_ore({
ore_type = "blob",
ore = "default:diorite",
wherein = {"default:stone"},
clust_scarcity= 16 * 16 * 16,
clust_size = 5,
y_min = -31000,
y_max = 31000,
});
minetest.register_ore({
ore_type = "blob",
ore = "default:granite",
wherein = {"default:stone"},
clust_scarcity= 16 * 16 * 16,
clust_size = 5,
y_min = -31000,
y_max = 31000,
});
end
--
-- Register biomes
--
-- All mapgens except mgv6 and singlenode
function default.register_biomes()
minetest.clear_registered_biomes()
-- Permanent ice
minetest.register_biome({
name = "glacier",
node_dust = "default:snowblock",
node_top = "default:snowblock",
depth_top = 1,
node_filler = "default:snowblock",
depth_filler = 3,
node_stone = "default:ice",
node_water_top = "default:ice",
depth_water_top = 10,
--node_water = "",
node_river_water = "default:ice",
node_riverbed = "default:gravel",
depth_riverbed = 2,
y_min = -8,
y_max = 31000,
heat_point = 0,
humidity_point = 50,
})
minetest.register_biome({
name = "glacier_ocean",
node_dust = "default:snowblock",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
y_min = -112,
y_max = -9,
heat_point = 0,
humidity_point = 50,
})
-- Cold
minetest.register_biome({
name = "tundra",
--node_dust = "",
node_top = "default:dirt_with_snow",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 1,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:gravel",
depth_riverbed = 2,
y_min = 2,
y_max = 31000,
heat_point = 15,
humidity_point = 35,
})
minetest.register_biome({
name = "tundra_beach",
--node_dust = "",
node_top = "default:gravel",
depth_top = 1,
node_filler = "default:gravel",
depth_filler = 2,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:gravel",
depth_riverbed = 2,
y_min = -3,
y_max = 1,
heat_point = 15,
humidity_point = 35,
})
minetest.register_biome({
name = "tundra_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:gravel",
depth_riverbed = 2,
y_min = -112,
y_max = -4,
heat_point = 15,
humidity_point = 35,
})
minetest.register_biome({
name = "taiga",
node_dust = "default:snow",
node_top = "default:dirt_with_snow",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 2,
y_max = 31000,
heat_point = 15,
humidity_point = 65,
})
minetest.register_biome({
name = "taiga_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = 1,
heat_point = 15,
humidity_point = 65,
})
-- Temperate
minetest.register_biome({
name = "stone_grassland",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 1,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 6,
y_max = 31000,
heat_point = 40,
humidity_point = 35,
})
minetest.register_biome({
name = "stone_grassland_dunes",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 2,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 5,
y_max = 5,
heat_point = 40,
humidity_point = 35,
})
minetest.register_biome({
name = "stone_grassland_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = 4,
heat_point = 40,
humidity_point = 35,
})
minetest.register_biome({
name = "coniferous_forest",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 6,
y_max = 31000,
heat_point = 40,
humidity_point = 65,
})
minetest.register_biome({
name = "coniferous_forest_dunes",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 5,
y_max = 5,
heat_point = 40,
humidity_point = 65,
})
minetest.register_biome({
name = "coniferous_forest_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = 4,
heat_point = 40,
humidity_point = 65,
})
minetest.register_biome({
name = "sandstone_grassland",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 1,
node_stone = "default:sandstone",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 6,
y_max = 31000,
heat_point = 60,
humidity_point = 35,
})
minetest.register_biome({
name = "sandstone_grassland_dunes",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 2,
node_stone = "default:sandstone",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 5,
y_max = 5,
heat_point = 60,
humidity_point = 35,
})
minetest.register_biome({
name = "sandstone_grassland_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
node_stone = "default:sandstone",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = 4,
heat_point = 60,
humidity_point = 35,
})
minetest.register_biome({
name = "deciduous_forest",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 1,
y_max = 31000,
heat_point = 60,
humidity_point = 65,
})
minetest.register_biome({
name = "deciduous_forest_swamp",
--node_dust = "",
node_top = "default:dirt",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -3,
y_max = 0,
heat_point = 60,
humidity_point = 65,
})
minetest.register_biome({
name = "deciduous_forest_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = -4,
heat_point = 60,
humidity_point = 65,
})
-- Hot
minetest.register_biome({
name = "desert",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 1,
node_stone = "default:sandstone",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 5,
y_max = 31000,
heat_point = 85,
humidity_point = 20,
})
minetest.register_biome({
name = "desert_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
node_stone = "default:sandstone",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = 4,
heat_point = 85,
humidity_point = 20,
})
minetest.register_biome({
name = "savanna",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 1,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 1,
y_max = 31000,
heat_point = 85,
humidity_point = 50,
})
minetest.register_biome({
name = "savanna_swamp",
--node_dust = "",
node_top = "default:dirt",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -3,
y_max = 0,
heat_point = 85,
humidity_point = 50,
})
minetest.register_biome({
name = "savanna_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = -4,
heat_point = 85,
humidity_point = 50,
})
minetest.register_biome({
name = "rainforest",
--node_dust = "",
node_top = "default:dirt_with_grass",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = 1,
y_max = 31000,
heat_point = 85,
humidity_point = 80,
})
minetest.register_biome({
name = "rainforest_swamp",
--node_dust = "",
node_top = "default:dirt",
depth_top = 1,
node_filler = "default:dirt",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -3,
y_max = 0,
heat_point = 85,
humidity_point = 80,
})
minetest.register_biome({
name = "rainforest_ocean",
--node_dust = "",
node_top = "default:sand",
depth_top = 1,
node_filler = "default:sand",
depth_filler = 3,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
node_riverbed = "default:sand",
depth_riverbed = 2,
y_min = -112,
y_max = -4,
heat_point = 85,
humidity_point = 80,
})
-- Underground
minetest.register_biome({
name = "underground",
--node_dust = "",
--node_top = "",
--depth_top = ,
--node_filler = "",
--depth_filler = ,
--node_stone = "",
--node_water_top = "",
--depth_water_top = ,
--node_water = "",
--node_river_water = "",
y_min = -31000,
y_max = -113,
heat_point = 50,
humidity_point = 50,
})
end
--
-- Register decorations
--
-- Mgv6
function default.register_mgv6_decorations()
minetest.clear_registered_decorations()
-- Long grasses
for length = 1, 5 do
minetest.register_decoration({
deco_type = "simple",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0,
scale = 0.007,
spread = {x = 100, y = 100, z = 100},
seed = 329,
octaves = 3,
persist = 0.6
},
y_min = 1,
y_max = 30,
decoration = "default:grass_"..length,
})
end
-- Dry shrubs
minetest.register_decoration({
deco_type = "simple",
place_on = {"default:sand", "default:dirt_with_snow"},
sidelen = 16,
noise_params = {
offset = 0,
scale = 0.035,
spread = {x = 100, y = 100, z = 100},
seed = 329,
octaves = 3,
persist = 0.6
},
y_min = 1,
y_max = 30,
decoration = "default:dry_shrub",
})
end
-- All mapgens except mgv6 and singlenode
local function register_grass_decoration(offset, scale, length)
minetest.register_decoration({
deco_type = "simple",
place_on = {"default:dirt_with_grass", "default:sand"},
sidelen = 16,
noise_params = {
offset = offset,
scale = scale,
spread = {x = 200, y = 200, z = 200},
seed = 329,
octaves = 3,
persist = 0.6
},
biomes = {"stone_grassland", "sandstone_grassland",
"deciduous_forest", "coniferous_forest",
"stone_grassland_dunes", "sandstone_grassland_dunes",
"coniferous_forest_dunes"},
y_min = 1,
y_max = 31000,
decoration = "default:grass_"..length,
})
end
function default.register_decorations()
minetest.clear_registered_decorations()
-- Apple tree and log
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0.036,
scale = 0.022,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"deciduous_forest"},
y_min = 1,
y_max = 31000,
schematic = minetest.get_modpath("default").."/schematics/apple_tree.mts",
flags = "place_center_x, place_center_z",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0.0018,
scale = 0.0011,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"deciduous_forest"},
y_min = 1,
y_max = 31000,
schematic = {
size = {x = 3, y = 3, z = 1},
data = {
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "default:tree", param2 = 12, prob = 191},
{name = "default:tree", param2 = 12},
{name = "default:tree", param2 = 12, prob = 127},
{name = "air", prob = 0},
{name = "flowers:mushroom_brown", prob = 63},
{name = "air", prob = 0},
},
},
flags = "place_center_x",
rotation = "random",
})
-- Jungle tree and log
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass", "default:dirt"},
sidelen = 80,
fill_ratio = 0.1,
biomes = {"rainforest", "rainforest_swamp"},
y_min = 0,
y_max = 31000,
schematic = minetest.get_modpath("default").."/schematics/jungle_tree.mts",
flags = "place_center_x, place_center_z",
rotation = "random",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass", "default:dirt"},
sidelen = 80,
fill_ratio = 0.005,
biomes = {"rainforest", "rainforest_swamp"},
y_min = 1,
y_max = 31000,
schematic = {
size = {x = 3, y = 3, z = 1},
data = {
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "default:jungletree", param2 = 12, prob = 191},
{name = "default:jungletree", param2 = 12},
{name = "default:jungletree", param2 = 12, prob = 127},
{name = "air", prob = 0},
{name = "flowers:mushroom_brown", prob = 127},
{name = "air", prob = 0},
},
},
flags = "place_center_x",
rotation = "random",
})
-- Taiga and temperate coniferous forest pine tree and log
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_snow", "default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0.036,
scale = 0.022,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"taiga", "coniferous_forest"},
y_min = 2,
y_max = 31000,
schematic = minetest.get_modpath("default").."/schematics/pine_tree.mts",
flags = "place_center_x, place_center_z",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_snow", "default:dirt_with_grass"},
sidelen = 80,
noise_params = {
offset = 0.0018,
scale = 0.0011,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"taiga", "coniferous_forest"},
y_min = 1,
y_max = 31000,
schematic = {
size = {x = 3, y = 3, z = 1},
data = {
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "default:pine_tree", param2 = 12, prob = 191},
{name = "default:pine_tree", param2 = 12},
{name = "default:pine_tree", param2 = 12, prob = 127},
{name = "air", prob = 0},
{name = "flowers:mushroom_red", prob = 63},
{name = "air", prob = 0},
},
},
flags = "place_center_x",
rotation = "random",
})
-- Acacia tree and log
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0,
scale = 0.002,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"savanna"},
y_min = 1,
y_max = 31000,
schematic = minetest.get_modpath("default").."/schematics/acacia_tree.mts",
flags = "place_center_x, place_center_z",
rotation = "random",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0,
scale = 0.001,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"savanna"},
y_min = 1,
y_max = 31000,
schematic = {
size = {x = 3, y = 2, z = 1},
data = {
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "default:acacia_tree", param2 = 12, prob = 191},
{name = "default:acacia_tree", param2 = 12},
{name = "default:acacia_tree", param2 = 12, prob = 127},
},
},
flags = "place_center_x",
rotation = "random",
})
-- Aspen tree and log
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0.0,
scale = -0.015,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"deciduous_forest"},
y_min = 1,
y_max = 31000,
schematic = minetest.get_modpath("default").."/schematics/aspen_tree.mts",
flags = "place_center_x, place_center_z",
})
minetest.register_decoration({
deco_type = "schematic",
place_on = {"default:dirt_with_grass"},
sidelen = 16,
noise_params = {
offset = 0.0,
scale = -0.0008,
spread = {x = 250, y = 250, z = 250},
seed = 2,
octaves = 3,
persist = 0.66
},
biomes = {"deciduous_forest"},
y_min = 1,
y_max = 31000,
schematic = {
size = {x = 3, y = 3, z = 1},
data = {
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "air", prob = 0},
{name = "default:aspen_tree", param2 = 12},
{name = "default:aspen_tree", param2 = 12},
{name = "default:aspen_tree", param2 = 12, prob = 127},
{name = "flowers:mushroom_red", prob = 63},
{name = "flowers:mushroom_brown", prob = 63},
{name = "air", prob = 0},
},
},
flags = "place_center_x",
rotation = "random",
})
-- Grasses
register_grass_decoration(-0.03, 0.09, 5)
register_grass_decoration(-0.015, 0.075, 4)
register_grass_decoration(0, 0.06, 3)
register_grass_decoration(0.015, 0.045, 2)
register_grass_decoration(0.03, 0.03, 1)
-- Junglegrass
minetest.register_decoration({
deco_type = "simple",
place_on = {"default:dirt_with_grass"},
sidelen = 80,
fill_ratio = 0.1,
biomes = {"rainforest"},
y_min = 1,
y_max = 31000,
decoration = "default:junglegrass",
})
-- Dry shrub
minetest.register_decoration({
deco_type = "simple",
place_on = {"default:sand", "default:dirt_with_snow"},
sidelen = 16,
noise_params = {
offset = 0,
scale = 0.02,
spread = {x = 200, y = 200, z = 200},
seed = 329,
octaves = 3,
persist = 0.6
},
biomes = {"desert", "tundra"},
y_min = 2,
y_max = 31000,
decoration = "default:dry_shrub",
})
end
--
-- Detect mapgen to select functions
--
local mg_name = minetest.get_mapgen_setting("mg_name")
if mg_name == "v6" then
default.register_ores()
default.register_mgv6_decorations()
else
default.register_biomes()
default.register_ores()
default.register_decorations()
end
| agpl-3.0 |
gajop/Zero-K | LuaUI/chat_preprocess.lua | 10 | 7376 | --Chat preprocessor. Provide preprocessed chat message for Chili Chat widget
--last update: 20 May 2014
local myName = Spring.GetPlayerInfo(Spring.GetMyPlayerID())
local transmitMagic = "> ["..myName.."]!transmit" -- Lobby is sending to LuaUI
local voiceMagic = "> ["..myName.."]!transmit voice" -- Lobby is sending a voice command to LuaUI
local transmitLobbyMagic = "!transmitlobby" -- LuaUI is sending to lobby
function StringStarts(s, start)
return string.sub(s, 1, string.len(start)) == start
end
local function Deserialize(text)
local f, err = loadstring(text)
if not f then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, "Error while deserializing table (compiling): "..tostring(err))
return
end
setfenv(f, {}) -- sandbox
local success, arg = pcall(f)
if not success then
Spring.Log(HANDLER_BASENAME, LOG.ERROR, "Error while deserializing table (calling): "..tostring(arg))
return
end
return arg
end
local MessageProcessor = {}
local PLAYERNAME_PATTERN = '([%w%[%]_]+)' -- to make message patterns easier to read/update
-- message definitions
--[[
pattern syntax:
see http://www.lua.org/manual/5.1/manual.html#5.4.1
pattern must contain at least 1 capture group; its content will end up in msg.argument after parseMessage()
PLAYERNAME will match anything that looks like a playername (see code for definition of PLAYERNAME_PATTERN); it is a capture group
if message does not contain a PLAYERNAME, add 'noplayername = true' to definition
it should be possible to add definitions to help debug widgets or whatever... (no guarantee)
--]]
MessageProcessor.MESSAGE_DEFINITIONS = {
{ msgtype = 'player_to_allies', pattern = '^<PLAYERNAME> Allies: (.*)' },
{ msgtype = 'player_to_player_received', pattern = '^<PLAYERNAME> Private: (.*)' }, -- TODO test!
{ msgtype = 'player_to_player_sent', pattern = '^You whispered PLAYERNAME: (.*)' }, -- TODO test!
{ msgtype = 'player_to_specs', pattern = '^<PLAYERNAME> Spectators: (.*)' },
{ msgtype = 'player_to_everyone', pattern = '^<PLAYERNAME> (.*)' },
{ msgtype = 'spec_to_specs', pattern = '^%[PLAYERNAME%] Spectators: (.*)' },
{ msgtype = 'spec_to_allies', pattern = '^%[PLAYERNAME%] Allies: (.*)' }, -- TODO is there a reason to differentiate spec_to_specs and spec_to_allies??
{ msgtype = 'spec_to_everyone', pattern = '^%[PLAYERNAME%] (.*)' },
-- shameful copy-paste -- TODO rewrite pattern matcher to remove this duplication
{ msgtype = 'replay_spec_to_specs', pattern = '^%[PLAYERNAME %(replay%)%] Spectators: (.*)' },
{ msgtype = 'replay_spec_to_allies', pattern = '^%[PLAYERNAME %(replay%)%] Allies: (.*)' }, -- TODO is there a reason to differentiate spec_to_specs and spec_to_allies??
{ msgtype = 'replay_spec_to_everyone', pattern = '^%[PLAYERNAME %(replay%)%] (.*)'},
{ msgtype = 'label', pattern = '^PLAYERNAME added point: (.+)', discard = true }, -- NOTE : these messages are discarded -- points and labels are provided through MapDrawCmd() callin
{ msgtype = 'point', pattern = '^PLAYERNAME added point: ', discard = true },
{ msgtype = 'autohost', pattern = '^> (.+)', noplayername = true },
{ msgtype = 'game_message', pattern = '^game_message:(.)(.*)', isgamemessage = true },
{ msgtype = 'other' } -- no pattern... will match anything else
}
local function escapePatternReplacementChars(s)
return string.gsub(s, "%%", "%%%%")
end
function MessageProcessor:Initialize()
local escapedPlayernamePattern = escapePatternReplacementChars(PLAYERNAME_PATTERN)
for _,def in ipairs(self.MESSAGE_DEFINITIONS) do
if def.pattern then
def.pattern = def.pattern:gsub('PLAYERNAME', escapedPlayernamePattern) -- patch definition pattern so it is an actual lua pattern string
end
end
end
local players = {}
function MessageProcessor:AddPlayer(playerID)
local name, active, spec, teamId, allyTeamId, _,_,_,_,customkeys = Spring.GetPlayerInfo(playerID)
players[name] = { id = playerID, spec = spec, allyTeamId = allyTeamId, muted = (customkeys and customkeys.muted == 1) }
end
function MessageProcessor:UpdatePlayer(playerID)
local name, active, spec, teamId, allyTeamId = Spring.GetPlayerInfo(playerID)
players[name].id = playerID
players[name].spec = spec
players[name].allyTeamId = allyTeamId
end
local function SetupPlayers()
local playerroster = Spring.GetPlayerList()
local spGetPlayerInfo = Spring.GetPlayerInfo
for i, id in ipairs(playerroster) do
local name,active, spec, teamId, allyTeamId, _,_,_,_,customkeys = spGetPlayerInfo(id)
players[name] = { id = id, spec = spec, allyTeamId = allyTeamId, muted = (customkeys and customkeys.muted == 1) }
end
-- register any AIs
-- Copied from gui_chili_crudeplayerlist.lua
local teamsSorted = Spring.GetTeamList()
local gaiaTeamID = Spring.GetGaiaTeamID()
local spGetTeamInfo = Spring.GetTeamInfo
local spGetAIInfo = Spring.GetAIInfo
for i=1,#teamsSorted do
local teamID = teamsSorted[i]
if teamID ~= gaiaTeamID then
local _,_,_,isAI,_,allyTeamId = spGetTeamInfo(teamID)
if isAI then
local skirmishAIID, name = spGetAIInfo(teamID)
--Note: to make AI appears like its doing an ally chat, do: Spring.Echo("<botname> Allies: bot_say_something")
--Note2: <botname> only use name and not shortname. For comparison, crude playerlist botname is: '<'.. name ..'> '.. shortName
players[name] = { id = skirmishAIID, allyTeamId = allyTeamId, isAI = true}
end
end --if teamID ~= Spring.GetGaiaTeamID()
end --for each team
end
local function getSource(spec, allyTeamId)
return (spec and 'spec')
or ((Spring.GetMyAllyTeamID() == allyTeamId) and 'ally')
or 'enemy'
end
-- update msg members msgtype, argument, source and playername (when relevant)
--loop thru all pattern combination (self.MESSAGE_DEFINITIONS) until a match is found
function MessageProcessor:ParseMessage(msg)
for _, candidate in ipairs(self.MESSAGE_DEFINITIONS) do
if candidate.pattern == nil then -- for fallback/other messages
msg.msgtype = candidate.msgtype
msg.argument = msg.text
msg.source = 'other'
return
end
--else
local capture1, capture2 = msg.text:match(candidate.pattern)
if capture1 then
msg.msgtype = candidate.msgtype
if candidate.noplayername then
msg.argument = capture1
msg.source = 'other'
return
elseif candidate.isgamemessage then
local message = capture2
if (capture1 ~= " ") then --skip any whitespace 1st char after "game_message:" (for display tidyness!)
message = capture1 .. message
end
msg.text = message
msg.argument = message
msg.source = 'widget/gadget'
return
else
local playername = capture1
local player = players[playername]
if player then
msg.player = player
msg.source = getSource(player.spec, player.allyTeamId)
msg.playername = playername
msg.argument = capture2
return
end
end
end
end
end
function MessageProcessor:ProcessConsoleLine(msg)
self:ParseMessage(msg)
end
function MessageProcessor:ProcessConsoleBuffer(count)
local bufferMessages = Spring.GetConsoleBuffer(count)
for i = 1,#bufferMessages do
self:ProcessConsoleLine(bufferMessages[i])
end
return bufferMessages
end
SetupPlayers()
MessageProcessor:Initialize()
return myName, transmitMagic, voiceMagic, transmitLobbyMagic, MessageProcessor | gpl-2.0 |
gajop/Zero-K | LuaUI/Widgets/gui_chili_rejoin_progress.lua | 9 | 16494 | function widget:GetInfo()
return {
name = "Chili Rejoining Progress Bar",
desc = "v1.132 Show the progress of rejoining and temporarily turn-off Text-To-Speech while rejoining",
author = "msafwan (use UI from KingRaptor's Chili-Vote) ",
date = "Oct 10, 2012",
license = "GNU GPL, v2 or later",
layer = 0,
experimental = false,
enabled = true, -- loaded by default?
--handler = true, -- allow this widget to use 'widgetHandler:FindWidget()'
}
end
--------------------------------------------------------------------------------
--Crude Documentation-----------------------------------------------------------
--How it meant to work:
--1) GameProgress return serverFrame --> IF I-am-behind THEN activate chili UI ELSE de-activate chili UI --> Update the estimated-time-of-completion every second.
--2) LuaRecvMsg return timeDifference --> IF I-am-behind THEN activate chili UI ELSE nothing ---> Update the estimated-time-of-completion every second.
--3) at GameStart send LuaMsg containing GameStart's UTC.
--Others: some tricks to increase efficiency, bug fix, ect
--------------------------------------------------------------------------------
--Localize Spring function------------------------------------------------------
local spGetSpectatingState = Spring.GetSpectatingState
--------------------------------------------------------------------------------
--Chili Variable----------------------------------------------------------------- ref: gui_chili_vote.lua by KingRaptor
local Chili
local Button
local Label
local Window
local Panel
local TextBox
local Image
local Progressbar
local Control
local Font
-- elements
local window, stack_main, label_title
local stack_vote, label_vote, button_vote, progress_vote
local voteCount, voteMax
--------------------------------------------------------------------------------
--Calculator Variable------------------------------------------------------------
local serverFrameRate_G = 30 --//constant: assume server run at x1.0 gamespeed.
local serverFrameNum1_G = nil --//variable: get the latest server's gameFrame from GameProgress() and do work with it.
local oneSecondElapsed_G = 0 --//variable: a timer for 1 second, used in Update(). Update UI every 1 second.
local myGameFrame_G = 0 --//variable: get latest my gameFrame from GameFrame() and do work with it.
local myLastFrameNum_G = 0 --//variable: used to calculate local game-frame rate.
local ui_active_G = false --//variable:indicate whether UI is shown or hidden.
local averageLocalSpeed_G = {sumOfSpeed= 0, sumCounter= 0} --//variable: store the local-gameFrame speeds so that an average can be calculated.
local defaultAverage_G = 30 --//constant: Initial/Default average is set at 30gfps (x1.0 gameSpeed)
local simpleMovingAverageLocalSpeed_G = {storage={},index = 1, runningAverage=defaultAverage_G} --//variable: for calculating rolling average. Initial/Default average is set at 30gfps (x1.0 gameSpeed)
--------------------------------------------------------------------------------
--Variable for fixing GameProgress delay at rejoin------------------------------
local myTimestamp_G = 0 --//variable: store my own timestamp at GameStart
local serverFrameNum2_G = nil --//variable: the expected server-frame of current running game
local submittedTimestamp_G = {} --//variable: store all timestamp at GameStart submitted by original players (assuming we are rejoining)
local functionContainer_G = function(x) end --//variable object: store a function
local myPlayerID_G = 0
local gameProgressActive_G = false --//variable: signal whether GameProgress has been updated.
local iAmReplay_G = false
--------------------------------------------------------------------------------
--For testing GUI---------------------------------------------------------------
local forceDisplay = nil
--------------------------------------------------------------------------------
--[[
if VFS.FileExists("Luaui/Config/ZK_data.lua") then
local configFile = VFS.Include("Luaui/Config/ZK_data.lua")
ttsControlEnabled_G = configFile["EPIC Menu"].config.epic_Text_To_Speech_Control_enable
if ttsControlEnabled_G == nil then
ttsControlEnabled_G = true
end
end --]]
local function ActivateGUI_n_TTS (frameDistanceToFinish, ui_active, ttsControlEnabled, altThreshold)
if frameDistanceToFinish >= (altThreshold or 120) then
if not ui_active then
screen0:AddChild(window)
ui_active = true
if ttsControlEnabled then
Spring.Echo(Spring.GetPlayerInfo(myPlayerID_G) .. " DISABLE TTS") --eg: output "<playerName> DISABLE TTS"
end
end
elseif frameDistanceToFinish < (altThreshold or 120) then
if ui_active then
screen0:RemoveChild(window)
ui_active = false
if ttsControlEnabled then
Spring.Echo(Spring.GetPlayerInfo(myPlayerID_G) .. " ENABLE TTS")
end
end
end
return ui_active
end
function widget:GameProgress(serverFrameNum) --this function run 3rd. It read the official serverFrameNumber
local myGameFrame = myGameFrame_G
local ui_active = ui_active_G
-----localize--
local ttsControlEnabled = CheckTTSwidget()
local serverFrameNum1 = serverFrameNum
local frameDistanceToFinish = serverFrameNum1-myGameFrame
ui_active = ActivateGUI_n_TTS (frameDistanceToFinish, ui_active, ttsControlEnabled)
-----return--
serverFrameNum1_G = serverFrameNum1
ui_active_G = ui_active
gameProgressActive_G = true
end
function widget:Update(dt) --this function run 4th. It update the progressBar
if ui_active_G then
oneSecondElapsed_G = oneSecondElapsed_G + dt
if oneSecondElapsed_G >= 1 then --wait for 1 second period
-----var localize-----
local serverFrameNum1 = serverFrameNum1_G
local serverFrameNum2 = serverFrameNum2_G
local oneSecondElapsed = oneSecondElapsed_G
local myLastFrameNum = myLastFrameNum_G
local serverFrameRate = serverFrameRate_G
local myGameFrame = myGameFrame_G
local simpleMovingAverageLocalSpeed = simpleMovingAverageLocalSpeed_G
-----localize
local serverFrameNum = serverFrameNum1 or serverFrameNum2 --use FrameNum from GameProgress if available, else use FrameNum derived from LUA_msg.
serverFrameNum = serverFrameNum + serverFrameRate*oneSecondElapsed -- estimate Server's frame number after each widget:Update() while waiting for GameProgress() to refresh with actual value.
local frameDistanceToFinish = serverFrameNum-myGameFrame
local myGameFrameRate = (myGameFrame - myLastFrameNum) / oneSecondElapsed
--Method1: simple average
--[[
averageLocalSpeed_G.sumOfSpeed = averageLocalSpeed_G.sumOfSpeed + myGameFrameRate -- try to calculate the average of local gameFrame speed.
averageLocalSpeed_G.sumCounter = averageLocalSpeed_G.sumCounter + 1
myGameFrameRate = averageLocalSpeed_G.sumOfSpeed/averageLocalSpeed_G.sumCounter -- using the average to calculate the estimate for time of completion.
--]]
--Method2: simple moving average
myGameFrameRate = SimpleMovingAverage(myGameFrameRate, simpleMovingAverageLocalSpeed) -- get our average frameRate
local timeToComplete = frameDistanceToFinish/myGameFrameRate -- estimate the time to completion.
local timeToComplete_string = "?/?"
local minute, second = math.modf(timeToComplete/60) --second divide by 60sec-per-minute, then saperate result from its remainder
second = 60*second --multiply remainder with 60sec-per-minute to get second back.
timeToComplete_string = string.format ("Time Remaining: %d:%02d" , minute, second)
progress_vote:SetCaption(timeToComplete_string)
progress_vote:SetValue(myGameFrame/serverFrameNum)
oneSecondElapsed = 0
myLastFrameNum = myGameFrame
if serverFrameNum1 then serverFrameNum1 = serverFrameNum --update serverFrameNum1 if value from GameProgress() is used,
else serverFrameNum2 = serverFrameNum end --update serverFrameNum2 if value from LuaRecvMsg() is used.
-----return
serverFrameNum1_G = serverFrameNum1
serverFrameNum2_G = serverFrameNum2
oneSecondElapsed_G = oneSecondElapsed
myLastFrameNum_G = myLastFrameNum
simpleMovingAverageLocalSpeed_G = simpleMovingAverageLocalSpeed
end
end
end
local function RemoveLUARecvMsg(n)
if n > 150 then
iAmReplay_G = nil
spGetSpectatingState = nil --de-reference the function so that garbage collector can clean it up.
widgetHandler:RemoveCallIn("RecvLuaMsg") --remove unused method for increase efficiency after frame> timestampLimit (150frame or 5 second).
functionContainer_G = function(x) end --replace this function with an empty function/method
end
end
function widget:GameFrame(n) --this function run at all time. It update current gameFrame
myGameFrame_G = n
functionContainer_G(n) --function that are able to remove itself. Reference: gui_take_reminder.lua (widget by EvilZerggin, modified by jK)
end
--//thanks to Rafal[0K] for pointing to the rolling average idea.
function SimpleMovingAverage(myGameFrameRate, simpleMovingAverageLocalSpeed)
--//remember current frameRate, and advance table index by 1
local index = (simpleMovingAverageLocalSpeed.index) --retrieve current index.
simpleMovingAverageLocalSpeed.storage[index] = myGameFrameRate --remember current frameRate at current index.
simpleMovingAverageLocalSpeed.index = simpleMovingAverageLocalSpeed.index +1 --advance index by 1.
--//wrap table index around. Create a circle
local poolingSize = 10 --//number of sample. note: simpleMovingAverage() is executed every second, so the value represent an average spanning 10 second.
if (simpleMovingAverageLocalSpeed.index == (poolingSize + 2)) then --when table out-of-bound:
simpleMovingAverageLocalSpeed.index = 1 --wrap the table index around (create a circle of 150 + 1 (ie: poolingSize plus 1 space) entry).
end
--//update averages
index = (simpleMovingAverageLocalSpeed.index) --retrieve an index advanced by 1.
local oldAverage = (simpleMovingAverageLocalSpeed.storage[index] or defaultAverage_G) --retrieve old average or use initial/default average as old average.
simpleMovingAverageLocalSpeed.runningAverage = simpleMovingAverageLocalSpeed.runningAverage + myGameFrameRate/poolingSize - oldAverage/poolingSize --calculate average: add new value, remove old value. Ref: http://en.wikipedia.org/wiki/Moving_average#Simple_moving_average
local avgGameFrameRate = simpleMovingAverageLocalSpeed.runningAverage -- replace myGameFrameRate with its average value.
return avgGameFrameRate, simpleMovingAverageLocalSpeed
end
function CheckTTSwidget()
local ttsValue
--[[
local widget = widgetHandler:FindWidget("Text To Speech Control") --find widget. Reference: gui_epicmenu.lua by Carrepairer/Wagonrepairer
if widget then --get all variable from TTS control widget.
ttsValue = widget.options.enable.value --get the value
else --If widget is not found, then 'Rejoin Progress widget' will not try to disable/enable TTS. It became neutral.
ttsValue = false --disable TTS control
end
--]]
if WG.textToSpeechCtrl then
ttsValue = WG.textToSpeechCtrl.ttsEnable --retrieve Text-To-Speech widget settings from global table.
else
ttsValue = false
end
return ttsValue
end
----------------------------------------------------------
--Chili--------------------------------------------------
function widget:Initialize()
functionContainer_G = RemoveLUARecvMsg
myPlayerID_G = Spring.GetMyPlayerID()
iAmReplay_G = Spring.IsReplay()
-- setup Chili
Chili = WG.Chili
Button = Chili.Button
Label = Chili.Label
Colorbars = Chili.Colorbars
Window = Chili.Window
StackPanel = Chili.StackPanel
Image = Chili.Image
Progressbar = Chili.Progressbar
Control = Chili.Control
screen0 = Chili.Screen0
--create main Chili elements
-- local height = tostring(math.floor(screenWidth/screenHeight*0.35*0.35*100)) .. "%"
-- local y = tostring(math.floor((1-screenWidth/screenHeight*0.35*0.35)*100)) .. "%"
local screenWidth, screenHeight = Spring.GetWindowGeometry()
local y = screenWidth*2/11 + 32
-- local labelHeight = 24
-- local fontSize = 16
window = Window:New{
--parent = screen0,
name = 'rejoinProgress';
color = {0, 0, 0, 0},
width = 260,
height = 60,
left = 2, --dock left?
y = y, --halfway on screen?
dockable = true,
draggable = false, --disallow drag to avoid capturing mouse click
resizable = false,
tweakDraggable = true,
tweakResizable = true,
minWidth = MIN_WIDTH,
minHeight = MIN_HEIGHT,
padding = {0, 0, 0, 0},
savespace = true, --probably could save space?
--itemMargin = {0, 0, 0, 0},
}
stack_main = StackPanel:New{
parent = window,
resizeItems = true;
orientation = "vertical";
height = "100%";
width = "100%";
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0},
}
label_title = Label:New{
parent = stack_main,
autosize=false;
align="center";
valign="top";
caption = '';
height = 16,
width = "100%";
}
--[[
stack_vote = StackPanel:New{
parent = stack_main,
resizeItems = true;
orientation = "horizontal";
y = (40*(1-1))+15 ..'%',
height = "40%";
width = "100%";
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0},
}
--]]
progress_vote = Progressbar:New{
parent = stack_main,
x = "0%",
y = '40%', --position at 40% of the window's height
width = "100%"; --maximum width
height = "100%",
max = 1;
caption = "?/?";
color = {0.9,0.15,0.2,1}; --Red, {0.2,0.9,0.3,1} --Green
}
progress_vote:SetValue(0)
voteCount = 0
voteMax = 1 -- protection against div0
label_title:SetCaption("Catching up.. Please Wait")
if forceDisplay then
ActivateGUI_n_TTS (1, false, false, 0) --force GUI to display for testing
return
end
end
----------------------------------------------------------
--fix for Game Progress delay-----------------------------
function widget:RecvLuaMsg(bigMsg, playerID) --this function run 2nd. It read the LUA timestamp
if forceDisplay then
ActivateGUI_n_TTS (1, false, false, 0) --force GUI to display for testing
return
end
if gameProgressActive_G or iAmReplay_G then --skip LUA message if gameProgress is already active OR game is a replay
return false
end
local iAmSpec = spGetSpectatingState()
local myMsg = (playerID == myPlayerID_G)
if (myMsg or iAmSpec) then
if bigMsg:sub(1,9) == "rejnProg " then --check for identifier
-----var localize-----
local ui_active = ui_active_G
local submittedTimestamp = submittedTimestamp_G
local myTimestamp = myTimestamp_G
-----localize
local timeMsg = bigMsg:sub(10) --saperate time-message from the identifier
local systemSecond = tonumber(timeMsg)
--Spring.Echo(systemSecond .. " B")
submittedTimestamp[#submittedTimestamp +1] = systemSecond --store all submitted timestamp from each players
local sumSecond= 0
for i=1, #submittedTimestamp,1 do
sumSecond = sumSecond + submittedTimestamp[i]
end
--Spring.Echo(sumSecond .. " C")
local avgSecond = sumSecond/#submittedTimestamp
--Spring.Echo(avgSecond .. " D")
local secondDiff = myTimestamp - avgSecond
--Spring.Echo(secondDiff .. " E")
local frameDiff = secondDiff*30
local serverFrameNum2 = frameDiff --this value represent the estimate difference in frame when everyone was submitting their timestamp at game start. Therefore the difference in frame will represent how much frame current player are ahead of us.
local ttsControlEnabled = CheckTTSwidget()
ui_active = ActivateGUI_n_TTS (frameDiff, ui_active, ttsControlEnabled, 1800)
-----return
ui_active_G = ui_active
serverFrameNum2_G = serverFrameNum2
submittedTimestamp_G = submittedTimestamp
end
end
end
function widget:GameStart() --this function run 1st, before any other function. It send LUA timestamp
--local format = "%H:%M"
local currentTime = os.date("!*t") --ie: clock on "gui_epicmenu.lua" (widget by CarRepairer), UTC & format: http://lua-users.org/wiki/OsLibraryTutorial
local systemSecond = currentTime.hour*3600 + currentTime.min*60 + currentTime.sec
local myTimestamp = systemSecond
--Spring.Echo(systemSecond .. " A")
local timestampMsg = "rejnProg " .. systemSecond --currentTime --create a timestamp message
Spring.SendLuaUIMsg(timestampMsg) --this message will remain in server's cache as a LUA message which rejoiner can intercept. Thus allowing the game to leave a clue at game start for latecomer. The latecomer will compare the previous timestamp with present and deduce the catch-up time.
------return
myTimestamp_G = myTimestamp
end
| gpl-2.0 |
gajop/Zero-K | LuaRules/Configs/MetalSpots/Charlie in the Hills v2.1.lua | 17 | 3179 | return {
spots = {
[1] = {x = 1960, z = 2760, metal = 1.7},
[2] = {x = 3416, z = 152, metal = 1.7},
[3] = {x = 4136, z = 8008, metal = 1.7},
[4] = {x = 4136, z = 3864, metal = 1.7},
[5] = {x = 4824, z = 7992, metal = 1.7},
[6] = {x = 4280, z = 7832, metal = 1.7},
[7] = {x = 6008, z = 2632, metal = 1.7},
[8] = {x = 3976, z = 7816, metal = 1.7},
[9] = {x = 4136, z = 7672, metal = 1.7},
[10] = {x = 5320, z = 3816, metal = 1.7},
[11] = {x = 3432, z = 7672, metal = 1.7},
[12] = {x = 4712, z = 6888, metal = 1.7},
[13] = {x = 4712, z = 2504, metal = 1.7},
[14] = {x = 3480, z = 6872, metal = 1.7},
[15] = {x = 3000, z = 3800, metal = 1.7},
[16] = {x = 3988, z = 6869, metal = 1.7},
[17] = {x = 4824, z = 6648, metal = 1.7},
[18] = {x = 3464, z = 2488, metal = 1.7},
[19] = {x = 3480, z = 6600, metal = 1.7},
[20] = {x = 6264, z = 3736, metal = 1.7},
[21] = {x = 5928, z = 6328, metal = 1.7},
[22] = {x = 5752, z = 2072, metal = 1.7},
[23] = {x = 5530, z = 6320, metal = 1.7},
[24] = {x = 2262, z = 6314, metal = 1.7},
[25] = {x = 2040, z = 3592, metal = 1.7},
[26] = {x = 2632, z = 6296, metal = 1.7},
[27] = {x = 2456, z = 6168, metal = 1.7},
[28] = {x = 2472, z = 2072, metal = 1.7},
[29] = {x = 5736, z = 6152, metal = 1.7},
[30] = {x = 3496, z = 5832, metal = 1.7},
[31] = {x = 6264, z = 3320, metal = 1.7},
[32] = {x = 4840, z = 5816, metal = 1.7},
[33] = {x = 5960, z = 5512, metal = 1.7},
[34] = {x = 6472, z = 4536, metal = 1.7},
[35] = {x = 2072, z = 5512, metal = 1.7},
[36] = {x = 2232, z = 5048, metal = 1.7},
[37] = {x = 4728, z = 1352, metal = 1.7},
[38] = {x = 3288, z = 4968, metal = 1.7},
[39] = {x = 4056, z = 4952, metal = 1.7},
[40] = {x = 5560, z = 1912, metal = 1.7},
[41] = {x = 6280, z = 4920, metal = 1.7},
[42] = {x = 4936, z = 4888, metal = 1.7},
[43] = {x = 3352, z = 3256, metal = 1.7},
[44] = {x = 1992, z = 4520, metal = 1.7},
[45] = {x = 3480, z = 1336, metal = 1.7},
[46] = {x = 2680, z = 1896, metal = 1.7},
[47] = {x = 2488, z = 1736, metal = 1.7},
[48] = {x = 5288, z = 4344, metal = 1.7},
[49] = {x = 4216, z = 3224, metal = 1.7},
[50] = {x = 4100, z = 440, metal = 1.7},
[51] = {x = 4936, z = 3288, metal = 1.7},
[52] = {x = 2296, z = 1896, metal = 1.7},
[53] = {x = 4728, z = 1624, metal = 1.7},
[54] = {x = 4776, z = 616, metal = 1.7,},
[55] = {x = 2344, z = 3144, metal = 1.7},
[56] = {x = 3384, z = 1592, metal = 1.7},
[57] = {x = 2952, z = 4376, metal = 1.7},
[58] = {x = 5757, z = 1784, metal = 1.7},
[59] = {x = 4136, z = 4328, metal = 1.7},
[60] = {x = 4136, z = 1260, metal = 1.7},
[61] = {x = 4137, z = 6738, metal = 1.7},
[62] = {x = 4303, z = 6859, metal = 1.7},
[63] = {x = 4137, z = 6982, metal = 1.7},
[64] = {x = 2440, z = 6420, metal = 1.7},
[65] = {x = 5700, z = 6470, metal = 1.7},
[66] = {x = 5937, z = 1912, metal = 1.7},
[67] = {x = 4375, z = 440, metal = 1.7},
[68] = {x = 4247, z = 302, metal = 1.7},
[69] = {x = 4270, z = 575, metal = 1.7},
[70] = {x = 4136, z = 1500, metal = 1.7},
[71] = {x = 3977, z = 1400, metal = 1.7},
[72] = {x = 4290, z = 1400, metal = 1.7},
},
} | gpl-2.0 |
hossein101/Tabchi | lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-3.0 |
sina7sk/test | bot/seedbot.lua | 1 | 9982 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '2'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"download_media",
"invite",
"all",
"leave_ban",
"admin"
},
sudo_users = {114934518,199642007},--Sudo users
disabled_channels = {},
moderation = {data = 'data/moderation.json'},
about_text = [[فروش گروه ضد اسپم
channels:
@safroid_group
]],
help_text_realm = [[
Realm Commands:
!creategroup [name]
Create a group
!createrealm [name]
Create a realm
!setname [name]
Set realm name
!setabout [group_id] [text]
Set a group's about text
!setrules [grupo_id] [text]
Set a group's rules
!lock [grupo_id] [setting]
Lock a group's setting
!unlock [grupo_id] [setting]
Unock a group's setting
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [grupo_id]
Kick all memebers and delete group
!kill realm [realm_id]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
» Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
Return group id or user id
!help
Get commands list
!lock [member|name|bots|leave]
Locks [member|name|bots|leaveing]
!unlock [member|name|bots|leave]
Unlocks [member|name|bots|leaving]
!set rules [text]
Set [text] as rules
!set about [text]
Set [text] as about
!settings
Returns group settings
!newlink
Create/revoke your group link
!link
Returns group link
!owner
Returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] [text]
Save [text] as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
Returns user id
!log
Will return group logs
!banlist
Will return group ban list
» U can use both "/" and "!"
» Only mods, owner and admin can add bots in group
» Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
» Only owner can use res,setowner,promote,demote and log commands
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
gajop/Zero-K | LuaRules/Utilities/unitDefReplacements.lua | 2 | 5660 | -------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local function GetGridTooltip (unitID)
local gridCurrent = Spring.GetUnitRulesParam(unitID, "OD_gridCurrent")
if not gridCurrent then return end
local windStr = ""
local minWind = Spring.GetUnitRulesParam(unitID, "minWind")
if minWind then
windStr = "\n" .. WG.Translate("common", "wind_range") .. " " .. math.round(minWind, 1) .. " - " .. math.round(Spring.GetGameRulesParam("WindMax") or 2.5, 1)
end
if gridCurrent < 0 then
return WG.Translate("common", "disabled_no_grid") .. windStr
end
local gridMaximum = Spring.GetUnitRulesParam(unitID, "OD_gridMaximum") or 0
local gridMetal = Spring.GetUnitRulesParam(unitID, "OD_gridMetal") or 0
return WG.Translate("common", "grid") .. ": " .. math.round(gridCurrent,2) .. "/" .. math.round(gridMaximum,2) .. " E => " .. math.round(gridMetal,2) .. " M " .. windStr
end
local function GetMexTooltip (unitID)
local metalMult = Spring.GetUnitRulesParam(unitID, "overdrive_proportion")
if not metalMult then return end
local currentIncome = Spring.GetUnitRulesParam(unitID, "current_metalIncome")
local mexIncome = Spring.GetUnitRulesParam(unitID, "mexIncome") or 0
local baseFactor = Spring.GetUnitRulesParam(unitID, "resourceGenerationFactor") or 1
if currentIncome == 0 then
return WG.Translate("common", "disabled_base_metal") .. ": " .. math.round(mexIncome,2)
end
return WG.Translate("common", "income") .. ": " .. math.round(mexIncome*baseFactor,2) .. " + " .. math.round(metalMult*100) .. "% " .. WG.Translate("common", "overdrive")
end
local function GetTerraformTooltip(unitID)
local spent = Spring.GetUnitRulesParam(unitID, "terraform_spent")
if not spent then return end
return WG.Translate("common", "terraform") .. " - " .. WG.Translate("common", "estimated_cost") .. ": " .. math.floor(spent) .. " / " .. math.floor(Spring.GetUnitRulesParam(unitID, "terraform_estimate") or 0)
end
local function GetZenithTooltip (unitID)
local meteorsControlled = Spring.GetUnitRulesParam(unitID, "meteorsControlled")
if not meteorsControlled then return end
return (WG.Translate("units", "zenith.description") or "Meteor Controller") .. " - " .. (WG.Translate("common", "meteors_controlled") or "Meteors controlled") .. " " .. (meteorsControlled or "0") .. "/500"
end
local function GetAvatarTooltip(unitID)
local commOwner = Spring.GetUnitRulesParam(unitID, "commander_owner")
if not commOwner then return end
return commOwner or ""
end
local function GetCustomTooltip (unitID)
return GetGridTooltip(unitID)
or GetMexTooltip(unitID)
or GetTerraformTooltip(unitID)
or GetZenithTooltip(unitID)
or GetAvatarTooltip(unitID)
end
function Spring.Utilities.GetHumanName(ud, unitID)
if not ud then
return ""
end
if unitID then
local name = Spring.GetUnitRulesParam(unitID, "comm_name")
if name then
local level = Spring.GetUnitRulesParam(unitID, "comm_level")
if level then
return name .. " " .. WG.Translate("common", "lvl") .. " " .. (level + 1)
else
return name
end
end
end
local name_override = ud.customParams.statsname or ud.name
return WG.Translate ("units", name_override .. ".name") or ud.humanName
end
function Spring.Utilities.GetDescription(ud, unitID)
if not ud then
return ""
end
local name_override = ud.customParams.statsname or ud.name
local desc = WG.Translate ("units", name_override .. ".description") or ud.tooltip
if Spring.ValidUnitID(unitID) then
local customTooltip = GetCustomTooltip(unitID)
if customTooltip then
return customTooltip
end
local buildPower = Spring.GetUnitRulesParam(unitID, "buildpower_mult")
if buildPower then
buildPower = buildPower*10
desc = desc .. ", " .. WG.Translate("common", "builds_at") .. " " .. buildPower .. " m/s"
end
end
return desc
end
function Spring.Utilities.GetHelptext(ud, unitID)
local name_override = ud.customParams.statsname or ud.name
return WG.Translate ("units", name_override .. ".helptext") or ud.customParams.helptext or WG.Translate("common", "no_helptext")
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local buildTimes = {}
for i = 1, #UnitDefs do
local ud = UnitDefs[i]
local realBuildTime = ud.customParams.real_buildtime
if realBuildTime then
buildTimes[i] = tonumber(realBuildTime)
else
buildTimes[i] = ud.buildTime
end
end
function Spring.Utilities.GetUnitCost(unitID, unitDefID)
if unitID then
local realCost = Spring.GetUnitRulesParam(unitID, "comm_cost")
if realCost then
return realCost
end
end
unitDefID = unitDefID or Spring.GetUnitDefID(unitID)
if unitDefID and buildTimes[unitDefID] then
return buildTimes[unitDefID]
end
return 50
end
function Spring.Utilities.GetUnitCanBuild(unitID, unitDefID)
unitDefID = unitDefID or Spring.GetUnitDefID(unitID)
if not unitDefID then
return 0
end
local ud = UnitDefs[unitDefID]
local buildPower = (ud and ((ud.customParams.nobuildpower and 0) or ud.buildSpeed)) or 0
return buildPower > 0
end
function Spring.Utilities.GetUnitBuildSpeed(unitID, unitDefID)
unitDefID = unitDefID or Spring.GetUnitDefID(unitID)
if not unitDefID then
return 0
end
local ud = UnitDefs[unitDefID]
local buildPower = (ud and ((ud.customParams.nobuildpower and 0) or ud.buildSpeed)) or 0
if unitID then
local mult = Spring.GetUnitRulesParam(unitID, "buildpower_mult")
if mult then
return mult * buildPower
end
end
return buildPower
end
| gpl-2.0 |
gajop/Zero-K | LuaUI/Widgets/cmd_customformations2.lua | 6 | 40293 | function widget:GetInfo()
return {
name = "CustomFormations2",
desc = "Allows you to draw a formation line:"..
"\n mouse drag draw various command on ground."..
"\n ALT+Attack draw attack command on the ground.",
author = "Niobium, modified by Skasi", -- Based on 'Custom Formations' by jK and gunblob
version = "v3.4", -- With modified dot drawing from v4.3
date = "Mar, 2010",
license = "GNU GPL, v2 or later",
layer = 1000000,
enabled = true,
handler = true,
}
end
VFS.Include("LuaRules/Configs/customcmds.h.lua")
--------------------------------------------------------------------------------
-- Epic Menu Options
--------------------------------------------------------------------------------
options_path = 'Settings/Interface/Command Visibility'--/Formations'
options_order = { 'drawmode_v2', 'linewidth', 'dotsize' }
options = {
drawmode_v2 = {
name = 'Draw mode',
-- desc is not supported here :(
-- desc = 'Change the formation display. Formations are drawn by moving the mouse while the mouse button is pressed. Supported commands are Move, Fight, Patrol, Manual attacks, Jump and with the ALT key held down Attack, Set target and Unload.'
-- (new) players might not even know about custom formations, so ultimately this should probably be displayed above these options
type = 'radioButton',
value = 'both',
items={
{key='lines', name='Lines only', desc='Draw stippled lines along the drawn formation'},
{key='dots', name='Dots only', desc='Draw dots at command locations'},
{key='both', name='Draw both', desc='Draw lines and dots'},
},
noHotkey = true,
},
linewidth = {
name = 'Width of lines',
type = 'number',
value = 2,
min = 1, max = 2, step=1,
-- For some reason drawing lines fails for numbers higher than 2.
},
dotsize = {
name = 'Size of dots',
type = 'number',
value = 1,
min = 0.5, max = 2, step=0.1,
},
}
--------------------------------------------------------------------------------
-- User Configurable Constants
--------------------------------------------------------------------------------
-- Minimum spacing between commands (Squared) when drawing a path for a single unit, must be >16*16 (Or orders overlap and cancel)
local minPathSpacingSq = 50 * 50
-- Minimum line length to cause formation move instead of single-click-style order
local minFormationLength = 20
-- How long should algorithms take. (~0.1 gives visible stutter, default: 0.05)
local maxHngTime = 0.05 -- Desired maximum time for hungarian algorithm
local maxNoXTime = 0.05 -- Strict maximum time for backup algorithm
local defaultHungarianUnits = 20 -- Need a baseline to start from when no config data saved
local minHungarianUnits = 10 -- If we kept reducing maxUnits it can get to a point where it can never increase, so we enforce minimums on the algorithms.
local unitIncreaseThresh = 0.85 -- We only increase maxUnits if the units are great enough for time to be meaningful
-- Alpha loss per second after releasing mouse
local lineFadeRate = 2.0
-- What commands are eligible for custom formations
local formationCmds = {
[CMD.MOVE] = true,
[CMD.FIGHT] = true,
[CMD.ATTACK] = true,
[CMD.MANUALFIRE] = true,
[CMD.PATROL] = true,
[CMD.UNLOAD_UNIT] = true,
[CMD_JUMP] = true, -- jump
[CMD_PLACE_BEACON] = true, -- teleport beacon
[CMD_UNIT_SET_TARGET] = true, -- settarget
[CMD_UNIT_SET_TARGET_CIRCLE] = true, -- settarget
}
-- What commands require alt to be held (Must also appear in formationCmds)
local requiresAlt = {
[CMD.ATTACK] = true,
[CMD.MANUALFIRE] = true,
[CMD.UNLOAD_UNIT] = true,
[CMD_UNIT_SET_TARGET] = true, -- settarget
[CMD_UNIT_SET_TARGET_CIRCLE] = true, -- settarget
}
-- Context-based default commands that can be overridden (i.e. guard when mouseover unit)
-- If the mouse remains on the same target for both Press/Release then the formation is ignored and original command is issued.
-- Normal logic will follow after override, i.e. must be a formationCmd to get formation, alt must be held if requiresAlt, etc.
local overrideCmds = {
[CMD.GUARD] = CMD.MOVE,
}
-- What commands are issued at a position or unit/feature ID (Only used by GetUnitPosition)
local positionCmds = {
[CMD.MOVE]=true, [CMD.ATTACK]=true, [CMD.RECLAIM]=true, [CMD.RESTORE]=true, [CMD.RESURRECT]=true,
[CMD.PATROL]=true, [CMD.CAPTURE]=true, [CMD.FIGHT]=true, [CMD.MANUALFIRE]=true, [CMD_JUMP]=true, -- jump
[CMD.UNLOAD_UNIT]=true, [CMD.UNLOAD_UNITS]=true,[CMD.LOAD_UNITS]=true, [CMD.GUARD]=true, [CMD.AREA_ATTACK] = true,
}
--------------------------------------------------------------------------------
-- Globals
--------------------------------------------------------------------------------
local maxHungarianUnits = defaultHungarianUnits -- Also set when loading config
local fNodes = {} -- Formation nodes, filled as we draw
local fDists = {} -- fDists[i] = distance from node 1 to node i
local totaldxy = 0 -- Measure of distance mouse has moved, used to unjag lines drawn in minimap
local lineLength = 0 -- Total length of the line
local dimmCmd = nil -- The dimming command (Used for color)
local dimmNodes = {} -- The current nodes of dimming line
local dimmAlpha = 0 -- The current alpha of dimming line
local pathCandidate = false -- True if we should start a path on mouse move
local draggingPath = false -- True if we are dragging a path for unit(s) to follow
local lastPathPos = nil -- The last point added to the path, used for min-distance check
local overriddenCmd = nil -- The command we ignored in favor of move
local overriddenTarget = nil -- The target (for params) we ignored
local usingCmd = nil -- The command to execute across the line
local usingRMB = false -- If the command is the default it uses right click, otherwise it is active and uses left click
local inMinimap = false -- Is the line being drawn in the minimap
local endShift = false -- True to reset command when shift is released
local MiniMapFullProxy = (Spring.GetConfigInt("MiniMapFullProxy", 0) == 1)
--------------------------------------------------------------------------------
-- Speedups
--------------------------------------------------------------------------------
local GL_LINE_STRIP = GL.LINE_STRIP
local glVertex = gl.Vertex
local glLineStipple = gl.LineStipple
local glLineWidth = gl.LineWidth
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glScale = gl.Scale
local glTranslate = gl.Translate
local glLoadIdentity = gl.LoadIdentity
local spGetActiveCommand = Spring.GetActiveCommand
local spSetActiveCommand = Spring.SetActiveCommand
local spGetDefaultCommand = Spring.GetDefaultCommand
local spFindUnitCmdDesc = Spring.FindUnitCmdDesc
local spGetModKeyState = Spring.GetModKeyState
local spGetInvertQueueKey = Spring.GetInvertQueueKey
local spIsAboveMiniMap = Spring.IsAboveMiniMap
local spGetSelectedUnitsCount = Spring.GetSelectedUnitsCount
local spGetSelectedUnits = Spring.GetSelectedUnits
local spGetUnitDefID = Spring.GetUnitDefID
local spGiveOrder = Spring.GiveOrder
local spGetUnitIsTransporting = Spring.GetUnitIsTransporting
local spGetCommandQueue = Spring.GetCommandQueue
local spGetUnitPosition = Spring.GetUnitPosition
local spGetGroundHeight = Spring.GetGroundHeight
local spGetFeaturePosition = Spring.GetFeaturePosition
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spGetUnitHeight = Spring.GetUnitHeight
local spGetCameraPosition = Spring.GetCameraPosition
local spGetViewGeometry = Spring.GetViewGeometry
local spTraceScreenRay = Spring.TraceScreenRay
local mapSizeX, mapSizeZ = Game.mapSizeX, Game.mapSizeZ
local maxUnits = Game.maxUnits
local osclock = os.clock
local tsort = table.sort
local floor = math.floor
local ceil = math.ceil
local sqrt = math.sqrt
local sin = math.sin
local cos = math.cos
local max = math.max
local huge = math.huge
local pi2 = 2*math.pi
local CMD_INSERT = CMD.INSERT
local CMD_MOVE = CMD.MOVE
local CMD_ATTACK = CMD.ATTACK
local CMD_UNLOADUNIT = CMD.UNLOAD_UNIT
local CMD_UNLOADUNITS = CMD.UNLOAD_UNITS
local CMD_SET_WANTED_MAX_SPEED = CMD.SET_WANTED_MAX_SPEED
local CMD_OPT_ALT = CMD.OPT_ALT
local CMD_OPT_CTRL = CMD.OPT_CTRL
local CMD_OPT_META = CMD.OPT_META
local CMD_OPT_SHIFT = CMD.OPT_SHIFT
local CMD_OPT_RIGHT = CMD.OPT_RIGHT
local keyShift = 304
local filledCircleOutFading = {} --Table of display lists keyed by cmdID
--------------------------------------------------------------------------------
-- Helper Functions
--------------------------------------------------------------------------------
local function CulledTraceScreenRay(mx, my, coords, minimap)
local targetType, params = spTraceScreenRay(mx, my, coords, minimap)
if targetType == "ground" then
params[4], params[5], params[6] = nil, nil, nil
return targetType, params
end
return targetType, params
end
local function GetModKeys()
local alt, ctrl, meta, shift = spGetModKeyState()
if spGetInvertQueueKey() then -- Shift inversion
shift = not shift
end
return alt, ctrl, meta, shift
end
local function GetUnitFinalPosition(uID)
local ux, uy, uz = spGetUnitPosition(uID)
local cmds = spGetCommandQueue(uID, -1)
for i = #cmds, 1, -1 do
local cmd = cmds[i]
if (cmd.id < 0) or positionCmds[cmd.id] then
local params = cmd.params
if #params >= 3 then
return params[1], params[2], params[3]
else
if #params == 1 then
local pID = params[1]
local px, py, pz
if pID > maxUnits then
px, py, pz = spGetFeaturePosition(pID - maxUnits)
else
px, py, pz = spGetUnitPosition(pID)
end
if px then
return px, py, pz
end
end
end
end
end
return ux, uy, uz
end
local function SetColor(cmdID, alpha)
if cmdID == CMD_MOVE then glColor(0.5, 1.0, 0.5, alpha) -- Green
elseif cmdID == CMD_ATTACK then glColor(1.0, 0.2, 0.2, alpha) -- Red
elseif cmdID == CMD.MANUALFIRE then glColor(1.0, 1.0, 1.0, alpha) -- White
elseif cmdID == CMD_UNLOADUNIT then glColor(1.0, 1.0, 0.0, alpha) -- Yellow
elseif cmdID == CMD_UNIT_SET_TARGET then glColor(1, 0.75, 0, alpha) -- Orange
elseif cmdID == CMD_UNIT_SET_TARGET_CIRCLE then glColor(1, 0.75, 0, alpha) -- Orange
else glColor(0.5, 0.5, 1.0, alpha) -- Blue
end
end
local function CanUnitExecute(uID, cmdID)
if cmdID == CMD_UNLOADUNIT then
local transporting = spGetUnitIsTransporting(uID)
return (transporting and #transporting > 0)
end
return (spFindUnitCmdDesc(uID, cmdID) ~= nil)
end
local function GetExecutingUnits(cmdID)
local units = {}
local selUnits = spGetSelectedUnits()
for i = 1, #selUnits do
local uID = selUnits[i]
if CanUnitExecute(uID, cmdID) then
units[#units + 1] = uID
end
end
return units
end
local function AddFNode(pos)
local px, pz = pos[1], pos[3]
if px < 0 or pz < 0 or px > mapSizeX or pz > mapSizeZ then
return false
end
local n = #fNodes
if n == 0 then
fNodes[1] = pos
fDists[1] = 0
else
local prevNode = fNodes[n]
local dx, dz = px - prevNode[1], pz - prevNode[3]
local distSq = dx*dx + dz*dz
if distSq == 0.0 then -- Don't add if duplicate
return false
end
local dis = sqrt(distSq)
fNodes[n + 1] = pos
fDists[n + 1] = fDists[n] + dis
lineLength = lineLength + dis
end
totaldxy = 0
return true
end
local function HasWaterWeapon(UnitDefID)
local haswaterweapon = false
local numweapons = #(UnitDefs[UnitDefID]["weapons"])
for j=1, numweapons do
local weapondefid = UnitDefs[UnitDefID]["weapons"][j]["weaponDef"]
local iswaterweapon = WeaponDefs[weapondefid]["waterWeapon"]
if iswaterweapon then haswaterweapon=true end
end
return haswaterweapon
end
local function GetInterpNodes(mUnits)
local number = #mUnits
local spacing = fDists[#fNodes] / (#mUnits - 1)
local haswaterweapon = {}
for i=1, number do
local UnitDefID = spGetUnitDefID(mUnits[i])
haswaterweapon[i] = HasWaterWeapon(UnitDefID)
end
--result of this and code below is that the height of the aimpoint for a unit [i] will be:
--(a) on GetGroundHeight(units aimed position), if the unit has a waterweapon
--(b) on whichever is highest out of water surface (=0) and GetGroundHeight(units aimed position), if the unit does not have water weapon.
--in BA this must match the behaviour of prevent_range_hax or commands will get modified.
local interpNodes = {}
local sPos = fNodes[1]
local sX = sPos[1]
local sZ = sPos[3]
local sDist = 0
local eIdx = 2
local ePos = fNodes[2]
local eX = ePos[1]
local eZ = ePos[3]
local eDist = fDists[2]
local sY
if haswaterweapon[1] then
sY = spGetGroundHeight(sX, sZ)
else
sY = math.max(0,spGetGroundHeight(sX,sZ))
end
interpNodes[1] = {sX, sY, sZ}
for n = 1, number - 2 do
local reqDist = n * spacing
while (reqDist > eDist) do
sX = eX
sZ = eZ
sDist = eDist
eIdx = eIdx + 1
ePos = fNodes[eIdx]
eX = ePos[1]
eZ = ePos[3]
eDist = fDists[eIdx]
end
local nFrac = (reqDist - sDist) / (eDist - sDist)
local nX = sX * (1 - nFrac) + eX * nFrac
local nZ = sZ * (1 - nFrac) + eZ * nFrac
local nY
if haswaterweapon[number+1] then
nY = spGetGroundHeight(nX, nZ)
else
nY = math.max(0,spGetGroundHeight(nX, nZ))
end
interpNodes[n + 1] = {nX, nY, nZ}
end
ePos = fNodes[#fNodes]
eX = ePos[1]
eZ = ePos[3]
local eY
if haswaterweapon[number] then eY=spGetGroundHeight(eX, eZ) else eY=math.max(0,spGetGroundHeight(eX, eZ)) end
interpNodes[number] = {eX, eY, eZ}
--DEBUG for i=1,number do Spring.Echo(interpNodes[i]) end
return interpNodes
end
local function GetCmdOpts(alt, ctrl, meta, shift, right)
local opts = { alt=alt, ctrl=ctrl, meta=meta, shift=shift, right=right }
local coded = 0
if alt then coded = coded + CMD_OPT_ALT end
if ctrl then coded = coded + CMD_OPT_CTRL end
if meta then coded = coded + CMD_OPT_META end
if shift then coded = coded + CMD_OPT_SHIFT end
if right then coded = coded + CMD_OPT_RIGHT end
opts.coded = coded
return opts
end
local function GiveNotifyingOrder(cmdID, cmdParams, cmdOpts)
if widgetHandler:CommandNotify(cmdID, cmdParams, cmdOpts) then
return
end
spGiveOrder(cmdID, cmdParams, cmdOpts.coded)
end
local function GiveNonNotifyingOrder(cmdID, cmdParams, cmdOpts)
spGiveOrder(cmdID, cmdParams, cmdOpts.coded)
end
local function GiveNotifyingOrderToUnit(uID, cmdID, cmdParams, cmdOpts)
local widgets = widgetHandler.widgets
for i=1, #widgets do
local w = widgets[i]
if w.UnitCommandNotify and w:UnitCommandNotify(uID, cmdID, cmdParams, cmdOpts) then
return
end
end
spGiveOrderToUnit(uID, cmdID, cmdParams, cmdOpts.coded)
end
--------------------------------------------------------------------------------
-- Mouse/keyboard Callins
--------------------------------------------------------------------------------
function widget:MousePress(mx, my, mButton)
lineLength = 0
-- Where did we click
inMinimap = spIsAboveMiniMap(mx, my)
if inMinimap and not MiniMapFullProxy then return false end
-- Get command that would've been issued
local _, activeCmdID = spGetActiveCommand()
if activeCmdID then
if mButton ~= 1 then
return false
end
usingCmd = activeCmdID
usingRMB = false
else
if mButton ~= 3 then
return false
end
local _, defaultCmdID = spGetDefaultCommand()
if not defaultCmdID then return false end
local overrideCmdID = overrideCmds[defaultCmdID]
if overrideCmdID then
local targType, targID = CulledTraceScreenRay(mx, my, false, inMinimap)
if targType == 'unit' then
overriddenCmd = defaultCmdID
overriddenTarget = targID
elseif targType == 'feature' then
overriddenCmd = defaultCmdID
overriddenTarget = targID + maxUnits
else
-- We can't reversibly override a command if we can't get the original target, so we give up overriding it.
return false
end
usingCmd = overrideCmdID
else
overriddenCmd = nil
overriddenTarget = nil
usingCmd = defaultCmdID
end
usingRMB = true
end
-- Without this, the unloads issued will use the area of the last area unload
if usingCmd == CMD_UNLOADUNITS then
usingCmd = CMD_UNLOADUNIT
end
-- Is this command eligible for a custom formation ?
local alt, ctrl, meta, shift = GetModKeys()
if not (formationCmds[usingCmd] and (alt or not requiresAlt[usingCmd])) then
return false
end
-- Get clicked position
local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap)
if not pos then return false end
-- Setup formation node array
if not AddFNode(pos) then return false end
-- Is this line a path candidate (We don't do a path off an overriden command)
pathCandidate = (not overriddenCmd) and (spGetSelectedUnitsCount()==1 or (alt and not requiresAlt[usingCmd]))
-- We handled the mouse press
return true
end
function widget:MouseMove(mx, my, dx, dy, mButton)
-- It is possible for MouseMove to fire after MouseRelease
if #fNodes == 0 then
return false
end
-- Minimap-specific checks
if inMinimap then
totaldxy = totaldxy + dx*dx + dy*dy
if (totaldxy < 5) or not spIsAboveMiniMap(mx, my) then
return false
end
end
-- Get clicked position
local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap)
if not pos then return false end
-- Add the new formation node
if not AddFNode(pos) then return false end
-- Have we started drawing a line?
if #fNodes == 2 then
-- We have enough nodes to start drawing now
widgetHandler:UpdateWidgetCallIn("DrawInMiniMap", self)
widgetHandler:UpdateWidgetCallIn("DrawWorld", self)
-- If the line is a path, start the units moving to this node
if pathCandidate then
local alt, ctrl, meta, shift = GetModKeys()
local cmdOpts = GetCmdOpts(false, ctrl, meta, shift, usingRMB) -- using alt uses springs box formation, so we set it off always
GiveNotifyingOrder(usingCmd, pos, cmdOpts)
lastPathPos = pos
draggingPath = true
end
else
-- Are we dragging a path?
if draggingPath then
local dx, dz = pos[1] - lastPathPos[1], pos[3] - lastPathPos[3]
if (dx*dx + dz*dz) > minPathSpacingSq then
local alt, ctrl, meta, shift = GetModKeys()
local cmdOpts = GetCmdOpts(false, ctrl, meta, true, usingRMB) -- using alt uses springs box formation, so we set it off always
GiveNonNotifyingOrder(usingCmd, pos, cmdOpts)
lastPathPos = pos
end
end
end
return false
end
function widget:MouseRelease(mx, my, mButton)
-- It is possible for MouseRelease to fire after MouseRelease
if #fNodes == 0 then
return false
end
-- Modkeys / command reset
local alt, ctrl, meta, shift = GetModKeys()
if not usingRMB then
if shift then
endShift = true -- Reset on release of shift
else
spSetActiveCommand(0) -- Reset immediately
end
end
-- Are we going to use the drawn formation?
local usingFormation = true
-- Override checking
if overriddenCmd then
local targetID
local targType, targID = CulledTraceScreenRay(mx, my, false, inMinimap)
if targType == 'unit' then
targetID = targID
elseif targType == 'feature' then
targetID = targID + maxUnits
end
if targetID and targetID == overriddenTarget then
-- Signal that we are no longer using the drawn formation
usingFormation = false
-- Process the original command instead
local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB)
GiveNotifyingOrder(overriddenCmd, {overriddenTarget}, cmdOpts)
end
end
-- Using path? If so then we do nothing
if draggingPath then
draggingPath = false
-- Using formation? If so then it's time to calculate and issue orders.
elseif usingFormation then
-- Add final position (Sometimes we don't get the last MouseMove before this MouseRelease)
if (not inMinimap) or spIsAboveMiniMap(mx, my) then
local _, pos = CulledTraceScreenRay(mx, my, true, inMinimap)
if pos then
AddFNode(pos)
end
end
-- Get command options
local cmdOpts = GetCmdOpts(alt, ctrl, meta, shift, usingRMB)
-- Single click ? (no line drawn)
--if (#fNodes == 1) then
if fDists[#fNodes] < minFormationLength then
-- We should check if any units are able to execute it,
-- but the order is small enough network-wise that the tiny bug potential isn't worth it.
GiveNotifyingOrder(usingCmd, fNodes[1], cmdOpts)
else
-- Order is a formation
-- Are any units able to execute it?
local mUnits = GetExecutingUnits(usingCmd)
if #mUnits > 0 then
local interpNodes = GetInterpNodes(mUnits)
local orders
if (#mUnits <= maxHungarianUnits) then
orders = GetOrdersHungarian(interpNodes, mUnits, #mUnits, shift and not meta)
else
orders = GetOrdersNoX(interpNodes, mUnits, #mUnits, shift and not meta)
end
if meta then
local altOpts = GetCmdOpts(true, false, false, false, false)
for i = 1, #orders do
local orderPair = orders[i]
local orderPos = orderPair[2]
GiveNotifyingOrderToUnit(orderPair[1], CMD_INSERT, {0, usingCmd, cmdOpts.coded, orderPos[1], orderPos[2], orderPos[3]}, altOpts)
end
else
for i = 1, #orders do
local orderPair = orders[i]
GiveNotifyingOrderToUnit(orderPair[1], usingCmd, orderPair[2], cmdOpts)
end
end
end
end
-- Move Speed (Applicable to every order)
local wantedSpeed = 99999 -- High enough to exceed all units speed, but not high enough to cause errors (i.e. vs math.huge)
if ctrl then
local selUnits = spGetSelectedUnits()
for i = 1, #selUnits do
local uSpeed = UnitDefs[spGetUnitDefID(selUnits[i])].speed
if uSpeed > 0 and uSpeed < wantedSpeed then
wantedSpeed = uSpeed
end
end
end
-- Directly giving speed order appears to work perfectly, including with shifted orders ...
-- ... But other widgets CMD.INSERT the speed order into the front (Posn 1) of the queue instead (which doesn't work with shifted orders)
local speedOpts = GetCmdOpts(alt, ctrl, meta, shift, true)
GiveNotifyingOrder(CMD_SET_WANTED_MAX_SPEED, {wantedSpeed / 30}, speedOpts)
end
if #fNodes > 1 then
dimmCmd = usingCmd
dimmNodes = fNodes
dimmAlpha = 1.0
widgetHandler:UpdateWidgetCallIn("Update", self)
end
fNodes = {}
fDists = {}
return true
end
function widget:KeyRelease(key)
if (key == keyShift) and endShift then
spSetActiveCommand(0)
endShift = false
end
end
--------------------------------------------------------------------------------
-- Drawing
--------------------------------------------------------------------------------
local function tVerts(verts)
for i = 1, #verts do
local v = verts[i]
if v[1] and v[2] and v[3] then
glVertex(v[1], v[2], v[3])
end
end
end
local function tVertsMinimap(verts)
for i = 1, #verts do
local v = verts[i]
if v[1] and v[3] then
glVertex(v[1], v[3], 1)
end
end
end
local function filledCircleVerts(cmd, cornerCount)
SetColor(cmd, 1)
glVertex(0,0,0)
SetColor(cmd, 0)
for t = 0, pi2, pi2 / cornerCount do
glVertex(sin(t), 0, cos(t))
end
end
-- local function DrawFilledCircle(pos, size, cornerCount)
-- glPushMatrix()
-- glTranslate(pos[1], pos[2], pos[3])
-- glScale(size, 1, size)
-- gl.CallList(filledCircleVerts)
-- glPopMatrix()
-- end
local function DrawFilledCircleOutFading(pos, size, cornerCount)
glPushMatrix()
glTranslate(pos[1], pos[2], pos[3])
glScale(size, 1, size)
local cmd = usingCmd
if filledCircleOutFading[usingCmd] == nil then
cmd = 0
end
gl.CallList(filledCircleOutFading[cmd])
-- glBeginEnd(GL.TRIANGLE_FAN, function()
-- glVertex(0,0,0)
-- for t = 0, pi2, pi2 / cornerCount do
-- glVertex(sin(t), 0, cos(t))
-- end
-- end)
-- draw extra glow as base
-- has hardly any effect but doubles gpuTime, so disabled for now
-- glBeginEnd(GL.TRIANGLE_FAN, function()
-- SetColor(usingCmd, 1/15)
-- glVertex(0,0,0)
-- SetColor(usingCmd, 0)
-- local baseSize = size * 2.8
-- for t = 0, pi2, pi2 / 8 do
-- glVertex(sin(t) * baseSize, 0, cos(t) * baseSize)
-- end
-- end)
glPopMatrix()
end
local function DrawFormationDots(vertFunction, zoomY, unitCount)
local currentLength = 0
local lengthPerUnit = lineLength / (unitCount-1)
local lengthUnitNext = lengthPerUnit
local dotSize = sqrt(zoomY*0.1)*options.dotsize.value
if (#fNodes > 1) and (unitCount > 1) then
SetColor(usingCmd, 1)
DrawFilledCircleOutFading(fNodes[1], dotSize, 8)
if (#fNodes > 2) then
for i=1, #fNodes-2 do -- first and last circle are drawn before and after the for loop
local x = fNodes[i][1]
local y = fNodes[i][3]
local x2 = fNodes[i+1][1]
local y2 = fNodes[i+1][3]
local dx = x - x2
local dy = y - y2
local length = sqrt((dx*dx)+(dy*dy))
while (currentLength + length >= lengthUnitNext) do
local factor = (lengthUnitNext - currentLength) / length
local factorPos =
{fNodes[i][1] + ((fNodes[i+1][1] - fNodes[i][1]) * factor),
fNodes[i][2] + ((fNodes[i+1][2] - fNodes[i][2]) * factor),
fNodes[i][3] + ((fNodes[i+1][3] - fNodes[i][3]) * factor)}
DrawFilledCircleOutFading(factorPos, dotSize, 8)
lengthUnitNext = lengthUnitNext + lengthPerUnit
end
currentLength = currentLength + length
end
end
DrawFilledCircleOutFading(fNodes[#fNodes], dotSize, 8)
end
end
local function DrawFormationLines(vertFunction, lineStipple)
glLineStipple(lineStipple, 4095)
glLineWidth(options.linewidth.value)
if #fNodes > 1 then
SetColor(usingCmd, 1.0)
glBeginEnd(GL_LINE_STRIP, vertFunction, fNodes)
glColor(1,1,1,1)
end
if #dimmNodes > 1 then
SetColor(dimmCmd, dimmAlpha)
glBeginEnd(GL_LINE_STRIP, vertFunction, dimmNodes)
glColor(1,1,1,1)
end
glLineWidth(1.0)
glLineStipple(false)
end
local Xs, Ys = spGetViewGeometry()
Xs, Ys = Xs*0.5, Ys*0.5
function widget:ViewResize(viewSizeX, viewSizeY)
Xs, Ys = spGetViewGeometry()
Xs, Ys = Xs*0.5, Ys*0.5
end
function widget:DrawWorld()
-- Draw lines when a path is drawn instead of a formation, OR when drawmode_v2 for formations is not "dots" only
if pathCandidate or options.drawmode_v2.value ~= "dots" then
DrawFormationLines(tVerts, 2)
end
-- Draw dots when no path is drawn AND nodenumber is high enough AND drawmode_v2 for formations is not "lines" only
if not pathCandidate and (#fNodes > 1 or #dimmNodes > 1) and options.drawmode_v2.value ~= "lines" then
local camX, camY, camZ = spGetCameraPosition()
local at, p = CulledTraceScreenRay(Xs,Ys,true,false,false)
if at == "ground" then
local dx, dy, dz = camX-p[1], camY-p[2], camZ-p[3]
--zoomY = ((dx*dx + dy*dy + dz*dz)*0.01)^0.25 --tests show that sqrt(sqrt(x)) is faster than x^0.25
zoomY = sqrt(dx*dx + dy*dy + dz*dz)
else
--zoomY = sqrt((camY - max(spGetGroundHeight(camX, camZ), 0))*0.1)
zoomY = camY - max(spGetGroundHeight(camX, camZ), 0)
end
if zoomY < 6 then
zoomY = 6
end
if lineLength > 0 then --don't try and draw if the command was cancelled by having two mouse buttons pressed at once
local unitCount = spGetSelectedUnitsCount()
DrawFormationDots(tVerts, zoomY, unitCount)
end
end
end
function widget:DrawInMiniMap()
glPushMatrix()
glLoadIdentity()
glTranslate(0, 1, 0)
glScale(1 / mapSizeX, -1 / mapSizeZ, 1)
DrawFormationLines(tVertsMinimap, 1)
glPopMatrix()
end
function InitFilledCircle(cmdID)
filledCircleOutFading[cmdID] = gl.CreateList(gl.BeginEnd, GL.TRIANGLE_FAN, filledCircleVerts, cmdID, 8)
end
function widget:Initialize()
-- filledCircle = gl.CreateList(gl.BeginEnd, GL.TRIANGLE_FAN, filledCircleVerts, 8)
InitFilledCircle(CMD_MOVE)
InitFilledCircle(CMD_ATTACK)
InitFilledCircle(CMD.MANUALFIRE)
InitFilledCircle(CMD_UNLOADUNIT)
InitFilledCircle(CMD_UNIT_SET_TARGET)
InitFilledCircle(CMD_UNIT_SET_TARGET_CIRCLE)
InitFilledCircle(0)
end
function widget:Update(deltaTime)
dimmAlpha = dimmAlpha - lineFadeRate * deltaTime
if dimmAlpha <= 0 then
dimmNodes = {}
widgetHandler:RemoveWidgetCallIn("Update", self)
if #fNodes == 0 then
widgetHandler:RemoveWidgetCallIn("DrawWorld", self)
widgetHandler:RemoveWidgetCallIn("DrawInMiniMap", self)
end
end
end
---------------------------------------------------------------------------------------------------------
-- Config
---------------------------------------------------------------------------------------------------------
function widget:GetConfigData() -- Saving
return {
['maxHungarianUnits'] = maxHungarianUnits,
}
end
function widget:SetConfigData(data) -- Loading
maxHungarianUnits = data['maxHungarianUnits'] or defaultHungarianUnits
end
---------------------------------------------------------------------------------------------------------
-- Matching Algorithms
---------------------------------------------------------------------------------------------------------
function GetOrdersNoX(nodes, units, unitCount, shifted)
-- Remember when we start
-- This is for capping total time
-- Note: We at least complete initial assignment
local startTime = osclock()
---------------------------------------------------------------------------------------------------------
-- Find initial assignments
---------------------------------------------------------------------------------------------------------
local unitSet = {}
local fdist = -1
local fm
for u = 1, unitCount do
-- Get unit position
local ux, uz
if shifted then
ux, _, uz = GetUnitFinalPosition(units[u])
else
ux, _, uz = spGetUnitPosition(units[u])
end
unitSet[u] = {ux, units[u], uz, -1} -- Such that x/z are in same place as in nodes (So we can use same sort function)
-- Work on finding furthest points (As we have ux/uz already)
for i = u - 1, 1, -1 do
local up = unitSet[i]
local vx, vz = up[1], up[3]
local dx, dz = vx - ux, vz - uz
local dist = dx*dx + dz*dz
if (dist > fdist) then
fdist = dist
fm = (vz - uz) / (vx - ux)
end
end
end
-- Maybe nodes are further apart than the units
for i = 1, unitCount - 1 do
local np = nodes[i]
local nx, nz = np[1], np[3]
for j = i + 1, unitCount do
local mp = nodes[j]
local mx, mz = mp[1], mp[3]
local dx, dz = mx - nx, mz - nz
local dist = dx*dx + dz*dz
if (dist > fdist) then
fdist = dist
fm = (mz - nz) / (mx - nx)
end
end
end
local function sortFunc(a, b)
-- y = mx + c
-- c = y - mx
-- c = y + x / m (For perp line)
return (a[3] + a[1] / fm) < (b[3] + b[1] / fm)
end
tsort(unitSet, sortFunc)
tsort(nodes, sortFunc)
for u = 1, unitCount do
unitSet[u][4] = nodes[u]
end
---------------------------------------------------------------------------------------------------------
-- Main part of algorithm
---------------------------------------------------------------------------------------------------------
-- M/C for each finished matching
local Ms = {}
local Cs = {}
-- Stacks to hold finished and still-to-check units
local stFin = {}
local stFinCnt = 0
local stChk = {}
local stChkCnt = 0
-- Add all units to check stack
for u = 1, unitCount do
stChk[u] = u
end
stChkCnt = unitCount
-- Begin algorithm
while ((stChkCnt > 0) and (osclock() - startTime < maxNoXTime)) do
-- Get unit, extract position and matching node position
local u = stChk[stChkCnt]
local ud = unitSet[u]
local ux, uz = ud[1], ud[3]
local mn = ud[4]
local nx, nz = mn[1], mn[3]
-- Calculate M/C
local Mu = (nz - uz) / (nx - ux)
local Cu = uz - Mu * ux
-- Check for clashes against finished matches
local clashes = false
for i = 1, stFinCnt do
-- Get opposing unit and matching node position
local f = stFin[i]
local fd = unitSet[f]
local tn = fd[4]
-- Get collision point
local ix = (Cs[f] - Cu) / (Mu - Ms[f])
local iz = Mu * ix + Cu
-- Check bounds
if ((ux - ix) * (ix - nx) >= 0) and
((uz - iz) * (iz - nz) >= 0) and
((fd[1] - ix) * (ix - tn[1]) >= 0) and
((fd[3] - iz) * (iz - tn[3]) >= 0) then
-- Lines cross
-- Swap matches, note this retains solution integrity
ud[4] = tn
fd[4] = mn
-- Remove clashee from finished
stFin[i] = stFin[stFinCnt]
stFinCnt = stFinCnt - 1
-- Add clashee to top of check stack
stChkCnt = stChkCnt + 1
stChk[stChkCnt] = f
-- No need to check further
clashes = true
break
end
end
if not clashes then
-- Add checked unit to finished
stFinCnt = stFinCnt + 1
stFin[stFinCnt] = u
-- Remove from to-check stack (Easily done, we know it was one on top)
stChkCnt = stChkCnt - 1
-- We can set the M/C now
Ms[u] = Mu
Cs[u] = Cu
end
end
---------------------------------------------------------------------------------------------------------
-- Return orders
---------------------------------------------------------------------------------------------------------
local orders = {}
for i = 1, unitCount do
local unit = unitSet[i]
orders[i] = {unit[2], unit[4]}
end
return orders
end
function GetOrdersHungarian(nodes, units, unitCount, shifted)
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
-- (the following code is written by gunblob)
-- this code finds the optimal solution (slow, but effective!)
-- it uses the hungarian algorithm from http://www.public.iastate.edu/~ddoty/HungarianAlgorithm.html
-- if this violates gpl license please let gunblob and me know
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local t = osclock()
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
-- cache node<->unit distances
local distances = {}
--for i = 1, unitCount do distances[i] = {} end
for i = 1, unitCount do
local uID = units[i]
local ux, uz
if shifted then
ux, _, uz = GetUnitFinalPosition(uID)
else
ux, _, uz = spGetUnitPosition(uID)
end
distances[i] = {}
local dists = distances[i]
for j = 1, unitCount do
local nodePos = nodes[j]
local dx, dz = nodePos[1] - ux, nodePos[3] - uz
dists[j] = floor(sqrt(dx*dx + dz*dz) + 0.5)
-- Integer distances = greatly improved algorithm speed
end
end
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
-- find optimal solution and send orders
local result = findHungarian(distances, unitCount)
--------------------------------------------------------------------------------------------
--------------------------------------------------------------------------------------------
-- determine needed time and optimize the maxUnits limit
local delay = osclock() - t
if (delay > maxHngTime) and (maxHungarianUnits > minHungarianUnits) then
-- Delay is greater than desired, we have to reduce units
maxHungarianUnits = maxHungarianUnits - 1
else
-- Delay is less than desired, so thats OK
-- To make judgements we need number of units to be close to max
-- Because we are making predictions of time and we want them to be accurate
if (#units > maxHungarianUnits*unitIncreaseThresh) then
-- This implementation of Hungarian algorithm is O(n3)
-- Because we have less than maxUnits, but are altering maxUnits...
-- We alter the time, to 'predict' time we would be getting at maxUnits
-- We then recheck that against maxHngTime
local nMult = maxHungarianUnits / #units
if ((delay*nMult*nMult*nMult) < maxHngTime) then
maxHungarianUnits = maxHungarianUnits + 1
else
if (maxHungarianUnits > minHungarianUnits) then
maxHungarianUnits = maxHungarianUnits - 1
end
end
end
end
-- Return orders
local orders = {}
for i = 1, unitCount do
local rPair = result[i]
orders[i] = {units[rPair[1]], nodes[rPair[2]]}
end
return orders
end
function findHungarian(array, n)
-- Vars
local colcover = {}
local rowcover = {}
local starscol = {}
local primescol = {}
-- Initialization
for i = 1, n do
rowcover[i] = false
colcover[i] = false
starscol[i] = false
primescol[i] = false
end
-- Subtract minimum from rows
for i = 1, n do
local aRow = array[i]
local minVal = aRow[1]
for j = 2, n do
if aRow[j] < minVal then
minVal = aRow[j]
end
end
for j = 1, n do
aRow[j] = aRow[j] - minVal
end
end
-- Subtract minimum from columns
for j = 1, n do
local minVal = array[1][j]
for i = 2, n do
if array[i][j] < minVal then
minVal = array[i][j]
end
end
for i = 1, n do
array[i][j] = array[i][j] - minVal
end
end
-- Star zeroes
for i = 1, n do
local aRow = array[i]
for j = 1, n do
if (aRow[j] == 0) and not colcover[j] then
colcover[j] = true
starscol[i] = j
break
end
end
end
-- Start solving system
while true do
-- Are we done ?
local done = true
for i = 1, n do
if not colcover[i] then
done = false
break
end
end
if done then
local pairings = {}
for i = 1, n do
pairings[i] = {i, starscol[i]}
end
return pairings
end
-- Not done
local r, c = stepPrimeZeroes(array, colcover, rowcover, n, starscol, primescol)
stepFiveStar(colcover, rowcover, r, c, n, starscol, primescol)
end
end
function doPrime(array, colcover, rowcover, n, starscol, r, c, rmax, primescol)
primescol[r] = c
local starCol = starscol[r]
if starCol then
rowcover[r] = true
colcover[starCol] = false
for i = 1, rmax do
if not rowcover[i] and (array[i][starCol] == 0) then
local rr, cc = doPrime(array, colcover, rowcover, n, starscol, i, starCol, rmax, primescol)
if rr then
return rr, cc
end
end
end
return
else
return r, c
end
end
function stepPrimeZeroes(array, colcover, rowcover, n, starscol, primescol)
-- Infinite loop
while true do
-- Find uncovered zeros and prime them
for i = 1, n do
if not rowcover[i] then
local aRow = array[i]
for j = 1, n do
if (aRow[j] == 0) and not colcover[j] then
local i, j = doPrime(array, colcover, rowcover, n, starscol, i, j, i-1, primescol)
if i then
return i, j
end
break -- this row is covered
end
end
end
end
-- Find minimum uncovered
local minVal = huge
for i = 1, n do
if not rowcover[i] then
local aRow = array[i]
for j = 1, n do
if (aRow[j] < minVal) and not colcover[j] then
minVal = aRow[j]
end
end
end
end
-- There is the potential for minVal to be 0, very very rarely though. (Checking for it costs more than the +/- 0's)
-- Covered rows = +
-- Uncovered cols = -
for i = 1, n do
local aRow = array[i]
if rowcover[i] then
for j = 1, n do
if colcover[j] then
aRow[j] = aRow[j] + minVal
end
end
else
for j = 1, n do
if not colcover[j] then
aRow[j] = aRow[j] - minVal
end
end
end
end
end
end
function stepFiveStar(colcover, rowcover, row, col, n, starscol, primescol)
-- Star the initial prime
primescol[row] = false
starscol[row] = col
local ignoreRow = row -- Ignore the star on this row when looking for next
repeat
local noFind = true
for i = 1, n do
if (starscol[i] == col) and (i ~= ignoreRow) then
noFind = false
-- Unstar the star
-- Turn the prime on the same row into a star (And ignore this row (aka star) when searching for next star)
local pcol = primescol[i]
primescol[i] = false
starscol[i] = pcol
ignoreRow = i
col = pcol
break
end
end
until noFind
for i = 1, n do
rowcover[i] = false
colcover[i] = false
primescol[i] = false
end
for i = 1, n do
local scol = starscol[i]
if scol then
colcover[scol] = true
end
end
end
| gpl-2.0 |
wxguidesigner/wxGUIDesigner | build/premake/4.3/src/base/validate.lua | 70 | 2531 | --
-- validate.lua
-- Tests to validate the run-time environment before starting the action.
-- Copyright (c) 2002-2009 Jason Perkins and the Premake project
--
--
-- Performs a sanity check of all of the solutions and projects
-- in the session to be sure they meet some minimum requirements.
--
function premake.checkprojects()
local action = premake.action.current()
for sln in premake.solution.each() do
-- every solution must have at least one project
if (#sln.projects == 0) then
return nil, "solution '" .. sln.name .. "' needs at least one project"
end
-- every solution must provide a list of configurations
if (#sln.configurations == 0) then
return nil, "solution '" .. sln.name .. "' needs configurations"
end
for prj in premake.solution.eachproject(sln) do
-- every project must have a language
if (not prj.language) then
return nil, "project '" ..prj.name .. "' needs a language"
end
-- and the action must support it
if (action.valid_languages) then
if (not table.contains(action.valid_languages, prj.language)) then
return nil, "the " .. action.shortname .. " action does not support " .. prj.language .. " projects"
end
end
for cfg in premake.eachconfig(prj) do
-- every config must have a kind
if (not cfg.kind) then
return nil, "project '" ..prj.name .. "' needs a kind in configuration '" .. cfg.name .. "'"
end
-- and the action must support it
if (action.valid_kinds) then
if (not table.contains(action.valid_kinds, cfg.kind)) then
return nil, "the " .. action.shortname .. " action does not support " .. cfg.kind .. " projects"
end
end
end
-- some actions have custom validation logic
if action.oncheckproject then
action.oncheckproject(prj)
end
end
end
return true
end
--
-- Check the specified tools (/cc, /dotnet, etc.) against the current action
-- to make sure they are compatible and supported.
--
function premake.checktools()
local action = premake.action.current()
if (not action.valid_tools) then
return true
end
for tool, values in pairs(action.valid_tools) do
if (_OPTIONS[tool]) then
if (not table.contains(values, _OPTIONS[tool])) then
return nil, "the " .. action.shortname .. " action does not support /" .. tool .. "=" .. _OPTIONS[tool] .. " (yet)"
end
else
_OPTIONS[tool] = values[1]
end
end
return true
end
| gpl-3.0 |
KayMD/Illarion-Content | item/id_66_markerstone.lua | 3 | 2989 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
-- UPDATE items SET itm_script='item.id_66_markerstone' WHERE itm_id IN (66);
local lookat = require("base.lookat")
local explorersguild = require("quest.explorersguild")
local common = require("base.common")
local ranklist = require("base.ranklist")
local explorerguild_320_questlog = require("quest.explorerguild_320_questlog")
local M = {}
function M.UseItem(User, SourceItem, ltstate) -- DONT EDIT THIS LINE!
local stonedata=SourceItem:getData("markerstone");
if tonumber(stonedata) then
local DisplayText
if not explorersguild.CheckStone(User,tonumber(stonedata)) then
--debug("Stone used. stonedata: "..stonedata)
DisplayText = common.GetNLS( User, "Du hast einen Markierungsstein der Abenteurergilde entdeckt; er trägt die Nummer "..stonedata,"You found a marker stone of the Explorers' Guild; it has the number "..stonedata);
explorersguild.WriteStone(User,tonumber(stonedata));
explorersguild.getReward(User);
ranklist.setRanklist(User, "explorerRanklist", explorersguild.CountStones(User));
User:setQuestProgress(320,1)
else
DisplayText = common.GetNLS( User, "Du hast diesen Markierungsstein der Abenteurergilde bereits früher gefunden; er trägt die Nummer "..stonedata..". Du hast bereits "..explorersguild.CountStones(User).." dieser Steine gefunden.","You have already found that marker stone of the Explorers' Guild earlier; it has the number "..stonedata..". You have already found "..explorersguild.CountStones(User).." of these stones.");
end
User:inform(DisplayText);
end
end
function M.LookAtItem(User,Item)
local stonedata=Item:getData("markerstone");
if tonumber(stonedata) then
if not explorersguild.CheckStone(User,tonumber(stonedata)) then
lookat.SetSpecialDescription( Item, "Ein Markierungsstein der Abenteurergilde.","A marker stone of the Explorers' Guild.");
else
lookat.SetSpecialDescription( Item, "Du hast diesen Markierungsstein der Abenteurergilde bereits früher gefunden; er trägt die Nummer "..stonedata,"You have already found that marker stone of the Explorers' Guild earlier; it has the number "..stonedata);
end
end
return lookat.GenerateLookAt(User, Item, lookat.NONE)
end
return M
| agpl-3.0 |
dmccuskey/dmc-lifecycle-mixin | dmc_corona/lib/dmc_lua/lua_events_mix.lua | 14 | 8192 | --====================================================================--
-- dmc_lua/lua_events_mix.lua
--
-- Documentation: http://docs.davidmccuskey.com/
--====================================================================--
--[[
The MIT License (MIT)
Copyright (C) 2014-2015 David McCuskey. All Rights Reserved.
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
--]]
--====================================================================--
--== DMC Lua Library : Lua Events Mixin
--====================================================================--
-- Semantic Versioning Specification: http://semver.org/
local VERSION = "0.2.2"
--====================================================================--
--== Setup, Constants
local Events
local Utils = {} -- make copying from Utils easier
local sfmt = string.format
--====================================================================--
--== Support Functions
--== Start: copy from lua_utils ==--
function Utils.createObjectCallback( object, method )
assert( object ~= nil, "missing object in Utils.createObjectCallback" )
assert( method ~= nil, "missing method in Utils.createObjectCallback" )
--==--
return function( ... )
return method( object, ... )
end
end
--== End: copy from lua_utils ==--
-- callback is either function or object (table)
-- creates listener lookup key given event name and handler
--
local function _createEventListenerKey( e_name, handler )
return e_name .. "::" .. tostring( handler )
end
-- return event unmodified
--
local function _createCoronaEvent( obj, event )
return event
end
-- obj,
-- event type, string
-- data, anything
-- params, table of params
-- params.merge, boolean, if to merge data (table) in with event table
--
local function _createDmcEvent( obj, e_type, data, params )
params = params or {}
if params.merge==nil then params.merge=false end
--==--
local e
if params.merge and type( data ) == 'table' then
e = data
e.name = obj.EVENT
e.type = e_type
e.target = obj
else
e = {
name=obj.EVENT,
type=e_type,
target=obj,
data=data
}
end
return e
end
local function _patch( obj )
obj = obj or {}
-- add properties
Events.__init__( obj )
obj.EVENT = Events.EVENT -- generic event name
-- add methods
obj.dispatchEvent = Events.dispatchEvent
obj.addEventListener = Events.addEventListener
obj.removeEventListener = Events.removeEventListener
obj.setDebug = Events.setDebug
obj.setEventFunc = Events.setEventFunc
obj._dispatchEvent = Events._dispatchEvent
return obj
end
--====================================================================--
--== Events Mixin
--====================================================================--
Events = {}
Events.EVENT = 'event_mix_event'
--======================================================--
-- Start: Mixin Setup for Lua Objects
function Events.__init__( self, params )
-- print( "Events.__init__" )
params = params or {}
--==--
--[[
event listeners key'd by:
* <event name>::<function>
* <event name>::<object>
{
<event name> = {
'event::function' = func,
'event::object' = object (table)
}
}
--]]
self.__event_listeners = {} -- holds event listeners
self.__debug_on = false
self.__event_func = params.event_func or _createDmcEvent
end
function Events.__undoInit__( self )
-- print( "Events.__undoInit__" )
self.__event_listeners = nil
self.__debug_on = nil
self.__event_func = nil
end
-- END: Mixin Setup for Lua Objects
--======================================================--
--====================================================================--
--== Public Methods
function Events.createCallback( self, method )
return Utils.createObjectCallback( self, method )
end
function Events.setDebug( self, value )
assert( type(value) == 'boolean', "setDebug requires boolean" )
self.__debug_on = value
end
function Events.setEventFunc( self, func )
assert( func and type(func)=='function', 'setEventFunc requires function' )
self.__event_func = func
end
function Events.createEvent( self, ... )
return self.__event_func( self, ... )
end
function Events.dispatchEvent( self, ... )
-- print( "Events.dispatchEvent" )
local f = self.__event_func
self:_dispatchEvent( f( self, ... ) )
end
function Events.dispatchRawEvent( self, event )
-- print( "Events.dispatchRawEvent", event )
assert( type(event)=='table', "wrong type for event" )
assert( event.name, "event must have property 'name'")
--==--
self:_dispatchEvent( event )
end
-- addEventListener()
--
function Events.addEventListener( self, e_name, listener )
-- print( "Events.addEventListener", e_name, listener )
assert( type(e_name)=='string', sfmt( "Events.addEventListener event name should be a string, received '%s'", tostring(e_name)) )
assert( type(listener)=='function' or type(listener)=='table', sfmt( "Events.addEventListener callback should be function or object, received '%s'", tostring(listener) ))
-- Sanity Check
if not e_name or type(e_name)~='string' then
error( "ERROR addEventListener: event name must be string", 2 )
end
if not listener and not Utils.propertyIn( {'function','table'}, type(listener) ) then
error( "ERROR addEventListener: listener must be a function or object", 2 )
end
-- Processing
local events, listeners, key
events = self.__event_listeners
if not events[ e_name ] then events[ e_name ] = {} end
listeners = events[ e_name ]
key = _createEventListenerKey( e_name, listener )
if listeners[ key ] then
print("WARNING:: Events:addEventListener, already have listener")
else
listeners[ key ] = listener
end
end
-- removeEventListener()
--
function Events.removeEventListener( self, e_name, listener )
-- print( "Events.removeEventListener" );
local listeners, key
listeners = self.__event_listeners[ e_name ]
if not listeners or type(listeners)~= 'table' then
print( "WARNING:: Events:removeEventListener, no listeners found" )
end
key = _createEventListenerKey( e_name, listener )
if not listeners[ key ] then
print( "WARNING:: Events:removeEventListener, listener not found" )
else
listeners[ key ] = nil
end
end
--====================================================================--
--== Private Methods
function Events:_dispatchEvent( event )
-- print( "Events:_dispatchEvent", event.name );
local e_name, listeners
e_name = event.name
if not e_name or not self.__event_listeners[ e_name ] then return end
listeners = self.__event_listeners[ e_name ]
if type(listeners)~='table' then return end
for k, callback in pairs( listeners ) do
if type( callback ) == 'function' then
-- have function
callback( event )
elseif type( callback )=='table' and callback[e_name] then
-- have object/table
local method = callback[e_name]
method( callback, event )
else
print( "WARNING: Events dispatchEvent", e_name )
end
end
end
--====================================================================--
--== Events Facade
--====================================================================--
return {
EventsMix=Events,
dmcEventFunc=_createDmcEvent,
coronaEventFunc=_createCoronaEvent,
patch=_patch,
}
| mit |
wangtianhang/UnityLuaTest | UnityLuaTest/Assets/ToLua/Lua/protobuf/wire_format.lua | 15 | 3767 | --
--------------------------------------------------------------------------------
-- FILE: wire_format.lua
-- DESCRIPTION: protoc-gen-lua
-- Google's Protocol Buffers project, ported to lua.
-- https://code.google.com/p/protoc-gen-lua/
--
-- Copyright (c) 2010 , 林卓毅 (Zhuoyi Lin) netsnail@gmail.com
-- All rights reserved.
--
-- Use, modification and distribution are subject to the "New BSD License"
-- as listed at <url: http://www.opensource.org/licenses/bsd-license.php >.
-- COMPANY: NetEase
-- CREATED: 2010年07月30日 15时59分53秒 CST
--------------------------------------------------------------------------------
--
local pb = require "pb"
module "protobuf.wire_format"
WIRETYPE_VARINT = 0
WIRETYPE_FIXED64 = 1
WIRETYPE_LENGTH_DELIMITED = 2
WIRETYPE_START_GROUP = 3
WIRETYPE_END_GROUP = 4
WIRETYPE_FIXED32 = 5
_WIRETYPE_MAX = 5
-- yeah, we don't need uint64
local function _VarUInt64ByteSizeNoTag(uint64)
if uint64 <= 0x7f then return 1 end
if uint64 <= 0x3fff then return 2 end
if uint64 <= 0x1fffff then return 3 end
if uint64 <= 0xfffffff then return 4 end
return 5
end
function PackTag(field_number, wire_type)
return field_number * 8 + wire_type
end
function UnpackTag(tag)
local wire_type = tag % 8
return (tag - wire_type) / 8, wire_type
end
ZigZagEncode32 = pb.zig_zag_encode32
ZigZagDecode32 = pb.zig_zag_decode32
ZigZagEncode64 = pb.zig_zag_encode64
ZigZagDecode64 = pb.zig_zag_decode64
function Int32ByteSize(field_number, int32)
return Int64ByteSize(field_number, int32)
end
function Int32ByteSizeNoTag(int32)
return _VarUInt64ByteSizeNoTag(int32)
end
function Int64ByteSize(field_number, int64)
return UInt64ByteSize(field_number, int64)
end
function UInt32ByteSize(field_number, uint32)
return UInt64ByteSize(field_number, uint32)
end
function UInt64ByteSize(field_number, uint64)
return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(uint64)
end
function SInt32ByteSize(field_number, int32)
return UInt32ByteSize(field_number, ZigZagEncode(int32))
end
function SInt64ByteSize(field_number, int64)
return UInt64ByteSize(field_number, ZigZagEncode(int64))
end
function Fixed32ByteSize(field_number, fixed32)
return TagByteSize(field_number) + 4
end
function Fixed64ByteSize(field_number, fixed64)
return TagByteSize(field_number) + 8
end
function SFixed32ByteSize(field_number, sfixed32)
return TagByteSize(field_number) + 4
end
function SFixed64ByteSize(field_number, sfixed64)
return TagByteSize(field_number) + 8
end
function FloatByteSize(field_number, flt)
return TagByteSize(field_number) + 4
end
function DoubleByteSize(field_number, double)
return TagByteSize(field_number) + 8
end
function BoolByteSize(field_number, b)
return TagByteSize(field_number) + 1
end
function EnumByteSize(field_number, enum)
return UInt32ByteSize(field_number, enum)
end
function StringByteSize(field_number, string)
return BytesByteSize(field_number, string)
end
function BytesByteSize(field_number, b)
return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(#b) + #b
end
function MessageByteSize(field_number, message)
return TagByteSize(field_number) + _VarUInt64ByteSizeNoTag(message.ByteSize()) + message.ByteSize()
end
function MessageSetItemByteSize(field_number, msg)
local total_size = 2 * TagByteSize(1) + TagByteSize(2) + TagByteSize(3)
total_size = total_size + _VarUInt64ByteSizeNoTag(field_number)
local message_size = msg.ByteSize()
total_size = total_size + _VarUInt64ByteSizeNoTag(message_size)
total_size = total_size + message_size
return total_size
end
function TagByteSize(field_number)
return _VarUInt64ByteSizeNoTag(PackTag(field_number, 0))
end
| mit |
saydulk/newfies-dialer | lua/libs/constant.lua | 4 | 1668 | --
-- Newfies-Dialer License
-- http://www.newfies-dialer.org
--
-- 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/.
--
-- Copyright (C) 2011-2015 Star2Billing S.L.
--
-- The primary maintainer of this project is
-- Arezqui Belaid <info@star2billing.com>
--
-- Constant Value SECTION_TYPE
PLAY_MESSAGE = "1"
MULTI_CHOICE = "2"
RATING_SECTION = "3"
CAPTURE_DIGITS = "4"
RECORD_MSG = "5"
CALL_TRANSFER = "6"
HANGUP_SECTION = "7"
CONFERENCE = "8"
DNC = "9"
SMS = "10"
SECTION_TYPE = {}
SECTION_TYPE["1"] = "PLAY_MESSAGE"
SECTION_TYPE["2"] = "MULTI_CHOICE"
SECTION_TYPE["3"] = "RATING_SECTION"
SECTION_TYPE["4"] = "CAPTURE_DIGITS"
SECTION_TYPE["5"] = "RECORD_MSG"
SECTION_TYPE["6"] = "CALL_TRANSFER"
SECTION_TYPE["7"] = "HANGUP_SECTION"
SECTION_TYPE["8"] = "CONFERENCE"
SECTION_TYPE["9"] = "DNC"
SECTION_TYPE["10"] = "SMS"
-- Constant Value SUBSCRIBER_STATUS
SUBSCRIBER_PENDING = "1"
SUBSCRIBER_PAUSE = "2"
SUBSCRIBER_ABORT = "3"
SUBSCRIBER_FAIL = "4"
SUBSCRIBER_SENT = "5"
SUBSCRIBER_IN_PROCESS = "6"
SUBSCRIBER_NOT_AUTHORIZED = "7"
SUBSCRIBER_COMPLETED = "8"
ROOT_DIR = '/usr/share/newfies-lua/'
TTS_DIR = ROOT_DIR..'tts/'
UPLOAD_DIR = '/usr/share/newfies/usermedia/'
AUDIODIR = '/usr/share/newfies/usermedia/tts/'
AUDIO_WELCOME = AUDIODIR..'script_9805d01afeec350f36ff3fd908f0cbd5.wav'
AUDIO_ENTERAGE = AUDIODIR..'script_4ee73b76b5b4c5d596ed1cb3257861f0.wav'
AUDIO_PRESSDIGIT = AUDIODIR..'script_610e09c761c4b592aaa954259ce4ce1d.wav'
FS_RECORDING_PATH = '/usr/share/newfies/usermedia/recording/'
USE_CACHE = false
| mpl-2.0 |
Flourish-Team/Flourish | Premake/source/modules/vstudio/tests/fs2005/projectsettings.lua | 7 | 8137 | --
-- tests/actions/vstudio/fs2005/projectsettings.lua
-- Validate generation of root <PropertyGroup/> in Visual Studio 2005+ .fsproj
-- Copyright (c) 2009-2017 Jason Perkins and the Premake project
--
local p = premake
local suite = test.declare("vstudio_dn2005_projectsettings")
local dn2005 = p.vstudio.dotnetbase
local cs2005 = p.vstudio.cs2005
--
-- Setup
--
local wks, prj
function suite.setup()
p.action.set("vs2005")
wks = test.createWorkspace()
language "F#"
uuid "AE61726D-187C-E440-BD07-2556188A6565"
end
local function prepare()
prj = test.getproject(wks, 1)
dn2005.prepare(cs2005)
dn2005.projectProperties(prj)
end
--
-- Version Tests
--
function suite.OnVs2005()
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
function suite.OnVs2008()
p.action.set("vs2008")
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>9.0.30729</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
function suite.OnVs2010()
p.action.set("vs2010")
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
]]
end
function suite.onVs2012()
p.action.set("vs2012")
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
</PropertyGroup>
]]
end
function suite.onVs2015()
p.action.set("vs2015")
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
]]
end
function suite.onVs2017()
p.action.set("vs2017")
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
]]
end
function suite.onVs2015_462()
p.action.set("vs2015")
framework "4.6.2"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.6.2</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
</PropertyGroup>
]]
end
--
-- Framework Tests
--
function suite.OnFrameworkVersion()
framework "3.0"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v3.0</TargetFrameworkVersion>
</PropertyGroup>
]]
end
function suite.OnDotNetFrameworkVersion()
dotnetframework "3.0"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v3.0</TargetFrameworkVersion>
</PropertyGroup>
]]
end
--
-- Make sure the root namespace can be overridden.
--
function suite.canOverrideRootNamespace()
namespace "MyCompany.%{prj.name}"
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.50727</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyCompany.MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
</PropertyGroup>
]]
end
--
-- WPF adds an additional element.
--
function suite.projectTypeGuids_onWPF()
p.action.set("vs2010")
flags { "WPF" }
prepare()
test.capture [[
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProductVersion>8.0.30703</ProductVersion>
<SchemaVersion>2.0</SchemaVersion>
<ProjectGuid>{AE61726D-187C-E440-BD07-2556188A6565}</ProjectGuid>
<OutputType>Exe</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>MyProject</RootNamespace>
<AssemblyName>MyProject</AssemblyName>
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
<TargetFrameworkProfile>
</TargetFrameworkProfile>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
</PropertyGroup>
]]
end
| mit |
KayMD/Illarion-Content | base/factions.lua | 2 | 29337 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local common = require("base.common")
local money = require("base.money")
local character = require("base.character")
local M = {}
-- NOTE: town IDs for:
M.outlaw = 0
M.cadomyr = 1
M.runewick = 2
M.galmair = 3
--Towns--
local TownList = {}
--A list with the ranks
local CadomyrRankListMale = {
{gRank = "Leibeigener", eRank = "Serf"}, --rank 1
{gRank = "Höriger", eRank = "Bondsman"}, --rank 2
{gRank = "Diener", eRank = "Servant"}, --rank 3
{gRank = "Freisasse", eRank = "Yeoman"}, --rank 4
{gRank = "Page", eRank = "Page"}, --rank 5
{gRank = "Knappe", eRank = "Squire"}, --rank 6
{gRank = "Ritter", eRank = "Knight"}, --rank 7
{gRank = "Baron", eRank = "Baron"}, --rank 8
{gRank = "Graf", eRank = "Count"}, --rank 9
{gRank = "Herzog", eRank = "Duke"}, --rank 10
{gRank = "König", eRank = "King"}}; --rank leader
local CadomyrRankListFemale = {
{gRank = "Leibeigene", eRank = "Serf"}, --rank 1
{gRank = "Hörige", eRank = "Bondswoman"}, --rank 2
{gRank = "Dienerin", eRank = "Servant"}, --rank 3
{gRank = "Freisassin", eRank = "Yeowoman"}, --rank 4
{gRank = "Pagin", eRank = "Page"}, --rank 5
{gRank = "Knappin", eRank = "Squire"}, --rank 6
{gRank = "Ritterin", eRank = "Knight"}, --rank 7
{gRank = "Baroin", eRank = "Baroness"}, --rank 8
{gRank = "Gräfin", eRank = "Countess"}, --rank 9
{gRank = "Herzogin", eRank = "Duchess"}, --rank 10
{gRank = "Königin", eRank = "Queen"}}; --rank leader
local RunewickRankListMale = {
{gRank = "Novize", eRank = "Novice"}, --rank 1
{gRank = "Anwärter", eRank = "Apprentice"}, --rank 2
{gRank = "Student", eRank = "Student"}, --rank 3
{gRank = "Gelehrter", eRank = "Scholar"}, --rank 4
{gRank = "Magister", eRank = "Master"}, --rank 5
{gRank = "Doktor", eRank = "Doctor"}, --rank 6
{gRank = "Dozent", eRank = "Docent"}, --rank 7
{gRank = "Professor", eRank = "Professor"}, --rank 8
{gRank = "Dekan", eRank = "Dean"}, --rank 9
{gRank = "Rektor", eRank = "Rector"}, --rank 10
{gRank = "Erzmagier", eRank = "Archmage"}}; --rank leader
local RunewickRankListFemale = {
{gRank = "Novizin", eRank = "Novice"}, --rank 1
{gRank = "Anwärterin", eRank = "Apprentice"}, --rank 2
{gRank = "Studentin", eRank = "Student"}, --rank 3
{gRank = "Gelehrte", eRank = "Scholar"}, --rank 4
{gRank = "Magister", eRank = "Master"}, --rank 5
{gRank = "Doktorin", eRank = "Doctor"}, --rank 6
{gRank = "Dozentin", eRank = "Docent"}, --rank 7
{gRank = "Professorin", eRank = "Professor"}, --rank 8
{gRank = "Dekanin", eRank = "Dean"}, --rank 9
{gRank = "Rektorin", eRank = "Rector"}, --rank 10
{gRank = "Erzmagierin", eRank = "Archmage"}}; --rank leader
local GalmairRankListMale = {
{gRank = "Rumtreiber", eRank = "Tramp"}, --rank 1
{gRank = "Gehilfe", eRank = "Assistant"}, --rank 2
{gRank = "Hausierer", eRank = "Pedlar"}, --rank 3
{gRank = "Krämer", eRank = "Grocer"}, --rank 4
{gRank = "Kaufmann", eRank = "Merchant"}, --rank 5
{gRank = "Finanzier", eRank = "Financier"}, --rank 6
{gRank = "Patrizier", eRank = "Patrician"}, --rank 7
{gRank = "Mogul", eRank = "Mogul"}, --rank 8
{gRank = "Magnat", eRank = "Magnate"}, --rank 9
{gRank = "Tycoon", eRank = "Tycoon"}, --rank 10
{gRank = "Don", eRank = "Don"}}; --rank leader
local GalmairRankListFemale = {
{gRank = "Rumtreiberin", eRank = "Tramp"}, --rank 1
{gRank = "Gehilfin", eRank = "Assistant"}, --rank 2
{gRank = "Hausiererin", eRank = "Pedlar"}, --rank 3
{gRank = "Krämerin", eRank = "Grocer"}, --rank 4
{gRank = "Kauffrau", eRank = "Merchant"}, --rank 5
{gRank = "Finanzier", eRank = "Financier"}, --rank 6
{gRank = "Patrizierin", eRank = "Patrician"}, --rank 7
{gRank = "Mogulin", eRank = "Mogul"}, --rank 8
{gRank = "Magnatin", eRank = "Magnate"}, --rank 9
{gRank = "Tycoon", eRank = "Tycoon"}, --rank 10
{gRank = "Don", eRank = "Don"}}; --rank leader
local NoneRankList ={};
NoneRankList[0] = {gRank = "Geächteter", eRank = "Outcast"};
M.townRanks = {CadomyrRankListMale, RunewickRankListMale, GalmairRankListMale, CadomyrRankListFemale, RunewickRankListFemale, GalmairRankListFemale}
M.townRanks[0] = NoneRankList;
--[[
AddTown
Add a Town to the Faction System(be carefull, adding a new town needs further changes in the whole script!)
@param TownID - the ID of the town(1-9 allowed)
@param TownName - the Townname
]]
local function AddTown(TownID, TownName)
table.insert(TownList,{townID=TownID, townName=TownName});
end
local citizenRank = 1;
M.highestRank = 7;
local specialRanks = {8,9,10};
local leaderRank = 11;
AddTown(0,"None");
AddTown(M.cadomyr,"Cadomyr");
AddTown(M.runewick,"Runewick");
AddTown(M.galmair,"Galmair");
--[[
returns the name of a town
@param TownID - the id of the town the name is looked up for
@return - name of town
]]
function M.getTownNameByID(TownID)
for i=1, #(TownList) do
if (TownList[i].townID == TownID) then
return TownList[i].townName
end
end
return "";
end
function M.getTownIdByName(name)
for i=1, #(TownList) do
if (TownList[i].townName == name) then
return TownList[i].townID
end
end
return 0;
end
--[[
returns the id of the town the char is a member of
@player - characterStruct
@return - Id of the town
]]
function M.getMembership(player)
return player:getQuestProgress(199)
end
function M.isCadomyrCitizen(player)
return M.getMembership(player) == M.cadomyr
end
function M.isGalmairCitizen(player)
return M.getMembership(player) == M.galmair
end
function M.isRunewickCitizen(player)
return M.getMembership(player) == M.runewick
end
function M.isOutlaw(player)
return M.getMembership(player) == M.outlaw
end
--[[
returns the name of the town the char is a member of
@player - characterStruct
@return - name of the town
]]
function M.getMembershipByName(player)
return M.getTownNameByID(player:getQuestProgress(199));
end
--[[
returns the current rank of a char.
@param player - characterStruct
@return - name of the rank
]]
function M.getRank(player, bothFlag)
local Faction = M.getFaction(player);
if (M.townRanks[Faction.tid] == nil) then
return "[ERROR: no ranks for " .. Faction.tid .. "]";
end
if (M.townRanks[Faction.tid][Faction.rankTown] == nil) then
return "[ERROR: no rank " .. Faction.rankTown .. " in town " .. Faction.tid .. "]";
end
if (player:increaseAttrib("sex",0) == 0) then --male Ranks
if not bothFlag then
if player:getPlayerLanguage() == 0 then
return M.townRanks[Faction.tid][Faction.rankTown].gRank;
else
return M.townRanks[Faction.tid][Faction.rankTown].eRank;
end
else
local gerRank = M.townRanks[Faction.tid][Faction.rankTown].gRank;
local enRank = M.townRanks[Faction.tid][Faction.rankTown].eRank
return gerRank, enRank;
end
else
if not bothFlag then
if player:getPlayerLanguage() == 0 then
return M.townRanks[tonumber(Faction.tid)+3][Faction.rankTown].gRank;
else
return M.townRanks[tonumber(Faction.tid)+3][Faction.rankTown].eRank;
end
else
local gerRank = M.townRanks[Faction.tid+3][Faction.rankTown].gRank;
local enRank = M.townRanks[Faction.tid+3][Faction.rankTown].eRank;
return gerRank, enRank;
end
end
end
--[[
Returns the special rank for a player
@param player - characterStruct
@return specialRank - special rank of player
]]
local function getSpecialRank(player)
local specialRank = player:getQuestProgress(200);
return specialRank;
end
--[[
returns the ranknumber of a players rank
@ player - characterStruct
@return - number of the rank
]]
function M.getRankAsNumber(player)
local rankTown;
local rankpoints;
if getSpecialRank(player) ~= 0 then
rankTown = getSpecialRank(player);
else
rankpoints = M.getRankpoints(player);
rankTown = math.floor(rankpoints/100)+1;
end
return rankTown;
end
--[[
returns the name of a specific rank
@player - characterStruct
@ranknumber - number of the rank, the name is needed for
@return - name of the rank
]]
function M.getRankName(player, ranknumber)
local Faction = M.getFaction(player);
if ranknumber > leaderRank then
return;
end
if (player:increaseAttrib("sex",0) == 0) then --male Ranks
if player:getPlayerLanguage() == 0 then
return M.townRanks[Faction.tid][ranknumber].gRank;
else
return M.townRanks[Faction.tid][ranknumber].eRank;
end
else
if player:getPlayerLanguage() == 0 then
return M.townRanks[tonumber(Faction.tid)+3][ranknumber].gRank;
else
return M.townRanks[tonumber(Faction.tid)+3][ranknumber].eRank;
end
end
end
--[[
getFaction
Looks up to which Faction a Character belongs and checks also his rank
@param originator -- the CharacterStruct
@return Array - 1. a counter how often a Char changed the town, 2.the Town he belongs to ,
3-5 the Ranks/Reputation in the Towns Cadomyr, Runewick and Galmair
]]
function M.getFaction(originator)
local rankTown;
--check for special rank
if getSpecialRank(originator) ~= 0 then
rankTown = getSpecialRank(originator);
else
rankTown = M.getRankAsNumber(originator);
end
local factionMembership = originator:getQuestProgress(199);
local towncnt = originator:getQuestProgress(201);
local rankpoints = M.getRankpoints(originator);
local specialRank = getSpecialRank(originator);
return { towncnt = towncnt, tid = factionMembership, rankTown = rankTown, rankpoints = rankpoints};
end
--[[
getRankpoints
Looks up how much Rankpoints a Character has
@param originator -- the CharacterStruct
@return qpg - rankpoints in realm
]]
function M.getRankpoints(originator)
local qpg = originator:getQuestProgress(202); -- rankpoints
return qpg;
end
--[[
setFaction
Saves the Factionchanges of the Char
@param CharacterStruct - The character who gets the new Questprogress
@param Faction - the Array which includes the values to be changed
]]
function M.setFaction(originator,Faction)
-------------write changes------------
originator:setQuestProgress(199,tonumber(Faction.tid));
originator:setQuestProgress(201,tonumber(Faction.towncnt));
originator:setQuestProgress(202,tonumber(Faction.rankpoints));
end
--[[
Sets a special rank if the rank given really is special
@param player - characterStruct
@param rank - new special rank (0 to take the specialness away)
@return - special rank was set (true|false)
]]
function M.setSpecialRank(player, rank)
local Faction = M.getFaction(player);
local rankpoints = Faction.rankpoints;
local inform;
if (rank > M.highestRank and rank < leaderRank) or rank == 0 then
if rankpoints >= (M.highestRank-1)*100 then
player:setQuestProgress(200, tonumber(rank));
if rank == 0 then
inform = common.GetNLS(player,"Du wurdest degradiert und hast nun keinen speziellen Rang mehr.","You have been demoted and have no special rank anymore.")
else
inform = common.GetNLS(player,"Du wurdest befördert und bist nun "..M.getRank(player)..".","You have been promoted and are now "..M.getRank(player)..".");
end
player:inform(inform)
return true;
else
return false;
end
end
end
--[[
Checks if the rank of a player has changed
@param rankpoints - the new rankpoints
@param rank - the current rank
]]
local function checkForRankChange(rankpoints,rank)
local newRank = math.floor(rankpoints/100)+1
if newRank > rank and newRank <= M.highestRank then
return newRank;
elseif newRank < rank and newRank >= citizenRank then
return newRank;
else
return rank;
end
end
--[[
inform the player about a rankchange
@param rankHigher - true|false (true = player advanced a rank)
@param factionValues - array of M.getFaction(player)
]]
local function informPlayerAboutRankchange(player, factionValues, rankHigher)
-- collect all data needed for rankchange inform
local townName = M.getTownNameByID(factionValues.tid)
local rankName
if (player:increaseAttrib("sex",0) == 0) then --male Ranks
rankName = M.townRanks[factionValues.tid][factionValues.rankTown]
else --female Ranks
rankName = M.townRanks[tonumber(factionValues.tid)+3][factionValues.rankTown]
end
-- Inform about rankchange
if rankHigher == true then
common.InformNLS( player, "Du hast soeben einen neuen Rang in "..townName.." erreicht. Du bist nun "..rankName.gRank..".",
"You reached a new town rank in "..townName..". You are now "..rankName.eRank..".");
else
common.InformNLS( player, "Durch deine ständigen Konflikte mit dem Gesetz ist dein Rang in "..townName.." um eine Stufe gesunken. Du bist nun "..rankName.gRank..".",
"Because of your permanent conflicts with the law your rank sinks for a degree in "..townName..". You are now "..rankName.eRank.."." );
end
end
--[[
informs the player about a rankpointchange
@param player - characterStruct
@modifierTextarray - Textarray with the info if the rankpoints were raised/ declined
]]
local function informPlayerAboutRankpointchange(player, modifierTextarray)
local faction = M.getMembership(player);
local factionLeadersDE = {"Königin Rosaline Edwards", "Erzmagier Elvaine Morgan", "Don Valerio Guilianni"};
local factionLeadersEN = {"Queen Rosaline Edwards'", "Archmage Elvaine Morgan's", "Don Valerio Guilianni's"};
if faction ~= 0 then
common.InformNLS(player, "Dein Ansehen bei "..factionLeadersDE[faction].." "..modifierTextarray[1], "You "..modifierTextarray[2].." in "..factionLeadersEN[faction].." favour.");
else
return;
end;
end
--[[
setRankpoints
Saves the Factionchanges of the Char//Guildchanges of the Char
@param CharacterStruct - The character who gets the new Questprogress
@param Rankpoints - the value Rankpoints
]]
function M.setRankpoints(originator, rankpoints)
local Faction = M.getFaction(originator);
local rank = Faction.rankTown;
if Faction.tid == 0 then --outlaw
return;
end
if rankpoints < 0 then
rankpoints = 0;
elseif rankpoints > ((M.highestRank-1)*100)+99 then
rankpoints = ((M.highestRank-1)*100)+99;
end
-- determine if player got a new rank
if rank <= M.highestRank then
Faction.rankTown = checkForRankChange(rankpoints,rank);
end
-- Factionleaders always have the leader rank 11 and 1000 rankpoints (just to keep it consistent)
if originator.name == "Valerio Guilianni" or originator.name == "Rosaline Edwards" or originator.name == "Elvaine Morgan" then
rankpoints = (leaderRank-1)*100;
Faction.rankTown = leaderRank;
end
if rankpoints < M.getRankpoints(originator) then
local playerText = {"sinkt.","decline"};
informPlayerAboutRankpointchange(originator, playerText);
if getSpecialRank(originator) ~= 0 then
M.setSpecialRank(originator, 0);
end
elseif rankpoints > M.getRankpoints(originator) then
local playerText = {"steigt.","advance"};
informPlayerAboutRankpointchange(originator, playerText);
end
-- Inform about rankchange
if Faction.rankTown>rank then
informPlayerAboutRankchange(originator, Faction, true)
elseif Faction.rankTown<rank then
informPlayerAboutRankchange(originator, Faction, false)
end
------save changes----------------
originator:setQuestProgress(202,rankpoints);
end
--[[
function to leave a faction and become an outlaw
@param originator - characterStruct
@param Faction - the List with the Factionvalues of the Char
@param thisNPC - NPCStruct
]]
local function leaveFaction(originator, Faction, thisNPC)
Faction.rankpoints = 0;
Faction.rankTown = 0;
Faction.tid = 0;
M.setFaction(originator,Faction); --write fv in Questprogress
local gText="Du gehört nun keinem Reich mehr an. Das bedeutet, dass du frei, aber auf dich selbst gestellt seid. Viel Glück.";
local eText="You're now not belonging to any realm. This means you're free but also on your own. Good luck.";
local outText=common.GetNLS(originator,gText,eText);
thisNPC:talk(Character.say, outText);
end
--[[
makeCharMemberOfTown
makes the char citizen of the town
@param originator -- the characterStruct
@param fv -- the List with the Factionvalues of the Char
@param theRank(number) -- the rank the char shall get in the town
]]
function M.makeCharMemberOfTown(originator,thisNPC,fv,theRank,theTown)
if theRank==leaderRank then --make char to leader of this town
fv.tid = theTown; --make him member of this town
fv.rankTown = leaderRank; --give him the leader rank
fv = M.setFaction(originator,fv);
return;
elseif theRank == 0 or theTown == 0 then --becoming an outlaw
leaveFaction(originator, fv, thisNPC)
elseif theRank~=leaderRank then --make char to citizen
if (fv.tid == theTown) then --already citizen
return;
end
local amountToPay = 1000*(2^fv.towncnt) -- amount in coppercoins
local GAmount, SAmount,CAmount = money.MoneyToCoins(amountToPay);
local germanMoney, englishMoney = money.MoneyToString(amountToPay);
if not money.CharHasMoney(originator,amountToPay) then --not enough money!
local gText="Du hast nicht genug Geld dabei! Du benötigst"..germanMoney..".";
local eText="You don't have enough money with you! You'll need"..englishMoney..".";
local outText=common.GetNLS(originator,gText,eText);
thisNPC:talk(Character.say, outText);
return;
end
originator:inform("Das Wechseln der Stadt hat"..germanMoney.." gekostet.", "It costs"..englishMoney.." to change the faction.");
fv.rankpoints = 0 -- set default value for rankpoints
fv.tid = theTown; --set new Town ID
fv.rankTown = theRank -- set the rank of the town
if (fv.towncnt<99) then fv.towncnt = fv.towncnt+1; end; -- raise the town counter
M.setFaction(originator,fv); --write fv in Questprogress
money.TakeMoneyFromChar(originator,amountToPay); --take money
end
return;
end
--- Relations
--
-- The following functions allow checking and controlling the relations between factions.
-- The following constants define the different relations modes.
M.RELATION_SELF = -1; -- This is the constant returned in case the relation of a faction to itself is checked.
M.RELATION_FRIENDLY = 1; -- The factions have a friendly relationship.
M.RELATION_NEUTRAL = 0; -- The factions have a neutral relationship, guards will only process the members of this faction in case they appear hostile.
M.RELATION_HOSTILE = 2; -- The factions have a hostile relationship. The guards will ensure that the members of this faction stay out of the home town.
M.RELATION_AGGRESSIVE = 3; -- The factions have a aggressive relationship. The guards will engage the members of this faction on sight.
M.RELATION_ACCEPTED = 4; -- This is a special relationship that only applies to individual players. It causes the total relationship to the town to be neutral, even if the relationship of the town and the player faction is hostile or aggressive
--- Get the individual relationship of a player to a faction. These overwriting values are time limited.
--
-- @param player the player who's relation is queried
-- @param townFaction the faction
-- @return int the relationship constant for the relation of the faction to the individual player
local function getIndividualPlayerRelation(player, townFaction)
local relationId = -1;
local daysId = -1;
if (townFaction == M.cadomyr) then
relationId = 191;
daysId = 192;
elseif (townFaction == M.runewick) then
relationId = 193;
daysId = 194;
elseif (townFaction == M.galmair) then
relationId = 195;
daysId = 196;
end
if (relationId < 0) or (daysId < 0) then
return M.RELATION_NEUTRAL;
end
local relation = player:getQuestProgress(relationId);
if (relation == M.RELATION_NEUTRAL) then
return M.RELATION_NEUTRAL;
end
local days, setTime = player:getQuestProgress(daysId);
if (relation ~= M.RELATION_FRIENDLY) and (relation ~= M.RELATION_NEUTRAL) and (relation ~= M.RELATION_AGGRESSIVE) and (relation ~= M.RELATION_ACCEPTED) and (relation ~= M.RELATION_HOSTILE) then
debug("[Error] ".. character.LogText(player).." got illegal value for temporary faction relation. Resetting.");
player:setQuestProgress(relationId, M.RELATION_NEUTRAL);
return M.RELATION_NEUTRAL;
end
if (days > 0) then
local daysInSec = (days / 3) * 24 * 60 * 60;
if ((world:getTime("unix") - setTime) >= daysInSec) then
return M.RELATION_NEUTRAL;
end
end
return relation;
end
--- Apply a individual relation of a town faction to a player.
--
-- @param player the player to receives the new relationship
-- @param townFaction the faction that is effected
-- @param newRelation the new relation value
-- @param the time limited in days for this change to wear off
function M.setIndividualPlayerRelation(player, townFaction, newRelation, timeLimitInDays)
if (newRelation ~= M.RELATION_FRIENDLY) and (newRelation ~= M.RELATION_NEUTRAL) and (newRelation ~= M.RELATION_HOSTILE) and (newRelation ~= M.RELATION_AGGRESSIVE) and (newRelation ~= M.RELATION_ACCEPTED) then
debug("[Error] Applied illegal relationship mode: "..tostring(newRelation));
return;
end
local relationId = -1;
local daysId = -1;
if (townFaction == M.cadomyr) then
relationId = 191;
daysId = 192;
elseif (townFaction == M.runewick) then
relationId = 193;
daysId = 194;
elseif (townFaction == M.galmair) then
relationId = 195;
daysId = 196;
end
if (relationId < 0) or (daysId < 0) then
debug("[Error] Can't apply individual relationship for unknown town faction: "..tostring(townFaction));
return;
end
player:setQuestProgress(relationId, newRelation);
if (newRelation == M.RELATION_NEUTRAL) then
player:setQuestProgress(daysId, 0);
else
player:setQuestProgress(daysId, timeLimitInDays);
end
end
--- Get the relation of a town faction to a specific player. This functions takes both the relation of the town faction and the player faction and the
--- relation of the town faction to the individual player into consideration. Administrators are always considered to be friendly, because they are
--- very friendly persons in general.
--
-- @param player the player
-- @param townFaction the faction of the town
-- @return int the relationship constant for the relationship between the town faction and the player
function M.getPlayerRelation(player, townFaction)
if player:isAdmin() then
return M.RELATION_FRIENDLY;
end
local individualRelation = getIndividualPlayerRelation(player, townFaction);
local playerFaction = M.getFaction(player).tid;
local factionRelation = M.getFactionRelation(townFaction, playerFaction);
if (individualRelation == M.RELATION_ACCEPTED) then
return (factionRelation == M.RELATION_FRIENDLY) and M.RELATION_FRIENDLY or M.RELATION_NEUTRAL;
end
if (factionRelation == M.RELATION_AGGRESSIVE) then
return M.RELATION_AGGRESSIVE;
elseif (factionRelation == M.RELATION_HOSTILE) then
if (individualRelation == M.RELATION_AGGRESSIVE) then
return M.RELATION_AGGRESSIVE;
else
return M.RELATION_HOSTILE;
end
elseif (factionRelation == M.RELATION_NEUTRAL) then
if (individualRelation == M.RELATION_AGGRESSIVE) or (individualRelation == M.RELATION_HOSTILE) then
return individualRelation;
else
return M.RELATION_NEUTRAL;
end
else
return individualRelation;
end
end
function M.isPlayerPermittedInTown(player, townFaction)
local playerRelation = M.getPlayerRelation(player, townFaction)
if playerRelation == M.RELATION_HOSTILE or playerRelation == M.RELATION_AGGRESSIVE then
return false
else
return true
end
end
--- Get the relationship between two factions. The looking direction for the relationship is always from the town faction to the player faction.
--- So if the towns faction is hostile to the players faction and the players faction is neutral to the towns faction the returned result will be hostile.
--
-- @param townFaction the faction of the town that is checked
-- @param playerFaction the faction of the player that is checked
-- @return int the relationship constant for the relation of the towns faction to the player faction
function M.getFactionRelation(townFaction, playerFaction)
if (townFaction == playerFaction) then
return M.RELATION_SELF;
end
local found, relation = ScriptVars:find("Mode_"..tostring(townFaction));
if not found then
return M.RELATION_HOSTILE;
end
relation = relation % (10 ^ (playerFaction + 1));
relation = math.floor(relation / (10 ^ playerFaction));
if (relation ~= M.RELATION_FRIENDLY) and (relation ~= M.RELATION_NEUTRAL) and (relation ~= M.RELATION_AGGRESSIVE) then
return M.RELATION_HOSTILE;
end
return relation;
end
--- Set the relationship of a faction to another faction. The faction set is the faction from the town faction to the player faction.
--
-- @param townFaction the town faction
-- @param playerFaction the player faction
-- @param newRelation the new relationship (M.RELATION_FRIENDLY,M.RELATION_NEUTRAL,M.RELATION_HOSTILE,M.RELATION_AGGRESSIVE)
function M.setFactionRelation(townFaction, playerFaction, newRelation)
if (newRelation ~= M.RELATION_FRIENDLY) and (newRelation ~= M.RELATION_NEUTRAL) and (newRelation ~= M.RELATION_HOSTILE) and (newRelation ~= M.RELATION_AGGRESSIVE) then
debug("[Error] Applied illegal relationship mode: "..tostring(newRelation));
return;
end
if (townFaction == playerFaction) then
return;
end
-- get mode for all factions
local found, relationships = ScriptVars:find("Mode_"..townFaction);
local oldRelation = 0;
if not found then
ScriptVars:set("Mode_".. townFaction, 2222); -- hostile to everyone
relationships = 2222;
oldRelation = 2;
else
-- calculate the old mode for the player faction
oldRelation = relationships % (10 ^ (playerFaction + 1));
oldRelation = math.floor(oldRelation / (10 ^ playerFaction));
end
if (oldRelation == newRelation) then
return;
end;
relationships = relationships - (oldRelation * (10 ^ playerFaction));
relationships = relationships + (newRelation * (10 ^ playerFaction));
relationships = math.max(0, math.min(9999, relationships)); -- must not be negative & exceed 9999 (3 towns + outcasts)
ScriptVars:set("Mode_"..townFaction, relationships);
end
return M
| agpl-3.0 |
Sojerbot/javan | plugins/ingroup.lua | 1 | 61924 | 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.0',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_join = 'no',
lock_media = 'no',
lock_share = '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.0',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_join = 'no',
lock_media = 'no',
lock_share = '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.0',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_join = 'no',
lock_media = 'no',
lock_share = '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.0',
groupmodel = 'normal',
tag = 'no',
lock_badw = 'no',
lock_english = 'no',
lock_join = 'no',
lock_media = 'no',
lock_share = '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 version = "2"
if data[tostring(msg.to.id)]['settings']['version'] then
version = data[tostring(msg.to.id)]['settings']['version']
end
local groupmodel = "normal"
if data[tostring(msg.to.id)]['settings']['groupmodel'] then
groupmodel = data[tostring(msg.to.id)]['settings']['groupmodel']
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_english = data[tostring(msg.to.id)]['settings']['lock_english']
end
local lock_join = "no"
if data[tostring(msg.to.id)]['settings']['lock_join'] then
lock_join = data[tostring(msg.to.id)]['settings']['lock_join']
end
local lock_media = "no"
if data[tostring(msg.to.id)]['settings']['lock_media'] then
lock_media = data[tostring(msg.to.id)]['settings']['lock_media']
end
local lock_share = "no"
if data[tostring(msg.to.id)]['settings']['lock_share'] then
lock_share = data[tostring(msg.to.id)]['settings']['lock_share']
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>قفل ورود : "..lock_join.."\n>قفل رسانه : "..lock_media.."\n>قفل اشتراک گذاری : "..lock_share.."\n>حساسیت اسپم : "..NUM_MSG_MAX.."\n>قفل ربات ها : "..bots_protection.."\n>خوشامد : "..welcome.."\n>قفل تگ : "..tag.."\n>قفل اینگلیسی :"..lock_english.."\n>قفل فحش : "..lock_badw.."\n>مدل گروه : "..groupmodel.."\n>ورژن : "..version
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_join(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_join_lock = data[tostring(target)]['settings']['lock_join']
if group_join_lock == 'yes' then
return 'ورود از قبل قفل است'
else
data[tostring(target)]['settings']['lock_join'] = 'yes'
save_data(_config.moderation.data, data)
return 'ورود قفل شد'
end
end
local function unlock_group_join(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_join_lock = data[tostring(target)]['settings']['lock_join']
if group_join_lock == 'no' then
return 'ورود از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_join'] = '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_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 == '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 'ارسال لینک آزاد شد✅🔓'
end
end
local function lock_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 == '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_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 lock_group_media(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_media_lock = data[tostring(target)]['settings']['lock_media']
if group_media_lock == 'yes' then
return 'رسانه از قبل قفل است'
else
data[tostring(target)]['settings']['lock_media'] = 'yes'
save_data(_config.moderation.data, data)
return 'ارسال رسانه ممنوع شد'
end
end
local function unlock_group_media(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_media_lock = data[tostring(target)]['settings']['lock_media']
if group_media_lock == 'no' then
return 'ارسال رسانه از قبل آزاد است'
else
data[tostring(target)]['settings']['lock_media'] = 'no'
save_data(_config.moderation.data, data)
return 'ارسال رسانه آزاد شد'
end
end
local function lock_group_share(msg, data, target)
if not is_momod(msg) then
return "قفط مدیران"
end
local group_share_lock = data[tostring(target)]['settings']['lock_share']
if group_share_lock == 'yes' then
return 'اشتراک گذاری شماره از قبل ممنوع است'
else
data[tostring(target)]['settings']['lock_share'] = 'yes'
save_data(_config.moderation.data, data)
return 'اشتراک گذاری شماره ممنوع شد'
end
end
local function unlock_group_share(msg, data, target)
if not is_momod(msg) then
return "فقط مدیران"
end
local group_share_lock = data[tostring(target)]['settings']['lock_share']
if group_share_lock == 'no' then
return 'اشتراک گذاری شماره آزاد بود'
else
data[tostring(target)]['settings']['lock_share'] = '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_english, 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_english..' از قبل مدیر است')
end
data[group]['moderators'][tostring(member_id)] = member_english
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_english..' ترفیع یافت')
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.english then
member_english = '@'.. msg.from.english
else
member_english = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return promote(get_receiver(msg), member_english, member_id)
end
end
local function demote(receiver, member_english, 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_english..' مدیر نیست !')
end
data[group]['moderators'][tostring(member_id)] = nil
save_data(_config.moderation.data, data)
return send_large_msg(receiver, member_english..' تنزل یافت')
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.english then
member_english = '@'..msg.from.english
else
member_english = full_name
end
local member_id = msg.from.id
if msg.to.type == 'chat' then
return demote(get_receiver(msg), member_english, 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_english = "@"..result.english
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_english, member_id)
elseif mod_cmd == 'تنزل' then
return demote(receiver, member_english, 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] == 'اضافه' or matches[1] == 'add' 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] == 'اضافه' or matches[1] == 'add ' and matches[2] == 'ریلیم' or matches[2] == 'realm' 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] == 'حذف' or matches[1] == 'rem' and not matches[2] then
print("group "..msg.to.print_name.."("..msg.to.id..") removed")
return modrem(msg)
end
if matches[1] == 'حذف' or matches[1] == 'rem' and matches[2] == 'ریلیم' or matches[2] == 'realm' 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] == 'تنظیم نام' or 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)
savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]")
end
if matches[1] == 'تنظیم عکس' or matches[1] == 'setphoto' 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] == 'ترفیع' or matches[1] == 'promote' 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] == 'ترفیع' or matches[1] == 'promote' 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 english = matches[2]
local english = string.gsub(matches[2], '@', '')
return res_user(english, promote_demote_res, cbres_extra)
end
if matches[1] == 'تنزل' or matches[1] == 'demote' 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] == 'تنزل' or matches[1] == 'demote' 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.english 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 english = matches[2]
local english = string.gsub(matches[2], '@', '')
return res_user(english, promote_demote_res, cbres_extra)
end
if matches[1] == 'لیست مدیران' or matches[1] == 'modlist' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist")
return modlist(msg)
end
if matches[1] == 'توضیحات' or matches[1] == 'about' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description")
return get_description(msg, data)
end
if matches[1] == 'قوانین' or matches[1] == 'rules' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules")
return get_rules(msg, data)
end
if matches[1] == 'تنظیم' or matches[1] == 'set' then
if matches[2] == 'قوانین' or matches[2] == 'rules'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] == 'توضیحات' or matches[2] == 'about' 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] == 'قفل' or matches[1] == 'lock' then
local target = msg.to.id
if matches[2] == 'نام' or matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' or matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
if matches[2] == 'اسپم' or matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ")
return lock_group_floodmod(msg, data, target)
end
if matches[2] == 'ورود' or matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked join ")
return lock_group_join(msg, data, target)
end
if matches[2] == 'رسانه' or matches[2] == 'media' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked media ")
return lock_group_media(msg, data, target)
end
if matches[2] == 'اشتراک گذاری' or matches[2] == 'share' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked share ")
return lock_group_share(msg, data, target)
end
if matches[2] == 'ربات ها' or matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ")
return lock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' or matches[2] == 'link' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link🔒 ")
return lock_group_link(msg, data, target)
end
if matches[2] == 'تگ' or matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag🔒 ")
return lock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' or matches[2] == 'badw' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw🔒 ")
return lock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' or matches[2] == 'english' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked english🔒 ")
return lock_group_english(msg, data, target)
end
if matches[2] == 'خروج' or matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ")
return lock_group_leave(msg, data, target)
end
end
if matches[1] == 'بازکردن' or matches[1] == 'unlock' then
local target = msg.to.id
if matches[2] == 'نام' or matches[2] == 'name' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[2] == 'اعضا' or matches[2] == 'member' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
if matches[2] == 'عکس' or matches[2] == 'photo' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ")
return unlock_group_photomod(msg, data, target)
end
if matches[2] == 'اسپم' or matches[2] == 'flood' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ")
return unlock_group_floodmod(msg, data, target)
end
if matches[2] == 'ورود' or matches[2] == 'join' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked join ")
return unlock_group_join(msg, data, target)
end
if matches[2] == 'رسانه' or matches[2] == 'media' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked media ")
return unlock_group_media(msg, data, target)
end
if matches[2] == 'اشتراگ گذاری' or matches[2] == 'share' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked share ")
return unlock_group_share(msg, data, target)
end
if matches[2] == 'ربات ها' or matches[2] == 'bots' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ")
return unlock_group_bots(msg, data, target)
end
if matches[2] == 'لینک' or matches[2] == 'link' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link🔓 ")
return unlock_group_link(msg, data, target)
end
if matches[2] == 'تگ' or matches[2] == 'tag' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag🔓 ")
return unlock_group_tag(msg, data, target)
end
if matches[2] == 'فحش' or matches[2] == 'badw' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw🔓 ")
return unlock_group_badw(msg, data, target)
end
if matches[2] == 'اینگلیسی' or matches[2] == 'english' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked english🔓 ")
return unlock_group_english(msg, data, target)
end
if matches[2] == 'خروج' or matches[2] == 'leave' then
savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ")
return unlock_group_leave(msg, data, target)
end
end
if matches[1] == 'setversion' then
if not is_sudo(msg) then
return "فقط برای سودو❗️"
end
if matches[2] == '1.0' then
if version ~= '1.0' then
data[tostring(msg.to.id)]['settings']['version'] = '1.0'
save_data(_config.moderation.data, data)
end
return 'group version has been changed to 1.0'
end
if matches[2] == '2.0' then
if version ~= '2.0' then
data[tostring(msg.to.id)]['settings']['version'] = '2.0'
save_data(_config.moderation.data, data)
end
return 'group version has been changed to 2.0'
end
if matches[2] == '3.0' then
if version == '3.0' then
return 'group version has been changed to 3.0'
else
data[tostring(msg.to.id)]['settings']['version'] = '3.0'
save_data(_config.moderation.data, data)
return 'group version has been changed to 3.0'
end
end
end
if matches[1] == 'setgroup' then
if not is_sudo(msg) then
return "فقط برای سودو❗️"
end
if matches[2] == 'realm' then
if groupmodel ~= 'realm' then
data[tostring(msg.to.id)]['settings']['groupmodel'] = 'realm'
save_data(_config.moderation.data, data)
end
return 'Group model has been changed to realm'
end
if matches[2] == 'support' then
if groupmodel ~= 'support' then
data[tostring(msg.to.id)]['settings']['groupmodel'] = 'support'
save_data(_config.moderation.data, data)
end
return 'Group model has been changed to support'
end
if matches[2] == 'feedback' then
if groupmodel ~= 'feedback' then
data[tostring(msg.to.id)]['settings']['groupmodel'] = 'feedback'
save_data(_config.moderation.data, data)
end
return 'Group model has been changed to feedback'
end
if matches[2] == 'vip' then
if groupmodel ~= 'vip' then
data[tostring(msg.to.id)]['settings']['groupmodel'] = 'vip'
save_data(_config.moderation.data, data)
end
return 'Group model has been changed to vip'
end
if matches[2] == 'normal' then
if groupmodel == 'normal' then
return 'Group model has been changed to normal'
else
data[tostring(msg.to.id)]['settings']['groupmodel'] = 'normal'
save_data(_config.moderation.data, data)
return 'Group model has been changed to normal'
end
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] == 'لینک جدید' or matches[1] == 'newlink' 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] == 'لینک' or matches[1] == 'link' 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_______________________________________________________\n"..group_link
end
if matches[1] == 'لینک خصوصی' or matches[1] == 'linkpv' 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_______________________________________________________\n"..group_link)
end
if matches[1] == 'تنظیم صاحب' or matches[1] == 'setleader' 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] == 'تنظیم صاحب' or matches[1] == 'setleader' 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] == 'صاحب گروه' or matches[1] == 'owner' 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] == 'صاحب' or matches[1] == 'setgpleader' 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] == 'حساسیت' or matches[1] == 'setflood' 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] == 'پاک کردن' or matches[1] == 'clean' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
if matches[2] == 'اعضا' or matches[2] == 'member' then
if not is_owner(msg) then
return "شما مجاز نیستید"
end
local receiver = get_receiver(msg)
chat_info(receiver, cleanmember, {receiver=receiver})
end
if matches[2] == 'مدیران' or matches[2] == 'modlist' 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' or 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] == 'توضیحات' or matches[2] == 'about' 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] == 'کمک' or matches[1] == 'group help'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] == 'کد' or matches[1] == 'res' and is_momod(msg) then
local cbres_extra = {
chatid = msg.to.id
}
local english = matches[2]
local english = english:gsub("@","")
savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..english)
return res_user(english, 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+)$",
"^(تنظیمات)$",
"^(لیست مدیران)$",
"^(لینک جدید)$",
"^(لینک)$",
"^(لینک خصوصی)$",
"^(setversion) (.*)$",
"^(setgroup) (.*)$",
"^(add)$",
"^(add) (realm)$",
"^(rem)$",
"^(rem) (realm)$",
"^(rules)$",
"^(about)$",
"^(setname) (.*)$",
"^(setphoto)$",
"^(promote) (.*)$",
"^(promote)",
"^(clean) (.*)$",
"^(demote) (.*)$",
"^(demote)",
"^(set) ([^%s]+) (.*)$",
"^(lock) (.*)$",
"^(setleader) (%d+)$",
"^(setleader)",
"^(owner)$",
"^(res) (.*)$",
"^(setgpleader) (%d+) (%d+)$",
"^(unlock) (.*)$",
"^(setflood) (%d+)$",
"^(settings)$",
"^(modlist)$",
"^(newlink)$",
"^(link)$",
"^(kickinactive)$",
"^(kickinactive) (%d+)$",
"^(linkpv)$",
"^[!/#](add)$",
"^[!/#](add) (realm)$",
"^[!/#](rem)$",
"^[!/#](rem) (realm)$",
"^[!/#](rules)$",
"^[!/#](about)$",
"^[!/#](setname) (.*)$",
"^[!/#](setphoto)$",
"^[!/#](promote) (.*)$",
"^[!/#](promote)",
"^[!/#](clean) (.*)$",
"^[!/#](demote) (.*)$",
"^[!/#](demote)",
"^[!/#](set) ([^%s]+) (.*)$",
"^[!/#](lock) (.*)$",
"^[!/#](setleader) (%d+)$",
"^[!/#](setleader)",
"^[!/#](owner)$",
"^[!/#](res) (.*)$",
"^[!/#](setgpleader) (%d+) (%d+)$",
"^[!/#](unlock) (.*)$",
"^[!/#](setflood) (%d+)$",
"^[!/#](settings)$",
"^[!/#](modlist)$",
"^[!/#](newlink)$",
"^[!/#](link)$",
"^[!/#](linkpv)$",
"%[(photo)%]",
"^!!tgservice (.+)$",
},
run = run
}
end
| gpl-2.0 |
flike/Atlas | examples/tutorial-states.lua | 40 | 2935 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
--[[
--]]
function connect_server()
print("--> a client really wants to talk to a server")
end
function read_handshake( )
local con = proxy.connection
print("<-- let's send him some information about us")
print(" mysqld-version: " .. con.server.mysqld_version)
print(" thread-id : " .. con.server.thread_id)
print(" scramble-buf : " .. string.format("%q", con.server.scramble_buffer))
print(" server-addr : " .. con.server.dst.address)
print(" client-addr : " .. con.client.src.address)
-- lets deny clients from !127.0.0.1
if con.client.src.address ~= "127.0.0.1" then
proxy.response.type = proxy.MYSQLD_PACKET_ERR
proxy.response.errmsg = "only local connects are allowed"
print("we don't like this client");
return proxy.PROXY_SEND_RESULT
end
end
function read_auth( )
local con = proxy.connection
print("--> there, look, the client is responding to the server auth packet")
print(" username : " .. con.client.username)
print(" password : " .. string.format("%q", con.client.scrambled_password))
print(" default_db : " .. con.client.default_db)
if con.client.username == "evil" then
proxy.response.type = proxy.MYSQLD_PACKET_ERR
proxy.response.errmsg = "evil logins are not allowed"
return proxy.PROXY_SEND_RESULT
end
end
function read_auth_result( auth )
local state = auth.packet:byte()
if state == proxy.MYSQLD_PACKET_OK then
print("<-- auth ok");
elseif state == proxy.MYSQLD_PACKET_ERR then
print("<-- auth failed");
else
print("<-- auth ... don't know: " .. string.format("%q", auth.packet));
end
end
function read_query( packet )
print("--> someone sent us a query")
if packet:byte() == proxy.COM_QUERY then
print(" query: " .. packet:sub(2))
if packet:sub(2) == "SELECT 1" then
proxy.queries:append(1, packet)
end
end
end
function read_query_result( inj )
print("<-- ... ok, this only gets called when read_query() told us")
proxy.response = {
type = proxy.MYSQLD_PACKET_RAW,
packets = {
"\255" ..
"\255\004" .. -- errno
"#" ..
"12S23" ..
"raw, raw, raw"
}
}
return proxy.PROXY_SEND_RESULT
end
| gpl-2.0 |
gajop/Zero-K | LuaUI/Widgets/unit_initial_queue.lua | 2 | 21058 | local version = "v1.544"
function widget:GetInfo()
return {
name = "Initial Queue ZK",
desc = version .. " Allows you to queue buildings before game start",
author = "Niobium, KingRaptor",
date = "7 April 2010",
license = "GNU GPL, v2 or later",
layer = -1, -- Puts it below cmd_mex_placement.lua, to catch mex placement order before the cmd_mex_placement.lua does.
enabled = true,
handler = true
}
end
-- 12 jun 2012: "uDef.isMetalExtractor" was replaced by "uDef.extractsMetal > 0" to fix "metal" mode map switching (by [teh]decay, thx to vbs and Beherith)
-- 20 march 2013: added keyboard support with BA keybinds (Bluestone)
-- august 2013: send queue length to cmd_idle_players (BrainDamage)
--TODO: find way to detect GameStart countdown, so that we can remove button before GameStart (not after gamestart) since it will cause duplicate button error.
------------------------------------------------------------
-- Config
------------------------------------------------------------
local buildOptions = VFS.Include("gamedata/buildoptions.lua")
-- Colors
local buildDistanceColor = {0.3, 1.0, 0.3, 0.7}
local buildLinesColor = {0.3, 1.0, 0.3, 0.7}
local borderNormalColor = {0.3, 1.0, 0.3, 0.5}
local borderClashColor = {0.7, 0.3, 0.3, 1.0}
local borderValidColor = {0.0, 1.0, 0.0, 1.0}
local borderInvalidColor = {1.0, 0.0, 0.0, 1.0}
local buildingQueuedAlpha = 0.5
local metalColor = '\255\196\196\255' -- Light blue
local energyColor = '\255\255\255\128' -- Light yellow
local buildColor = '\255\128\255\128' -- Light green
local whiteColor = '\255\255\255\255' -- White
local fontSize = 14
------------------------------------------------------------
-- Globals
------------------------------------------------------------
local myTeamID = Spring.GetMyTeamID()
local myPlayerID = Spring.GetMyPlayerID()
local sDefID = Spring.GetTeamRulesParam(myTeamID, "commChoice") or UnitDefNames.dyntrainer_strike_base.id-- Starting unit def ID
local sDef = UnitDefs[sDefID]
local buildDistance = sDef.buildDistance
local selDefID = nil -- Currently selected def ID
local buildQueue = {}
local buildNameToID = {}
local gameStarted = false
local othersBuildQueue = {}
local isMex = {} -- isMex[uDefID] = true / nil
local weaponRange = {} -- weaponRange[uDefID] = # / nil
local changeStartUnitRegex = '^\138(%d+)$'
local startUnitParamName = 'startUnit'
local scrW, scrH = Spring.GetViewGeometry()
local mCost, eCost, bCost, buildTime = 0, 0, 0, 0
local CMD_STOP = CMD.STOP
------------------------------------------------------------
-- Local functions
------------------------------------------------------------
local function GetBuildingDimensions(uDefID, facing)
local bDef = UnitDefs[uDefID]
if (facing % 2 == 1) then
return 4 * bDef.zsize, 4 * bDef.xsize
else
return 4 * bDef.xsize, 4 * bDef.zsize
end
end
local function DrawBuilding(buildData, borderColor, buildingAlpha, drawRanges,teamID,drawSelectionBox)
local bDefID, bx, by, bz, facing = buildData[1], buildData[2], buildData[3], buildData[4], buildData[5]
local bw, bh = GetBuildingDimensions(bDefID, facing)
gl.DepthTest(false)
gl.Color(borderColor)
if drawSelectionBox then
gl.Shape(GL.LINE_LOOP, {{v={bx - bw, by, bz - bh}},
{v={bx + bw, by, bz - bh}},
{v={bx + bw, by, bz + bh}},
{v={bx - bw, by, bz + bh}}})
end
if drawRanges then
--[[
if isMex[bDefID] then
gl.Color(1.0, 0.3, 0.3, 0.7)
gl.DrawGroundCircle(bx, by, bz, Game.extractorRadius, 40)
end
]]
local wRange = weaponRange[bDefID]
if wRange then
gl.Color(1.0, 0.3, 0.3, 0.7)
gl.DrawGroundCircle(bx, by, bz, wRange, 40)
end
end
gl.DepthTest(GL.LEQUAL)
gl.DepthMask(true)
if buildingAlpha == 1 then gl.Lighting(true) end
gl.Color(1.0, 1.0, 1.0, buildingAlpha)
gl.PushMatrix()
gl.Translate(bx, by, bz)
gl.Rotate(90 * facing, 0, 1, 0)
gl.Texture("%"..bDefID..":0") --.s3o texture atlas for .s3o model
gl.UnitShape(bDefID, teamID, false, true, false)
gl.Texture(false)
gl.PopMatrix()
gl.Lighting(false)
gl.DepthTest(false)
gl.DepthMask(false)
end
local function DrawUnitDef(uDefID, uTeam, ux, uy, uz, rot)
gl.Color(1.0, 1.0, 1.0, 1.0)
gl.DepthTest(GL.LEQUAL)
gl.DepthMask(true)
gl.Lighting(true)
gl.PushMatrix()
gl.Translate(ux, uy, uz)
gl.Rotate(rot, 0, 1, 0)
gl.UnitShape(uDefID, uTeam, false, true, true)
gl.PopMatrix()
gl.Lighting(false)
gl.DepthTest(false)
gl.DepthMask(false)
end
local function DoBuildingsClash(buildData1, buildData2)
local w1, h1 = GetBuildingDimensions(buildData1[1], buildData1[5])
local w2, h2 = GetBuildingDimensions(buildData2[1], buildData2[5])
return math.abs(buildData1[2] - buildData2[2]) < w1 + w2 and
math.abs(buildData1[4] - buildData2[4]) < h1 + h2
end
local function SetSelDefID(defID)
selDefID = defID
-- if (isMex[selDefID] ~= nil) ~= (Spring.GetMapDrawMode() == "metal") then
-- Spring.SendCommands("ShowMetalMap")
-- end
-- if defID then
-- Spring.SetActiveCommand(defID)
-- end
end
local function GetSelDefID(defID)
return selDefID
end
local function GetUnitCanCompleteQueue(uID)
local uDefID = Spring.GetUnitDefID(uID)
if uDefID == sDefID then
return true
end
-- What can this unit build ?
local uCanBuild = {}
local uBuilds = UnitDefs[uDefID].buildOptions
for i = 1, #uBuilds do
uCanBuild[uBuilds[i]] = true
end
-- Can it build everything that was queued ?
for i = 1, #buildQueue do
if not uCanBuild[buildQueue[i][1]] then
return false
end
end
return true
end
local function GetQueueBuildTime()
local t = 0
for i = 1, #buildQueue do
t = t + UnitDefs[buildQueue[i][1]].buildTime
end
return t / sDef.buildSpeed
end
local function GetQueueCosts()
local mCost = 0
local eCost = 0
local bCost = 0
for i = 1, #buildQueue do
local uDef = UnitDefs[buildQueue[i][1]]
mCost = mCost + uDef.metalCost
eCost = eCost + uDef.energyCost
bCost = bCost + uDef.buildTime
end
return mCost, eCost, bCost
end
local function GetBuildOptions()
return buildOptions
end
------------------------------------------------------------
-- Initialize/shutdown
------------------------------------------------------------
function widget:Initialize()
if (Spring.GetGameFrame() > 0) then -- Don't run if game has already started
Spring.Echo("Game already started or Start Position is randomized. Removed: Initial Queue ZK") --added this message because widget removed message might not appear (make debugging harder)
widgetHandler:RemoveWidget(self)
return
end
for uDefID, uDef in pairs(UnitDefs) do
if uDef.customParams.ismex then
isMex[uDefID] = true
end
if uDef.maxWeaponRange > 16 then
weaponRange[uDefID] = uDef.maxWeaponRange
end
end
if UnitDefNames["cormex"] then
isMex[UnitDefNames["cormex"].id] = true;
end
WG.InitialQueue = true
end
function widget:Shutdown()
WG.InitialQueue = nil
end
------------------------------------------------------------
-- Drawing
------------------------------------------------------------
--local queueTimeFormat = whiteColor .. 'Queued: ' .. buildColor .. '%.1f sec ' .. whiteColor .. '[' .. metalColor .. '%d m' .. whiteColor .. ', ' .. energyColor .. '%d e' .. whiteColor .. ']'
local queueTimeFormat = whiteColor .. 'Queued ' .. metalColor .. '%dm ' .. buildColor .. '%.1f sec'
--local queueTimeFormat = metalColor .. '%dm ' .. whiteColor .. '/ ' .. energyColor .. '%de ' .. whiteColor .. '/ ' .. buildColor .. '%.1f sec'
-- "Queued 23.9 seconds (820m / 2012e)" (I think this one is the best. Time first emphasises point and goodness of widget)
-- Also, it is written like english and reads well, none of this colon stuff or figures stacked together
local timer = 0
local updateFreq = 0.15
-- check if we're chosen a new comm
function widget:Update(dt)
timer = timer + dt
if timer > updateFreq then
local defID = Spring.GetTeamRulesParam(myTeamID, "commChoice")
if defID and defID ~= sDefID then
local def = UnitDefs[defID]
if def then
sDefID = defID
sDef = def
buildDistance = sDef.buildDistance
mCost, eCost, bCost = GetQueueCosts()
buildTime = bCost / sDef.buildSpeed
end
end
timer = 0
end
end
--[[
function widget:DrawScreen()
gl.PushMatrix()
gl.Translate(scrW/2, scrH*0.4, 0)
if #buildQueue > 0 then
gl.Text(string.format(queueTimeFormat, mCost, buildTime), 0, 0, fontSize, 'cdo')
end
gl.PopMatrix()
end
]]--
local function DrawWorldFunc()
--don't draw anything once the game has started; after that engine can draw queues itself
if gameStarted then
return
end
-- local clash = false
-- Set up gl
gl.LineWidth(1.49)
-- We need data about currently selected building, for drawing clashes etc
local selBuildData
if selDefID then
local mx, my = Spring.GetMouseState()
local _, pos = Spring.TraceScreenRay(mx, my, true)
if pos then
local bx, by, bz = Spring.Pos2BuildPos(selDefID, pos[1], pos[2], pos[3])
local buildFacing = Spring.GetBuildFacing()
selBuildData = {selDefID, bx, by, bz, buildFacing}
end
end
-- local myTeamID = Spring.GetMyTeamID()
local sx, sy, sz = Spring.GetTeamStartPosition(myTeamID) -- Returns -100, -100, -100 when none chosen
local startChosen = (sx > 0)
if startChosen then
-- Correction for start positions in the air
sy = Spring.GetGroundHeight(sx, sz)
-- Draw the starting unit at start position
local rot = (math.abs(Game.mapSizeX/2 - sx) > math.abs(Game.mapSizeZ/2 - sz))
and ((sx>Game.mapSizeX/2) and 270 or 90)
or ((sz>Game.mapSizeZ/2) and 180 or 0)
DrawUnitDef(sDefID, myTeamID, sx, sy, sz, rot)
-- Draw start units build radius
gl.Color(buildDistanceColor)
gl.DrawGroundCircle(sx, sy, sz, buildDistance, 40)
end
-- Draw all the buildings
local queueLineVerts = startChosen and {{v={sx, sy, sz}}} or {}
for b = 1, #buildQueue do
local buildData = buildQueue[b]
--[[
if selBuildData and DoBuildingsClash(selBuildData, buildData) then
DrawBuilding(buildData, borderClashColor, buildingQueuedAlpha,false,myTeamID,true)
clash = true
end
--]]
--else
DrawBuilding(buildData, borderNormalColor, buildingQueuedAlpha,false,myTeamID,true)
--end
queueLineVerts[#queueLineVerts + 1] = {v={buildData[2], buildData[3], buildData[4]}}
end
-- Draw queue lines
gl.Color(buildLinesColor)
gl.LineStipple("springdefault")
gl.Shape(GL.LINE_STRIP, queueLineVerts)
gl.LineStipple(false)
for teamID,playerXBuildQueue in pairs(othersBuildQueue)do
sx, sy, sz = Spring.GetTeamStartPosition(teamID) -- Returns -100, -100, -100 when none chosen
startChosen = sx and (sx > 0)
-- Draw all the buildings
queueLineVerts = startChosen and {{v={sx, sy, sz}}} or {}
for b = 1, #playerXBuildQueue do
local buildData = playerXBuildQueue[b]
DrawBuilding(buildData, borderNormalColor, buildingQueuedAlpha,false,teamID,false)
queueLineVerts[#queueLineVerts + 1] = {v={buildData[2], buildData[3], buildData[4]}}
end
-- Draw queue lines
gl.Color(buildLinesColor)
gl.LineStipple("springdefault")
gl.Shape(GL.LINE_STRIP, queueLineVerts)
gl.LineStipple(false)
end
-- Draw selected building
--[[
if selBuildData then
if (not clash) and Spring.TestBuildOrder(selDefID, selBuildData[2], selBuildData[3], selBuildData[4], selBuildData[5]) ~= 0 then
DrawBuilding(selBuildData, borderValidColor, 1.0, true,myTeamID,true)
else
DrawBuilding(selBuildData, borderInvalidColor, 1.0, true,myTeamID,true)
end
end
--]]
-- Reset gl
gl.Color(1.0, 1.0, 1.0, 1.0)
gl.LineWidth(1.0)
end
function widget:DrawWorld()
DrawWorldFunc()
end
function widget:DrawWorldRefraction()
DrawWorldFunc()
end
function widget:ViewResize(vsx, vsy)
scrW = vsx
scrH = vsy
end
local function explode(div,str) --copied from gui_epicmenu.lua
if (div=='') then return false end
local pos,arr = 0,{}
-- for each divider found
for st,sp in function() return string.find(str,div,pos,true) end do
table.insert(arr,string.sub(str,pos,st-1)) -- Attach chars left of current divider
pos = sp + 1 -- Jump past current divider
end
table.insert(arr,string.sub(str,pos)) -- Attach chars right of last divider
return arr
end
function widget:RecvLuaMsg(msg, playerID)
if myPlayerID~=playerID and msg:sub(1,3) == "IQ|" then
--Example: IQ|4|404|648|2|3304|1
--Header|unitdefID|x|y|z|facing
msg = msg:sub(4)
local msgArray = explode('|',msg)
local typeArg, unitDefID = tonumber(msgArray[1]), tonumber(msgArray[2])
if typeArg == 5 then -- Cancel queue
local teamID = select(4,Spring.GetPlayerInfo(playerID))
othersBuildQueue[teamID] = {}
return
end
if not UnitDefs[unitDefID] or typeArg > 5 or typeArg < 1 then
return --invalid unitDefID and message type
end
local x,y,z,face = tonumber(msgArray[3]),tonumber(msgArray[4]),tonumber(msgArray[5]),tonumber(msgArray[6])
if not (x and y and z and face) then
return --invalid coordinate and facing
end
local teamID = select(4,Spring.GetPlayerInfo(playerID))
othersBuildQueue[teamID] = othersBuildQueue[teamID] or {}
local playerXBuildQueue = othersBuildQueue[teamID]
if typeArg == 1 then
table.insert(playerXBuildQueue, 1, {unitDefID,x,y,z,face})
elseif typeArg == 2 then
table.remove(playerXBuildQueue, unitDefID)
elseif typeArg == 3 then
playerXBuildQueue[#playerXBuildQueue+1] = {unitDefID,x,y,z,face}
elseif typeArg == 4 then
othersBuildQueue[teamID] = {{unitDefID,x,y,z,face}}
end
end
end
------------------------------------------------------------
-- Game start
------------------------------------------------------------
function widget:GameFrame(n)
if not gameStarted then
gameStarted = true
end
-- Don't run if we are a spec
local areSpec = Spring.GetSpectatingState()
if areSpec then
widgetHandler:RemoveWidget(self)
return
end
-- Don't run if we didn't queue anything
if (#buildQueue == 0) then
widgetHandler:RemoveWidget(self)
return
end
if (n < 2) then return end -- Give the unit frames 0 and 1 to spawn
--inform gadget how long is our queue
local buildTime = GetQueueBuildTime()
--Spring.SendCommands("luarules initialQueueTime " .. buildTime)
if (n == 4) then
--Spring.Echo("> Starting unit never spawned !")
widgetHandler:RemoveWidget(self)
return
end
local tasker
-- Search for our starting unit
local units = Spring.GetTeamUnits(Spring.GetMyTeamID())
for u = 1, #units do
local uID = units[u]
if GetUnitCanCompleteQueue(uID) then --Spring.GetUnitDefID(uID) == sDefID then
--we found our com, assigning queue to this particular unit
tasker = uID
break
end
end
if tasker then
--Spring.Echo("sending queue to unit")
for b = 1, #buildQueue do
local buildData = buildQueue[b]
Spring.GiveOrderToUnit(tasker, -buildData[1], {buildData[2], buildData[3], buildData[4], buildData[5]}, {"shift"})
end
if selDefID and UnitDefs[selDefID] and UnitDefs[selDefID].name then
WG.InitialActiveCommand = "buildunit_" .. UnitDefs[selDefID].name
end
widgetHandler:RemoveWidget(self)
end
end
------------------------------------------------------------
-- Mouse
------------------------------------------------------------
--[[
--Task handled by CommandNotify()
function widget:MousePress(mx, my, mButton)
if selDefID then
if mButton == 1 then
local mx, my = Spring.GetMouseState()
local _, pos = Spring.TraceScreenRay(mx, my, true)
if not pos then return end
local bx, by, bz = Spring.Pos2BuildPos(selDefID, pos[1], pos[2], pos[3])
if isMex[selDefID] then
local bestSpot = WG.GetClosestMetalSpot(bx, bz)
bx, by, bz = bestSpot.x, bestSpot.y, bestSpot.z
end
local buildFacing = Spring.GetBuildFacing()
if Spring.TestBuildOrder(selDefID, bx, by, bz, buildFacing) ~= 0 then
local buildData = {selDefID, bx, by, bz, buildFacing}
local _, _, meta, shift = Spring.GetModKeyState()
if meta then
table.insert(buildQueue, 1, buildData)
elseif shift then
local anyClashes = false
for i = #buildQueue, 1, -1 do
if DoBuildingsClash(buildData, buildQueue[i]) then
anyClashes = true
table.remove(buildQueue, i)
end
end
if not anyClashes then
buildQueue[#buildQueue + 1] = buildData
end
else
buildQueue = {buildData}
end
mCost, eCost, bCost = GetQueueCosts()
buildTime = bCost / sDef.buildSpeed
if not shift then
SetSelDefID(nil)
end
end
return true
elseif mButton == 3 then
SetSelDefID(nil)
return true
end
end
end
function widget:MouseMove(mx, my, dx, dy, mButton)
if areDragging then
wl = wl + dx
wt = wt + dy
end
end
function widget:MouseRelease(mx, my, mButton)
areDragging = false
end
--]]
------------------------------------------------------------
-- Command Button
------------------------------------------------------------
function widget:CommandsChanged()
if (gameStarted) then
return
end
for i=1, #buildOptions do
local unitName = buildOptions[i]
if not Spring.GetGameRulesParam("disabled_unit_" .. unitName) then
table.insert(widgetHandler.customCommands, {
id = -1*UnitDefNames[unitName].id,
type = 20,
tooltip = "Build: " .. UnitDefNames[unitName].humanName .. " - " .. UnitDefNames[unitName].tooltip,
cursor = unitName,
action = "buildunit_" .. unitName,
params = {},
texture = "", --"#"..id,
name = unitName,
})
end
end
table.insert(widgetHandler.customCommands, {
id = CMD_STOP,
type = CMDTYPE.ICON,
tooltip = "Stop",
params = {},
})
end
local function GetClosestMetalSpot(x, z) --is used by single mex placement, not used by areamex
local bestSpot
local bestDist = math.huge
local bestIndex
for i = 1, #WG.metalSpots do
local spot = WG.metalSpots[i]
local dx, dz = x - spot.x, z - spot.z
local dist = dx*dx + dz*dz
if dist < bestDist then
bestSpot = spot
bestDist = dist
bestIndex = i
end
end
return bestSpot
end
local function CancelQueue()
buildQueue = {}
Spring.SendLuaUIMsg("IQ|5",'a')
Spring.SendLuaUIMsg("IQ|5",'s')
mCost, eCost, bCost = GetQueueCosts()
buildTime = bCost / sDef.buildSpeed
end
function widget:CommandNotify(cmdID, cmdParams, cmdOptions)
local areSpec = Spring.GetSpectatingState()
if areSpec then
return false
end
if cmdID == CMD_STOP then
-- This only handles pressing the stop button in integral menu.
CancelQueue()
return true
end
if cmdID >= 0 or not(cmdParams[1] and cmdParams[2] and cmdParams[3]) then --can't handle other command.
return false
end
SetSelDefID(-1*cmdID)
local bx,by,bz = cmdParams[1],cmdParams[2],cmdParams[3]
local buildFacing = Spring.GetBuildFacing()
if Spring.TestBuildOrder(selDefID, bx, by, bz, buildFacing) ~= 0 then
if isMex[selDefID] and WG.metalSpots then
local bestSpot = GetClosestMetalSpot(bx, bz)
bx, by, bz = bestSpot.x, bestSpot.y, bestSpot.z
end
local buildData = {selDefID, bx, by, bz, buildFacing}
local msg
if cmdOptions.meta then
table.insert(buildQueue, 1, buildData)
msg = "IQ|1|"..selDefID.."|"..math.modf(bx).."|"..math.modf(by).."|"..math.modf(bz).."|"..buildFacing
elseif cmdOptions.shift then
local anyClashes = false
for i = #buildQueue, 1, -1 do
if DoBuildingsClash(buildData, buildQueue[i]) then
anyClashes = true
table.remove(buildQueue, i)
msg = "IQ|2|"..i
end
end
if not anyClashes then
buildQueue[#buildQueue + 1] = buildData
msg = "IQ|3|"..selDefID.."|"..math.modf(bx).."|"..math.modf(by).."|"..math.modf(bz).."|"..buildFacing
end
else
buildQueue = {buildData}
msg = "IQ|4|"..selDefID.."|"..math.modf(bx).."|"..math.modf(by).."|"..math.modf(bz).."|"..buildFacing
--msg = "IQ|4|404|648|2|3304|1" --example spoof. This will not work
end
if msg then
Spring.SendLuaUIMsg(msg,'a')
Spring.SendLuaUIMsg(msg,'s') --need 2 msg because since Spring 97 LuaUIMsg without parameter is send info to EVERYONE (including enemy)
end
mCost, eCost, bCost = GetQueueCosts()
buildTime = bCost / sDef.buildSpeed
SetSelDefID(nil)
return true
end
return false
end
------------------------------------------------------------
-- Misc
------------------------------------------------------------
function widget:TextCommand(cmd)
-- Facing commands are only handled by spring if we have a building selected, which isn't possible pre-game
local m = cmd:match("^buildfacing (.+)$")
if m then
local oldFacing = Spring.GetBuildFacing()
local newFacing
if (m == "inc") then
newFacing = (oldFacing + 1) % 4
elseif (m == "dec") then
newFacing = (oldFacing + 3) % 4
else
return false
end
Spring.SetBuildFacing(newFacing)
Spring.Echo("Buildings set to face " .. ({"South", "East", "North", "West"})[1 + newFacing])
return true
end
local buildName = cmd:match("^buildunit_([^%s]+)$")
if buildName then
local bDefID = buildNameToID[buildName]
if bDefID then
SetSelDefID(bDefID)
return true
end
end
if cmd == "stop" then
-- This only handles the stop hotkey
CancelQueue()
end
end
| gpl-2.0 |
gajop/Zero-K | scripts/nanoaim.h.lua | 15 | 2783 | -------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
--
-- Author: jK @ 2010
--
-- How to use:
--
-- 1. Add to the start of your script: include "nanoaim.h.lua"
-- 2. After you define your pieces tell which you want to smoke e.g.: local nanoPieces = { piece "nano_aim" }
-- 3. In your 'function script:Create()' add: StartThread(UpdateNanoDirectionThread, nanoPieces [, updateInterval = 1000 [, turnSpeed = 0.75*math.pi [, turnSpeedVert = turnSpeed ]]])
-- 4. In your 'function script.StartBuilding()' add: UpdateNanoDirection(nanoPieces [, turnSpeed = 0.75*math.pi [, turnSpeedVert = turnSpeed ]])
-- 5. Don't forget to set COB.INBUILDSTANCE:=1 & COB.INBUILDSTANCE:=0 in StartBuilding/StopBuilding
--
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
local Utils_GetUnitNanoTarget = Spring.Utilities.GetUnitNanoTarget
function UpdateNanoDirection(nanopieces,turnSpeed,turnSpeedVert)
local type, target, isFeature = Utils_GetUnitNanoTarget(unitID)
if (target) then
local x,y,z
if (type == "restore") then
x,y,z = target[1],target[2],target[3]
elseif (not isFeature) then
x,y,z = Spring.GetUnitPosition(target)
else
x,y,z = Spring.GetFeaturePosition(target)
end
local ux,uy,uz = Spring.GetUnitPosition(unitID)
local dx,dy,dz = x-ux,y-uy,z-uz
local th = Spring.GetHeadingFromVector(dx,dz)
local h = Spring.GetUnitHeading(unitID)
local heading = (th - h) * math.pi / 32768
local length = math.sqrt(dx*dx + dy*dy + dz*dz)
local norm_dy = (length > 0 and dy / length) or 0
local tp = math.asin(norm_dy)
local p = math.asin(select(2,Spring.GetUnitDirection(unitID)))
local pitch = p - tp
turnSpeed = turnSpeed or (0.75*math.pi)
turnSpeedVert = turnSpeedVert or turnSpeed
local turned = false
for i=1,#nanopieces do
local nano = nanopieces[i]
local cur_head,cur_pitch = Spring.UnitScript.GetPieceRotation(nano)
if (cur_head ~= heading)or(cur_pitch ~= pitch) then
Turn(nano, y_axis, heading, turnSpeed)
Turn(nano, x_axis, pitch, turnSpeedVert)
turned = true
end
end
if (turned) then
WaitForTurn(nanopieces[1], y_axis)
end
end
end
function UpdateNanoDirectionThread(nanopieces, updateInterval, turnSpeed,turnSpeedVert)
updateInterval = updateInterval or 1000
while true do
UpdateNanoDirection(nanopieces,turnSpeed,turnSpeedVert)
Sleep(updateInterval)
end
end
-------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------
| gpl-2.0 |
litnimax/luci | contrib/luadoc/lua/luadoc/init.lua | 172 | 1333 | -------------------------------------------------------------------------------
-- LuaDoc main function.
-- @release $Id: init.lua,v 1.4 2008/02/17 06:42:51 jasonsantos Exp $
-------------------------------------------------------------------------------
local require = require
local util = require "luadoc.util"
logger = {}
module ("luadoc")
-------------------------------------------------------------------------------
-- LuaDoc version number.
_COPYRIGHT = "Copyright (c) 2003-2007 The Kepler Project"
_DESCRIPTION = "Documentation Generator Tool for the Lua language"
_VERSION = "LuaDoc 3.0.1"
-------------------------------------------------------------------------------
-- Main function
-- @see luadoc.doclet.html, luadoc.doclet.formatter, luadoc.doclet.raw
-- @see luadoc.taglet.standard
function main (files, options)
logger = util.loadlogengine(options)
-- load config file
if options.config ~= nil then
-- load specified config file
dofile(options.config)
else
-- load default config file
require("luadoc.config")
end
local taglet = require(options.taglet)
local doclet = require(options.doclet)
-- analyze input
taglet.options = options
taglet.logger = logger
local doc = taglet.start(files)
-- generate output
doclet.options = options
doclet.logger = logger
doclet.start(doc)
end
| apache-2.0 |
gajop/Zero-K | units/armmstor.lua | 7 | 3326 | unitDef = {
unitname = [[armmstor]],
name = [[Storage]],
description = [[Stores Metal and Energy (500)]],
activateWhenBuilt = true,
buildCostEnergy = 100,
buildCostMetal = 100,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 5,
buildingGroundDecalSizeY = 5,
buildingGroundDecalType = [[armmstor_aoplane.dds]],
buildPic = [[ARMMSTOR.png]],
buildTime = 100,
category = [[SINK UNARMED]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[60 60 60]],
collisionVolumeTest = 1,
collisionVolumeType = [[ellipsoid]],
corpse = [[DEAD]],
energyStorage = 500,
explodeAs = [[SMALL_BUILDINGEX]],
footprintX = 3,
footprintZ = 3,
iconType = [[storage]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 700,
maxSlope = 18,
metalStorage = 500,
minCloakDistance = 150,
objectName = [[pylon.s3o]],
script = "armmstor.lua",
seismicSignature = 4,
selfDestructAs = [[SMALL_BUILDINGEX]],
sightDistance = 273,
useBuildingGroundDecal = true,
yardMap = [[ooo ooo ooo]],
customParams = {
description_de = [[Lagert Energie und Metall (500)]],
description_pl = [[Przechowuje surowce (500)]],
helptext = [[Storages act as a buffer when one expects a big influx of metal, such as reclaiming a vast wreckage field. However, longer periods of increased metal income are better dealt with by acquiring more buildpower.]],
helptext_de = [[Dieser Energie- und Metallspeicher erweitert deine Lagermöglichkeiten um 500.]],
helptext_pl = [[Magazyn pozwala na przechowywanie surowcow na wypadek, gdy nie masz wystarczajaco duzo budowniczych, by je wykorzystac. Lepiej jest jednak zbudowac wiecej budowniczych, a magazynu uzywac bardziej jako bufora na wypadek duzych, niespodziewanych zyskow, na przyklad zbierania duzego zlomowiska.]],
modelradius = [[30]],
removewait = 1,
},
featureDefs = {
DEAD = {
description = [[Wreckage - Storage]],
blocking = true,
damage = 700,
energy = 0,
featureDead = [[HEAP]],
footprintX = 3,
footprintZ = 3,
metal = 40,
object = [[storage_d.dae]],
reclaimable = true,
reclaimTime = 40,
},
HEAP = {
description = [[Debris - Storage]],
blocking = false,
damage = 700,
energy = 0,
footprintX = 3,
footprintZ = 3,
metal = 20,
object = [[debris4x4c.s3o]],
reclaimable = true,
reclaimTime = 20,
},
},
}
return lowerkeys({ armmstor = unitDef })
| gpl-2.0 |
gajop/Zero-K | libs/chonsole/luaui/widgets/modules/suggestions.lua | 1 | 15789 | -- suggestions
local currentSuggestion = 0
local currentSubSuggestion = 0
local suggestions = {}
local suggestionNameMapping = {} -- name -> index in "suggestions" table
local filteredSuggestions = {}
local dynamicSuggestions = {}
local preText -- used to determine if text changed
-- name suggestions
local nameSuggestions = {}
local nameSuggestionIndx = 1
local nameSuggestionTxt
function GetSuggestionIndexByName(name)
local index = suggestionNameMapping[name]
if index then
return suggestions[index]
else
return nil
end
end
function MakeSuggestion(suggestion)
local ctrlSuggestion = Chili.Button:New {
x = 0,
minHeight = config.suggestions.font.size + config.suggestions.suggestionPadding,
autosize = true,
width = "100%",
resizable = false,
draggable = false,
padding = {0,0,0,0},
--focusColor = { 0, 0, 0, 0 },
caption = "",
}
local lblSuggestion = Chili.Label:New {
x = 0,
caption = "",
autosize = true,
padding = {0, 0, 0, 0},
font = {
size = config.suggestions.font.size,
-- shadow = false,
color = config.suggestions.suggestionColor,
font = config.console.font.file,
},
parent = ctrlSuggestion,
}
ctrlSuggestion.lblSuggestion = lblSuggestion
local lblDescription = Chili.Label:New {
x = 300,
autosize = true,
caption = "",
padding = {0, 0, 0, 0},
font = {
size = config.suggestions.font.size,
-- shadow = false,
color = config.suggestions.descriptionColor,
font = config.console.fontFile,
},
parent = ctrlSuggestion,
}
ctrlSuggestion.lblDescription = lblDescription
if suggestion.cheat then
local lblCheat = Chili.Label:New {
width = 100,
x = 200,
caption = i18n("cheat_command", {default="(cheat)"}),
align = "right",
padding = {0, 0, 0, 0},
font = {
size = config.suggestions.fontSize,
-- shadow = false,
font = config.console.fontFile,
},
parent = ctrlSuggestion,
}
ctrlSuggestion.lblCheat = lblCheat
end
return ctrlSuggestion
end
function PopulateSuggestion(ctrlSuggestion, suggestion)
ctrlSuggestion.id = suggestion.id
ctrlSuggestion.OnClick = {
function()
local txt = suggestion.text
if suggestion.dynId ~= nil then
txt = suggestions[filteredSuggestions[1]].text .. " " .. txt
end
ebConsole:SetText(txt)
ebConsole.cursor = #ebConsole.text + 1
screen0:FocusControl(ebConsole)
UpdateSuggestions()
end,
}
ctrlSuggestion.lblSuggestion:SetCaption(suggestion.text)
ctrlSuggestion.lblDescription:SetCaption(suggestion.description or "")
return ctrlSuggestion
end
function CreateSuggestion(suggestion)
return PopulateSuggestion(MakeSuggestion(suggestion), suggestion)
end
function GenerateSuggestions()
suggestions = GetCommandList()
for i, suggestion in pairs(suggestions) do
suggestion.text = "/" .. suggestion.command:lower()
suggestion.visible = false
suggestion.id = i
suggestionNameMapping[suggestion.command:lower()] = i
end
if config.suggestions.disableMenu then
return
end
spSuggestions.ctrls = {}
for _, suggestion in pairs(suggestions) do
local ctrlSuggestion = CreateSuggestion(suggestion)
spSuggestions.ctrls[suggestion.id] = ctrlSuggestion
spSuggestions:AddChild(ctrlSuggestion)
end
local fakeCtrl = Chili.Button:New {
x = 0,
y = (#suggestions - 1) * (config.suggestions.font.size + config.suggestions.suggestionPadding),
height = (config.suggestions.font.size + config.suggestions.suggestionPadding),
autosize = true,
--width = "100%",
resizable = false,
draggable = false,
padding = {0,0,0,0},
focusColor = { 0, 0, 0, 0 },
backgroundColor = { 0, 0, 0, 0 },
id = -1,
caption = "",
}
-- FIXME: fake control because chili has bugs
spSuggestions:AddChild(fakeCtrl)
spSuggestions.fakeCtrl = fakeCtrl
end
function CleanupSuggestions()
-- cleanup dynamic suggestions
for _, dynamicSuggestion in pairs(dynamicSuggestions) do
dynamicSuggestion.visible = false
end
filteredSuggestions = {}
for _, suggestion in pairs(suggestions) do
suggestion.visible = false
end
end
function FilterSuggestions(txt)
CleanupSuggestions()
local count = 0
if txt:sub(1, 1) == "/" then
local cmdParts = explode(" ", txt:sub(2):trimLeft():gsub("%s+", " "))
local partialCmd = cmdParts[1]:lower()
local addedCommands = {}
for _, suggestion in pairs(suggestions) do
local cmdName = suggestion.command:lower()
local matched
if #cmdParts > 1 then
matched = cmdName == partialCmd
else
matched = cmdName:starts(partialCmd)
end
if matched and not addedCommands[suggestion.id] then
suggestion.visible = true
count = count + 1
table.insert(filteredSuggestions, suggestion.id)
addedCommands[suggestion.id] = true
end
end
-- for _, command in pairs(commandList) do
-- if command.command:lower():find(partialCmd:lower()) and not addedCommands[command.command] then
-- table.insert(suggestions, { command = "/" .. command.command, text = command.command, description = command.description, cheat = command.cheat })
-- addedCommands[command.command] = true
-- end
-- end
-- generate sub suggestions when only one field is visible
if count == 1 then
local suggestion = suggestions[filteredSuggestions[1]]
if suggestion.suggestions ~= nil then
local subSuggestions
local success, err = pcall(function()
subSuggestions = suggestion.suggestions(txt, cmdParts)
end)
if not success then
Spring.Log("Chonsole", LOG.ERROR, "Error obtaining suggestions for command: " .. tostring(suggestion.command))
Spring.Log("Chonsole", LOG.ERROR, err)
return
end
-- if config.suggestions.disableMenu then
-- return
-- end
for i, subSuggestion in pairs(subSuggestions) do
if subSuggestion.visible == nil then
subSuggestion.visible = true
end
subSuggestion.dynId = #dynamicSuggestions + 1
if i > #dynamicSuggestions then
if not config.suggestions.disableMenu then
local ctrlSuggestion = CreateSuggestion(subSuggestion)
subSuggestion.ctrlSuggestion = ctrlSuggestion
spSuggestions:AddChild(ctrlSuggestion)
end
table.insert(dynamicSuggestions, subSuggestion)
else
local ctrlSuggestion = dynamicSuggestions[i].ctrlSuggestion
dynamicSuggestions[i] = subSuggestion
if not config.suggestions.disableMenu then
dynamicSuggestions[i].ctrlSuggestion = ctrlSuggestion
PopulateSuggestion(ctrlSuggestion, subSuggestion)
end
end
end
end
end
end
end
function ShowSuggestions()
if not scrollSuggestions.visible and not config.suggestions.disableMenu then
scrollSuggestions:Show()
end
FilterSuggestions(ebConsole.text)
UpdateSuggestions()
end
function UpdateSuggestionDisplay(suggestion, ctrlSuggestion, row)
if suggestion.visible then
ctrlSuggestion.y = (row - 1) * (config.suggestions.font.size + config.suggestions.suggestionPadding)
if not ctrlSuggestion.visible then
ctrlSuggestion:Show()
end
if currentSubSuggestion == 0 and suggestion.id ~= nil and suggestion.id == filteredSuggestions[currentSuggestion] then
ctrlSuggestion.backgroundColor = config.suggestions.suggestionColor
elseif suggestion.dynId ~= nil and suggestion.dynId == currentSubSuggestion then
ctrlSuggestion.backgroundColor = config.suggestions.suggestionColor
elseif suggestion.id == nil then
ctrlSuggestion.backgroundColor = config.suggestions.subsuggestionColor
else
ctrlSuggestion.backgroundColor = { 0, 0, 0, 0 }
end
if suggestion.cheat then
local cheatColor
if Spring.IsCheatingEnabled() then
cheatColor = config.suggestions.cheatEnabledColor
elseif autoCheat then
cheatColor = config.suggestions.autoCheatColor
else
cheatColor = config.suggestions.cheatDisabledColor
end
ctrlSuggestion.lblCheat.font.color = cheatColor
ctrlSuggestion.lblCheat:Invalidate()
end
ctrlSuggestion:Invalidate()
elseif ctrlSuggestion.visible then
ctrlSuggestion:Hide()
end
end
function UpdateSuggestions()
if config.suggestions.disableMenu then
return
end
UpdateTexture()
local count = 0
for _, suggestion in pairs(suggestions) do
local ctrlSuggestion = spSuggestions.ctrls[suggestion.id]
if suggestion.visible then
count = count + 1
end
UpdateSuggestionDisplay(suggestion, ctrlSuggestion, count)
end
for _, dynamicSuggestion in pairs(dynamicSuggestions) do
count = count + 1
local ctrlSuggestion = dynamicSuggestion.ctrlSuggestion
ctrlSuggestion.x = 50
UpdateSuggestionDisplay(dynamicSuggestion, ctrlSuggestion, count)
end
-- FIXME: magic numbers and fake controls ^_^
spSuggestions.fakeCtrl.y = (count-1+1) * (config.suggestions.font.size + config.suggestions.suggestionPadding)
if currentSuggestion ~= 0 and scrollSuggestions.visible then
local suggestion = suggestions[filteredSuggestions[currentSuggestion]]
if suggestion == nil then
Spring.Echo("BUG!", currentSuggestion, #filteredSuggestions, filteredSuggestions[currentSuggestion])
else
local selY = spSuggestions.ctrls[suggestion.id].y
scrollSuggestions:SetScrollPos(0, selY, true, false)
end
end
if count > 0 and not scrollSuggestions.visible then
scrollSuggestions:RequestUpdate()
scrollSuggestions:Show()
elseif count == 0 and scrollSuggestions.visible then
scrollSuggestions:Hide()
end
spSuggestions:Invalidate()
end
function HideSuggestions()
CleanupSuggestions()
if scrollSuggestions.visible then
scrollSuggestions:Hide()
end
end
function AreSuggestionsInverted()
if config.suggestions.forceDirection == "up" then
return true
elseif config.suggestions.forceDirection == "down" then
return false
end
local _, vsy = Spring.GetViewGeometry()
local y = ebConsole.y + ebConsole.height
local h = config.suggestions.height
return y + h > vsy and y - h >= 0
end
function SuggestionsUp()
if currentSubSuggestion > 1 then
currentSubSuggestion = currentSubSuggestion - 1
local suggestion = dynamicSuggestions[currentSubSuggestion]
ebConsole:SetText(suggestion.command)
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
return true
elseif currentSuggestion > 1 then
currentSuggestion = currentSuggestion - 1
local id = filteredSuggestions[currentSuggestion]
ebConsole:SetText(suggestions[id].text)
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
return true
end
end
function SuggestionsDown()
if not (#filteredSuggestions > currentSuggestion or (#dynamicSuggestions > currentSubSuggestion and dynamicSuggestions[currentSubSuggestion+1].visible)) then
return false
end
if #filteredSuggestions == 1 and #dynamicSuggestions ~= 0 then
if #dynamicSuggestions > currentSubSuggestion and dynamicSuggestions[currentSubSuggestion+1].visible then
currentSubSuggestion = currentSubSuggestion + 1
local suggestion = dynamicSuggestions[currentSubSuggestion]
ebConsole:SetText(suggestion.command)
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
return true
end
elseif #filteredSuggestions > currentSuggestion then
currentSuggestion = currentSuggestion + 1
local id = filteredSuggestions[currentSuggestion]
ebConsole:SetText(suggestions[id].text)
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
return true
end
end
function PrintSuggestions()
for _, suggestion in pairs(suggestions) do
Spring.Echo(suggestion.text)
end
end
function SuggestionsTab()
if #filteredSuggestions == 0 then
return
end
if config.suggestions.disableMenu then
-- PrintSuggestions()
-- return
end
local nextSuggestion, nextSubSuggestion
if #filteredSuggestions > currentSuggestion then
nextSuggestion = currentSuggestion + 1
else
nextSuggestion = 1
end
if #dynamicSuggestions > currentSubSuggestion and dynamicSuggestions[currentSubSuggestion+1].visible then
nextSubSuggestion = currentSubSuggestion + 1
else
nextSubSuggestion = 1
end
if #filteredSuggestions == 1 and #dynamicSuggestions ~= 0 and #suggestions[filteredSuggestions[1]].text <= #ebConsole.text then
if #dynamicSuggestions[nextSubSuggestion].command >= #ebConsole.text or currentSubSuggestion ~= 0 then
currentSubSuggestion = nextSubSuggestion
local suggestion = dynamicSuggestions[currentSubSuggestion]
if #dynamicSuggestions > 1 then
ebConsole:SetText(suggestion.command)
else
ebConsole:SetText(suggestion.command .. " ")
end
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
end
elseif #suggestions[filteredSuggestions[nextSuggestion]].text >= #ebConsole.text or currentSuggestion ~= 0 then
currentSuggestion = nextSuggestion
local id = filteredSuggestions[currentSuggestion]
if #filteredSuggestions > 1 then
ebConsole:SetText(suggestions[id].text)
else
-- this will also select it if there's only one option
ebConsole:SetText(suggestions[id].text .. " ")
end
ebConsole.cursor = #ebConsole.text + 1
UpdateSuggestions()
end
return true
end
local function _GetCurrentWord()
local txt = ebConsole.text
local startX, endX = 1, 1
for i = ebConsole.cursor-1, 1, -1 do
if txt:sub(i, i) == " " then
startX = i + 1
break
end
end
endX = txt:find(" ", ebConsole.cursor) or (#txt + 1)
endX = endX - 1
return txt:sub(startX, endX), startX, endX
end
local function _GetPlayerNames()
local playerNames = {}
for _, playerID in pairs(Spring.GetPlayerList()) do
local name = Spring.GetPlayerInfo(playerID)
table.insert(playerNames, name)
end
return playerNames
end
local function _ParseClan(word)
if word:sub(1, 1) == "[" then
local endClan = word:find("]")
if endClan then
word = word:sub(endClan+1)
end
end
return word
end
local function _SetName(playerName, startX, endX)
ebConsole:SetText(ebConsole.text:sub(1, startX-1) .. playerName .. ebConsole.text:sub(endX + 1))
ebConsole.cursor = startX + #playerName
end
local function _ResetNameSuggestions()
nameSuggestions = {}
nameSuggestionIndx = 1
nameSuggestionTxt = word
end
function NameSuggestionTab()
local playerNames = _GetPlayerNames()
local word, startX, endX = _GetCurrentWord()
word = _ParseClan(word)
if #word == 0 then
return
end
if #nameSuggestions ~= 0 and nameSuggestionTxt == word then
nameSuggestionIndx = nameSuggestionIndx + 1
if nameSuggestionIndx > #nameSuggestions then
nameSuggestionIndx = 1
end
_SetName(nameSuggestions[nameSuggestionIndx], startX, endX)
return true
end
_ResetNameSuggestions()
for _, playerName in pairs(playerNames) do
if playerName:starts(word) or _ParseClan(playerName):starts(word) then
_SetName(playerName, startX, endX)
table.insert(nameSuggestions, playerName)
end
end
return #nameSuggestions > 0
end
function GetCommandList()
local commandList = {}
if Spring.GetUICommands then
commandList = Spring.GetUICommands()
else
Spring.Log("Chonsole", LOG.ERROR, "Using unsupported engine: no Spring.GetUICommands function")
end
local names = {}
for _, command in pairs(commandList) do
if command.synced then
names[command.command:lower()] = true
end
end
-- removed unsynced commands
for i = #commandList, 1, -1 do
local cmd = commandList[i]
if not cmd.synced and names[cmd.command:lower()] then
Spring.Log("Chonsole", LOG.NOTICE, "Removed duplicate command: ", cmd.command, cmd.description)
table.remove(commandList, i)
end
end
-- create a name mapping and merge any existing commands
names = {}
for _, command in pairs(commandList) do
names[command.command:lower()] = command
end
for _, command in pairs(GetExtensions()) do
local cmd = names[command.command:lower()]
if cmd == nil then
table.insert(commandList, command)
else
table.merge(cmd, command)
end
end
table.sort(commandList, function(cmd1, cmd2)
return cmd1.command:lower() < cmd2.command:lower()
end)
return commandList
end
| gpl-2.0 |
arya5123/tell | admin.lua | 230 | 6382 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
patterns = {
"^[!/](pm) (%d+) (.*)$",
"^[!/](import) (.*)$",
"^[!/](unblock) (%d+)$",
"^[!/](block) (%d+)$",
"^[!/](markread) (on)$",
"^[!/](markread) (off)$",
"^[!/](setbotphoto)$",
"%[(photo)%]",
"^[!/](contactlist)$",
"^[!/](dialoglist)$",
"^[!/](delcontact) (%d+)$",
"^[!/](whois) (%d+)$"
},
run = run,
}
--By @imandaneshi :)
--https://github.com/SEEDTEAM/TeleSeed/blob/master/plugins/admin.lua
| gpl-2.0 |
gajop/Zero-K | lups/ParticleClasses/NanoLasersNoShader.lua | 14 | 8740 | -- $Id: NanoLasersNoShader.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local NanoLasersNoShader = {}
NanoLasersNoShader.__index = NanoLasersNoShader
local cam_up
local knownNanoLasersNoShader = {}
local lastTexture = ""
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader.GetInfo()
return {
name = "NanoLasersNoShader",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = -16, --// extreme simply z-ordering :x
--// gfx requirement
fbo = false,
shader = false,
rtt = false,
ctt = false,
}
end
NanoLasersNoShader.Default = {
layer = 0,
worldspace = true,
repeatEffect = false,
--// shared options with all nanofx
dir = {0,1,0},
pos = {0,0,0}, --// start pos
radius = 0, --// terraform/unit radius
color = {0, 0, 0, 0},
count = 1,
inversed = false, --// reclaim?
terraform = false, --// for terraform (2d target)
unit = -1,
nanopiece = -1,
life = 30,
--// some unit informations
targetID = -1,
unitID = -1,
unitpiece = -1,
unitDefID = -1,
teamID = -1,
allyID = -1,
--// custom (user) options
flare = false,
streamSpeed = 10,
streamThickness = -1, --//streamThickness = 4+self.count*0.34,
corethickness = 1,
corealpha = 1,
texture = "bitmaps/largelaserfalloff.tga",
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
--//speed ups
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
local GL_QUADS = GL.QUADS
local GL_TEXTURE = GL.TEXTURE
local GL_MODELVIEW = GL.MODELVIEW
local glColor = gl.Color
local glTexture = gl.Texture
local glBlending = gl.Blending
local glTexCoord = gl.TexCoord
local glVertex = gl.Vertex
local glTranslate = gl.Translate
local glMatrixMode = gl.MatrixMode
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glBeginEnd = gl.BeginEnd
local max = math.max
local GetCameraVectors = Spring.GetCameraVectors
local IsSphereInView = Spring.IsSphereInView
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader:BeginDraw()
glBlending(GL_ONE, GL_ONE_MINUS_SRC_ALPHA)
cam_up = GetCameraVectors().forward
end
function NanoLasersNoShader:EndDraw()
glColor(1,1,1,1)
glTexture(false)
glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
lastTexture=""
end
local function DrawNanoLasersNoShader(dir,dir_upright,visibility,streamThickness,core_alpha,core_thickness)
local startF,endF = 0,1
if (visibility==0)
then startF=-visibility
else endF = visibility end
local start_dir = Vmul(dir,startF)
local end_dir = Vmul(dir,endF)
local dir_upright1 = Vmul(dir_upright,streamThickness)
glTexCoord(0,0)
glVertex(start_dir[1]+dir_upright1[1],start_dir[2]+dir_upright1[2],start_dir[3]+dir_upright1[3])
glTexCoord(0,1)
glVertex(start_dir[1]-dir_upright1[1],start_dir[2]-dir_upright1[2],start_dir[3]-dir_upright1[3])
glTexCoord(1,1)
glVertex(end_dir[1]-dir_upright1[1],end_dir[2]-dir_upright1[2],end_dir[3]-dir_upright1[3])
glTexCoord(1,0)
glVertex(end_dir[1]+dir_upright1[1],end_dir[2]+dir_upright1[2],end_dir[3]+dir_upright1[3])
glColor(core_alpha,core_alpha,core_alpha,0.003)
dir_upright = Vmul(dir_upright,core_thickness)
glTexCoord(0,0)
glVertex(start_dir[1]+dir_upright[1],start_dir[2]+dir_upright[2],start_dir[3]+dir_upright[3])
glTexCoord(0,1)
glVertex(start_dir[1]-dir_upright[1],start_dir[2]-dir_upright[2],start_dir[3]-dir_upright[3])
glTexCoord(1,1)
glVertex(end_dir[1]-dir_upright[1],end_dir[2]-dir_upright[2],end_dir[3]-dir_upright[3])
glTexCoord(1,0)
glVertex(end_dir[1]+dir_upright[1],end_dir[2]+dir_upright[2],end_dir[3]+dir_upright[3])
end
function NanoLasersNoShader:Draw()
if (lastTexture~=self.texture) then
glTexture(self.texture)
lastTexture=self.texture
end
glPushMatrix()
glTranslate(self.pos[1],self.pos[2],self.pos[3])
glMatrixMode(GL_TEXTURE)
glPushMatrix()
if (self.inversed) then
glTranslate( (thisGameFrame+Spring.GetFrameTimeOffset())*self.streamSpeed, 0,0)
else
glTranslate( -(thisGameFrame+Spring.GetFrameTimeOffset())*self.streamSpeed, 0,0)
end
local dir_upright = Vcross(self.normdir,cam_up)
local color = self.color
glColor(color[1],color[2],color[3],0.003)
glBeginEnd(GL_QUADS,DrawNanoLasersNoShader,self.dir,dir_upright,self.visibility,self.streamThickness,self.corealpha,self.corethickness)
glPopMatrix()
glMatrixMode(GL_MODELVIEW)
glPopMatrix()
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader:Update(n)
UpdateNanoParticles(self)
if (self._dead) then
RemoveParticles(self.id)
end
end
-- used if repeatEffect=true;
function NanoLasersNoShader:ReInitialize()
self.dieGameFrame = self.dieGameFrame + self.life
end
function NanoLasersNoShader:Visible()
if (self.allyID ~= LocalAllyTeamID)and(self.visibility == 0) then
return false
end
local midPos = self._midpos
return IsSphereInView(midPos[1],midPos[2],midPos[3], self._radius)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader:Initialize()
end
function NanoLasersNoShader:Finalize()
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader:CreateParticle()
self.life = self.life + 1 --// so we can reuse existing fx's
self.firstGameFrame = thisGameFrame
self.dieGameFrame = self.firstGameFrame + self.life
self.visibility = 0
self:Update(0) --//update los
if (self.streamThickness<0) then
self.streamThickness = 4+self.count*0.34
end
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function NanoLasersNoShader.Create(Options)
local unit,nanopiece=Options.unitID,Options.nanopiece
if (unit and nanopiece)and(knownNanoLasersNoShader[unit])and(knownNanoLasersNoShader[unit][nanopiece]) then
local reuseFx = knownNanoLasersNoShader[unit][nanopiece]
CopyTable(reuseFx,Options)
reuseFx:CreateParticle()
return false,reuseFx.id
else
local newObject = MergeTable(Options, NanoLasersNoShader.Default)
setmetatable(newObject,NanoLasersNoShader) -- make handle lookup
newObject:CreateParticle()
if (unit and nanopiece) then
if (not knownNanoLasersNoShader[unit]) then
knownNanoLasersNoShader[unit] = {}
end
knownNanoLasersNoShader[unit][nanopiece] = newObject
end
return newObject
end
end
function NanoLasersNoShader:Destroy()
local unit,nanopiece=self.unitID,self.nanopiece
knownNanoLasersNoShader[unit][nanopiece] = nil
if (not next(knownNanoLasersNoShader[unit])) then
knownNanoLasersNoShader[unit] = nil
end
if (self.flare) then
RemoveParticles(self.flare1id)
RemoveParticles(self.flare2id)
end
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return NanoLasersNoShader | gpl-2.0 |
gajop/Zero-K | scripts/corsh.lua | 11 | 1979 | include "constants.lua"
local base = piece 'base'
local turret = piece 'turret'
local gun = piece 'gun'
local flare = piece 'flare'
local ground = piece 'ground01'
local wakes = {}
for i = 1, 8 do
wakes[i] = piece('wake0' .. i)
end
local function WobbleUnit()
local wobble = true
while true do
if wobble == true then
Move(base, y_axis, 2, 3)
else
Move(base, y_axis, -2, 3)
end
wobble = not wobble
Sleep(750)
end
end
local sfxNum = 0
function script.setSFXoccupy(num)
sfxNum = num
end
local function MoveScript()
while Spring.GetUnitIsStunned(unitID) do
Sleep(2000)
end
while true do
if not Spring.GetUnitIsCloaked(unitID) then
if (sfxNum == 1 or sfxNum == 2) and select(2, Spring.GetUnitPosition(unitID)) == 0 then
for i = 1, 8 do
EmitSfx(wakes[i], 3)
end
else
EmitSfx(ground, 1024)
end
end
Sleep(150)
end
end
function script.Create()
StartThread(SmokeUnit, {base})
StartThread(WobbleUnit)
StartThread(MoveScript)
end
local function RestoreAfterDelay()
SetSignalMask(SIG_AIM)
Sleep(5000)
Turn(turret, y_axis, 0, math.rad(20))
Turn(gun, x_axis, 0, math.rad(20))
end
function script.AimFromWeapon()
return turret
end
function script.AimWeapon(num, heading, pitch)
Signal(SIG_AIM)
SetSignalMask(SIG_AIM)
Turn(turret, y_axis, heading, math.rad(320))
Turn(gun, x_axis, -pitch, math.rad(320))
WaitForTurn(turret, y_axis)
WaitForTurn(gun, x_axis)
StartThread(RestoreAfterDelay)
return (1)
end
function script.QueryWeapon(piecenum)
return flare
end
local pieces = {turret, gun}
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage / maxHealth
for i = 1, #pieces do
if math.random() < severity then
Explode(pieces[i], sfxShatter)
end
if math.random() < (severity*2) then
Explode(pieces[i], sfxFall + ((math.random() > severity) and (sfxSmoke + sfxFire) or 0))
end
end
if severity < 0.5 then
return 1
else
Explode(base, sfxShatter)
return 2
end
end
| gpl-2.0 |
zhangxudongyxkf/MyGameServer | skynet_test/socket3.lua | 1 | 3290 | package.cpath = "../skynet/luaclib/?.so"
package.path = "../skynet/lualib/?.lua;?.lua"
local skynet = require "skynet"
require "skynet.manager" -- import skynet.register
local socket = require "skynet.socket"
local proto = require "proto"
local sproto = require "sproto"
local host
local REQUEST = {}
function REQUEST:say()
print("say", self.name, self.msg)
end
function REQUEST:handshake()
print("handshake")
end
function REQUEST:quit()
print("quit")
end
local function request(name, args, response)
local f = assert(REQUEST[name])
local r = f(args)
if response then
-- 生成回应包(response是一个用于生成回应包的函数。)
-- 处理session对应问题
-- return response(r)
end
end
local function send_package(fd,pack)
-- 协议与客户端对应(两字节长度包头+内容)
local package = string.pack(">s2", pack)
socket.write(fd, package)
end
local function accept(id)
socket.start(id)
host = sproto.new(proto.c2s):host "dongpackage"
-- request = host:attach(sproto.new(proto.c2s))
while true do
local str = socket.read(id)
if str then
local type,str2,str3,str4 = host:dispatch(str)
if type=="REQUEST" then
-- REQUEST : 第一个返回值为 "REQUEST" 时,表示这是一个远程请求。如果请求包中没有 session 字段,表示该请求不需要回应。这时,第 2 和第 3 个返回值分别为消息类型名(即在 sproto 定义中提到的某个以 . 开头的类型名),以及消息内容(通常是一个 table );如果请求包中有 session 字段,那么还会有第 4 个返回值:一个用于生成回应包的函数。
local ok, result = pcall(request, str2,str3,str4)
if ok then
if result then
socket.write(id, "get it")
-- 暂时不使用回应包回应
-- print("response:"..result)
-- send_package(id,result)
end
else
skynet.error(result)
end
end
if type=="RESPONSE" then
-- RESPONSE :第一个返回值为 "RESPONSE" 时,第 2 和 第 3 个返回值分别为 session 和消息内容。消息内容通常是一个 table ,但也可能不存在内容(仅仅是一个回应确认)。
-- 暂时不处理客户端的回应
print("client response")
end
else
socket.close(id)
return
end
end
end
skynet.start(function()
print("==========Socket3 Start=========")
local id = socket.listen("127.0.0.1", 8888)
print("Listen socket :", "127.0.0.1", 8888)
socket.start(id , function(id, addr)
-- 接收到客户端连接或发送消息()
print("connect from " .. addr .. " " .. id)
-- 处理接收到的消息
accept(id)
end)
--可以为自己注册一个别名。(别名必须在 32 个字符以内)
skynet.register "SOCKET3"
end) | mit |
Sweet-kid/Algorithm-Implementations | Bogobogosort/Lua/Yonaba/bogobogosort_test.lua | 27 | 1996 | -- Tests for bogobogosort.lua
local bogobogosort = require 'bogobogosort'
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
-- Wrap for Lua's table sort so that it returns
-- the passed-in table
local function sort(t, comp)
table.sort(t, comp)
return t
end
-- Returns a copy of a an array
local function clone(t)
local _t = {}
for k,v in ipairs(t) do _t[k] = v end
return _t
end
-- Checks if t1 and t2 arrays are the same
local function same(t1, t2)
for k,v in ipairs(t1) do
if t2[k] ~= v then return false end
end
return true
end
math.randomseed(os.time())
-- Note: Due to the nature of Bogobogosort, we will use
-- short tables to perform tests. For higher values of
-- n, we cannot predict the time it will take to perform the
-- sort.
run('Empty arrays', function()
local t = {}
assert(same(sort(clone(t)),bogobogosort(t)))
end)
run('Sorted array', function()
local t = {1, 2, 3, 4, 5}
assert(same(sort(clone(t)),bogobogosort(t)))
end)
run('Array sorted in reverse', function()
local t = {5, 4, 3, 2, 1}
assert(same(sort(clone(t)),bogobogosort(t)))
local t = {5, 4, 3, 2, 1}
local comp = function(a,b) return a>b end
assert(same(sort(clone(t), comp),bogobogosort(t, comp)))
end)
run('Array containing multiple occurences of the same value', function()
local t = {4, 4, 8, 2, 2}
local comp = function(a,b) return a <= b end
assert(same(sort(clone(t)),bogobogosort(t, comp)))
local t = {0, 0, 0, 0, 0}
local comp = function(a,b) return a <= b end
assert(same(sort(clone(t)),bogobogosort(t, comp)))
end)
print(('-'):rep(80))
print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%')
:format(total, pass, total-pass, (pass*100/total)))
| mit |
CodeAnxiety/premake-core | src/base/detoken.lua | 5 | 4751 | --
-- detoken.lua
--
-- Expands tokens.
--
-- Copyright (c) 2011-2014 Jason Perkins and the Premake project
--
premake.detoken = {}
local p = premake
local detoken = p.detoken
--
-- Expand tokens in a value.
--
-- @param value
-- The value containing the tokens to be expanded.
-- @param environ
-- An execution environment for any token expansion. This is a list of
-- key-value pairs that will be inserted as global variables into the
-- token expansion runtime environment.
-- @param field
-- The definition of the field which stores the value.
-- @param basedir
-- If provided, path tokens encountered in non-path fields (where
-- field.paths is set to false) will be made relative to this location.
-- @return
-- The value with any contained tokens expanded.
--
function detoken.expand(value, environ, field, basedir)
field = field or {}
-- fetch the path variable from the action, if needed
local varMap = {}
if field.pathVars then
local action = p.action.current()
if action then
varMap = action.pathVars or {}
end
end
-- fetch the pathVars from the enviroment.
local envMap = environ.pathVars or {}
-- enable access to the global environment
setmetatable(environ, {__index = _G})
function expandtoken(token, e)
-- convert the token into a function to execute
local func, err = loadstring("return " .. token)
if not func then
return nil, "load error: " .. err
end
-- give the function access to the project objects
setfenv(func, e)
-- run it and get the result
local success, result = pcall(func)
if not success then
err = result
result = nil
else
err = nil
result = result or ""
end
-- If the result is an absolute path, and it is being inserted into
-- a NON-path value, I need to make it relative to the project that
-- will contain it. Otherwise I ended up with an absolute path in
-- the generated project, and it can no longer be moved around.
local isAbs = false
if result ~= nil then
isAbs = path.isabsolute(result)
if isAbs and not field.paths and basedir then
result = path.getrelative(basedir, result)
end
end
-- If this token is in my path variable mapping tables, replace the
-- value with the one from the map. This needs to go here because
-- I don't want to make the result relative, but I don't want the
-- absolute path handling below.
local mapped = envMap[token] or varMap[token]
if mapped then
err = nil
result = mapped
if type(result) == "function" then
success, result = pcall(result, e)
if not success then
return nil, result
end
end
if (type(result) == "table") then
isAbs = result.absolute
result = result.token
else
isAbs = path.isabsolute(result)
end
end
-- If the result is an absolute path, and it is being inserted into
-- a path value, place a special marker at the start of it. After
-- all results have been processed, I can look for these markers to
-- find the last absolute path expanded.
--
-- Example: the value "/home/user/myprj/%{cfg.objdir}" expands to:
-- "/home/user/myprj//home/user/myprj/obj/Debug".
--
-- By inserting a marker this becomes:
-- "/home/user/myprj/[\0]/home/user/myprj/obj/Debug".
--
-- I can now trim everything before the marker to get the right
-- result, which should always be the last absolute path specified:
-- "/home/user/myprj/obj/Debug"
if result ~= nil and isAbs and field.paths then
result = "\0" .. result
end
return result, err
end
function expandvalue(value, e)
if type(value) ~= "string" then
return value
end
local count
repeat
value, count = value:gsub("%%{(.-)}", function(token)
local result, err = expandtoken(token:gsub("\\", "\\\\"), e)
if err then
error(err .. " in token: " .. token, 0)
end
if not result then
error("Token returned nil, it may not exist: " .. token, 0)
end
return result
end)
until count == 0
-- if a path, look for a split out embedded absolute paths
if field.paths then
local i, j
repeat
i, j = value:find("\0")
if i then
value = value:sub(i + 1)
end
until not i
end
return value
end
function recurse(value, e)
if type(value) == "table" then
local res_table = {}
for k, v in pairs(value) do
if tonumber(k) ~= nil then
res_table[k] = recurse(v, e)
else
local nk = recurse(k, e);
res_table[nk] = recurse(v, e)
end
end
return res_table
else
return expandvalue(value, e)
end
end
return recurse(value, environ)
end
| bsd-3-clause |
miralireza2/gpf | 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 |
shkan/telebot2 | plugins/search_youtube.lua | 674 | 1270 | do
local google_config = load_from_file('data/google.lua')
local function httpsRequest(url)
print(url)
local res,code = https.request(url)
if code ~= 200 then return nil end
return json:decode(res)
end
local function searchYoutubeVideos(text)
local url = 'https://www.googleapis.com/youtube/v3/search?'
url = url..'part=snippet'..'&maxResults=4'..'&type=video'
url = url..'&q='..URL.escape(text)
if google_config.api_keys then
local i = math.random(#google_config.api_keys)
local api_key = google_config.api_keys[i]
if api_key then
url = url.."&key="..api_key
end
end
local data = httpsRequest(url)
if not data then
print("HTTP Error")
return nil
elseif not data.items then
return nil
end
return data.items
end
local function run(msg, matches)
local text = ''
local items = searchYoutubeVideos(matches[1])
if not items then
return "Error!"
end
for k,item in pairs(items) do
text = text..'http://youtu.be/'..item.id.videoId..' '..
item.snippet.title..'\n\n'
end
return text
end
return {
description = "Search video on youtube and send it.",
usage = "!youtube [term]: Search for a youtube video and send it.",
patterns = {
"^!youtube (.*)"
},
run = run
}
end
| gpl-2.0 |
amir32002/feedback-networks | lib/LogNLLCriterion.lua | 1 | 1167 | local LogNLLCriterion, parent = torch.class("nn.LogNLLCriterion", "nn.Criterion")
function LogNLLCriterion:__init()
self.inputModule = nn.Log()
if self.inputModule then
local params = self.inputModule:parameters()
if params and #params > 0 then
print"Warning: nn.LogNLLCriterion doesn't support parameter updates"
end
end
self.criterion = nn.ClassNLLCriterion()
end
function LogNLLCriterion:updateOutput(input, target)
--print(input)
if self.inputModule then
self.input = self.inputModule:forward(input)
end
--print(self.input)
self.output = self.criterion:forward(self.input or input, target)
return self.output
end
function LogNLLCriterion:updateGradInput(input, target)
self.gradInput = self.criterion:backward(self.input or input, target)
if self.inputModule then
self.gradInput = self.inputModule:backward(input, self.gradInput)
end
return self.gradInput
end
function LogNLLCriterion:type(type, typecache)
if self.inputModule then
self.inputModule:type(type, typecache)
end
self.criterion:type(type, typecache)
return parent.type(self, type, typecache)
end
| mit |
pixeltailgames/gm-mediaplayer | lua/mediaplayer/players/entity/sh_meta.lua | 1 | 2523 | --[[---------------------------------------------------------
Media Player Entity Meta
-----------------------------------------------------------]]
local EntityMeta = FindMetaTable("Entity")
if not EntityMeta then return end
function EntityMeta:GetMediaPlayer()
return self._mp
end
--
-- Installs a media player reference to the entity.
--
-- @param Table|String? mp Media player table or string type.
-- @param String? mpId Media player unique ID.
--
function EntityMeta:InstallMediaPlayer( mp, mpId )
if not istable(mp) then
local mpType = isstring(mp) and mp or "entity"
if not MediaPlayer.IsValidType(mpType) then
ErrorNoHalt("ERROR: Attempted to install invalid mediaplayer type onto an entity!\n")
ErrorNoHalt("ENTITY: " .. tostring(self) .. "\n")
ErrorNoHalt("TYPE: " .. tostring(mpType) .. "\n")
mpType = "entity" -- default
end
local mpId = mpId or "Entity" .. self:EntIndex()
mp = MediaPlayer.Create( mpId, mpType )
end
self._mp = mp
self._mp:SetEntity(self)
local creator = self.GetCreator and self:GetCreator()
if IsValid( creator ) then
self._mp:SetOwner( creator )
end
if isfunction(self.SetupMediaPlayer) then
self:SetupMediaPlayer(mp)
end
return mp
end
local DefaultConfig = {
offset = Vector(0,0,0), -- translation from entity origin
angle = Angle(0,90,90), -- rotation
-- attachment = "corner" -- attachment name
width = 64, -- screen width
height = 64 * 9/16 -- screen height
}
function EntityMeta:GetMediaPlayerPosition()
local cfg = self.PlayerConfig or DefaultConfig
local w = (cfg.width or DefaultConfig.width)
local h = (cfg.height or DefaultConfig.height)
local angles = (cfg.angle or DefaultConfig.angle)
local pos, ang
if cfg.attachment then
local idx = self:LookupAttachment(cfg.attachment)
if not idx then
local err = string.format("MediaPlayer:Entity.Draw: Invalid attachment '%s'\n", cfg.attachment)
Error(err)
end
-- Get attachment orientation
local attach = self:GetAttachment(idx)
pos = attach.pos
ang = attach.ang
else
pos = self:GetPos() -- TODO: use GetRenderOrigin?
end
-- Apply offset
if cfg.offset then
pos = pos +
self:GetForward() * cfg.offset.x +
self:GetRight() * cfg.offset.y +
self:GetUp() * cfg.offset.z
end
-- Set angles
ang = ang or self:GetAngles() -- TODO: use GetRenderAngles?
ang:RotateAroundAxis( ang:Right(), angles.p )
ang:RotateAroundAxis( ang:Up(), angles.y )
ang:RotateAroundAxis( ang:Forward(), angles.r )
return w, h, pos, ang
end
| mit |
Sojerbot/javan | plugins/media.lua | 18 | 1671 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "دانلود فایل با لینک! کافیه یک لینک ارسال کنید",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
NowTeam/Now | plugins/media.lua | 18 | 1671 | do
local function run(msg, matches)
local receiver = get_receiver(msg)
local url = matches[1]
local ext = matches[2]
local file = download_to_file(url)
local cb_extra = {file_path=file}
local mime_type = mimetype.get_content_type_no_sub(ext)
if ext == 'gif' then
print('send_file')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'text' then
print('send_document')
send_document(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'image' then
print('send_photo')
send_photo(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'audio' then
print('send_audio')
send_audio(receiver, file, rmtmp_cb, cb_extra)
elseif mime_type == 'video' then
print('send_video')
send_video(receiver, file, rmtmp_cb, cb_extra)
else
print('send_file')
send_file(receiver, file, rmtmp_cb, cb_extra)
end
end
return {
description = "دانلود فایل با لینک! کافیه یک لینک ارسال کنید",
usage = "When user sends media URL (ends with gif, mp4, pdf, etc.) download and send it to origin.",
patterns = {
"(https?://[%w-_%.%?%.:/%+=&]+%.(gif))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp4))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(pdf))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(ogg))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(zip))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(mp3))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(rar))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(wmv))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(doc))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(avi))$",
"(https?://[%w-_%.%?%.:/%+=&]+%.(webp))$"
},
run = run
}
end
| gpl-2.0 |
damoguyan8844/ABTestingGateway | lib/abtesting/adapter/policy.lua | 22 | 4584 | ---
-- @classmod abtesting.adapter.policy
-- @release 0.0.1
local modulename = "abtestingAdapterPolicy"
local _M = { _VERSION = "0.0.1" }
local mt = { __index = _M }
local ERRORINFO = require('abtesting.error.errcode').info
local separator = ':'
local fields = {}
fields.divtype = 'divtype'
fields.divdata = 'divdata'
fields.idCount = 'idCount'
---
-- policyIO new function
-- @param database opened redis.
-- @param baseLibrary a library(prefix of redis key) of policies.
-- @return runtimeInfoIO object
_M.new = function(self, database, baseLibrary)
if not database then
error{ERRORINFO.PARAMETER_NONE, 'need avaliable redis db'}
end
if not baseLibrary then
error{ERRORINFO.PARAMETER_NONE, 'need avaliable policy baselib'}
end
self.database = database
self.baseLibrary = baseLibrary
self.idCountKey = table.concat({baseLibrary, fields.idCount}, separator)
local ok, err = database:exists(self.idCountKey)
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
if 0 == ok then
local ok, err = database:set(self.idCountKey, '-1')
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
end
return setmetatable(self, mt)
end
---
-- get id for current policy
-- @return the id
_M.getIdCount = function(self)
local database = self.database
local key = self.idCountKey
local idCount, err = database:incr(key)
if not idCount then error{ERRORINFO.REDIS_ERROR, err} end
return idCount
end
---
-- private function, set diversion type
-- @param id identify a policy
-- @param divtype diversion type (ipange/uid/...)
-- @return allways returned SUCCESS
_M._setDivtype = function(self, id, divtype)
local database = self.database
local key = table.concat({self.baseLibrary, id, fields.divtype}, separator)
local ok, err = database:set(key, divtype)
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
end
---
-- private function, set diversion data
-- @param id identify a policy
-- @param divdata diversion data
-- @param modulename module name of diversion data (decision by diversion type)
-- @return allways returned SUCCESS
_M._setDivdata = function(self, id, divdata, modulename)
local divModule = require(modulename)
local database = self.database
local key = table.concat({self.baseLibrary, id, fields.divdata}, separator)
divModule:new(database, key):set(divdata)
end
---
-- addtion a policy to specified redis lib
-- @param policy policy of addtion
-- @return allways returned SUCCESS
_M.set = function(self, policy)
local id = self:getIdCount()
local database = self.database
local divModulename = table.concat({'abtesting', 'diversion', policy.divtype}, '.')
self:_setDivtype(id, policy.divtype)
self:_setDivdata(id, policy.divdata, divModulename)
return id
end
_M.check = function(self, policy)
local divModulename = table.concat({'abtesting', 'diversion', policy.divtype}, '.')
local divModule = require(divModulename)
local database = self.database
return divModule:new(database, ''):check(policy.divdata)
end
---
-- delete a policy from specified redis lib
-- @param id the policy identify
-- @return allways returned SUCCESS
_M.del = function(self, id)
local database = self.database
local policyLib = table.concat({self.baseLibrary, id}, separator)
ngx.log(ngx.ERR, policyLib)
local keys, err = database:keys(policyLib..'*')
if not keys then
error{ERRORINFO.REDIS_ERROR, err}
end
database:init_pipeline()
for _i, key in pairs(keys) do
database:del(key)
end
local ok, err = database:commit_pipeline()
if not ok then error{ERRORINFO.REDIS_ERROR, err} end
end
_M.get = function(self, id)
local divTypeKey = table.concat({self.baseLibrary, id, fields.divtype}, separator)
local divDataKey = table.concat({self.baseLibrary, id, fields.divdata}, separator)
local database = self.database
local policy = {}
policy.divtype = ngx.null
policy.divdata = ngx.null
local divtype, err = database:get(divTypeKey)
if not divtype then
error{ERRORINFO.REDIS_ERROR, err}
elseif divtype == ngx.null then
return policy
end
local divModulename = table.concat({'abtesting', 'diversion', divtype}, '.')
local divModule = require(divModulename):new(database, divDataKey)
local divdata = divModule:get()
policy.divtype = divtype
policy.divdata = divdata
return policy
end
return _M
| mit |
ifoxhz/iFox | scripts/callbacks/daily.lua | 2 | 2184 | --
-- (C) 2013-15 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
require "alert_utils"
if(ntop.isPro()) then
package.path = dirs.installdir .. "/pro/scripts/callbacks/?.lua;" .. package.path
require("daily")
end
-- Delete JSON files older than a 30 days
-- TODO: make 30 configurable
harvestJSONTopTalkers(30)
-- Scan "day" alerts
scanAlerts("day")
local debug = false
local delete_keys = true
function harverstExpiredMySQLFlows(ifname, mysql_retention)
sql = "DELETE FROM flowsv4 where FIRST_SWITCHED < "..mysql_retention
sql = sql.." AND (INTERFACE = '"..ifname.."' OR INTERFACE IS NULL)"
sql = sql.." AND (NTOPNG_INSTANCE_NAME='"..ntop.getPrefs()["instance_name"].."' OR NTOPNG_INSTANCE_NAME IS NULL)"
interface.execSQLQuery(sql)
if(debug) then io.write(sql.."\n") end
sql = "DELETE FROM flowsv6 where FIRST_SWITCHED < "..mysql_retention
sql = sql.." AND (INTERFACE = '"..ifname.."' OR INTERFACE IS NULL)"
sql = sql.." AND (NTOPNG_INSTANCE_NAME='"..ntop.getPrefs()["instance_name"].."' OR NTOPNG_INSTANCE_NAME IS NULL)"
interface.execSQLQuery(sql)
if(debug) then io.write(sql.."\n") end
end
begin = os.clock()
t = os.time()-86400
if((_GET ~= nil) and (_GET["debug"] ~= nil)) then
debug = true
t = t + 86400
end
if(debug) then sendHTTPHeader('text/plain') end
when = os.date("%y%m%d", t)
mysql_retention = ntop.getCache("ntopng.prefs.mysql_retention")
if((mysql_retention == nil) or (mysql_retention == "")) then mysql_retention = "30" end
mysql_retention = os.time() - 86400*tonumber(mysql_retention)
ifnames = interface.getIfNames()
for _,_ifname in pairs(ifnames) do
interface.select(purifyInterfaceName(_ifname))
interface_id = getInterfaceId(ifname)
ntop.deleteMinuteStatsOlderThan(interface_id, 365)
harverstExpiredMySQLFlows(_ifname, mysql_retention)
hosts_stats = interface.getHostsInfo()
for key, value in pairs(hosts_stats) do
interface.resetPeriodicStats(key, value["vlan"])
end
if(interface.getInterfaceDumpDiskPolicy() == true) then
ntop.deleteDumpFiles(interface_id)
end
end
| gpl-3.0 |
Tgfire/tgFire | plugins/MyInfo.lua | 4 | 1428 | local function run(msg, matches)
if matches[1]:lower() == 'myinfo' then
function get_id(arg, data)
local username
if data.first_name_ then
if data.username_ then
username = '@'..data.username_
else
username = '<i>No Username!</i>'
end
local telNum
if data.phone_number_ then
telNum = '+'..data.phone_number_
else
telNum = '----'
end
local lastName
if data.last_name_ then
lastName = data.last_name_
else
lastName = '----'
end
local rank
if is_sudo(msg) then
rank = 'Sudo'
elseif is_owner(msg) then
rank = 'Bot Owner'
elseif is_admin(msg) then
rank = 'Admin'
elseif is_mod(msg) then
rank = 'Moderator'
else
rank = 'Group Member'
end
local text = '<b>🔹Information:</b>\n<b>✨First Name:</b> <i>'..data.first_name_..'</i>\n<b>✨Last Name:</b> <i>'..lastName..'</i>\n<b>✨Username:</b> '..username..'\n<b>✨ID:</b> [ <code>'..data.id_..'</code> ]\n<b>✨Group ID:</b> [ <code>'..arg.chat_id..'</code> ]\n<b>📱Phone Number:</b> [ <code>'..telNum..'</code> ]\n<b>✨Rank:</b> <i>'..rank..'</i>'
tdcli.sendMessage(arg.chat_id, msg.id_, 1, text, 1, 'html')
end
end
tdcli_function({ ID = 'GetUser', user_id_ = msg.sender_user_id_, }, get_id, {chat_id=msg.chat_id_, user_id=msg.sendr_user_id_})
end
end
return { patterns = { "^[/!#]([Mm][Yy][Ii][Nn][Ff][Oo])$" }, run = run }
| gpl-3.0 |
wangtianhang/UnityLuaTest | toluaSnapshotTest/toluaUnityProject/Assets/ToLua/Lua/System/Timer.lua | 4 | 3928 | --------------------------------------------------------------------------------
-- Copyright (c) 2015 , 蒙占志(topameng) topameng@gmail.com
-- All rights reserved.
-- Use, modification and distribution are subject to the "MIT License"
--------------------------------------------------------------------------------
local setmetatable = setmetatable
local UpdateBeat = UpdateBeat
local CoUpdateBeat = CoUpdateBeat
local Time = Time
Timer = {}
local Timer = Timer
local mt = {__index = Timer}
--unscaled false 采用deltaTime计时,true 采用 unscaledDeltaTime计时
function Timer.New(func, duration, loop, unscaled)
unscaled = unscaled or false and true
loop = loop or 1
return setmetatable({func = func, duration = duration, time = duration, loop = loop, unscaled = unscaled, running = false}, mt)
end
function Timer:Start()
self.running = true
if not self.handle then
self.handle = UpdateBeat:CreateListener(self.Update, self)
end
UpdateBeat:AddListener(self.handle)
end
function Timer:Reset(func, duration, loop, unscaled)
self.duration = duration
self.loop = loop or 1
self.unscaled = unscaled
self.func = func
self.time = duration
end
function Timer:Stop()
self.running = false
if self.handle then
UpdateBeat:RemoveListener(self.handle)
end
end
function Timer:Update()
if not self.running then
return
end
local delta = self.unscaled and Time.unscaledDeltaTime or Time.deltaTime
self.time = self.time - delta
if self.time <= 0 then
self.func()
if self.loop > 0 then
self.loop = self.loop - 1
self.time = self.time + self.duration
end
if self.loop == 0 then
self:Stop()
elseif self.loop < 0 then
self.time = self.time + self.duration
end
end
end
--给协同使用的帧计数timer
FrameTimer = {}
local FrameTimer = FrameTimer
local mt2 = {__index = FrameTimer}
function FrameTimer.New(func, count, loop)
local c = Time.frameCount + count
loop = loop or 1
return setmetatable({func = func, loop = loop, duration = count, count = c, running = false}, mt2)
end
function FrameTimer:Reset(func, count, loop)
self.func = func
self.duration = count
self.loop = loop
self.count = Time.frameCount + count
end
function FrameTimer:Start()
if not self.handle then
self.handle = CoUpdateBeat:CreateListener(self.Update, self)
end
CoUpdateBeat:AddListener(self.handle)
self.running = true
end
function FrameTimer:Stop()
self.running = false
if self.handle then
CoUpdateBeat:RemoveListener(self.handle)
end
end
function FrameTimer:Update()
if not self.running then
return
end
if Time.frameCount >= self.count then
self.func()
if self.loop > 0 then
self.loop = self.loop - 1
end
if self.loop == 0 then
self:Stop()
else
self.count = Time.frameCount + self.duration
end
end
end
CoTimer = {}
local CoTimer = CoTimer
local mt3 = {__index = CoTimer}
function CoTimer.New(func, duration, loop)
loop = loop or 1
return setmetatable({duration = duration, loop = loop, func = func, time = duration, running = false}, mt3)
end
function CoTimer:Start()
if not self.handle then
self.handle = CoUpdateBeat:CreateListener(self.Update, self)
end
self.running = true
CoUpdateBeat:AddListener(self.handle)
end
function CoTimer:Reset(func, duration, loop)
self.duration = duration
self.loop = loop or 1
self.func = func
self.time = duration
end
function CoTimer:Stop()
self.running = false
if self.handle then
CoUpdateBeat:RemoveListener(self.handle)
end
end
function CoTimer:Update()
if not self.running then
return
end
if self.time <= 0 then
self.func()
if self.loop > 0 then
self.loop = self.loop - 1
self.time = self.time + self.duration
end
if self.loop == 0 then
self:Stop()
elseif self.loop < 0 then
self.time = self.time + self.duration
end
end
self.time = self.time - Time.deltaTime
end | mit |
gajop/Zero-K | LuaUI/Widgets/chili_new/handlers/debughandler.lua | 8 | 12947 | --//=============================================================================
--// Chili DebugHandler
--//=============================================================================
--// todo:
--// * use the custom errorhandler for any widget->chili interaction,
--// atm if a widget calls mybutton:SetCaption() the widgethandler errorhandler is used,
--// but this one uses pcall and so it can't generate a stacktrace, which makes debugging
--// nearly impossible (cuz the error mostly occurs in a ver low level chili object as `Font`).
--// So any :New{} should in thoery return a wrapped table to the widgets, I already tried
--// to wrap the whole WG.Chili namespace (check the `SafeWrap` function beneath), but my tests
--// ended in crashes in chili, cuz such wrapped tables ended in chili itself
--// (chili should only use links and direct ones, but never wrapped tables)
DebugHandler = {}
--//=============================================================================
--// List of all chili object for easy debugging
--// DebugHandler.objectsOwnedByWidgets[widget][n] = owned_object
--// hint: because the per-widget table is a weaktable you still need to use pairs() to iterate it!
DebugHandler.objectsOwnedByWidgets = {}
setmetatable(DebugHandler.objectsOwnedByWidgets, {
__mode="k",
__index=function(t,i)
local st = {};
setmetatable(st,{__mode="v"});
if (not i) then
Spring.Echo("WAAA",debug.traceback())
end
t[i] = st;
return st;
end,
})
--// holds all created chili objects (uses a weaktable to do so)
--// hint: because it is a weaktable you still need to use pairs() to iterate it!
DebugHandler.allObjects = {}
setmetatable(DebugHandler.allObjects, {
__mode="v",
})
--//=============================================================================
--// Chili ErrorHandler
--//
--// Chili is a framework, so many widgets move parts of their code into its
--// thread. If now a widget error happens, it could be shown as chili errors and
--// the widgethandler would unload chili instead of the causing widget.
--//
--// Now this errorhandler removes the widget itself (and its owned chili objects)
--// w/o crashing the whole framework.
DebugHandler.maxStackLength = 20
DebugHandler.maxChiliErrors = 20
local numChiliErrors = 0
local lastError = 0
local function ChiliErrorHandler(msg,...)
local control
local _i = 2 --// 1 is this function, so skip it
repeat
if (not debug.getinfo(_i)) then
break
end
local i = 1
repeat
local name,value = debug.getlocal(_i, i)
if (not name) then
break
end
if (name == "self") then
if (value._widget ~= widget) then --// ignore controls owned by Chili Framework!
control = value
end
end
i = i + 1
until(control)
_i = _i + 1
until(control)
if (control) then
local w = control._widget
if isindexable(w) then
local wname = (w.whInfo and w.whInfo.name) or "unknown"
Spring.Log("Chili", "error", ("in `%s`:%s : %s"):format(wname, control.name, msg))
Spring.Log("Chili", "error", DebugHandler.Stacktrace())
--// this also unloads all owned chili objects
Spring.Log("Chili", "error", "Removed widget: " .. wname)
widgetHandler:RemoveWidget(w)
else
Spring.Log("Chili", "error", ("in `%s` (couldn't detect the owner widget): %s"):format(control.name, msg))
Spring.Log("Chili", "error", DebugHandler.Stacktrace())
control:Dispose()
end
else
--// error in Chili itself
Spring.Log("Chili", "error", ("%s"):format(msg))
Spring.Log("Chili", "error", DebugHandler.Stacktrace())
if (os.clock() - lastError < 5) then
numChiliErrors = numChiliErrors + 1
else
numChiliErrors = 1
end
lastError = os.clock()
--// unload Chili to avoid error spam
if (numChiliErrors>=DebugHandler.maxChiliErrors) then
Spring.Log("Chili", "error", "Removed widget: " .. widget.whInfo.name)
widgetHandler:RemoveWidget(widget)
end
end
end
DebugHandler.ChiliErrorHandler = ChiliErrorHandler
--//=============================================================================
--// Stacktrace
function DebugHandler.Stacktrace()
local self_src = debug.getinfo(1).short_src
local trace = {"stacktrace:"}
local _i = 3
repeat
local info = debug.getinfo(_i)
if (not info) then break end
--// we remove any occurence of the debughandler in the stacktrace (it's useless for debugging)
if (info.short_src ~= self_src)
and(info.name ~= "SafeCall")
and(info.name ~= "cdxpcall")
and(info.name ~= "cdCreateList")
then
local curLine = info.currentline
if (curLine<0) then
curLine = ""
else
curLine = ":" .. curLine
end
if (info.name) then
if (info.name=="") then
trace[#trace+1] = ("%s%s: in [?]"):format(info.short_src,curLine)
else
trace[#trace+1] = ("%s%s: in %s"):format(info.short_src,curLine,info.name)
end
else
trace[#trace+1] = ("%s%s"):format(info.short_src,curLine)
end
end
_i = _i + 1
until(false)
if ((#trace-1) > DebugHandler.maxStackLength) then
local i = 1 + math.ceil(DebugHandler.maxStackLength/2)+1
local tail = (DebugHandler.maxStackLength - i)
local j = #trace - tail
trace[i] = ("... (%i calls)"):format(#trace - (i + tail))
for n=1,tail do
trace[i+n] = trace[j+n]
end
for i=1+DebugHandler.maxStackLength+1, #trace do
trace[i] = nil
end
end
return table.concat(trace,"\n\t")
end
--//=============================================================================
--// Define some helper functions needed for xpcall
--// we do this so we can identify it in Stacktrace() (cd = chili debug)
local cdxpcall = xpcall
local sharedEnv = {_f = nil}
local setArgsFuncs = {}
local callFuncs = {}
do
local function CreateNewHelpers(_,n)
local t0 = {}
local t1 = {}
local t2 = {}
for i=1,n do
t0[i] = "a" .. i
t1[i] = "arg" .. i
t2[i] = "a" .. i .. "=arg" .. i
end
local varargs = table.concat(t0, ", ")
local arglist = table.concat(t1, ",")
local setargs = table.concat(t2, "; ")
local src = ([[local %s;
local setargs = function(%s) %s; end;
local call = function() return _f(%s); end
return setargs,call
]]):format(varargs, arglist, setargs, varargs)
local setargsfunc,callfunc = assert(loadstring(src))()
setfenv(setargsfunc,sharedEnv)
setfenv(callfunc,sharedEnv)
rawset(setArgsFuncs, n, setargsfunc)
rawset(callFuncs, n, callfunc)
return setargsfunc
end
setmetatable(setArgsFuncs, {__index = CreateNewHelpers})
setmetatable(callFuncs, {__index = CreateNewHelpers})
end
local function GetResults(status,...)
if (status) then
return ...
else
return nil
end
end
local function xpcall_va(func, ...)
local n = select("#", ...)
if (n == 0) then
return GetResults(cdxpcall(func,ChiliErrorHandler))
else
sharedEnv._f = func
setArgsFuncs[n](...)
return GetResults(cdxpcall(callFuncs[n],ChiliErrorHandler))
end
end
--//=============================================================================
--// Define Chili.SafeCall
DebugHandler.SafeCall = xpcall_va
SafeCall = xpcall_va --// external code should access it via Chili.SafeCall()
--//=============================================================================
--// Use our errorhandler in gl.CreateList
local orig_gl = gl
local cdCreateList = gl.CreateList
gl = {}
setmetatable(gl,{__index=function(t,i) t[i] = orig_gl[i]; return t[i]; end}) --// use metatable to copy table entries on-demand
gl.CreateList = function(...)
return cdCreateList(xpcall_va, ...)
end
--//=============================================================================
--// Chili.DebugHandler.SafeWrap
--// usage:
--// used for WG.Chili & screen0 to make any calling to them safe
--// how:
--// it wraps a table, so any calling to a function in it (or ones of its subtables)
--// uses automatically the Chili internal error handler
--// note:
--// it doesn't auto wrap th return values of such functions (for performance reasons)
local function IndexWrappedTable(t,i)
local v_orig = t.__orig[i]
local v
if (isindexable(v_orig)) then
--Spring.Echo("wrap table", i)
v = DebugHandler.SafeWrap(v_orig);
t[i] = v;
elseif (isfunc(v_orig)) then
--Spring.Echo("wrap func", i)
v = function(self,...)
if (isindexable(self))and(self.__orig) then
self = self.__orig
end
return DebugHandler.SafeWrap(xpcall_va(v_orig,self,...));
end;
t[i] = v;
else
v = v_orig;
--t[i] = v; don't cache values (else they wouldn't update when they got in the original table)
end
return v;
end
local function HasSubFunctions(t)
if (not istable(t)) then
return true
end
for i,v in pairs(t) do
if (isfunc(v)) then
return true
elseif (isindexable(v)) then
local r = HasSubFunctions(v)
if (r) then return true end
end
end
return false
end
local function IndexWrappedLink(link,i)
local t = link()
local v_orig = t[i]
--local t_wrap = getmetatable(link)._wrap
local v = v_orig;
if (isindexable(v_orig)) then
-- Spring.Echo("wrap table", i,HasSubFunctions(v_orig))
-- if (HasSubFunctions(v_orig)) then
-- v = DebugHandler.SafeWrap(v_orig);
-- t_wrap[i] = v;
-- end
elseif (isfunc(v_orig)) then
--Spring.Echo("wrap func", i)
v = function(self,...)
if (isindexable(self))and(self.__orig) then
self = self.__orig
end
return xpcall_va(v_orig,self,...);
--return DebugHandler.SafeWrap(xpcall_va(v_orig,self,...));
end;
--t_wrap[i] = v;
end
return v;
end
local safewrap_meta = {
__index = IndexWrappedTable
}
function DebugHandler.SafeWrap(t_orig,...)
if isindexable(t_orig) then
local meta = getmetatable(t_orig)
if (meta)and(meta._islink) then
meta._wrap = {}
meta[meta._wrap] = true
meta.__index = IndexWrappedLink
return t_orig
else
local t = {__orig = t_orig}
setmetatable(t, safewrap_meta)
return t
end
else
return t_orig,...
end
end
--//=============================================================================
--// When a Widget gets removed destroy all its owned chili object, too
local origRemoveWidget = widgetHandler.RemoveWidget
widgetHandler.RemoveWidget = function(self,widget,...)
local ownedObjects = DebugHandler.objectsOwnedByWidgets[widget]
for k,obj in pairs(ownedObjects) do
obj:Dispose()
ownedObjects[k] = nil
end
origRemoveWidget(self,widget,...)
end
--//=============================================================================
--// Check the stack for any indication for an user widget
--// so we can remove all owned chili object when the widget crashes/unloads
--// (also useful for a lot of other debugging purposes)
function DebugHandler.GetWidgetOrigin(_i)
local chiliwidget = widget
_i = _i or 4 --// 1:=this function, 2:=RegisterObject, 3:=class:New{}, 4:=user widget?
repeat
--// CHECK STACK
local info = debug.getinfo(_i,"f")
if (not info) then
return
end
--// CHECK ENVIROMENT
if (info.func) then
local _G = debug.getfenv(info.func)
if (_G.widget)and(_G.widget~=chiliwidget)and(_G.widget.GetInfo) then
--Spring.Echo("env widget found", _G.widget:GetInfo().name)
return _G.widget
end
end
--// CHECK LOCALS
local i=1
repeat
local name,value = debug.getlocal(_i, i)
if (not name) then
break
end
if (name == "widget")and(value.GetInfo) then
--Spring.Echo("local widget found", value:GetInfo().name)
return value
else
--// this code gets triggered when a chili control creates another one
--// (the new control should then inherit the widget origin)
local typ = type(value)
if (typ=="table")or(typ=="metatable")or(typ=="userdata") then
if (typ._widget)and(typ._widget.GetInfo) then
--Spring.Echo("local2 widget found", typ._widget:GetInfo().name)
return typ._widget
end
end
end
i = i + 1
until(false)
_i = _i + 1
until(false)
end
--//=============================================================================
--// gets called by Chili.Object:New{}
function DebugHandler:RegisterObject(obj)
local w = self.GetWidgetOrigin()
if (w) then
obj._widget = w
local t = self.objectsOwnedByWidgets[w]
t[#t+1] = obj
end
local ta = self.allObjects
ta[#ta+1] = obj
--// hint: both tables above are weaktables, so we don't need a UnregisterObject!
end
--//=============================================================================
| gpl-2.0 |
gajop/Zero-K | lups/ParticleClasses/Ribbons.lua | 9 | 11129 | -- $Id: Ribbons.lua 3171 2008-11-06 09:06:29Z det $
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
--// only works with >=77b1
if (Game.version=="0.76b1") then
return false
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local Ribbon = {}
Ribbon.__index = Ribbon
local RibbonShader
local widthLoc, quadsLoc
local oldPosUniform = {}
local lastTexture
local DLists = {}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon.GetInfo()
return {
name = "Ribbon",
backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.)
desc = "",
layer = 1, --// extreme simply z-ordering :x
--// gfx requirement
fbo = false,
shader = true,
rtt = false,
ctt = false,
}
end
Ribbon.Default = {
layer = 1,
life = math.huge,
unit = nil,
projectile=nil,
piece = 0,
width = 1,
size = 24, --//max 256
color = {0.9,0.9,1,1},
texture = "bitmaps/GPL/Lups/jet.bmp",
decayRate = 0.01,
worldspace = true,
repeatEffect = true,
dieGameFrame = math.huge,
isvalid = true,
}
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local spGetUnitDefID = Spring.GetUnitDefID
local spGetUnitIsDead = Spring.GetUnitIsDead
local spIsUnitValid = Spring.IsUnitValid
local spIsSphereInView = Spring.IsSphereInView
local spGetUnitVelocity = Spring.GetUnitVelocity
local spGetUnitPiecePosition = Spring.GetUnitPiecePosition
local spGetUnitViewPosition = Spring.GetUnitViewPosition
local spGetUnitPiecePosDir = Spring.GetUnitPiecePosDir
local spGetUnitVectors = Spring.GetUnitVectors
local spGetProjectilePosition = Spring.GetProjectilePosition
local spGetProjectileVelocity = Spring.GetProjectileVelocity
local glUniform = gl.Uniform
local glUniformInt = gl.UniformInt
local glUseShader = gl.UseShader
local glColor = gl.Color
local glCallList = gl.CallList
local glTexture = gl.Texture
local glBlending = gl.Blending
local GL_ONE = GL.ONE
local GL_SRC_ALPHA = GL.SRC_ALPHA
local GL_ONE_MINUS_SRC_ALPHA = GL.ONE_MINUS_SRC_ALPHA
local function GetPiecePos(unit,piece)
local x,y,z = spGetUnitViewPosition(unit,false)
local front,up,right = spGetUnitVectors(unit)
local px,py,pz = spGetUnitPiecePosition(unit,piece)
return x + (pz*front[1] + py*up[1] + px*right[1]),
y + (pz*front[2] + py*up[2] + px*right[2]),
z + (pz*front[3] + py*up[3] + px*right[3])
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon:BeginDraw()
glUseShader(RibbonShader)
glBlending(GL_SRC_ALPHA,GL_ONE)
end
function Ribbon:EndDraw()
glUseShader(0)
glBlending(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA)
glTexture(0,false)
lastTexture = nil
glColor(1,1,1,1)
end
function Ribbon:Draw()
local quads0 = self.quads0
if self.texture ~= lastTexture then
glTexture(0,":c:"..self.texture)
lastTexture = self.texture
end
glUniform(widthLoc, self.width )
glUniformInt(quadsLoc, quads0 )
--// insert old pos
local j = ((self.posIdx==self.size) and 1) or (self.posIdx+1)
for i=1,quads0 do
local dir = self.oldPos[j]
j = ((j==self.size) and 1) or (j+1)
glUniform( oldPosUniform[i] , dir[1], dir[2], dir[3] )
end
--// insert interpolated current unit pos
if (self.isvalid) then
--local x,y,z = GetPiecePos(self.unit,self.piecenum)
local x,y,z
if self.unit then
x,y,z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
if x and y and z then
glUniform( oldPosUniform[quads0+1] , x,y,z )
end
else
local dir = self.oldPos[j]
glUniform( oldPosUniform[quads0+1] , dir[1], dir[2], dir[3] )
end
--// define color and add speed blending (don't show ribbon for slow/landing units!)
if (self.blendfactor<1) then
local clr = self.color
glColor(clr[1],clr[2],clr[3],clr[4]*self.blendfactor)
else
glColor(self.color)
end
glCallList(DLists[quads0])
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon.Initialize()
RibbonShader = gl.CreateShader({
vertex = [[
uniform float width;
uniform int quads;
uniform vec3 oldPos[256];
varying vec2 texCoord;
void main()
{
vec3 updir,right;
vec3 vertex = oldPos[int(gl_MultiTexCoord0.w)];
gl_Position = gl_ModelViewMatrix * vec4(vertex,1.0);
vec3 vertex2,pos2;
if (int(gl_MultiTexCoord0.w) == quads) {
vertex2 = oldPos[int(gl_MultiTexCoord0.w)-1];
pos2 = (gl_ModelViewMatrix * vec4(vertex2,1.0)).xyz;
updir = gl_Position.xyz - pos2.xyz;
}else{
vertex2 = oldPos[int(gl_MultiTexCoord0.w)+1];
pos2 = (gl_ModelViewMatrix * vec4(vertex2,1.0)).xyz;
updir = pos2.xyz - gl_Position.xyz;
}
right = normalize( cross(updir,gl_Position.xyz) );
gl_Position.xyz += right * gl_MultiTexCoord0.x * width;
gl_Position = gl_ProjectionMatrix * gl_Position;
texCoord = gl_MultiTexCoord0.pt;
gl_FrontColor = gl_Color;
}
]],
fragment = [[
uniform sampler2D ribbonTex;
varying vec2 texCoord;
void main()
{
gl_FragColor = texture2D(ribbonTex, texCoord )*gl_Color;
}
]],
uniformInt={
ribbonTex = 0,
},
})
if (RibbonShader == nil) then
print(PRIO_MAJOR,"LUPS->Ribbon: critical shader error: "..gl.GetShaderLog())
return false
end
widthLoc = gl.GetUniformLocation(RibbonShader, 'width')
quadsLoc = gl.GetUniformLocation(RibbonShader, 'quads')
for i=1,256 do
oldPosUniform[i] = gl.GetUniformLocation(RibbonShader,"oldPos["..(i-1).."]")
end
end
function Ribbon.Finalize()
if (gl.DeleteShader) then
gl.DeleteShader(RibbonShader)
end
while (next(DLists)) do
local i,v = next(DLists)
DLists[i] = nil
gl.DeleteList(v)
end
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
function Ribbon:Update(n)
self.isvalid = (self.unit and spGetUnitIsDead(self.unit) == false) or (self.projectile and Spring.GetProjectileDefID(self.projectile))
if (self.isvalid) then
local x,y,z
if self.unit then
x, y, z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
if x and y and z then
self.posIdx = (self.posIdx % self.size)+1
self.oldPos[self.posIdx] = {x,y,z}
local vx,vy,vz
if self.unit then
vx, vy, vz = spGetUnitVelocity(self.unit)
elseif self.projectile then
vx, vy, vz = spGetProjectileVelocity(self.projectile)
end
if vx and vy and vz then
self.blendfactor = (vx*vx+vy*vy+vz*vz)/30
end
end
else
local lastIndex = self.posIdx
self.posIdx = (self.posIdx % self.size)+1
self.oldPos[self.posIdx] = self.oldPos[lastIndex]
self.blendfactor = self.blendfactor - n * self.decayRate
end
end
function Ribbon:Visible()
self.isvalid = (self.unit and spGetUnitIsDead(self.unit) == false) or (self.projectile and Spring.GetProjectileDefID(self.projectile))
local pos = self.oldPos[self.posIdx]
return (self.blendfactor>0) and (spIsSphereInView(pos[1],pos[2],pos[3], self.radius))
end
function Ribbon:Valid()
return self.isvalid or (self.blendfactor>0)
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local function CreateDList(quads0)
for i=0,quads0-1 do
local tex_t = i/quads0
local tex_t_next = (i+1)/quads0
gl.TexCoord(-1,tex_t_next,0,i+1)
gl.Vertex(0,0,0)
gl.TexCoord(1,tex_t_next,1,i+1)
gl.Vertex(0,0,0)
gl.TexCoord(1,tex_t,1,i)
gl.Vertex(0,0,0)
gl.TexCoord(-1,tex_t,0,i)
gl.Vertex(0,0,0)
end
end
-- used if repeatEffect=true;
function Ribbon:ReInitialize()
self.dieGameFrame = self.dieGameFrame + self.life
end
function Ribbon:CreateParticle()
if (self.size>256) then self.size=256
elseif (self.size<2) then self.size=2 end
self.posIdx = 1
self.quads0 = self.size-1
self.blendfactor = 1
local x,y,z
if self.unit then
x,y,z = spGetUnitPiecePosDir(self.unit,self.piecenum)
elseif self.projectile then
x,y,z = spGetProjectilePosition(self.projectile)
end
local curpos = {x,y,z}
self.oldPos = {}
for i=1,self.size do
self.oldPos[i] = curpos
end
local udid = self.unit and spGetUnitDefID(self.unit)
local weapon = self.weapon
local speed = self.speed or (UnitDefs[udid] and UnitDefs[udid].speed) or (weapon and WeaponDefs[weapon] and WeaponDefs[weapon].projectilespeed*30) or 100
self.radius = (speed/30.0)*self.size
if (not DLists[self.quads0]) then
DLists[self.quads0] = gl.CreateList(gl.BeginEnd,GL.QUADS,CreateDList,self.quads0)
end
self.startGameFrame = thisGameFrame
self.dieGameFrame = self.startGameFrame + self.life
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
local MergeTable = MergeTable
local setmetatable = setmetatable
function Ribbon.Create(Options)
local newObject = MergeTable(Options, Ribbon.Default)
setmetatable(newObject,Ribbon) -- make handle lookup
newObject:CreateParticle()
return newObject
end
function Ribbon:Destroy()
end
-----------------------------------------------------------------------------------------------------------------
-----------------------------------------------------------------------------------------------------------------
return Ribbon | gpl-2.0 |
Mutos/NAEV-StarsOfCall | dat/missions/neutral/dts_02.lua | 5 | 13614 | --[[
MISSION: Defend the System 3
DESCRIPTION: A mission to defend the system against swarm of pirate ships.
This will be the third in a series of random encounters.
After the mission, perhaps there'll be a regular diet of similar missions
Perhaps the random missions will eventually lead on to a plot line relating to the pirates.
Notable events:
* Stage one: From the bar, the player learns of a pirate fleet attacking the system and joins a defense force.
* Stage two: The volunteer force attacks the pirates.
* Stage three: When a sufficient number have been killed, the pirates retreat.
* Stage four: The portmaster welcomes the fleet back and thanks them with money.
* Stage five: In the bar afterward, another pilot wonders why the pirates behaved unusually.
TO DO
Make comm chatter appear during the battle
NOTE
Because of bad planning, this mission is badly organized.
Anyone looking for a model of good mission-making should look elsewhere! -- the author
]]--
include "dat/scripts/numstring.lua"
-- localization stuff, translators would work here
lang = naev.lang()
if lang == "es" then
else -- default english
-- This section stores the strings (text) for the mission.
-- Mission details
misn_title = "Defend the System"
misn_reward = "%s credits and the pleasure of serving the Empire."
misn_desc = "Defend the system against a pirate fleet."
-- Stage one: in the bar you hear a fleet of Pirates have invaded the system.
title = {}
text = {}
title[1] = "In the bar"
text[1] = [[The bar rests in the dull clink of glasses and the scattered murmur of conversation when the door bursts open. An older couple stumbles in, faces gaping, eyes staring. They take a few steps before the woman sinks to her knees and bursts into tears.
"Our son... his ship was supposed to land a minute ago," her partner says mechanically. "But pirates, suddenly everywhere-" he swallows. "-they didn't make it." His wife throws her head back and wails.
Two young men rise abruptly from a table in the back of the room and come stiffly forward. One goes to the grieving couple while the other turns address the room.
"These raiders must be stopped. We are cadets at the Imperial Flight School. If you feel the injustice of this family's loss, will you fly with us to avenge their son's death?"]]
title[11] = "Volunteers"
text[11] = [["These terrorists cannot sustain many losses," one of the young men explains as you and a group of other volunteers prepare for takeoff, "and they have no organization. We can destroy them if you team up and focus your fire on one ship at a time."]]
-- Stage two: comm chatter, now no longer used except to initialize the table
comm = {}
-- Stage three: Victorious comm chatter
comm[6] = "We've got them on the run!"
comm[61] = "Broadcast %s> The raiders are retreating!"
comm[7] = "Good flying, volunteers. The governor is waiting for us back in port."
comm[71] = "Comm %s> Good flying, volunteers. The governor is waiting for you back in port."
-- Stage four: the governor greets you and the cadets in front of a crowd
title[2] = "A public occasion"
text[2] = [[Night is falling by the time you land back on %s. Looking solemn in front of a gathering crowd and news recorders, a large man with a fleshy face comes forward to greet the survivors of the fight. A flock of men and women follow him.
When he shakes your hand, the Governor looks keenly at you at smiles, "Very well done."
After meeting each surviving pilot, the tall man stands still for aide to attach an amplifier to his lapel. Then he turns his face to the news-casters and the crowd.]]
-- Stage five: the commander welcomes you back
title[3] = "The Governor's speech"
text[3] = [[
"Even here on %s, even in the protective embrace of civilization, we face many dangers. The ties that bind us through space to other worlds are fragile. When criminals attack these precious connections, they trouble the very foundations of our peace. How glad we are now for the security of the Empire whose young navy cadets led a team of independent pilots to defend us today." The Governor turns to the pair of officers-in-training. "In the name of the Emperor, I have the privilege of decorating these two young heroes with the %s Silver Heart. I hope they and their volunteers will not be too proud to also accept a generous purse, along with the gratitude of all our people. Please join me in applauding their bravery."
The public ceremony lasts only a few minutes. Afterwards, as interviewers draw the young navy officers aside and the crowd disperses, you catch sight of the elderly couple from the bar holding each other and looking up into the darkening sky.]]
-- Other text for the mission
comm[8] = "You fled from the battle. The Empire won't forget."
comm[9] = "Comm Lancelot> You're a coward, %s. You better hope I never see you again."
comm[10] = "Comm Lancelot> You're running away now, %s? The fight's finished, you know..."
title[4] = "Good job!"
text[4] = [[A freighter hails you as you jump into the system.
"Thank you for responding %s, are you coming in from %s? I have a delivery I need to get to %s and I can't wait much longer. Is the system safe now?"
You relate the outcome of the space battle.
"Oh, that's good news! You know, these raids are getting worse all the time. I wish the Empire would do something about it. Anyway, thank you for the information. Safe travels."]]
title[5] = "Not fighting"
text[5] = [[You stand by the grieving couple as the two cadets lead a group of pilots out of the bar toward the padfield.
"Oh no!" the woman cries suddenly, looking up into her partner's face. "They're going off to fight. Those young men, they... there'll be more killing because of us."
He nods grimly. "That's the way of things."
For long time, the two of them sit on the floor of the bar holding each other.]]
bounce_title = "Not done yet."
bounce_text = "The system isn't safe yet. Get back out there!"
noReward = "No reward for you."
noDesc = "Watch others defend the system."
noTitle = "Observe the action."
end
-- Create the mission on the current planet, and present the first Bar text.
function create()
this_planet, this_system = planet.cur()
if ( this_system:presences()["Pirate"] or
this_system:presences()["Collective"] or
this_system:presences()["FLF"] or
this_system:name() == "Gamma Polaris" or
this_system:name() == "Doeston" or
this_system:name() == "NGC-7291") then
misn.finish(false)
end
missys = {this_system}
if not misn.claim(missys) then
misn.finish(false)
end
planet_name = planet.name( this_planet)
system_name = this_system:name()
if tk.yesno( title[1], text[1] ) then
misn.accept()
tk.msg( title[11], text[11])
reward = 40000
misn.setReward( string.format( misn_reward, numstring(reward)) )
misn.setDesc( misn_desc)
misn.setTitle( misn_title)
misn.markerAdd( this_system, "low" )
defender = true
-- hook an abstract deciding function to player entering a system
hook.enter( "enter_system")
-- hook warm reception to player landing
hook.land( "celebrate_victory")
else
-- If player didn't accept the mission, the battle's still on, but player has no stake.
misn.accept()
var.push( "dts_firstSystem", "planet_name")
tk.msg( title[5], text[5])
misn.setReward( noReward)
misn.setDesc( noDesc)
misn.setTitle( noTitle)
defender = false
-- hook an abstract deciding function to player entering a system when not part of defense
hook.enter( "enter_system")
end
end
-- Decides what to do when player either takes off starting planet or jumps into another system
function enter_system()
if this_system == system.cur() and defender == true then
defend_system()
elseif victory == true and defender == true then
pilot.add( "Trader Koala", "def", player.pos(), false)
hook.timer(1000, "ship_enters")
elseif defender == true then
player.msg( comm[8])
faction.modPlayerSingle( "Empire", -3)
misn.finish( true)
elseif this_system == system.cur() and been_here_before ~= true then
been_here_before = true
defend_system()
else
misn.finish( true)
end
end
-- There's a battle to defend the system
function defend_system()
-- Makes the system empty except for the two fleets. No help coming.
pilot.clear ()
pilot.toggleSpawn( false )
-- Set up distances
angle = rnd.rnd() * 2 * math.pi
if defender == true then
raider_position = vec2.new( 400*math.cos(angle), 400*math.sin(angle) )
defense_position = vec2.new( 0, 0 )
else
raider_position = vec2.new( 800*math.cos(angle), 800*math.sin(angle) )
defense_position = vec2.new( 400*math.cos(angle), 400*math.sin(angle) )
end
-- Create a fleet of raiding pirates
raider_fleet = pilot.add( "DTS Raiders", "def", raider_position )
for k,v in ipairs( raider_fleet) do
pilot.setHostile( v)
end
-- And a fleet of defending independents
defense_fleet = pilot.add( "DTS Defense Fleet", "def", defense_position )
cadet1 = pilot.add( "Empire Lancelot", "def", defense_position )[1]
do
cadet1_alive = true
hook.pilot( cadet1, "death", "cadet1_dead")
end
cadet2 = pilot.add( "Empire Lancelot", "def", defense_position )[1]
do
cadet2_alive = true
hook.pilot( cadet2, "death", "cadet2_dead")
end
for k,v in ipairs( defense_fleet) do
v:setFriendly()
end
cadet1:setFriendly()
cadet2:setFriendly()
--[[ Set conditions for the end of the Battle:
hook fleet departure to disabling or killing ships]]
casualties = 0
casualty_max = (#raider_fleet / 2 + 1)
victories = 0
victory = false
for k, v in ipairs( raider_fleet) do
hook.pilot (v, "disable", "add_cas_and_check")
end
if defender == false then
misn.finish( true)
end
end
-- If they die, they can't communicate with the player.
function cadet1_dead() cadet1_alive = false end
function cadet2_dead() cadet2_alive = false end
-- Record each raider death and make the raiders flee after too many casualties
function add_cas_and_check()
if victory then return end
casualties = casualties + 1
if casualties > casualty_max then
raiders_left = pilot.get( { faction.get("Raider") } )
for k, v in ipairs( raiders_left ) do
pilot.changeAI( v, "flee")
end
if victories < 1 then -- Send in the second wave
victories = victories + 1
second_wave_attacks()
else
victory = true
player.msg( comm[6]) -- A few seconds after victory, the system is back under control
hook.timer(8000, "victorious")
return
end
end
end
function second_wave_attacks()
casualties = 0
second_wave = pilot.add( "Pirate Hyena Pack", "def", player.pos(), true)
for k, v in ipairs( second_wave) do
v:setFaction( "Raider")
v:setHostile()
end
casualty_max = math.modf( #second_wave / 2)
for k, v in ipairs( second_wave) do
hook.pilot (v, "disable", "add_cas_and_check")
end
end
-- Separate mission for a mid-mission interjection <-- bad organization
function cadet_first_comm()
if cadet1_alive then
cadet1:comm( comm[6])
elseif cadet2_alive then
cadet2:comm( comm[6])
else player.msg( string.format(comm[61], planet_name))
end
end
-- When the raiders are on the run then the Empire takes over
function victorious()
if cadet1_alive then
cadet1:comm( comm[7])
elseif cadet2_alive then
cadet2:comm( comm[7])
else player.msg( string.format(comm[71], planet_name))
end
end
-- The player lands to a warm welcome (if the job is done).
function celebrate_victory()
if victory == true then
tk.msg( title[2], string.format( text[2], planet_name) )
player.pay( reward)
faction.modPlayerSingle( "Empire", 3)
tk.msg( title[3], string.format( text[3], planet_name, planet_name) )
misn.finish( true)
else
tk.msg( bounce_title, bounce_text) -- If any pirates still alive, send player back out.
player.takeoff()
end
end
-- A fellow warrior says hello in passing if player jumps out of the system without landing
function ship_enters()
enter_vect = player.pos()
hook.timer(1000, "congratulations")
end
function congratulations()
tk.msg( title[4], string.format( text[4], player.ship(), system_name, planet_name))
misn.finish( true)
end
-- If the player aborts the mission, the Empire and Traders react
function abort()
if victory == false then
faction.modPlayerSingle( "Empire", -10)
faction.modPlayerSingle( "Trader", -10)
player.msg( string.format( comm[9], player.name()))
else
player.msg( string.format( comm[10], player.name()))
end
misn.finish( true)
end
| gpl-3.0 |
gajop/Zero-K | LuaUI/Widgets/init_startup_info_selector.lua | 2 | 9995 | local versionNumber = "1.22"
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:GetInfo()
return {
name = "Startup Info and Selector",
desc = "[v" .. string.format("%s", versionNumber ) .. "] Shows important information and options on startup.",
author = "SirMaverick",
date = "2009,2010",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
--[[
-- Features:
_ Show a windows at game start with pictures to choose commander type.
]]--
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetGameRulesParam = Spring.GetGameRulesParam
-- FIXME use tobool instead of this string comparison silliness
local coop = (Spring.GetModOptions().coop == "1") or false
local forcejunior = (Spring.GetModOptions().forcejunior == "1") or false
local Chili
local Window
local ScrollPanel
local Grid
local Label
local screen0
local Image
local Button
local vsx, vsy = widgetHandler:GetViewSizes()
local modoptions = Spring.GetModOptions() --used in LuaUI\Configs\startup_info_selector.lua for planetwars
local selectorShown = false
local mainWindow
local scroll
local grid
local trainerCheckbox
local buttons = {}
local buttonLabels = {}
local trainerLabels = {}
local actionShow = "showstartupinfoselector"
local optionData
local noComm = false
local gameframe = Spring.GetGameFrame()
local COMM_DROP_FRAME = 450
local WINDOW_WIDTH = 720
local WINDOW_HEIGHT = 480
local BUTTON_WIDTH = 128
local BUTTON_HEIGHT = 128
if (vsx < 1024 or vsy < 768) then
--shrinker
WINDOW_WIDTH = vsx* (WINDOW_WIDTH/1024)
WINDOW_HEIGHT = vsy* (WINDOW_HEIGHT/768)
BUTTON_WIDTH = vsx* (BUTTON_WIDTH/1024)
BUTTON_HEIGHT = vsy* (BUTTON_HEIGHT/768)
end
--local wantLabelUpdate = false
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- wait for next screenframe so Grid can resize its elements first -- doesn't actually work
local function ToggleTrainerButtons(bool)
for i=1,#buttons do
if buttons[i].trainer then
if bool then
grid:AddChild(buttons[i])
else
grid:RemoveChild(buttons[i])
end
end
end
end
options_path = 'Settings/HUD Panels/Commander Selector'
options = {
hideTrainers = {
name = 'Hide Trainer Commanders',
--desc = '',
type = 'bool',
value = false,
noHotkey = true,
OnChange = function(self)
if trainerCheckbox then
trainerCheckbox.checked = self.value
trainerCheckbox.state.checked = self.value
trainerCheckbox:Invalidate()
end
ToggleTrainerButtons(not self.value)
end
},
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local function PlaySound(filename, ...)
local path = filename..".WAV"
if (VFS.FileExists(path)) then
Spring.PlaySoundFile(path, ...)
else
--Spring.Echo(filename)
Spring.Echo("<Startup Info Selector>: Error - file "..path.." doesn't exist.")
end
end
function widget:ViewResize(viewSizeX, viewSizeY)
vsx = viewSizeX
vsy = viewSizeY
end
function Close (permanently)
if mainWindow then
mainWindow:Dispose()
end
if permanently then
if not noComm then
widgetHandler:RemoveAction(actionShow)
noComm = true
end
if (Spring.GetGameFrame() <= COMM_DROP_FRAME) then
widgetHandler:RemoveCallIn('GameFrame')
widgetHandler:RemoveCallIn('GameProgress')
end
end
end
local function CreateWindow()
if mainWindow then
mainWindow:Dispose()
end
local numColumns = math.floor(WINDOW_WIDTH/BUTTON_WIDTH)
local numRows = math.ceil(#optionData/numColumns)
mainWindow = Window:New{
resizable = false,
draggable = false,
clientWidth = WINDOW_WIDTH,
clientHeight = WINDOW_HEIGHT,
x = (vsx - WINDOW_WIDTH)/2,
y = ((vsy - WINDOW_HEIGHT)/2),
parent = screen0,
caption = "COMMANDER SELECTOR",
}
--scroll = ScrollPanel:New{
-- parent = mainWindow,
-- horizontalScrollbar = false,
-- bottom = 36,
-- x = 2,
-- y = 12,
-- right = 2,
--}
grid = Grid:New{
parent = mainWindow,
autosize = false,
resizeItems = true,
x=0, right=0,
y=0, bottom=36,
centerItems = false,
}
-- add posters
local i = 0
for index,option in ipairs(optionData) do
i = i + 1
local hideButton = options.hideTrainers.value and option.trainer
local button = Button:New {
parent = (not hideButton) and grid or nil,
caption = "", --option.name, --option.trainer and "TRAINER" or "",
valign = "bottom",
tooltip = option.tooltip, --added comm name under cursor on tooltip too, like for posters
width = BUTTON_WIDTH,
height = BUTTON_HEIGHT,
padding = {5,5,5,5},
OnClick = {function()
Spring.SendLuaRulesMsg("customcomm:"..option.commProfile)
Spring.SendCommands({'say a:I choose: '..option.name..'!'})
Close()
end},
trainer = option.trainer,
}
buttons[i] = button
local image = Image:New{
parent = button,
file = option.image,--lookup Configs/startup_info_selector.lua to get optiondata
tooltip = option.tooltip,
x = 2,
y = 2,
right = 2,
bottom = 12,
}
local label = Label:New{
parent = button,
x = "15%",
bottom = 4,
caption = option.name,
align = "center",
font = {size = 14},
}
buttonLabels[i] = label
if option.trainer then
local trainerLabel = Label:New{
parent = image,
x = "25%",
y = "50%",
caption = "TRAINER",
align = "center",
font = {color = {1,0.2,0.2,1}, size=16, outline=true, outlineColor={1,1,1,0.8}},
}
trainerLabels[i] = trainerLabel
end
end
local cbWidth = WINDOW_WIDTH*0.4
local closeButton = Button:New{
parent = mainWindow,
caption = "CLOSE",
width = cbWidth,
x = WINDOW_WIDTH*0.5 + (WINDOW_WIDTH*0.5 - cbWidth)/2,
height = 30,
bottom = 2,
OnClick = {function() Close() end}
}
trainerCheckbox = Chili.Checkbox:New{
parent = mainWindow,
x = 4,
bottom = 2,
width = 160,
caption = "Hide Trainer Comms",
checked = options.hideTrainers.value,
OnChange = { function(self)
-- this is called *before* the 'checked' value is swapped, hence negation everywhere
if options.hideTrainers.epic_reference then
options.hideTrainers.epic_reference.checked = not self.checked
options.hideTrainers.epic_reference.state.checked = not self.checked
options.hideTrainers.epic_reference:Invalidate()
end
options.hideTrainers.value = not self.checked
ToggleTrainerButtons(self.checked)
end },
}
grid:Invalidate()
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function widget:Initialize()
optionData = include("Configs/startup_info_selector.lua")
if not (WG.Chili) then
widgetHandler:RemoveWidget()
end
-- chili setup
Chili = WG.Chili
Window = Chili.Window
ScrollPanel = Chili.ScrollPanel
Grid = Chili.Grid
Label = Chili.Label
screen0 = Chili.Screen0
Image = Chili.Image
Button = Chili.Button
-- FIXME: because this code runs before gadget:GameLoad(), the selector window pops up
-- even if comm is already selected
-- nothing serious, just annoying
local playerID = Spring.GetMyPlayerID()
local teamID = Spring.GetMyTeamID()
if ((coop and playerID and Spring.GetGameRulesParam("commSpawnedPlayer"..playerID) == 1)
or (not coop and Spring.GetTeamRulesParam(teamID, "commSpawned") == 1)
or (Spring.GetSpectatingState() or Spring.IsReplay() or forcejunior))
--and (not Spring.IsCheatingEnabled())
then
noComm = true -- will prevent window from auto-appearing; can still be brought up from the button
end
vsx, vsy = widgetHandler:GetViewSizes()
if (not noComm) then
widgetHandler:AddAction(actionShow, CreateWindow, nil, "t")
buttonWindow = Window:New{
resizable = false,
draggable = false,
width = 64,
height = 64,
right = 0,
y = 160,
tweakDraggable = true,
color = {0, 0, 0, 0},
padding = {0, 0, 0, 0},
itemMargin = {0, 0, 0, 0}
}
if Spring.GetGameSeconds() <= 0 then
screen0:AddChild(buttonWindow)
end
button = Button:New{
parent = buttonWindow,
caption = '',
tooltip = "Open comm selection screen",
width = "100%",
height = "100%",
x = 0,
y = 0,
OnClick = {function() Spring.SendCommands({"luaui "..actionShow}) end}
}
buttonImage = Image:New{
parent = button,
width="100%";
height="100%";
x=0;
y=0;
file = "LuaUI/Images/startup_info_selector/selecticon.png",
keepAspect = false,
}
CreateWindow()
end
end
-- hide window if game was loaded
local timer = 0
function widget:Update(dt)
timer = timer + dt
if timer >= 0.1 then
if (spGetGameRulesParam("loadedGame") == 1) then
Close(true)
end
widgetHandler:RemoveCallIn('Update')
end
end
function widget:Shutdown()
Close(true)
end
function widget:GameFrame(n)
if n == COMM_DROP_FRAME then
Close(true)
end
end
function widget:GameProgress(n)
if n == COMM_DROP_FRAME then
Close(true)
end
end
function widget:GameStart()
screen0:RemoveChild(buttonWindow)
end
-- this a pretty retarded place to put this but:
-- Update can fire before the game is actually loaded
-- GameStart is the actual game starting (not loading finished)
-- there is probably some better way
function widget:DrawWorld()
if (Spring.GetGameFrame() < 1) then
PlaySound("LuaUI/Sounds/Voices/initialized_core_1", 1, 'ui')
end
widgetHandler:RemoveCallIn('DrawWorld')
end
--------------------------------------------------------------------------------
-------------------------------------------------------------------------------- | gpl-2.0 |
padrinoo1/telebak | 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 |
nobie/sesame_fw | feeds/luci/applications/luci-wshaper/dist/usr/lib/lua/luci/model/cbi/wshaper.lua | 53 | 2056 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
require("luci.tools.webadmin")
m = Map("wshaper", translate("Wondershaper"),
translate("Wondershaper uses traffic shaping to ensure low latencies for interactive traffic even when your " ..
"internet connection is highly saturated."))
s = m:section(NamedSection, "settings", "wshaper", translate("Wondershaper settings"))
s.anonymous = true
network = s:option(ListValue, "network", translate("Interface"))
luci.tools.webadmin.cbi_add_networks(network)
uplink = s:option(Value, "uplink", translate("Uplink"), translate("Upstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "240"
uplink = s:option(Value, "downlink", translate("Downlink"), translate("Downstream bandwidth in kbit/s"))
uplink.optional = false
uplink.datatype = "uinteger"
uplink.default = "200"
nopriohostsrc = s:option(DynamicList, "nopriohostsrc", translate("Low priority hosts (Source)"), translate("Host or Network in CIDR notation."))
nopriohostsrc.optional = true
nopriohostsrc.datatype = ipaddr
nopriohostsrc.placeholder = "10.0.0.1/32"
nopriohostdst = s:option(DynamicList, "nopriohostdst", translate("Low priority hosts (Destination)"), translate("Host or Network in CIDR notation."))
nopriohostdst.optional = true
nopriohostdst.datatype = ipaddr
nopriohostdst.placeholder = "10.0.0.1/32"
noprioportsrc = s:option(DynamicList, "noprioportsrc", translate("Low priority source ports"))
noprioportsrc.optional = true
noprioportsrc.datatype = "range(0,65535)"
noprioportsrc.placeholder = "21"
noprioportdst = s:option(DynamicList, "noprioportdst", translate("Low priority destination ports"))
noprioportdst.optional = true
noprioportdst.datatype = "range(0,65535)"
noprioportdst.placeholder = "21"
return m
| gpl-2.0 |
KayMD/Illarion-Content | magic/learnMagic.lua | 3 | 7928 | --[[
Illarion Server
This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License as published by the Free
Software Foundation, either version 3 of the License, or (at your option) any
later version.
This program is distributed in the hope that it will be useful, but WITHOUT ANY
WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
PARTICULAR PURPOSE. See the GNU Affero General Public License for more
details.
You should have received a copy of the GNU Affero General Public License along
with this program. If not, see <http://www.gnu.org/licenses/>.
]]
local common = require("base.common")
-- IMPORTANT: Add new books to the END of the list. The list must not contain more than 30 elements.
local magicBooks = {337, 351, 379, 382, 398, 401, 404, 411, 402, 413}
local amountNeeded = 3
local M = {}
function M.readMagicBooks(user, bookId)
-- Alchemists cannot become mages.
if user:getMagicType() == 3 then
return
end
-- Attribute requirements
if user:increaseAttrib("willpower", 0) + user:increaseAttrib("essence", 0) + user:increaseAttrib("intelligence", 0) < 30 then
return
end
-- Already is a mage
if user:getMagicType() == 0 and (user:getQuestProgress(37) ~= 0 or user:getMagicFlags(0) > 0) then
return
end
local questProgress = user:getQuestProgress(38)
-- Already did all the reading
if bit32.extract(questProgress, 30) == 1 then
return
end
-- Register new book if it is a magical one and hasn't been read before
local foundNewBook = false
for i = 1, #magicBooks do
if magicBooks[i] == bookId then
local bitToChange = i - 1
if bit32.extract(questProgress, bitToChange) == 0 then
questProgress = bit32.replace(questProgress, 1, bitToChange)
foundNewBook = true
end
end
end
if foundNewBook then
-- Count how many magic books have been read
local readBooks = 0
for i = 0, #magicBooks-1 do
if bit32.extract(questProgress, i) == 1 then
readBooks = readBooks + 1
end
end
if readBooks < 3 then
user:inform("Das Lesen dieses Buches hat dein Verständnis der Magie vertieft. Wenn du weitere Bücher über Magie findest, kannst du ja vielleicht selbst bald ein Magier werden.", "This book forwards your understanding of magic. If you want more books about magic, you might be able to become a magician yourself as well.", Character.highPriority)
elseif bit32.extract(questProgress, 30) == 0 then
local callback = function(dialog)end;
local dialog
if user:getPlayerLanguage() == Player.german then
dialog = MessageDialog("Magische Lektüre", "Durch das Lesen der verschiedenen Bücher über Magie hast du ein tiefes Verständnis für die arkanen Künste erlangt. Um den Pfad der Magie zu betreten, ergreife einen Zauberstab und konzentriere dich auf deine innere Stärke.", callback)
else
dialog = MessageDialog("Magical reading", "Reading the various books about magic gave you a vast understanding of the arcane arts. To follow the path of magic, you should acquire a magical wand, hold it firmly and concentrate on your inner strength.", callback)
end
user:requestMessageDialog(dialog)
questProgress = bit32.replace(questProgress, 1, 30)
end
end
user:setQuestProgress(38, questProgress)
end
function M.useMagicWand(user, sourceItem)
-- Alchemists cannot become mages.
if user:getMagicType() == 3 then
user:inform("Alchemisten können die Stabmagie nicht erlernen.",
"Alchemist are unable to use wand magic.")
return
end
-- Attribute requirements
if user:increaseAttrib("willpower", 0) + user:increaseAttrib("essence", 0) + user:increaseAttrib("intelligence", 0) < 30 then
user:inform("Um Stabmagie zu benutzen muss die Summe der Attribute Intelligenz, Essenz und Willensstärke 30 ergeben. Attribute können bei den Trainer NPC's geändert werden.",
"To use wand magic, your combined attributes of intelligence, essence, and willpower must total at least 30. Attributes can be changed at the trainer NPC.")
return
end
-- Already is a mage
if user:getMagicType() == 0 and (user:getQuestProgress(37) ~= 0 or user:getMagicFlags(0) > 0) then
return
end
local questProgress = user:getQuestProgress(38)
-- Has not read enough books
if bit32.extract(questProgress, 30) == 0 then
user:inform("Um das Handwerk der Stabmagie zu erlernen, musst du drei Bücher über magische Theorie lesen. Sieh dir die Liste der Bücher in den Bibliotheken der Städte.",
"To learn the craft of wand magic you must read three books of magical theory. Look for the list of books in your town's library.")
return
end
local callback = function(dialog)
local success = dialog:getSuccess()
if success then
if dialog:getSelectedIndex() == 0 then
local messageCallback = function(messageDialog)
user:setMagicType(0)
world:makeSound(13,user.pos)
world:gfx(31,user.pos)
world:gfx(52,user.pos)
world:gfx(31,user.pos)
user:setQuestProgress(37, 1)
end
local messageDialog
if user:getPlayerLanguage() == Player.german then
messageDialog = MessageDialog("Ein neuer Magier", "Du gibst dich der im Stab verborgenen arkanen Kraft hin und lässt sie durch deinen Körper fließen. Ja! Du kannst diese Macht beherrschen. Von nun an bist du in der Lage Magier zu werden. Der Stab wird dir gehorchen.", messageCallback)
else
messageDialog = MessageDialog("A new mage", "You induldge in the hidden arcane powers which you found in the wand. You let it run through your body. Yes! You are now able to control this force. From this day on, you are able to use magic. The wand will obey your commands.", messageCallback)
end
user:requestMessageDialog(messageDialog)
else
user:inform("Du hast dich dagegen entschieden Magier zu werden. Die Möglichkeit bleibt dir aber offen.", "You decided against becoming a mage. The option, however, will remain available to you.", Character.highPriority)
end
else
user:inform("Du hast dich dagegen entschieden Magier zu werden. Die Möglichkeit bleibt dir aber offen.", "You decided against becoming a mage. The option, however, will remain available to you.", Character.highPriority)
end
end
local dialog = SelectionDialog(common.GetNLS(user, "Der Weg der Magie", "The path of magic"), common.GetNLS(user, "Als du den Stab berührst, kannst du seine magische Macht spüren. Dir scheint, dass es dir gelingen könnte, sie dir nutzbar zu machen. Willst du das tun und somit zu einem Magier werden? Bedenke, dass eine weitere hohe Kunst - die Alchemie - dir so dann verschlossen sein wird.", "As you touch the wand, you can feel its magical power. It seems to you that you should be able to use this power. Do you want to do so and, therefore, become a mage? Mind that an other high art - alchemy - will not be accessable for you once you became a mage."), callback)
dialog:addOption(0, common.GetNLS(user, "Werde Magier", "Become a mage"))
dialog:addOption(0, common.GetNLS(user, "Nein. Vielleicht später.", "No. Maybe later."))
user:requestSelectionDialog(dialog)
end
return M | agpl-3.0 |
gajop/Zero-K | units/cormak.lua | 1 | 7129 | unitDef = {
unitname = [[cormak]],
name = [[Outlaw]],
description = [[Riot Bot]],
acceleration = 0.25,
brakeRate = 0.25,
buildCostEnergy = 250,
buildCostMetal = 250,
buildPic = [[cormak.png]],
buildTime = 250,
canAttack = true,
canGuard = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
corpse = [[DEAD]],
customParams = {
description_bp = [[Robô dispersador]],
description_es = [[Robot de alboroto]],
description_fr = [[Robot ?meurier]],
description_it = [[Robot da rissa]],
description_de = [[Riot Roboter]],
description_pl = [[Bot wsparcia]],
helptext = [[The Outlaw emits an electromagnetic disruption pulse in a wide circle around it that damages and slows enemy units. Friendly units are unaffected.]],
helptext_de = [[Der Outlaw stößt einen elektromagnetischen Störungspuls, in einem weiten Kreis um sich herum, aus, welcher feindliche Einheiten schädigt und verlangsamt. Freundliche Einheiten sind davon aber nicht betroffen.]],
helptext_pl = [[Outlaw wyzwala fale, ktore uszkadzaja i spowalniaja wszystkie wrogie jednostki wokol niego, zostawiajac sojusznikow bez szwanku.]],
},
explodeAs = [[BIG_UNITEX]],
footprintX = 2,
footprintZ = 2,
iconType = [[walkerriot]],
idleAutoHeal = 5,
idleTime = 1800,
leaveTracks = true,
maxDamage = 1050,
maxSlope = 36,
maxVelocity = 1.9,
maxWaterDepth = 22,
minCloakDistance = 75,
movementClass = [[KBOT2]],
noChaseCategory = [[TERRAFORM FIXEDWING GUNSHIP SUB]],
objectName = [[behethud.s3o]],
onoffable = true,
seismicSignature = 4,
selfDestructAs = [[BIG_UNITEX]],
script = [[cormak.lua]],
sfxtypes = {
explosiongenerators = {
[[custom:RIOTBALL]],
[[custom:RAIDMUZZLE]],
[[custom:LEVLRMUZZLE]],
[[custom:RIOT_SHELL_L]],
[[custom:BEAMWEAPON_MUZZLE_RED]],
},
},
sightDistance = 347,
trackOffset = 0,
trackStrength = 8,
trackStretch = 1,
trackType = [[ComTrack]],
trackWidth = 22,
turnRate = 2000,
upright = true,
weapons = {
{
def = [[FAKEGUN1]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
{
def = [[BLAST]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
{
def = [[FAKEGUN2]],
badTargetCategory = [[FIXEDWING GUNSHIP]],
onlyTargetCategory = [[LAND SINK TURRET SHIP SWIM FLOAT HOVER GUNSHIP FIXEDWING]],
},
},
weaponDefs = {
BLAST = {
name = [[Disruptor Pulser]],
areaOfEffect = 550,
craterBoost = 0,
craterMult = 0,
customParams = {
light_radius = 0,
},
damage = {
default = 20,
planes = 20,
subs = 0.1,
},
customParams = {
lups_explodespeed = 1,
lups_explodelife = 0.6,
nofriendlyfire = 1,
timeslow_damagefactor = 3.75,
},
edgeeffectiveness = 1,
explosionGenerator = [[custom:NONE]],
explosionSpeed = 11,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
myGravity = 10,
noSelfDamage = true,
range = 300,
reloadtime = 0.95,
soundHitVolume = 1,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 230,
},
FAKEGUN1 = {
name = [[Fake Weapon]],
areaOfEffect = 8,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1E-06,
planes = 1E-06,
subs = 5E-08,
},
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 1,
impactOnly = true,
interceptedByShieldType = 1,
range = 32,
reloadtime = 0.95,
size = 1E-06,
smokeTrail = false,
textures = {
[[null]],
[[null]],
[[null]],
},
turnrate = 10000,
turret = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[StarburstLauncher]],
weaponVelocity = 200,
},
FAKEGUN2 = {
name = [[Fake Weapon]],
areaOfEffect = 8,
avoidFriendly = false,
collideFriendly = false,
craterBoost = 0,
craterMult = 0,
damage = {
default = 1E-06,
planes = 1E-06,
subs = 5E-08,
},
explosionGenerator = [[custom:NONE]],
fireStarter = 0,
flightTime = 1,
impactOnly = true,
interceptedByShieldType = 1,
range = 300,
reloadtime = 0.95,
size = 1E-06,
smokeTrail = false,
textures = {
[[null]],
[[null]],
[[null]],
},
turnrate = 10000,
turret = true,
weaponAcceleration = 200,
weaponTimer = 0.1,
weaponType = [[StarburstLauncher]],
weaponVelocity = 200,
},
},
featureDefs = {
DEAD = {
description = [[Wreckage - Outlaw]],
blocking = true,
damage = 1050,
featureDead = [[HEAP]],
footprintX = 2,
footprintZ = 2,
metal = 100,
object = [[behethud_dead.s3o]],
reclaimable = true,
reclaimTime = 100,
},
HEAP = {
description = [[Debris - Outlaw]],
blocking = false,
damage = 1050,
footprintX = 2,
footprintZ = 2,
metal = 50,
object = [[debris2x2c.s3o]],
reclaimable = true,
reclaimTime = 50,
},
},
}
return lowerkeys({ cormak = unitDef })
| gpl-2.0 |
dhotson/prosody-modules | mod_auth_sql/mod_auth_sql.lua | 32 | 3498 | -- Simple SQL Authentication module for Prosody IM
-- Copyright (C) 2011 Tomasz Sterna <tomek@xiaoka.com>
-- Copyright (C) 2011 Waqas Hussain <waqas20@gmail.com>
--
local log = require "util.logger".init("auth_sql");
local new_sasl = require "util.sasl".new;
local DBI = require "DBI"
local connection;
local params = module:get_option("auth_sql", module:get_option("sql"));
local resolve_relative_path = require "core.configmanager".resolve_relative_path;
local function test_connection()
if not connection then return nil; end
if connection:ping() then
return true;
else
module:log("debug", "Database connection closed");
connection = nil;
end
end
local function connect()
if not test_connection() then
prosody.unlock_globals();
local dbh, err = DBI.Connect(
params.driver, params.database,
params.username, params.password,
params.host, params.port
);
prosody.lock_globals();
if not dbh then
module:log("debug", "Database connection failed: %s", tostring(err));
return nil, err;
end
module:log("debug", "Successfully connected to database");
dbh:autocommit(true); -- don't run in transaction
connection = dbh;
return connection;
end
end
do -- process options to get a db connection
params = params or { driver = "SQLite3" };
if params.driver == "SQLite3" then
params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite");
end
assert(params.driver and params.database, "Both the SQL driver and the database need to be specified");
assert(connect());
end
local function getsql(sql, ...)
if params.driver == "PostgreSQL" then
sql = sql:gsub("`", "\"");
end
if not test_connection() then connect(); end
-- do prepared statement stuff
local stmt, err = connection:prepare(sql);
if not stmt and not test_connection() then error("connection failed"); end
if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end
-- run query
local ok, err = stmt:execute(...);
if not ok and not test_connection() then error("connection failed"); end
if not ok then return nil, err; end
return stmt;
end
local function get_password(username)
local stmt, err = getsql("SELECT `password` FROM `authreg` WHERE `username`=? AND `realm`=?", username, module.host);
if stmt then
for row in stmt:rows(true) do
return row.password;
end
end
end
provider = {};
function provider.test_password(username, password)
return password and get_password(username) == password;
end
function provider.get_password(username)
return get_password(username);
end
function provider.set_password(username, password)
return nil, "Setting password is not supported.";
end
function provider.user_exists(username)
return get_password(username) and true;
end
function provider.create_user(username, password)
return nil, "Account creation/modification not supported.";
end
function provider.get_sasl_handler()
local profile = {
plain = function(sasl, username, realm)
local password = get_password(username);
if not password then return "", nil; end
return password, true;
end
};
return new_sasl(module.host, profile);
end
function provider.users()
local stmt, err = getsql("SELECT `username` FROM `authreg` WHERE `realm`=?", module.host);
if stmt then
local next, state = stmt:rows(true)
return function()
for row in next, state do
return row.username;
end
end
end
return stmt, err;
end
module:provides("auth", provider);
| mit |
padrinoo1/telebak | bot/creed.lua | 1 | 9249 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
VERSION = '1.0'
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
local receiver = get_receiver(msg)
print (receiver)
-- vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
-- mark_read(receiver, ok_cb, false)
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < now then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
local login_group_id = 1
--It will send login codes to this chat
send_large_msg('chat#id'..login_group_id, msg.text)
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Allowed user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"onservice",
"inrealm",
"Moderator_Gp",
"LockTag",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"plugins",
"lock_link",
"all"
},
sudo_users = {156218623},--Sudo users
disabled_channels = {},
realm = {},--Realms Id
moderation = {data = 'data/moderation.json'},
about_text = [[Creed bot 2.0
Hello my Good friends 😀🖐🏻
‼️ this bot is made by : @creed_is_dead
〰〰〰〰〰〰〰〰
🚩 Our admins are :
🔰 @sorblack_creed
🔰 @amircc_creed
🔰 @aria_creed
🔰 @alireza_mah_creed
〰〰〰〰〰〰〰〰
♻️ You can send your Ideas and messages to Us By sending them into bots account by this command :
!feedback (your ideas and messages)
]],
help_text = [[
Creed bots Help for mods : 😈
Plugins : 🔻
1. banhammer ⭕️
Help For Banhammer👇
!Kick @UserName 😜
And You Can do It by Replay 🙈
!Ban @UserName 〽️
You Can Do It By Replay👌
!Unban @UserName
You Can Do it By Replay😱
For Admins : 👇
!banall @UserName or (user_id)😺
you Can do it By Replay 👤
!unbanall 🆔User_Id🆔
〰〰〰〰〰〰〰〰〰〰
2. GroupManager :🔹
!Creategroup "GroupName" 🙈
You Can CreateGroup With this command😱
!setflood😃
Set the group flood control🈹
!settings ❌
Watch group settings
!owner🚫
watch group owner
!setowner user_id❗️
You can set someone to the group owner‼️
!modlist💯
watch Group mods🔆
!lock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅
lock Something🚼
!unlock (bots-member-flood-photo-name-Arabic-english-tag-join-link)✅
Unlock Something🚼
!rules 🆙 or !set rules🆗
watch group rules or set
!about or !set about 🔴
!res @username🔘
See UserInfo©
!who♦️
Get Ids Chat🔺
!log 🎴
get members id ♠️
!all🔴
this is like stats in a file🔸
added !clink *
and !glink :)
〰〰〰〰〰〰〰〰
Admins :®
!add 😎
You Can add the group to moderation.json😱
!rem😏
You Can Remove the group from mod.json⭕️
!setgpowner (Gpid) user_id ⚫️
from realm®®
!addadmin 🔶
set some one to global admin🔸
!removeadmin🔘
remove somone from global admin🔹
〰〰〰〰〰〰〰〰〰〰〰
3. Stats :©
!stats creedbot (sudoers)✔️
shows bt stats🔚
!stats🔘
shows group stats💲
〰〰〰〰〰〰〰〰
4. Feedback⚫️
!feedback txt🔻◼️
send maseage to admins via bot🔈
〰〰〰〰〰〰〰〰〰〰〰
5. Tagall◻️
!tagall txt🔸
will tag users©
〰〰〰〰〰〰〰〰〰
🔜 more plugins
⚠️ We are Creeds ... ⚠️
our channel : @creedantispam_channel🔋
You Can user both "!" & "/" for them🎧
]]
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
casseveritt/premake | src/actions/example/example_project.lua | 71 | 2633 | -- An example project generator; see _example.lua for action description
--
-- The project generation function, attached to the action in _example.lua.
-- By now, premake.generate() has created the project file using the name
-- provided in _example.lua, and redirected input to this new file.
--
function premake.example.project(prj)
-- If necessary, set an explicit line ending sequence
-- io.eol = '\r\n'
-- Let's start with a header
_p('-- Example project file version 1.0')
_p('Name: %s', prj.name)
_p('Kind: %s', prj.kind)
_p('Language: %s', prj.language)
_p('ID: {%s}', prj.uuid)
_p('')
-- List the build configurations, and the settings for each
for cfg in premake.eachconfig(prj) do
_p('Configuration %s:', cfg.name)
_p(1, 'Objects directory: %s', cfg.objectsdir)
_p(1, 'Build target:')
_p(2, 'Full path: %s', cfg.buildtarget.fullpath)
_p(2, 'Directory: %s', cfg.buildtarget.directory)
_p(2, 'Name: %s', cfg.buildtarget.name)
_p(2, 'Base name: %s', cfg.buildtarget.basename)
_p(2, 'Prefix: %s', cfg.buildtarget.prefix)
_p(2, 'Suffix: %s', cfg.buildtarget.suffix)
_p('')
_p(1, 'Compiling:')
_p(2, 'Defines: %s', table.concat(cfg.defines, ";"))
_p(2, 'Include paths: %s', table.concat(cfg.includedirs, ";"))
_p(2, 'Flags: %s', table.concat(cfg.flags, ", "))
if not cfg.flags.NoPCH and cfg.pchheader then
_p(2, 'Precompiled header: %s (%s)', cfg.pchheader, cfg.pchsource)
end
_p(2, 'Options: %s', table.concat(cfg.buildoptions, " "))
_p('')
_p(1, 'Linking:')
_p(2, 'Library paths: %s', table.concat(cfg.libdirs, ";"))
_p(2, 'Options: %s', table.concat(cfg.linkoptions, " "))
_p(2, 'Libraries: %s', table.concat(premake.getlinks(cfg, "all", "fullpath")))
_p('')
if #cfg.prebuildcommands > 0 then
_p(1, 'Prebuild commands:')
for _, cmd in ipairs(cfg.prebuildcommands) do
_p(2, cmd)
end
_p('')
end
if #cfg.prelinkcommands > 0 then
_p(1, 'Prelink commands:')
for _, cmd in ipairs(cfg.prelinkcommands) do
_p(2, cmd)
end
_p('')
end
if #cfg.postbuildcommands > 0 then
_p(1, 'Postbuild commands:')
for _, cmd in ipairs(cfg.postbuildcommands) do
_p(2, cmd)
end
_p('')
end
end
-- List out the folders and files that make up the build
local tr = premake.project.buildsourcetree(prj)
premake.tree.sort(tr)
premake.tree.traverse(tr, {
onbranch = function(node, depth)
_p(depth, path.getname(node.name) .. "/")
end,
onleaf = function(node, depth)
_p(depth, path.getname(node.name))
end
})
end
| bsd-3-clause |
gajop/Zero-K | LuaUI/Widgets/chili/Controls/colorbars.lua | 25 | 2469 | --//=============================================================================
Colorbars = Control:Inherit{
classname = "colorbars",
color = {1,1,1,1},
defaultWidth = 100,
defaultHeight = 20,
OnChange = {},
}
local this = Colorbars
local inherited = this.inherited
--//=============================================================================
function Colorbars:SetColor(c)
self:CallListeners(self.OnChange,c)
self.value = c
self:Invalidate()
end
--//=============================================================================
local GL_LINE_LOOP = GL.LINE_LOOP
local GL_LINES = GL.LINES
local glPushMatrix = gl.PushMatrix
local glPopMatrix = gl.PopMatrix
local glTranslate = gl.Translate
local glVertex = gl.Vertex
local glRect = gl.Rect
local glColor = gl.Color
local glBeginEnd = gl.BeginEnd
function Colorbars:DrawControl()
glPushMatrix()
glTranslate(self.x,self.y,0)
local barswidth = self.width - (self.height + 4)
local color = self.color
local step = self.height/7
--bars
local rX1,rY1,rX2,rY2 = 0,0*step,color[1]*barswidth,1*step
local gX1,gY1,gX2,gY2 = 0,2*step,color[2]*barswidth,3*step
local bX1,bY1,bX2,bY2 = 0,4*step,color[3]*barswidth,5*step
local aX1,aY1,aX2,aY2 = 0,6*step,(color[4] or 1)*barswidth,7*step
glColor(1,0,0,1)
glRect(rX1,rY1,rX2,rY2)
glColor(0,1,0,1)
glRect(gX1,gY1,gX2,gY2)
glColor(0,0,1,1)
glRect(bX1,bY1,bX2,bY2)
glColor(1,1,1,1)
glRect(aX1,aY1,aX2,aY2)
glColor(self.color)
glRect(barswidth + 2,self.height,self.width - 2,0)
gl.BeginEnd(GL.TRIANGLE_STRIP, theme.DrawBorder_, barswidth + 2,0,self.width - barswidth - 4,self.height, 1, self.borderColor, self.borderColor2)
glPopMatrix()
end
--//=============================================================================
function Colorbars:HitTest()
return self
end
function Colorbars:MouseDown(x,y)
local step = self.height/7
local yp = y/step
local r = yp%2
local barswidth = self.width - (self.height + 4)
if (x<=barswidth)and(r<=1) then
local barIdx = (yp-r)/2 + 1
local newvalue = x/barswidth
if (newvalue>1) then newvalue=1 elseif (newvalue<0) then newvalue=0 end
self.color[barIdx] = newvalue
self:SetColor(self.color)
return self
end
end
function Colorbars:MouseMove(x,y,dx,dy,button)
if (button==1) then
return self:MouseDown(x,y)
end
end
--//=============================================================================
| gpl-2.0 |
nobie/sesame_fw | feeds/luci/modules/rpc/dist/usr/lib/lua/luci/jsonrpcbind/uci.lua | 81 | 1914 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local uci = require "luci.model.uci".cursor()
local ucis = require "luci.model.uci".cursor_state()
local table = require "table"
module "luci.jsonrpcbind.uci"
_M, _PACKAGE, _NAME = nil, nil, nil
function add(config, ...)
uci:load(config)
local stat = uci:add(config, ...)
return uci:save(config) and stat
end
function apply(config)
return uci:apply(config)
end
function changes(...)
return uci:changes(...)
end
function commit(config)
return uci:load(config) and uci:commit(config)
end
function delete(config, ...)
uci:load(config)
return uci:delete(config, ...) and uci:save(config)
end
function delete_all(config, ...)
uci:load(config)
return uci:delete_all(config, ...) and uci:save(config)
end
function foreach(config, stype)
uci:load(config)
local sections = {}
return uci:foreach(config, stype, function(section)
table.insert(sections, section)
end) and sections
end
function get(config, ...)
uci:load(config)
return uci:get(config, ...)
end
function get_all(config, ...)
uci:load(config)
return uci:get_all(config, ...)
end
function get_state(config, ...)
ucis:load(config)
return ucis:get(config, ...)
end
function revert(config)
return uci:load(config) and uci:revert(config)
end
function section(config, ...)
uci:load(config)
return uci:section(config, ...) and uci:save(config)
end
function set(config, ...)
uci:load(config)
return uci:set(config, ...) and uci:save(config)
end
function tset(config, ...)
uci:load(config)
return uci:tset(config, ...) and uci:save(config)
end
| gpl-2.0 |
reloadlife/sprcpubot | Plugins/buyspr.lua | 1 | 9207 |
http = require "socket.http"
http = require "socket.http"
ltn12 = require 'ltn12'
multipart = require 'multipart-post'
local function makeRequest(uRL, request_body)
local response = {}
local body, boundary = multipart.encode(request_body)
local success, code, headers, status = https.request{
url = uRL,
method = 'POST',
headers = {
['Content-Type'] = 'multipart/form-data; boundary=' .. boundary,
['Content-Length'] = string.len(body),
},
source = ltn12.source.string(body),
sink = ltn12.sink.table(response),
}
local respbody = table.concat(response or {"no response"})
local jbody = json.decode(respbody)
return jbody
end
function ApiRun(msg, matches)
AP_KEY = _Config.PayIRKey
if matches[2] == 'SPR' then
if matches[1] == '100' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '1000' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '200' then
Coust = tonumber(matches[1]) * 1000
SPRC = tonumber(matches[1])
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '2000' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '300' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '3000' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '400' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '4000' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '500' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
elseif matches[1] == '5000' then
SPRC = tonumber(matches[1])
Coust = tonumber(matches[1]) * 1000
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = "شما در حال خرید "..SPRC.." تغداد SPR به قیمت "..Coust.."ریال هستید\nبرای ادامه دادن خرید روی دکمه کلیک کنید !"
else
TEXT = 'Your Going to buy '..SPRC..', Coust : '.. Coust..' Rials\n Tap to next !'
end
else
TEXT = ':|'
end
redis:set('Count:'..msg.from.id, SPRC)
url = 'https://pay.ir/payment/send'
JDT = makeRequest(url, {
amount = tostring(Coust),
api = AP_KEY,
redirect = 'http://pay.Tele-fake.ir',
})
keyboard = {
inline_keyboard = {
{ { text = 'بله ادامه', callback_data = 'PayMent '..JDT.transId } },
{ { text = 'Back|بازگشت', callback_data = 'buy spr' } }
}
}
api.editMessageText(_Config.TOKEN, msg.message.chat.id, msg.message.message_id, TEXT, 'md', keyboard)
end
if matches[1] == 'PayMent' then
URLTOPAY = 'https://pay.ir/payment/gateway/'.. matches[2]
if (redis:get(msg.message.chat.id..'Lang') or 'fa') == 'fa' then
TEXT = 'لینک پرداخت شما : [برای پرداخت کلیک کنید !]('..URLTOPAY .. ')\n'
..'بعد از پرداخت بر روی دکمه ✅ کلیک کنید در غیر این صورت لغو را برنید !'
else
TEXT = 'Your Payment link : [Click To Pay]('.. URLTOPAY ..')'
..'\nAfter pay use Buttens !'
end
keyboard = {
inline_keyboard = {
{ { text = '✅', callback_data = 'CheckPay '..matches[2] } },
{ { text = 'Back|بازگشت', callback_data = 'buy spr' } }
}
}
api.editMessageText(_Config.TOKEN, msg.message.chat.id, msg.message.message_id, TEXT, 'md', keyboard)
end
if matches[1] == 'CheckPay' then
JDT = makeRequest('https://pay.ir/payment/verify', {
transId = matches[2],
api = AP_KEY,
})
if tostring(JDT.status) == tostring('1') then
redis:set(msg.from.id..'GettingsGroup!', 'vip')
redis:set(msg.from.id..'GettingsGroup!!', redis:get('Count:'..msg.from.id))
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = 'لینک خود را ارسال کنید!'
else
TEXT = 'Send Your link!'
end
else
VarDump(JDT)
if (redis:get(msg.from.id..'Lang') or 'fa') == 'fa' then
TEXT = 'پرداخت تایید نشد !'
else
TEXT = 'unSuccess Payment !'
end
end
keyboard = {
inline_keyboard = {
{ { text = 'Back|بازگشت', callback_data = 'buy spr' } }
}
}
api.editMessageText(_Config.TOKEN, msg.from.id, msg.message.message_id, TEXT, 'md', keyboard)
end
end
return {
HELP = {
NAME = {
fa = 'خرید موجودی !',
en = 'Buy SPR !',
call = 'buyspr',
},
Dec = {
fa = 'پلاکینی برای خرید SPR',
en = 'A plugin for buy SPR!',
},
Usage = {
fa = '*برای خرید SRP ابتدا به* @SPRCPU\\_BOT *مراجعه کرده و سپس به قشمت خرید SPR رفته و تعداد مورد نظر را انتخاب کنید\nسپس به قمت پرداخت رفته و بعد از پرداخت مبلغ مورد نظر پرداهت را تایید کنید !*',
en = '*fist start* @SPRCPU\\_BOT *and then use Butten "Buy SPR" and then select the amount of SPRs you need and Pay it\n after that Verify it :-)*',
},
rank = 'NIL',
},
cli = {
_MSG = {
},
-- Pre = Pre,
-- run = Run
},
api = {
_MSG = {
'^!#MessageCall (PayMent) (.*)$',
'^!#MessageCall (CheckPay) (.*)$',
'^!#MessageCall (100) (SPR)$',
'^!#MessageCall (1000) (SPR)$',
'^!#MessageCall (200) (SPR)$',
'^!#MessageCall (2000) (SPR)$',
'^!#MessageCall (300) (SPR)$',
'^!#MessageCall (3000) (SPR)$',
'^!#MessageCall (400) (SPR)$',
'^!#MessageCall (4000) (SPR)$',
'^!#MessageCall (500) (SPR)$',
'^!#MessageCall (5000) (SPR)$',
},
-- Pre = ApiPre,
run = ApiRun
},
CheckMethod = 'f80', -- Also Can use as 'TeleSeed' ! # If use TeleSeed Input Will be msg = { to = {}, from = {}} :))
-- Cron = Cron
} | gpl-3.0 |
aadddjj/testbotantispam | plugins/get.lua | 613 | 1067 | local function get_variables_hash(msg)
if msg.to.type == 'chat' then
return 'chat:'..msg.to.id..':variables'
end
if msg.to.type == 'user' then
return 'user:'..msg.from.id..':variables'
end
end
local function list_variables(msg)
local hash = get_variables_hash(msg)
if hash then
local names = redis:hkeys(hash)
local text = ''
for i=1, #names do
text = text..names[i]..'\n'
end
return text
end
end
local function get_value(msg, var_name)
local hash = get_variables_hash(msg)
if hash then
local value = redis:hget(hash, var_name)
if not value then
return'Not found, use "!get" to list variables'
else
return var_name..' => '..value
end
end
end
local function run(msg, matches)
if matches[2] then
return get_value(msg, matches[2])
else
return list_variables(msg)
end
end
return {
description = "Retrieves variables saved with !set",
usage = "!get (value_name): Returns the value_name value.",
patterns = {
"^(!get) (.+)$",
"^!get$"
},
run = run
}
| gpl-2.0 |
Flourish-Team/Flourish | Premake/source/src/base/tools.lua | 14 | 1780 | ---
-- tools.lua
-- Work with Premake's collection of tool adapters.
-- Author Jason Perkins
-- Copyright (c) 2015 Jason Perkins and the Premake project
---
local p = premake
p.tools = {}
---
-- Given a toolset identifier (e.g. "gcc" or "gcc-4.8") returns the
-- corresponding tool adapter and the version, if one was provided.
--
-- @param identifier
-- A toolset identifier composed of two parts: the toolset name,
-- which should match of the name of the adapter object ("gcc",
-- "clang", etc.) in the p.tools namespace, and and optional
-- version number, separated by a dash.
--
-- To make things more intuitive for Visual Studio users, supports
-- identifiers like "v100" to represent the v100 Microsoft platform
-- toolset.
-- @return
-- If successful, returns the toolset adapter object. If a version
-- was specified as part of the identifier, that is returned as a
-- second return value. If no corresponding tool adapter exists,
-- returns nil.
---
function p.tools.normalize(identifier)
if identifier:startswith("v") then -- TODO: this should be deprecated?
identifier = 'msc-' .. identifier
end
local parts = identifier:explode("-", true, 1)
if parts[2] == nil then
return parts[1]
end
-- 'msc-100' is accepted, but the code expects 'v100'
if parts[1] == "msc" and tonumber(parts[2]:sub(1,3)) ~= nil then
parts[2] = "v" .. parts[2]
end
-- perform case-correction of the LLVM toolset
if parts[2]:startswith("llvm-vs") then
parts[2] = "LLVM-" .. parts[2]:sub(6)
end
return parts[1] .. '-' .. parts[2]
end
function p.tools.canonical(identifier)
identifier = p.tools.normalize(identifier)
local parts = identifier:explode("-", true, 1)
return p.tools[parts[1]], parts[2]
end
| mit |
nobie/sesame_fw | feeds/luci/applications/luci-asterisk/dist/usr/lib/lua/luci/asterisk/cc_idd.lua | 92 | 7735 | --[[
LuCI - Asterisk - International Direct Dialing Prefixes and Country Codes
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
module "luci.asterisk.cc_idd"
CC_IDD = {
-- Country, CC, IDD
{ "Afghanistan", "93", "00" },
{ "Albania", "355", "00" },
{ "Algeria", "213", "00" },
{ "American Samoa", "684", "00" },
{ "Andorra", "376", "00" },
{ "Angola", "244", "00" },
{ "Anguilla", "264", "011" },
{ "Antarctica", "672", "" },
{ "Antigua", "268", "011" },
{ "Argentina", "54", "00" },
{ "Armenia", "374", "00" },
{ "Aruba", "297", "00" },
{ "Ascension Island", "247", "00" },
{ "Australia", "61", "0011" },
{ "Austria", "43", "00" },
{ "Azberbaijan", "994", "00" },
{ "Bahamas", "242", "011" },
{ "Bahrain", "973", "00" },
{ "Bangladesh", "880", "00" },
{ "Barbados", "246", "011" },
{ "Barbuda", "268", "011" },
{ "Belarus", "375", "810" },
{ "Belgium", "32", "00" },
{ "Belize", "501", "00" },
{ "Benin", "229", "00" },
{ "Bermuda", "441", "011" },
{ "Bhutan", "975", "00" },
{ "Bolivia", "591", "00" },
{ "Bosnia", "387", "00" },
{ "Botswana", "267", "00" },
{ "Brazil", "55", "00" },
{ "British Virgin Islands", "284", "011" },
{ "Brunei", "673", "00" },
{ "Bulgaria", "359", "00" },
{ "Burkina Faso", "226", "00" },
{ "Burma (Myanmar)", "95", "00" },
{ "Burundi", "257", "00" },
{ "Cambodia", "855", "001" },
{ "Cameroon", "237", "00" },
{ "Canada", "1", "011" },
{ "Cape Verde Islands", "238", "0" },
{ "Cayman Islands", "345", "011" },
{ "Central African Rep.", "236", "00" },
{ "Chad", "235", "15" },
{ "Chile", "56", "00" },
{ "China", "86", "00" },
{ "Christmas Island", "61", "0011" },
{ "Cocos Islands", "61", "0011" },
{ "Colombia", "57", "00" },
{ "Comoros", "269", "00" },
{ "Congo", "242", "00" },
{ "Congo, Dem. Rep. of", "243", "00" },
{ "Cook Islands", "682", "00" },
{ "Costa Rica", "506", "00" },
{ "Croatia", "385", "00" },
{ "Cuba", "53", "119" },
{ "Cyprus", "357", "00" },
{ "Czech Republic", "420", "00" },
{ "Denmark", "45", "00" },
{ "Diego Garcia", "246", "00" },
{ "Djibouti", "253", "00" },
{ "Dominica", "767", "011" },
{ "Dominican Rep.", "809", "011" },
{ "Ecuador", "593", "00" },
{ "Egypt", "20", "00" },
{ "El Salvador", "503", "00" },
{ "Equatorial Guinea", "240", "00" },
{ "Eritrea", "291", "00" },
{ "Estonia", "372", "00" },
{ "Ethiopia", "251", "00" },
{ "Faeroe Islands", "298", "00" },
{ "Falkland Islands", "500", "00" },
{ "Fiji Islands", "679", "00" },
{ "Finland", "358", "00" },
{ "France", "33", "00" },
{ "French Antilles", "596", "00" },
{ "French Guiana", "594", "00" },
{ "French Polynesia", "689", "00" },
{ "Gabon", "241", "00" },
{ "Gambia", "220", "00" },
{ "Georgia", "995", "810" },
{ "Germany", "49", "00" },
{ "Ghana", "233", "00" },
{ "Gibraltar", "350", "00" },
{ "Greece", "30", "00" },
{ "Greenland", "299", "00" },
{ "Grenada", "473", "011" },
{ "Guadeloupe", "590", "00" },
{ "Guam", "671", "011" },
{ "Guantanamo Bay", "5399", "00" },
{ "Guatemala", "502", "00" },
{ "Guinea", "224", "00" },
{ "Guinea Bissau", "245", "00" },
{ "Guyana", "592", "001" },
{ "Haiti", "509", "00" },
{ "Honduras", "504", "00" },
{ "Hong Kong", "852", "001" },
{ "Hungary", "36", "00" },
{ "Iceland", "354", "00" },
{ "India", "91", "00" },
{ "Indonesia", "62", { "001", "008" } },
{ "Iran", "98", "00" },
{ "Iraq", "964", "00" },
{ "Ireland", "353", "00" },
{ "Israel", "972", "00" },
{ "Italy", "39", "00" },
{ "Ivory Coast", "225", "00" },
{ "Jamaica", "876", "011" },
{ "Japan", "81", "001" },
{ "Jordan", "962", "00" },
{ "Kazakhstan", "7", "810" },
{ "Kenya", "254", "000" },
{ "Kiribati", "686", "00" },
{ "Korea, North", "850", "00" },
{ "Korea, South", "82", "001" },
{ "Kuwait", "965", "00" },
{ "Kyrgyzstan", "996", "00" },
{ "Laos", "856", "00" },
{ "Latvia", "371", "00" },
{ "Lebanon", "961", "00" },
{ "Lesotho", "266", "00" },
{ "Liberia", "231", "00" },
{ "Libya", "218", "00" },
{ "Liechtenstein", "423", "00" },
{ "Lithuania", "370", "00" },
{ "Luxembourg", "352", "00" },
{ "Macau", "853", "00" },
{ "Macedonia", "389", "00" },
{ "Madagascar", "261", "00" },
{ "Malawi", "265", "00" },
{ "Malaysia", "60", "00" },
{ "Maldives", "960", "00" },
{ "Mali", "223", "00" },
{ "Malta", "356", "00" },
{ "Mariana Islands", "670", "011" },
{ "Marshall Islands", "692", "011" },
{ "Martinique", "596", "00" },
{ "Mauritania", "222", "00" },
{ "Mauritius", "230", "00" },
{ "Mayotte Islands", "269", "00" },
{ "Mexico", "52", "00" },
{ "Micronesia", "691", "011" },
{ "Midway Island", "808", "011" },
{ "Moldova", "373", "00" },
{ "Monaco", "377", "00" },
{ "Mongolia", "976", "001" },
{ "Montserrat", "664", "011" },
{ "Morocco", "212", "00" },
{ "Mozambique", "258", "00" },
{ "Myanmar (Burma)", "95", "00" },
{ "Namibia", "264", "00" },
{ "Nauru", "674", "00" },
{ "Nepal", "977", "00" },
{ "Netherlands", "31", "00" },
{ "Netherlands Antilles", "599", "00" },
{ "Nevis", "869", "011" },
{ "New Caledonia", "687", "00" },
{ "New Zealand", "64", "00" },
{ "Nicaragua", "505", "00" },
{ "Niger", "227", "00" },
{ "Nigeria", "234", "009" },
{ "Niue", "683", "00" },
{ "Norfolk Island", "672", "00" },
{ "Norway", "47", "00" },
{ "Oman", "968", "00" },
{ "Pakistan", "92", "00" },
{ "Palau", "680", "011" },
{ "Palestine", "970", "00" },
{ "Panama", "507", "00" },
{ "Papua New Guinea", "675", "05" },
{ "Paraguay", "595", "002" },
{ "Peru", "51", "00" },
{ "Philippines", "63", "00" },
{ "Poland", "48", "00" },
{ "Portugal", "351", "00" },
{ "Puerto Rico", { "787", "939" }, "011" },
{ "Qatar", "974", "00" },
{ "Reunion Island", "262", "00" },
{ "Romania", "40", "00" },
{ "Russia", "7", "810" },
{ "Rwanda", "250", "00" },
{ "St. Helena", "290", "00" },
{ "St. Kitts", "869", "011" },
{ "St. Lucia", "758", "011" },
{ "St. Perre & Miquelon", "508", "00" },
{ "St. Vincent", "784", "011" },
{ "San Marino", "378", "00" },
{ "Sao Tome & Principe", "239", "00" },
{ "Saudi Arabia", "966", "00" },
{ "Senegal", "221", "00" },
{ "Serbia", "381", "99" },
{ "Seychelles", "248", "00" },
{ "Sierra Leone", "232", "00" },
{ "Singapore", "65", "001" },
{ "Slovakia", "421", "00" },
{ "Slovenia", "386", "00" },
{ "Solomon Islands", "677", "00" },
{ "Somalia", "252", "00" },
{ "South Africa", "27", "09" },
{ "Spain", "34", "00" },
{ "Sri Lanka", "94", "00" },
{ "Sudan", "249", "00" },
{ "Suriname", "597", "00" },
{ "Swaziland", "268", "00" },
{ "Sweden", "46", "00" },
{ "Switzerland", "41", "00" },
{ "Syria", "963", "00" },
{ "Taiwan", "886", "002" },
{ "Tajikistan", "992", "810" },
{ "Tanzania", "255", "00" },
{ "Thailand", "66", "001" },
{ "Togo", "228", "00" },
{ "Tonga", "676", "00" },
{ "Trinidad & Tobago", "868", "011" },
{ "Tunisia", "216", "00" },
{ "Turkey", "90", "00" },
{ "Turkmenistan", "993", "810" },
{ "Turks & Caicos", "649", "011" },
{ "Tuvalu", "688", "00" },
{ "Uganda", "256", "000" },
{ "Ukraine", "380", "810" },
{ "United Arab Emirates", "971", "00" },
{ "United Kingdom", "44", "00" },
{ "Uruguay", "598", "00" },
{ "USA", "1", "011" },
{ "US Virgin Islands", "340", "011" },
{ "Uzbekistan", "998", "810" },
{ "Vanuatu", "678", "00" },
{ "Vatican City", "39", "00" },
{ "Venezuela", "58", "00" },
{ "Vietnam", "84", "00" },
{ "Wake Island", "808", "00" },
{ "Wallis & Futuna", "681", "19" },
{ "Western Samoa", "685", "00" },
{ "Yemen", "967", "00" },
{ "Yugoslavia", "381", "99" },
{ "Zambia", "260", "00" },
{ "Zimbabwe", "263", "00" }
}
| gpl-2.0 |
DeterGent-Legion/MeGa_SaTaN | plugins/admin.lua | 60 | 6680 | local function set_bot_photo(msg, success, result)
local receiver = get_receiver(msg)
if success then
local file = 'data/photos/bot.jpg'
print('File downloaded to:', result)
os.rename(result, file)
print('File moved to:', file)
set_profile_photo(file, ok_cb, false)
send_large_msg(receiver, 'Photo changed!', ok_cb, false)
redis:del("bot:photo")
else
print('Error downloading: '..msg.id)
send_large_msg(receiver, 'Failed, please try again!', ok_cb, false)
end
end
local function parsed_url(link)
local parsed_link = URL.parse(link)
local parsed_path = URL.parse_path(parsed_link.path)
return parsed_path[2]
end
local function get_contact_list_callback (cb_extra, success, result)
local text = " "
for k,v in pairs(result) do
if v.print_name and v.id and v.phone then
text = text..string.gsub(v.print_name , "_" , " ").." ["..v.id.."] = "..v.phone.."\n"
end
end
local file = io.open("contact_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.txt", ok_cb, false)--.txt format
local file = io.open("contact_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"contact_list.json", ok_cb, false)--json format
end
local function user_info_callback(cb_extra, success, result)
result.access_hash = nil
result.flags = nil
result.phone = nil
if result.username then
result.username = '@'..result.username
end
result.print_name = result.print_name:gsub("_","")
local text = serpent.block(result, {comment=false})
text = text:gsub("[{}]", "")
text = text:gsub('"', "")
text = text:gsub(",","")
if cb_extra.msg.to.type == "chat" then
send_large_msg("chat#id"..cb_extra.msg.to.id, text)
else
send_large_msg("user#id"..cb_extra.msg.to.id, text)
end
end
local function get_dialog_list_callback(cb_extra, success, result)
local text = ""
for k,v in pairs(result) do
if v.peer then
if v.peer.type == "chat" then
text = text.."group{"..v.peer.title.."}["..v.peer.id.."]("..v.peer.members_num..")"
else
if v.peer.print_name and v.peer.id then
text = text.."user{"..v.peer.print_name.."}["..v.peer.id.."]"
end
if v.peer.username then
text = text.."("..v.peer.username..")"
end
if v.peer.phone then
text = text.."'"..v.peer.phone.."'"
end
end
end
if v.message then
text = text..'\nlast msg >\nmsg id = '..v.message.id
if v.message.text then
text = text .. "\n text = "..v.message.text
end
if v.message.action then
text = text.."\n"..serpent.block(v.message.action, {comment=false})
end
if v.message.from then
if v.message.from.print_name then
text = text.."\n From > \n"..string.gsub(v.message.from.print_name, "_"," ").."["..v.message.from.id.."]"
end
if v.message.from.username then
text = text.."( "..v.message.from.username.." )"
end
if v.message.from.phone then
text = text.."' "..v.message.from.phone.." '"
end
end
end
text = text.."\n\n"
end
local file = io.open("dialog_list.txt", "w")
file:write(text)
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.txt", ok_cb, false)--.txt format
local file = io.open("dialog_list.json", "w")
file:write(json:encode_pretty(result))
file:flush()
file:close()
send_document("user#id"..cb_extra.target,"dialog_list.json", ok_cb, false)--json format
end
local function run(msg,matches)
local data = load_data(_config.moderation.data)
local receiver = get_receiver(msg)
local group = msg.to.id
if not is_admin(msg) then
return
end
if msg.media then
if msg.media.type == 'photo' and redis:get("bot:photo") then
if redis:get("bot:photo") == 'waiting' then
load_photo(msg.id, set_bot_photo, msg)
end
end
end
if matches[1] == "setbotphoto" then
redis:set("bot:photo", "waiting")
return 'Please send me bot photo now'
end
if matches[1] == "markread" then
if matches[2] == "on" then
redis:set("bot:markread", "on")
return "Mark read > on"
end
if matches[2] == "off" then
redis:del("bot:markread")
return "Mark read > off"
end
return
end
if matches[1] == "pm" then
send_large_msg("user#id"..matches[2],matches[3])
return "Msg sent"
end
if matches[1] == "block" then
if is_admin2(matches[2]) then
return "You can't block admins"
end
block_user("user#id"..matches[2],ok_cb,false)
return "User blocked"
end
if matches[1] == "unblock" then
unblock_user("user#id"..matches[2],ok_cb,false)
return "User unblocked"
end
if matches[1] == "import" then--join by group link
local hash = parsed_url(matches[2])
import_chat_link(hash,ok_cb,false)
end
if matches[1] == "contactlist" then
get_contact_list(get_contact_list_callback, {target = msg.from.id})
return "I've sent contact list with both json and text format to your private"
end
if matches[1] == "delcontact" then
del_contact("user#id"..matches[2],ok_cb,false)
return "User "..matches[2].." removed from contact list"
end
if matches[1] == "dialoglist" then
get_dialog_list(get_dialog_list_callback, {target = msg.from.id})
return "I've sent dialog list with both json and text format to your private"
end
if matches[1] == "whois" then
user_info("user#id"..matches[2],user_info_callback,{msg=msg})
end
return
end
return {
usage = {
"pm: Send Pm To Priavate Chat.",
"block: Block User [id].",
"unblock: Unblock User [id].",
"markread on: Reads Messages agancy Bot.",
"markread off: Don't Reads Messages agancy Bot.",
"setbotphoto: Set New Photo For Bot Account.",
"contactlist: Send A List Of Bot Contacts.",
"dialoglist: Send A Dialog Of Chat.",
"delcontact: Delete Contact.",
"import: Added Bot In Group With Link.",
},
patterns = {
"^(pm) (%d+) (.*)$",
"^(import) (.*)$",
"^(unblock) (%d+)$",
"^(block) (%d+)$",
"^(markread) (on)$",
"^(markread) (off)$",
"^(setbotphoto)$",
"%[(photo)%]",
"^(contactlist)$",
"^(dialoglist)$",
"^(delcontact) (%d+)$",
"^(whois) (%d+)$"
},
run = run,
}
| gpl-2.0 |
nobie/sesame_fw | feeds/luci/applications/luci-radvd/dist/usr/lib/lua/luci/model/cbi/radvd/prefix.lua | 74 | 3766 | --[[
LuCI - Lua Configuration Interface
Copyright 2010 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local sid = arg[1]
local utl = require "luci.util"
m = Map("radvd", translatef("Radvd - Prefix"),
translate("Radvd is a router advertisement daemon for IPv6. " ..
"It listens to router solicitations and sends router advertisements " ..
"as described in RFC 4861."))
m.redirect = luci.dispatcher.build_url("admin/network/radvd")
if m.uci:get("radvd", sid) ~= "prefix" then
luci.http.redirect(m.redirect)
return
end
s = m:section(NamedSection, sid, "interface", translate("Prefix Configuration"))
s.addremove = false
s:tab("general", translate("General"))
s:tab("advanced", translate("Advanced"))
--
-- General
--
o = s:taboption("general", Flag, "ignore", translate("Enable"))
o.rmempty = false
function o.cfgvalue(...)
local v = Flag.cfgvalue(...)
return v == "1" and "0" or "1"
end
function o.write(self, section, value)
Flag.write(self, section, value == "1" and "0" or "1")
end
o = s:taboption("general", Value, "interface", translate("Interface"),
translate("Specifies the logical interface name this section belongs to"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.optional = false
function o.formvalue(...)
return Value.formvalue(...) or "-"
end
function o.validate(self, value)
if value == "-" then
return nil, translate("Interface required")
end
return value
end
function o.write(self, section, value)
m.uci:set("radvd", section, "ignore", 0)
m.uci:set("radvd", section, "interface", value)
end
o = s:taboption("general", DynamicList, "prefix", translate("Prefixes"),
translate("Advertised IPv6 prefixes. If empty, the current interface prefix is used"))
o.optional = true
o.datatype = "ip6addr"
o.placeholder = translate("default")
function o.cfgvalue(self, section)
local l = { }
local v = m.uci:get_list("radvd", section, "prefix")
for v in utl.imatch(v) do
l[#l+1] = v
end
return l
end
o = s:taboption("general", Flag, "AdvOnLink", translate("On-link determination"),
translate("Indicates that this prefix can be used for on-link determination (RFC4861)"))
o.rmempty = false
o.default = "1"
o = s:taboption("general", Flag, "AdvAutonomous", translate("Autonomous"),
translate("Indicates that this prefix can be used for autonomous address configuration (RFC4862)"))
o.rmempty = false
o.default = "1"
--
-- Advanced
--
o = s:taboption("advanced", Flag, "AdvRouterAddr", translate("Advertise router address"),
translate("Indicates that the address of interface is sent instead of network prefix, as is required by Mobile IPv6"))
o = s:taboption("advanced", Value, "AdvValidLifetime", translate("Valid lifetime"),
translate("Advertises the length of time in seconds that the prefix is valid for the purpose of on-link determination."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 86400
o = s:taboption("advanced", Value, "AdvPreferredLifetime", translate("Preferred lifetime"),
translate("Advertises the length of time in seconds that addresses generated from the prefix via stateless address autoconfiguration remain preferred."))
o.datatype = 'or(uinteger,"infinity")'
o.placeholder = 14400
o = s:taboption("advanced", Value, "Base6to4Interface", translate("6to4 interface"),
translate("Specifies a logical interface name to derive a 6to4 prefix from. The interfaces public IPv4 address is combined with 2002::/3 and the value of the prefix option"))
o.template = "cbi/network_netlist"
o.nocreate = true
o.unspecified = true
return m
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.