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 |
|---|---|---|---|---|---|
Lsty/ygopro-scripts | c50074392.lua | 5 | 2261 | --霊水鳥シレーヌ・オルカ
function c50074392.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c50074392.spcon)
e1:SetValue(1)
c:RegisterEffect(e1)
--lv
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(50074392,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_SPSUMMON_SUCCESS)
e2:SetCondition(c50074392.lvcon)
e2:SetTarget(c50074392.lvtg)
e2:SetOperation(c50074392.lvop)
c:RegisterEffect(e2)
end
function c50074392.cfilter(c,rc)
return c:IsFaceup() and c:IsRace(rc)
end
function c50074392.spcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c50074392.cfilter,tp,LOCATION_MZONE,0,1,nil,RACE_FISH)
and Duel.IsExistingMatchingCard(c50074392.cfilter,tp,LOCATION_MZONE,0,1,nil,RACE_WINDBEAST)
end
function c50074392.lvcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():GetSummonType()==SUMMON_TYPE_SPECIAL+1
end
function c50074392.filter(c)
return c:IsFaceup() and c:GetLevel()>0
end
function c50074392.lvtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c50074392.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,567)
local lv=Duel.AnnounceNumber(tp,3,4,5)
e:SetLabel(lv)
end
function c50074392.lvop(e,tp,eg,ep,ev,re,r,rp)
local lv=e:GetLabel()
local g=Duel.GetMatchingGroup(c50074392.filter,tp,LOCATION_MZONE,0,nil)
local tc=g:GetFirst()
while tc do
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_CHANGE_LEVEL)
e1:SetValue(lv)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
tc=g:GetNext()
end
local e2=Effect.CreateEffect(e:GetHandler())
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_TRIGGER)
e2:SetProperty(EFFECT_FLAG_IGNORE_RANGE)
e2:SetTarget(c50074392.actfilter)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c50074392.actfilter(e,c)
return c:GetControler()==e:GetHandlerPlayer() and c:IsType(TYPE_MONSTER) and not c:IsAttribute(ATTRIBUTE_WATER)
end
| gpl-2.0 |
ThingMesh/openwrt-luci | libs/lucid-http/luasrc/lucid/http/server.lua | 50 | 14678 | --[[
LuCId HTTP-Slave
(c) 2009 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 ipairs, pairs = ipairs, pairs
local tostring, tonumber = tostring, tonumber
local pcall, assert, type = pcall, assert, type
local set_memory_limit = set_memory_limit
local os = require "os"
local nixio = require "nixio"
local util = require "luci.util"
local ltn12 = require "luci.ltn12"
local proto = require "luci.http.protocol"
local table = require "table"
local date = require "luci.http.protocol.date"
--- HTTP Daemon
-- @cstyle instance
module "luci.lucid.http.server"
VERSION = "1.0"
statusmsg = {
[200] = "OK",
[206] = "Partial Content",
[301] = "Moved Permanently",
[302] = "Found",
[304] = "Not Modified",
[400] = "Bad Request",
[401] = "Unauthorized",
[403] = "Forbidden",
[404] = "Not Found",
[405] = "Method Not Allowed",
[408] = "Request Time-out",
[411] = "Length Required",
[412] = "Precondition Failed",
[416] = "Requested range not satisfiable",
[500] = "Internal Server Error",
[503] = "Server Unavailable",
}
--- Create a new IO resource response.
-- @class function
-- @param fd File descriptor
-- @param len Length of data
-- @return IO resource
IOResource = util.class()
function IOResource.__init__(self, fd, len)
self.fd, self.len = fd, len
end
--- Create a server handler.
-- @class function
-- @param name Name
-- @return Handler
Handler = util.class()
function Handler.__init__(self, name)
self.name = name or tostring(self)
end
--- Create a failure reply.
-- @param code HTTP status code
-- @param msg Status message
-- @return status code, header table, response source
function Handler.failure(self, code, msg)
return code, { ["Content-Type"] = "text/plain" }, ltn12.source.string(msg)
end
--- Add an access restriction.
-- @param restriction Restriction specification
function Handler.restrict(self, restriction)
if not self.restrictions then
self.restrictions = {restriction}
else
self.restrictions[#self.restrictions+1] = restriction
end
end
--- Enforce access restrictions.
-- @param request Request object
-- @return nil or HTTP statuscode, table of headers, response source
function Handler.checkrestricted(self, request)
if not self.restrictions then
return
end
local localif, user, pass
for _, r in ipairs(self.restrictions) do
local stat = true
if stat and r.interface then -- Interface restriction
if not localif then
for _, v in ipairs(request.server.interfaces) do
if v.addr == request.env.SERVER_ADDR then
localif = v.name
break
end
end
end
if r.interface ~= localif then
stat = false
end
end
if stat and r.user then -- User restriction
local rh, pwe
if not user then
rh = (request.headers.Authorization or ""):match("Basic (.*)")
rh = rh and nixio.bin.b64decode(rh) or ""
user, pass = rh:match("(.*):(.*)")
pass = pass or ""
end
pwe = nixio.getsp and nixio.getsp(r.user) or nixio.getpw(r.user)
local pwh = (user == r.user) and pwe and (pwe.pwdp or pwe.passwd)
if not pwh or #pwh < 1 or nixio.crypt(pass, pwh) ~= pwh then
stat = false
end
end
if stat then
request.env.HTTP_AUTH_USER, request.env.HTTP_AUTH_PASS = user, pass
return
end
end
return 401, {
["WWW-Authenticate"] = ('Basic realm=%q'):format(self.name),
["Content-Type"] = 'text/plain'
}, ltn12.source.string("Unauthorized")
end
--- Process a request.
-- @param request Request object
-- @param sourcein Request data source
-- @return HTTP statuscode, table of headers, response source
function Handler.process(self, request, sourcein)
local stat, code, hdr, sourceout
local stat, code, msg = self:checkrestricted(request)
if stat then -- Access Denied
return stat, code, msg
end
-- Detect request Method
local hname = "handle_" .. request.env.REQUEST_METHOD
if self[hname] then
-- Run the handler
stat, code, hdr, sourceout = pcall(self[hname], self, request, sourcein)
-- Check for any errors
if not stat then
return self:failure(500, code)
end
else
return self:failure(405, statusmsg[405])
end
return code, hdr, sourceout
end
--- Create a Virtual Host.
-- @class function
-- @return Virtual Host
VHost = util.class()
function VHost.__init__(self)
self.handlers = {}
end
--- Process a request and invoke the appropriate handler.
-- @param request Request object
-- @param ... Additional parameters passed to the handler
-- @return HTTP statuscode, table of headers, response source
function VHost.process(self, request, ...)
local handler
local hlen = -1
local uri = request.env.SCRIPT_NAME
local sc = ("/"):byte()
-- SCRIPT_NAME
request.env.SCRIPT_NAME = ""
-- Call URI part
request.env.PATH_INFO = uri
if self.default and uri == "/" then
return 302, {Location = self.default}
end
for k, h in pairs(self.handlers) do
if #k > hlen then
if uri == k or (uri:sub(1, #k) == k and uri:byte(#k+1) == sc) then
handler = h
hlen = #k
request.env.SCRIPT_NAME = k
request.env.PATH_INFO = uri:sub(#k+1)
end
end
end
if handler then
return handler:process(request, ...)
else
return 404, nil, ltn12.source.string("No such handler")
end
end
--- Get a list of registered handlers.
-- @return Table of handlers
function VHost.get_handlers(self)
return self.handlers
end
--- Register handler with a given URI prefix.
-- @oaram match URI prefix
-- @param handler Handler object
function VHost.set_handler(self, match, handler)
self.handlers[match] = handler
end
-- Remap IPv6-IPv4-compatibility addresses back to IPv4 addresses.
local function remapipv6(adr)
local map = "::ffff:"
if adr:sub(1, #map) == map then
return adr:sub(#map+1)
else
return adr
end
end
-- Create a source that decodes chunked-encoded data from a socket.
local function chunksource(sock, buffer)
buffer = buffer or ""
return function()
local output
local _, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
while not count and #buffer <= 1024 do
local newblock, code = sock:recv(1024 - #buffer)
if not newblock then
return nil, code
end
buffer = buffer .. newblock
_, endp, count = buffer:find("^([0-9a-fA-F]+);?.-\r\n")
end
count = tonumber(count, 16)
if not count then
return nil, -1, "invalid encoding"
elseif count == 0 then
return nil
elseif count + 2 <= #buffer - endp then
output = buffer:sub(endp+1, endp+count)
buffer = buffer:sub(endp+count+3)
return output
else
output = buffer:sub(endp+1, endp+count)
buffer = ""
if count - #output > 0 then
local remain, code = sock:recvall(count-#output)
if not remain then
return nil, code
end
output = output .. remain
count, code = sock:recvall(2)
else
count, code = sock:recvall(count+2-#buffer+endp)
end
if not count then
return nil, code
end
return output
end
end
end
-- Create a sink that chunk-encodes data and writes it on a given socket.
local function chunksink(sock)
return function(chunk, err)
if not chunk then
return sock:writeall("0\r\n\r\n")
else
return sock:writeall(("%X\r\n%s\r\n"):format(#chunk, tostring(chunk)))
end
end
end
--- Create a server object.
-- @class function
-- @return Server object
Server = util.class()
function Server.__init__(self)
self.vhosts = {}
end
--- Get a list of registered virtual hosts.
-- @return Table of virtual hosts
function Server.get_vhosts(self)
return self.vhosts
end
--- Register a virtual host with a given name.
-- @param name Hostname
-- @param vhost Virtual host object
function Server.set_vhost(self, name, vhost)
self.vhosts[name] = vhost
end
--- Send a fatal error message to given client and close the connection.
-- @param client Client socket
-- @param code HTTP status code
-- @param msg status message
function Server.error(self, client, code, msg)
hcode = tostring(code)
client:writeall( "HTTP/1.0 " .. hcode .. " " ..
statusmsg[code] .. "\r\n" )
client:writeall( "Connection: close\r\n" )
client:writeall( "Content-Type: text/plain\r\n\r\n" )
if msg then
client:writeall( "HTTP-Error " .. code .. ": " .. msg .. "\r\n" )
end
client:close()
end
local hdr2env = {
["Content-Length"] = "CONTENT_LENGTH",
["Content-Type"] = "CONTENT_TYPE",
["Content-type"] = "CONTENT_TYPE",
["Accept"] = "HTTP_ACCEPT",
["Accept-Charset"] = "HTTP_ACCEPT_CHARSET",
["Accept-Encoding"] = "HTTP_ACCEPT_ENCODING",
["Accept-Language"] = "HTTP_ACCEPT_LANGUAGE",
["Connection"] = "HTTP_CONNECTION",
["Cookie"] = "HTTP_COOKIE",
["Host"] = "HTTP_HOST",
["Referer"] = "HTTP_REFERER",
["User-Agent"] = "HTTP_USER_AGENT"
}
--- Parse the request headers and prepare the environment.
-- @param source line-based input source
-- @return Request object
function Server.parse_headers(self, source)
local env = {}
local req = {env = env, headers = {}}
local line, err
repeat -- Ignore empty lines
line, err = source()
if not line then
return nil, err
end
until #line > 0
env.REQUEST_METHOD, env.REQUEST_URI, env.SERVER_PROTOCOL =
line:match("^([A-Z]+) ([^ ]+) (HTTP/1%.[01])$")
if not env.REQUEST_METHOD then
return nil, "invalid magic"
end
local key, envkey, val
repeat
line, err = source()
if not line then
return nil, err
elseif #line > 0 then
key, val = line:match("^([%w-]+)%s?:%s?(.*)")
if key then
req.headers[key] = val
envkey = hdr2env[key]
if envkey then
env[envkey] = val
end
else
return nil, "invalid header line"
end
else
break
end
until false
env.SCRIPT_NAME, env.QUERY_STRING = env.REQUEST_URI:match("([^?]*)%??(.*)")
return req
end
--- Handle a new client connection.
-- @param client client socket
-- @param env superserver environment
function Server.process(self, client, env)
local sourcein = function() end
local sourcehdr = client:linesource()
local sinkout
local buffer
local close = false
local stat, code, msg, message, err
env.config.memlimit = tonumber(env.config.memlimit)
if env.config.memlimit and set_memory_limit then
set_memory_limit(env.config.memlimit)
end
client:setsockopt("socket", "rcvtimeo", 5)
client:setsockopt("socket", "sndtimeo", 5)
repeat
-- parse headers
message, err = self:parse_headers(sourcehdr)
-- any other error
if not message or err then
if err == 11 then -- EAGAIN
break
else
return self:error(client, 400, err)
end
end
-- Prepare sources and sinks
buffer = sourcehdr(true)
sinkout = client:sink()
message.server = env
if client:is_tls_socket() then
message.env.HTTPS = "on"
end
-- Addresses
message.env.REMOTE_ADDR = remapipv6(env.host)
message.env.REMOTE_PORT = env.port
local srvaddr, srvport = client:getsockname()
message.env.SERVER_ADDR = remapipv6(srvaddr)
message.env.SERVER_PORT = srvport
-- keep-alive
if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
close = (message.env.HTTP_CONNECTION == "close")
else
close = not message.env.HTTP_CONNECTION
or message.env.HTTP_CONNECTION == "close"
end
-- Uncomment this to disable keep-alive
close = close or env.config.nokeepalive
if message.env.REQUEST_METHOD == "GET"
or message.env.REQUEST_METHOD == "HEAD" then
-- Be happy
elseif message.env.REQUEST_METHOD == "POST" then
-- If we have a HTTP/1.1 client and an Expect: 100-continue header
-- respond with HTTP 100 Continue message
if message.env.SERVER_PROTOCOL == "HTTP/1.1"
and message.headers.Expect == '100-continue' then
client:writeall("HTTP/1.1 100 Continue\r\n\r\n")
end
if message.headers['Transfer-Encoding'] and
message.headers['Transfer-Encoding'] ~= "identity" then
sourcein = chunksource(client, buffer)
buffer = nil
elseif message.env.CONTENT_LENGTH then
local len = tonumber(message.env.CONTENT_LENGTH)
if #buffer >= len then
sourcein = ltn12.source.string(buffer:sub(1, len))
buffer = buffer:sub(len+1)
else
sourcein = ltn12.source.cat(
ltn12.source.string(buffer),
client:blocksource(nil, len - #buffer)
)
end
else
return self:error(client, 411, statusmsg[411])
end
close = true
else
return self:error(client, 405, statusmsg[405])
end
local host = self.vhosts[message.env.HTTP_HOST] or self.vhosts[""]
if not host then
return self:error(client, 404, "No virtual host found")
end
local code, headers, sourceout = host:process(message, sourcein)
headers = headers or {}
-- Post process response
if sourceout then
if util.instanceof(sourceout, IOResource) then
if not headers["Content-Length"] then
headers["Content-Length"] = sourceout.len
end
end
if not headers["Content-Length"] and not close then
if message.env.SERVER_PROTOCOL == "HTTP/1.1" then
headers["Transfer-Encoding"] = "chunked"
sinkout = chunksink(client)
else
close = true
end
end
elseif message.env.REQUEST_METHOD ~= "HEAD" then
headers["Content-Length"] = 0
end
if close then
headers["Connection"] = "close"
else
headers["Connection"] = "Keep-Alive"
headers["Keep-Alive"] = "timeout=5, max=50"
end
headers["Date"] = date.to_http(os.time())
local header = {
message.env.SERVER_PROTOCOL .. " " .. tostring(code) .. " "
.. statusmsg[code],
"Server: LuCId-HTTPd/" .. VERSION
}
for k, v in pairs(headers) do
if type(v) == "table" then
for _, h in ipairs(v) do
header[#header+1] = k .. ": " .. h
end
else
header[#header+1] = k .. ": " .. v
end
end
header[#header+1] = ""
header[#header+1] = ""
-- Output
stat, code, msg = client:writeall(table.concat(header, "\r\n"))
if sourceout and stat then
local closefd
if util.instanceof(sourceout, IOResource) then
if not headers["Transfer-Encoding"] then
stat, code, msg = sourceout.fd:copyz(client, sourceout.len)
closefd = sourceout.fd
sourceout = nil
else
closefd = sourceout.fd
sourceout = sourceout.fd:blocksource(nil, sourceout.len)
end
end
if sourceout then
stat, msg = ltn12.pump.all(sourceout, sinkout)
end
if closefd then
closefd:close()
end
end
-- Write errors
if not stat then
if msg then
nixio.syslog("err", "Error sending data to " .. env.host ..
": " .. msg .. "\n")
end
break
end
if buffer then
sourcehdr(buffer)
end
until close
client:shutdown()
client:close()
end
| apache-2.0 |
sdgathman/cjdns | contrib/lua/cjdns/udp.lua | 52 | 2682 | -- Cjdns admin module for Lua
-- Written by Philip Horger
common = require 'cjdns/common'
UDPInterface = {}
UDPInterface.__index = UDPInterface
common.UDPInterface = UDPInterface
function UDPInterface.new(ai, config, ptype)
properties = {
ai = ai,
config = config or ai.config,
ptype = ptype or "ai"
}
return setmetatable(properties, UDPInterface)
end
function UDPInterface:call(name, args)
local func = self[name .. "_" .. self.ptype]
return func(self, unpack(args))
end
function UDPInterface:newBind(...)
return self:call("newBind", arg)
end
function UDPInterface:beginConnection(...)
return self:call("beginConnection", arg)
end
function UDPInterface:newBind_ai(address)
local response, err = self.ai:auth({
q = "UDPInterface_new",
bindAddress = address
})
if not response then
return nil, err
elseif response.error ~= "none" then
return nil, response.error
elseif response.interfaceNumber then
return response.interfaceNumber
else
return nil, "bad response format"
end
end
function UDPInterface:newBind_config(address)
local udpif = self.config.contents.interfaces.UDPInterface
local new_interface = {
bind = address,
connectTo = {}
}
table.insert(udpif, new_interface)
return (#udpif - 1), new_interface
end
function UDPInterface:newBind_perm(...)
return
self:newBind_config(unpack(arg)),
self:newBind_ai(unpack(arg))
end
function UDPInterface:beginConnection_ai(pubkey, addr, password, interface)
local request = {
q = "UDPInterface_beginConnection",
publicKey = pubkey,
address = addr,
password = password
}
if interface then
request.interfaceNumber = interface
end
local response, err = self.ai:auth(request)
if not response then
return nil, err
elseif response.error == "none" then
-- Unfortunately, no real success indicator either.
return "No error"
else
return nil, response.error
end
end
function UDPInterface:beginConnection_config(pubkey, addr, password, interface)
local udpif = self.config.contents.interfaces.UDPInterface
local connections = udpif[(interface or 0) + 1].connectTo
local this_conn = {
password = password,
publicKey = pubkey
}
connections[addr] = this_conn
return this_conn -- allows adding metadata fields afterwards
end
function UDPInterface:beginConnection_perm(...)
return
self:beginConnection_config(unpack(arg)),
self:beginConnection_ai(unpack(arg))
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/Davoi/npcs/_45d.lua | 9 | 1052 | -----------------------------------
-- Area: Davoi
-- NPC: Wall of Banishing
-- Used In Quest: Whence Blows the Wind
-- !pos 181 0.1 -218 149
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
local ID = require("scripts/zones/Davoi/IDs");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
if (npc:getAnimation() == 9) then
if (player:hasKeyItem(dsp.ki.CRIMSON_ORB)) then
player:startEvent(42);
else
player:messageSpecial(ID.text.CAVE_HAS_BEEN_SEALED_OFF);
player:messageSpecial(ID.text.MAY_BE_SOME_WAY_TO_BREAK);
player:setCharVar("miniQuestForORB_CS",99);
end
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option,npc)
if (csid == 42 and option == 0) then
player:messageSpecial(ID.text.POWER_OF_THE_ORB_ALLOW_PASS);
npc:openDoor(16);
end
end; | gpl-3.0 |
pyridiss/devilsai | data/quest/1-KillStolas.lua | 1 | 1634 | --[[
Quest "First Demon" (birnam:demon)
Steps:
1 - Texts are displayed.
2 - The player must kill Stolas.
3 - The player must talk to Fluellen. The next quest is launched.
]]
-- global section
-- --------------
player_ptr = 0
stolas_ptr = 0
fluellen_ptr = 0
questStep = "0"
-- functions
-- ---------
function questBegin(addNewElements)
if questStep == "0" then
player_ptr = getElement("player")
fluellen_ptr = getElement("fluellen")
stolas_ptr = getElement("stolas")
if addNewElements == "true" then
pushDialog("birnam", "dialog-demon-introduction")
addJournalEntry("birnam", "demon", "journal-demon-title")
addJournalEntry("birnam", "demon", "journal-demon-text1")
end
questStep = "1"
end
end
function questManage()
if questStep == "1" then
if get(stolas_ptr, "life") == 0 then
questStep = "2"
-- END OF GAME
-- pushDialog("1-KillStolas-GoToCamp")
pushDialog("birnam", "EndOfGame")
end
-- END OF GAME
-- elseif questStep == "2" then
-- if interact(player_ptr, fluellen_ptr) then
-- questStep = "3"
-- pushDialog("1-KillStolas-Fluellen")
-- end
end
end
function questIsDone()
-- return (questStep == "3")
-- END OF GAME
return false
end
function questSave()
return "" .. questStep
end
function questRecoverState(data)
_, _, questStep = string.find(data, "(%d+)")
if questStep == "2" then
-- END OF GAME
-- pushDialog("1-KillStolas-GoToCamp")
pushDialog("birnam", "EndOfGame")
end
end
function questEnd()
-- END OF GAME
-- addQuest("1-GowersWorries")
addExperience(player_ptr, 5000)
end
| gpl-3.0 |
gallenmu/MoonGen | libmoon/lua/proto/template.lua | 4 | 3550 | local fill
local get
local getString
local resolveNextHeader
local setDefaultNamedArgs
local getVariableLength
local getSubType
--- Initialize a new header structure.
--- Adds automatic generated set/get/getString for all members
--- Works for uint8_t, uint16_t and uint32_t
--- For all other types the created functions have to be manualy overwritten
--- Adds empty template functions for all required functions on the complete header
--- fill/get/getString have to be filled in manually
--- All other functions only when required for this protocol
--- @param struct The header format as string
--- @return metatable for the header structure
function initHeader(struct)
local mod = {}
mod.__index = mod
-- create setter and getter for all members of the defined C struct
if struct then
for line in string.gmatch(struct, "(.-)\n") do
-- skip empty lines
if not (line == '') then
-- get name of member: at the end must be a ';', before that might be [<int>] which is ignored
local member = string.match(line, "([^%s%[%]]*)%[?%d*%]?%s*;")
local func_name = member:gsub("^%l", string.upper)
local type = string.match(line, "%s*(.-)%s+([^%s]*)%s*;")
if not (member == '') and not (type == '') then
-- automatically set byte order for integers
local conversion = ''
local close_conversion = ''
if type == 'uint16_t' then
conversion = 'hton16('
close_conversion = ')'
elseif type == 'uint32_t' then
conversion = 'hton('
close_conversion = ')'
end
-- set
local str = [[
return function(self, val)
val = val or 0
self.]] .. member .. [[ = ]] .. conversion .. [[val]] .. close_conversion .. [[
end]]
-- load new function and return it
local func = assert(loadstring(str))()
mod['set' .. func_name] = func
-- get
local str = [[
return function(self)
return ]] .. conversion .. [[self.]] .. member .. close_conversion .. [[
end]]
-- load new function and return it
local func = assert(loadstring(str))()
mod['get' .. func_name] = func
-- getFooString
local str = [[
return function(self)
return tostring(self:get]] .. func_name .. [[())
end]]
-- load new function and return it
local func = assert(loadstring(str))()
mod['get' .. func_name .. 'String'] = func
else
print('Warning: empty or malicious line cannot be parsed')
end
end
end
end
-- add templates for header-wide functions
mod.fill = fill
mod.get = get
mod.getString = getString
mod.resolveNextHeader = resolveNextHeader
mod.setDefaultNamedArgs = setDefaultNamedArgs
mod.getVariableLength = getVariableLength
mod.getSubType = getSubType
return setmetatable({}, mod)
end
function fill(self, args, pre)
end
function get(self, pre)
return {}
end
function getString(self)
return ""
end
--- Defines how, based on the data of this header, the next following protocol in the stack can be resolved
function resolveNextHeader(self)
return nil
end
--- Defines how, based on the data of this header and the complete stack, the default values of this headers member change
function setDefaultNamedArgs(self, pre, namedArgs, nextHeader, accumulatedLength, headerLength)
return namedArgs
end
--- Defines how, based on the data of this header, the length of the variable sized member can be determined
function getVariableLength(self)
return nil
end
--- Defines how, based on the data of this header, the protocol subtype can be determined
function getSubType(self)
return nil
end
| mit |
CommandPost/CommandPost-App | extensions/base64/base64.lua | 4 | 1408 | --- === hs.base64 ===
---
--- Base64 encoding and decoding
---
--- Portions sourced from (https://gist.github.com/shpakovski/1902994).
local module = require("hs.libbase64")
-- private variables and methods -----------------------------------------
-- Public interface ------------------------------------------------------
--- hs.base64.encode(val[,width]) -> str
--- Function
--- Encodes a given string to base64
---
--- Parameters:
--- * val - A string to encode as base64
--- * width - Optional line width to split the string into (usually 64 or 76)
---
--- Returns:
--- * A string containing the base64 representation of the input string
module.encode = function(data, width)
local _data = module._encode(data)
if width then
local _hold, i, j = _data, 1, width
_data = ""
repeat
_data = _data.._hold:sub(i,j).."\n"
i = i + width
j = j + width
until i > #_hold
return _data:sub(1,#_data - 1)
else
return _data
end
end
--- hs.base64.decode(str) -> val
--- Function
--- Decodes a given base64 string
---
--- Parameters:
--- * str - A base64 encoded string
---
--- Returns:
--- * A string containing the decoded data
module.decode = function(data)
return module._decode((data:gsub("[\r\n]+","")))
end
-- Return Module Object --------------------------------------------------
return module
| mit |
MalRD/darkstar | scripts/globals/mobskills/wire_cutter.lua | 11 | 1222 | ---------------------------------------------------
-- Wire_Cutter
-- Single-target damage (~500-1500), absorbed by 2 Utsusemi shadows.
--
---------------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------------
function onMobSkillCheck(target,mob,skill)
-- skillList 54 = Omega
-- skillList 727 = Proto-Omega
-- skillList 728 = Ultima
-- skillList 729 = Proto-Ultima
local skillList = mob:getMobMod(dsp.mobMod.SKILL_LIST)
local mobhp = mob:getHPP()
local phase = mob:getLocalVar("battlePhase")
if ((skillList == 729 and phase < 2) or (skillList == 728 and mobhp > 70)) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 2
local accmod = 1
local dmgmod = 3
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
return dmg
end | gpl-3.0 |
cshore-firmware/openwrt-luci | applications/luci-app-ocserv/luasrc/model/cbi/ocserv/main.lua | 22 | 6871 | -- Copyright 2014 Nikos Mavrogiannopoulos <n.mavrogiannopoulos@gmail.com>
-- Licensed to the public under the Apache License 2.0.
local fs = require "nixio.fs"
local has_ipv6 = fs.access("/proc/net/ipv6_route")
m = Map("ocserv", translate("OpenConnect VPN"))
s = m:section(TypedSection, "ocserv", "OpenConnect")
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("ca", translate("CA certificate"))
s:tab("template", translate("Edit Template"))
local e = s:taboption("general", Flag, "enable", translate("Enable server"))
e.rmempty = false
e.default = "1"
local o_sha = s:taboption("general", DummyValue, "sha_hash", translate("Server's certificate SHA1 hash"),
translate("That value should be communicated to the client to verify the server's certificate"))
local o_pki = s:taboption("general", DummyValue, "pkid", translate("Server's Public Key ID"),
translate("An alternative value to be communicated to the client to verify the server's certificate; this value only depends on the public key"))
local fd = io.popen("/usr/bin/certtool -i --infile /etc/ocserv/server-cert.pem", "r")
if fd then local ln
local found_sha = false
local found_pki = false
local complete = 0
while complete < 2 do
local ln = fd:read("*l")
if not ln then
break
elseif ln:match("SHA%-?1 fingerprint:") then
found_sha = true
elseif found_sha then
local hash = ln:match("([a-f0-9]+)")
o_sha.default = hash and hash:upper()
complete = complete + 1
found_sha = false
elseif ln:match("Public Key I[Dd]:") then
found_pki = true
elseif found_pki then
local hash = ln:match("([a-f0-9]+)")
o_pki.default = hash and "sha1:" .. hash:upper()
complete = complete + 1
found_pki = false
end
end
fd:close()
end
function m.on_commit(map)
luci.sys.call("/usr/bin/occtl reload >/dev/null 2>&1")
end
function e.write(self, section, value)
if value == "0" then
luci.sys.call("/etc/init.d/ocserv stop >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv disable >/dev/null 2>&1")
else
luci.sys.call("/etc/init.d/ocserv enable >/dev/null 2>&1")
luci.sys.call("/etc/init.d/ocserv restart >/dev/null 2>&1")
end
Flag.write(self, section, value)
end
local o
o = s:taboption("general", ListValue, "auth", translate("User Authentication"),
translate("The authentication method for the users. The simplest is plain with a single username-password pair. Use PAM modules to authenticate using another server (e.g., LDAP, Radius)."))
o.rmempty = false
o.default = "plain"
o:value("plain")
o:value("PAM")
s:taboption("general", Value, "port", translate("Port"),
translate("The same UDP and TCP ports will be used"))
s:taboption("general", Value, "max_clients", translate("Max clients"))
s:taboption("general", Value, "max_same", translate("Max same clients"))
s:taboption("general", Value, "dpd", translate("Dead peer detection time (secs)"))
local pip = s:taboption("general", Flag, "predictable_ips", translate("Predictable IPs"),
translate("The assigned IPs will be selected deterministically"))
pip.default = "1"
local compr = s:taboption("general", Flag, "compression", translate("Enable compression"),
translate("Enable compression"))
compr.default = "1"
local udp = s:taboption("general", Flag, "udp", translate("Enable UDP"),
translate("Enable UDP channel support; this must be enabled unless you know what you are doing"))
udp.default = "1"
local cisco = s:taboption("general", Flag, "cisco_compat", translate("AnyConnect client compatibility"),
translate("Enable support for CISCO AnyConnect clients"))
cisco.default = "1"
tmpl = s:taboption("template", Value, "_tmpl",
translate("Edit the template that is used for generating the ocserv configuration."))
tmpl.template = "cbi/tvalue"
tmpl.rows = 20
function tmpl.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ocserv.conf.template")
end
function tmpl.write(self, section, value)
value = value:gsub("\r\n?", "\n")
nixio.fs.writefile("/etc/ocserv/ocserv.conf.template", value)
end
ca = s:taboption("ca", Value, "_ca",
translate("View the CA certificate used by this server. You will need to save it as 'ca.pem' and import it into the clients."))
ca.template = "cbi/tvalue"
ca.rows = 20
function ca.cfgvalue(self, section)
return nixio.fs.readfile("/etc/ocserv/ca.pem")
end
--[[Networking options]]--
local parp = s:taboption("general", Flag, "proxy_arp", translate("Enable proxy arp"),
translate("Provide addresses to clients from a subnet of LAN; if enabled the network below must be a subnet of LAN. Note that the first address of the specified subnet will be reserved by ocserv, so it should not be in use. If you have a network in LAN covering 192.168.1.0/24 use 192.168.1.192/26 to reserve the upper 62 addresses."))
parp.default = "0"
ipaddr = s:taboption("general", Value, "ipaddr", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Network-Address"),
translate("The IPv4 subnet address to provide to clients; this should be some private network different than the LAN addresses unless proxy ARP is enabled. Leave empty to attempt auto-configuration."))
ipaddr.datatype = "ip4addr"
ipaddr.default = "192.168.100.1"
nm = s:taboption("general", Value, "netmask", translate("VPN <abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"),
translate("The mask of the subnet above."))
nm.datatype = "ip4addr"
nm.default = "255.255.255.0"
nm:value("255.255.255.0")
nm:value("255.255.0.0")
nm:value("255.0.0.0")
if has_ipv6 then
ip6addr = s:taboption("general", Value, "ip6addr", translate("VPN <abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Network-Address"), translate("<abbr title=\"Classless Inter-Domain Routing\">CIDR</abbr>-Notation: address/prefix"),
translate("The IPv6 subnet address to provide to clients; leave empty to attempt auto-configuration."))
ip6addr.datatype = "ip6addr"
end
--[[DNS]]--
s = m:section(TypedSection, "dns", translate("DNS servers"),
translate("The DNS servers to be provided to clients; can be either IPv6 or IPv4. Typically you should include the address of this device"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
s.datatype = "ipaddr"
--[[Routes]]--
s = m:section(TypedSection, "routes", translate("Routing table"),
translate("The routing table to be provided to clients; you can mix IPv4 and IPv6 routes, the server will send only the appropriate. Leave empty to set a default route"))
s.anonymous = true
s.addremove = true
s.template = "cbi/tblsection"
s:option(Value, "ip", translate("IP Address")).rmempty = true
o = s:option(Value, "netmask", translate("Netmask (or IPv6-prefix)"))
o.default = "255.255.255.0"
o:value("255.255.255.0")
o:value("255.255.0.0")
o:value("255.0.0.0")
return m
| apache-2.0 |
mohammad25253/new43 | plugins/Expire.lua | 47 | 1782 | local filename='data/expire.lua'
local cronned = load_from_file(filename)
local function save_cron(msg, text,date)
local origin = get_receiver(msg)
if not cronned[date] then
cronned[date] = {}
end
local arr = { origin, text } ;
table.insert(cronned[date], arr)
serialize_to_file(cronned, filename)
return 'Saved!'
end
local function delete_cron(date)
for k,v in pairs(cronned) do
if k == date then
cronned[k]=nil
end
end
serialize_to_file(cronned, filename)
end
local function cron()
for date, values in pairs(cronned) do
if date < os.time() then —time's up
send_msg(values[1][1], "Time's up:"..values[1][2], ok_cb, false)
delete_cron(date)
end
end
end
local function actually_run(msg, delay,text)
if (not delay or not text) then
return "Usage: !remind [delay: 2h3m1s] text"
end
save_cron(msg, text,delay)
return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'"
end
local function run(msg, matches)
local sum = 0
for i = 1, #matches-1 do
local b,_ = string.gsub(matches[i],"[a-zA-Z]","")
if string.find(matches[i], "s") then
sum=sum+b
end
if string.find(matches[i], "m") then
sum=sum+b*60
end
if string.find(matches[i], "h") then
sum=sum+b*3600
end
end
local date=sum+os.time()
local text = matches[#matches]
local text = actually_run(msg, date, text)
return text
end
return {
patterns = {
"^[!/](expire) ([0-9]+[hmsdHMSD]) (.+)$", —- e.g : for a month enter : 720hms - then , in text enter gp id and admin id
"^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$",
"^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
LeMagnesium/minetest-mod-gravity_items | init.lua | 1 | 4865 | -- Gravity items
-- Little mod ßý Mg
-- License : WTFPL
gravity_items = {}
gravity_items.data = {}
gravity_items.p_override = {}
function movement_loop(player)
local ctrls = player:get_player_control()
if ctrls.jump then
local v = (player:getvelocity() or {x = 0, z = 0})
player:setvelocity({x = v.x, y = 10, z = v.z})
elseif ctrls.down then
local v = (player:getvelocity() or {x = 0, z = 0})
player:setvelocity({x = v.x, y = -10, z = v.z})
end
if not gravity_items.p_override[player:get_player_name()] or gravity_items.p_override[player:get_player_name()] ~= 0 then
return
end
minetest.after(0.1, movement_loop, player)
end
gravity_items.register_item = function(name, number)
if not number or not name or not type(number) == "number"
or not type(name) == "string" then
minetest.log("error", "[gravity_items] Cannot register item without " ..
"valid number nor valid name")
return false
end
minetest.register_craftitem("gravity_items:"..name.."_item", {
description = number.." gravity item",
inventory_image = "gravity_items_" .. name .. ".png",
on_use = function(itemstack, user, pointed_thing)
gravity_items.p_override[user:get_player_name()] = number
user:set_physics_override({gravity = number})
minetest.chat_send_player(user:get_player_name(), "Gravity set to "
.. number)
if number == 0 then
movement_loop(user)
end
end
})
end
gravity_items.register_node = function(name, number, radius)
if not number or not name or not tonumber(number)
or not type(name) == "string" then
minetest.log("error", "[gravity_items] Cannot register node without " ..
"valid number nor valid name")
return false
end
minetest.register_node("gravity_items:"..name.."_"..radius.."_node", {
description = number.." gravity node (radius " .. radius .. ")",
tiles = {"gravity_items_" .. name .. ".png"},
groups = {oddly_breakable_by_hand = 2},
on_construct = function(pos)
local nodetimer = minetest.get_node_timer(pos)
nodetimer:start(0.1)
minetest.get_meta(pos):set_string("players", minetest.serialize({}))
end,
on_timer = function(pos, elapsed)
local entities_around = minetest.get_objects_inside_radius(pos, radius)
local meta = minetest.get_meta(pos)
local registered_players = meta:get_string("players")
registered_players = minetest.deserialize(registered_players)
for _, ref in pairs(entities_around) do
if ref:is_player() then
local playername = ref:get_player_name()
gravity_items.p_override[ref:get_player_name()] = number
ref:set_physics_override({gravity = number})
registered_players[playername] = 1
end
end
for name, presence in pairs(registered_players) do
if presence == 0 then
local player = minetest.get_player_by_name(name)
if player then
player:set_physics_override({gravity = 1})
gravity_items.p_override[player:get_player_name()] = nil
end
registered_players[name] = nil
else
registered_players[name] = 0
end
end
meta:set_string("players", minetest.serialize(registered_players))
minetest.get_node_timer(pos):start(0.1)
end,
on_destruct = function(pos)
local meta = minetest.get_meta(pos)
local players = minetest.deserialize(meta:get_string("players"))
for name, _ in pairs(players) do
local player = minetest.get_player_by_name(name)
player:set_physics_override({gravity = 1})
gravity_items.p_override[player:get_player_name()] = nil
end
end
})
end
gravity_items.data.items = {
["negative_point_one"] = {value = -0.1, radiuses = {5,10,15,20,25}},
["null"] = {value = 0, radiuses = {5, 10, 15, 30}},
["point_one"] = {value = 0.1, radiuses = {10,20,30}},
["point_five"] = {value = 0.5, radiuses = {10,15,20}},
["one"] = {value = 1, radiuses = {10,20}},
["ten"] = {value = 10, radiuses = {10}},
}
for name, data in pairs(gravity_items.data.items) do
gravity_items.register_item(name, data.value)
for _, radius in pairs(data.radiuses) do
gravity_items.register_node(name, data.value, radius)
end
-- minetest.register_alias("gravity_items:"..name.."_"..data.radiuses[1].."_node", "gravity_items:"..name.."_node")
end
| gpl-3.0 |
Lsty/ygopro-scripts | c81873903.lua | 7 | 1031 | --エヴォルド・ウェストロ
function c81873903.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(81873903,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FLIP+EFFECT_TYPE_SINGLE)
e1:SetTarget(c81873903.target)
e1:SetOperation(c81873903.operation)
c:RegisterEffect(e1)
end
function c81873903.filter(c,e,tp)
return c:IsSetCard(0x604e) and c:IsCanBeSpecialSummoned(e,151,tp,false,false)
end
function c81873903.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c81873903.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c81873903.filter,tp,LOCATION_DECK,0,1,1,nil,e,tp)
if g:GetCount()>0 then
Duel.SpecialSummon(g,151,tp,tp,false,false,POS_FACEUP)
local rf=g:GetFirst().evolreg
if rf then rf(g:GetFirst()) end
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/globals/items/pogaca_+1.lua | 11 | 1131 | -----------------------------------------
-- ID: 5638
-- Item: pogaca_+1
-- Food Effect: 5Min, All Races
-----------------------------------------
-- Lizard Killer +12
-- Resist Paralyze +12
-- HP Recovered While Healing 6
-- MP Recovered While Healing 6
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,360,5638)
end
function onEffectGain(target,effect)
target:addMod(dsp.mod.LIZARD_KILLER, 12)
target:addMod(dsp.mod.PARALYZERES, 12)
target:addMod(dsp.mod.HPHEAL, 6)
target:addMod(dsp.mod.MPHEAL, 6)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.LIZARD_KILLER, 12)
target:delMod(dsp.mod.PARALYZERES, 12)
target:delMod(dsp.mod.HPHEAL, 6)
target:delMod(dsp.mod.MPHEAL, 6)
end
| gpl-3.0 |
sagarwaghmare69/nn | VolumetricAveragePooling.lua | 19 | 1404 | local VolumetricAveragePooling, parent = torch.class(
'nn.VolumetricAveragePooling', 'nn.Module')
function VolumetricAveragePooling:__init(kT, kW, kH, dT, dW, dH)
parent.__init(self)
dT = dT or kT
dW = dW or kW
dH = dH or kH
self.kT = kT
self.kH = kH
self.kW = kW
self.dT = dT
self.dW = dW
self.dH = dH
end
function VolumetricAveragePooling:updateOutput(input)
input.THNN.VolumetricAveragePooling_updateOutput(
input:cdata(),
self.output:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH
)
return self.output
end
function VolumetricAveragePooling:updateGradInput(input, gradOutput)
input.THNN.VolumetricAveragePooling_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH
)
return self.gradInput
end
function VolumetricAveragePooling:empty()
return parent.clearState(self)
end
function VolumetricAveragePooling:__tostring__()
local s = string.format('%s(%dx%dx%d, %d,%d,%d', torch.type(self),
self.kT, self.kW, self.kH, self.dT, self.dW, self.dH)
if (self.padT or self.padW or self.padH) and
(self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padT.. ',' .. self.padW .. ','.. self.padH
end
s = s .. ')'
return s
end
| bsd-3-clause |
Lsty/ygopro-scripts | c95448692.lua | 5 | 1760 | --ダメージ・ダイエット
function c95448692.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetOperation(c95448692.activate)
c:RegisterEffect(e1)
--effect damage
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetRange(LOCATION_GRAVE)
e2:SetCost(c95448692.cost2)
e2:SetOperation(c95448692.activate2)
c:RegisterEffect(e2)
end
c95448692[0]=0
c95448692[1]=0
function c95448692.activate(e,tp,eg,ep,ev,re,r,rp)
c95448692[tp]=1
if Duel.GetFlagEffect(tp,95448692)~=0 then return end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(c95448692.val)
e1:SetReset(RESET_PHASE+PHASE_END,1)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,95448692,RESET_PHASE+PHASE_END,0,1)
end
function c95448692.cost2(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end
Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_EFFECT)
end
function c95448692.activate2(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFlagEffect(tp,95448692)~=0 then return end
c95448692[tp]=0
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(1,0)
e1:SetValue(c95448692.val)
e1:SetReset(RESET_PHASE+PHASE_END,1)
Duel.RegisterEffect(e1,tp)
Duel.RegisterFlagEffect(tp,95448692,RESET_PHASE+PHASE_END,0,1)
end
function c95448692.val(e,re,dam,r,rp,rc)
if c95448692[e:GetOwnerPlayer()]==1 or bit.band(r,REASON_EFFECT)~=0 then
return dam/2
else return dam end
end
| gpl-2.0 |
tryroach/vlc | share/lua/intf/http.lua | 64 | 10445 | --[==========================================================================[
http.lua: HTTP interface module for VLC
--[==========================================================================[
Copyright (C) 2007-2009 the VideoLAN team
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
--[==========================================================================[
Configuration options:
* dir: Directory to use as the http interface's root.
* no_error_detail: If set, do not print the Lua error message when generating
a page fails.
* no_index: If set, don't build directory indexes
--]==========================================================================]
require "common"
vlc.msg.info("Lua HTTP interface")
open_tag = "<?vlc"
close_tag = "?>"
-- TODO: use internal VLC mime lookup function for mimes not included here
mimes = {
txt = "text/plain",
json = "text/plain",
html = "text/html",
xml = "text/xml",
js = "text/javascript",
css = "text/css",
png = "image/png",
jpg = "image/jpeg",
jpeg = "image/jpeg",
ico = "image/x-icon",
}
function escape(s)
return (string.gsub(s,"([%^%$%%%.%[%]%*%+%-%?])","%%%1"))
end
function process_raw(filename)
local input = io.open(filename):read("*a")
-- find the longest [===[ or ]=====] type sequence and make sure that
-- we use one that's longer.
local str="X"
for str2 in string.gmatch(input,"[%[%]]=*[%[%]]") do
if #str < #str2 then str = str2 end
end
str=string.rep("=",#str-1)
--[[ FIXME:
<?xml version="1.0" encoding="charset" standalone="yes" ?> is still a problem. The closing '?>' needs to be printed using '?<?vlc print ">" ?>' to prevent a parse error.
--]]
local code0 = string.gsub(input,escape(close_tag)," print(["..str.."[")
local code1 = string.gsub(code0,escape(open_tag),"]"..str.."]) ")
local code = "print(["..str.."["..code1.."]"..str.."])"
--[[ Uncomment to debug
if string.match(filename,"vlm_cmd.xml$") then
io.write(code)
io.write("\n")
end
--]]
return assert(loadstring(code,filename))
end
function process(filename)
local mtime = 0 -- vlc.net.stat(filename).modification_time
local func = false -- process_raw(filename)
return function(...)
local new_mtime = vlc.net.stat(filename).modification_time
if new_mtime ~= mtime then
-- Re-read the file if it changed
if mtime == 0 then
vlc.msg.dbg("Loading `"..filename.."'")
else
vlc.msg.dbg("Reloading `"..filename.."'")
end
func = process_raw(filename)
mtime = new_mtime
end
return func(...)
end
end
function callback_error(path,url,msg)
local url = url or "<page unknown>"
return [[<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Error loading ]]..url..[[</title>
</head>
<body>
<h1>Error loading ]]..url..[[</h1><pre>]]..(config.no_error_detail and "Remove configuration option `no_error_detail' on the server to get more information."
or vlc.strings.convert_xml_special_chars(tostring(msg)))..[[</pre>
<p>
<a href="http://www.videolan.org/">VideoLAN</a><br/>
<a href="http://www.lua.org/manual/5.1/">Lua 5.1 Reference Manual</a>
</p>
</body>
</html>]]
end
function dirlisting(url,listing)
local list = {}
for _,f in ipairs(listing) do
if not string.match(f,"^%.") then
table.insert(list,"<li><a href='"..f.."'>"..f.."</a></li>")
end
end
list = table.concat(list)
local function callback()
return [[<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Directory listing ]]..url..[[</title>
</head>
<body>
<h1>Directory listing ]]..url..[[</h1><ul>]]..list..[[</ul>
</body>
</html>]]
end
return h:file(url,"text/html",nil,password,callback,nil)
end
-- FIXME: Experimental art support. Needs some cleaning up.
function callback_art(data, request, args)
local art = function(data, request)
local num = nil
if args ~= nil then
num = string.gmatch(args, "item=(.*)")
if num ~= nil then
num = num()
end
end
local item
if num == nil then
item = vlc.input.item()
else
item = vlc.playlist.get(num).item
end
local metas = item:metas()
local filename = vlc.strings.decode_uri(string.gsub(metas["artwork_url"],"file://",""))
local windowsdrive = string.match(filename, "^/%a:/.+$") --match windows drive letter
if windowsdrive then
filename = string.sub(filename, 2) --remove starting forward slash before the drive letter
end
local size = vlc.net.stat(filename).size
local ext = string.match(filename,"%.([^%.]-)$")
local raw = io.open(filename, 'rb'):read("*a")
local content = [[Content-Type: ]]..mimes[ext]..[[
Content-Length: ]]..size..[[
]]..raw..[[
]]
return content
end
local ok, content = pcall(art, data, request)
if not ok then
return [[Status: 404
Content-Type: text/plain
Content-Length: 5
Error
]]
end
return content
end
function file(h,path,url,mime)
local generate_page = process(path)
local callback = function(data,request)
-- FIXME: I'm sure that we could define a real sandbox
-- redefine print
local page = {}
local function pageprint(...)
for i=1,select("#",...) do
if i== 1 then
table.insert(page,tostring(select(i,...)))
else
table.insert(page," "..tostring(select(i,...)))
end
end
end
_G._GET = parse_url_request(request)
local oldprint = print
print = pageprint
local ok, msg = pcall(generate_page)
-- reset
print = oldprint
if not ok then
return callback_error(path,url,msg)
end
return table.concat(page)
end
return h:file(url or path,mime,nil,password,callback,nil)
end
function rawfile(h,path,url)
local filename = path
local mtime = 0 -- vlc.net.stat(filename).modification_time
local page = false -- io.open(filename):read("*a")
local callback = function(data,request)
local new_mtime = vlc.net.stat(filename).modification_time
if mtime ~= new_mtime then
-- Re-read the file if it changed
if mtime == 0 then
vlc.msg.dbg("Loading `"..filename.."'")
else
vlc.msg.dbg("Reloading `"..filename.."'")
end
page = io.open(filename,"rb"):read("*a")
mtime = new_mtime
end
return page
end
return h:file(url or path,nil,nil,password,callback,nil)
end
function parse_url_request(request)
if not request then return {} end
local t = {}
for k,v in string.gmatch(request,"([^=&]+)=?([^=&]*)") do
local k_ = vlc.strings.decode_uri(k)
local v_ = vlc.strings.decode_uri(v)
if t[k_] ~= nil then
local t2
if type(t[k_]) ~= "table" then
t2 = {}
table.insert(t2,t[k_])
t[k_] = t2
else
t2 = t[k_]
end
table.insert(t2,v_)
else
t[k_] = v_
end
end
return t
end
local function find_datadir(name)
local list = vlc.config.datadir_list(name)
for _, l in ipairs(list) do
local s = vlc.net.stat(l)
if s then
return l
end
end
error("Unable to find the `"..name.."' directory.")
end
http_dir = config.dir or find_datadir("http")
do
local oldpath = package.path
package.path = http_dir.."/?.lua"
local ok, err = pcall(require,"custom")
if not ok then
vlc.msg.warn("Couldn't load "..http_dir.."/custom.lua",err)
else
vlc.msg.dbg("Loaded "..http_dir.."/custom.lua")
end
package.path = oldpath
end
files = {}
local function load_dir(dir,root)
local root = root or "/"
local has_index = false
local d = vlc.net.opendir(dir)
for _,f in ipairs(d) do
if not string.match(f,"^%.") then
local s = vlc.net.stat(dir.."/"..f)
if s.type == "file" then
local url
if f == "index.html" then
url = root
has_index = true
else
url = root..f
end
local ext = string.match(f,"%.([^%.]-)$")
local mime = mimes[ext]
-- print(url,mime)
if mime and string.match(mime,"^text/") then
table.insert(files,file(h,dir.."/"..f,url,mime))
else
table.insert(files,rawfile(h,dir.."/"..f,url))
end
elseif s.type == "dir" then
load_dir(dir.."/"..f,root..f.."/")
end
end
end
if not has_index and not config.no_index then
-- print("Adding index for", root)
table.insert(files,dirlisting(root,d))
end
end
if config.host then
vlc.msg.err("\""..config.host.."\" HTTP host ignored")
local port = string.match(config.host, ":(%d+)[^]]*$")
vlc.msg.info("Pass --http-host=IP "..(port and "and --http-port="..port.." " or "").."on the command line instead.")
end
password = vlc.var.inherit(nil,"http-password")
h = vlc.httpd()
load_dir( http_dir )
a = h:handler("/art",nil,password,callback_art,nil)
| gpl-2.0 |
MalRD/darkstar | scripts/mixins/families/hpemde.lua | 9 | 3077 | require("scripts/globals/mixins")
require("scripts/globals/status")
-----------------------------------
g_mixins = g_mixins or {}
g_mixins.families = g_mixins.families or {}
local function dive(mob)
mob:hideName(true)
mob:untargetable(true)
mob:SetAutoAttackEnabled(false)
mob:SetMobAbilityEnabled(false)
mob:AnimationSub(5)
end
local function surface(mob)
mob:hideName(false)
mob:untargetable(false)
local animationSub = mob:AnimationSub()
if animationSub == 0 or animationSub == 5 then
mob:AnimationSub(6)
mob:wait(2000)
end
end
local function openMouth(mob)
mob:addMod(dsp.mod.ATTP, 100)
mob:addMod(dsp.mod.DEFP, -50)
mob:addMod(dsp.mod.DMGMAGIC, -50)
mob:setLocalVar("[hpemde]closeMouthHP", mob:getHP() - math.ceil(mob:getMaxHP() / 3))
mob:AnimationSub(3)
mob:wait(2000)
end
local function closeMouth(mob)
mob:delMod(dsp.mod.ATTP, 100)
mob:delMod(dsp.mod.DEFP, -50)
mob:delMod(dsp.mod.DMGMAGIC, -50)
mob:setLocalVar("[hpemde]changeTime", mob:getBattleTime() + 30)
mob:AnimationSub(6)
mob:wait(2000)
end
g_mixins.families.hpemde = function(mob)
mob:addListener("SPAWN", "HPEMDE_SPAWN", function(mob)
mob:setMod(dsp.mod.REGEN, 10)
dive(mob)
end)
mob:addListener("ROAM_TICK", "HPEMDE_RTICK", function(mob)
if mob:getHPP() == 100 then
mob:setLocalVar("[hpemde]damaged", 0)
end
if mob:AnimationSub() ~= 5 then
dive(mob)
end
end)
mob:addListener("ENGAGE", "HPEMDE_ENGAGE", function(mob, target)
mob:setLocalVar("[hpemde]disengageTime", mob:getBattleTime() + 45)
surface(mob)
end)
mob:addListener("MAGIC_TAKE", "HPEMDE_MAGIC_TAKE", function(target, caster, spell)
target:setLocalVar("[hpemde]disengageTime", target:getBattleTime() + 45)
end)
mob:addListener("COMBAT_TICK", "HPEMDE_CTICK", function(mob)
if mob:getLocalVar("[hpemde]damaged") == 0 then
local disengageTime = mob:getLocalVar("[hpemde]disengageTime")
if mob:getHP() < mob:getMaxHP() then
mob:SetAutoAttackEnabled(true)
mob:SetMobAbilityEnabled(true)
mob:setLocalVar("[hpemde]damaged", 1)
mob:setLocalVar("[hpemde]changeTime", mob:getBattleTime() + 30)
elseif disengageTime > 0 and mob:getBattleTime() > disengageTime then
mob:setLocalVar("[hpemde]disengageTime", 0)
mob:disengage()
end
else
if mob:AnimationSub() == 6 and mob:getBattleTime() > mob:getLocalVar("[hpemde]changeTime") then
openMouth(mob)
elseif mob:AnimationSub() == 3 and mob:getHP() < mob:getLocalVar("[hpemde]closeMouthHP") then
closeMouth(mob)
end
end
end)
mob:addListener("CRITICAL_TAKE", "HPEMDE_CRITICAL_TAKE", function(mob)
if mob:AnimationSub() == 3 then
closeMouth(mob)
end
end)
end
return g_mixins.families.hpemde
| gpl-3.0 |
Lsty/ygopro-scripts | c99173029.lua | 3 | 1600 | --霊子エネルギー固定装置
function c99173029.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--spirit do not return
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPIRIT_DONOT_RETURN)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
c:RegisterEffect(e2)
--leave
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetOperation(c99173029.levop)
c:RegisterEffect(e3)
--maintain
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e4:SetCode(EVENT_PHASE+PHASE_END)
e4:SetRange(LOCATION_SZONE)
e4:SetCountLimit(1)
e4:SetCondition(c99173029.mtcon)
e4:SetOperation(c99173029.mtop)
c:RegisterEffect(e4)
end
function c99173029.filter(c)
return c:IsFaceup() and c:IsType(TYPE_SPIRIT)
end
function c99173029.levop(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c99173029.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
end
end
function c99173029.mtcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()==tp
end
function c99173029.mtop(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,LOCATION_HAND,0)>0 and Duel.SelectYesNo(tp,aux.Stringid(99173029,0)) then
Duel.DiscardHand(tp,nil,1,1,REASON_COST+REASON_DISCARD)
else
Duel.Destroy(e:GetHandler(),REASON_RULE)
end
end
| gpl-2.0 |
Aaa1r/DRAGON | plugins/addreplay.lua | 10 | 2669 | --[[
BY-@Sadik_alknani10
BY_CH : @KINGTELE1
]]
local function get_variables_hash(msg)
if msg.to.type == 'chat' or msg.to.type == 'channel' then
return 'chat:bot:variables'
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
else
return value
end
end
end
local function list_chats(msg)
local hash = get_variables_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
else
return
end
end
local function save_value(msg, name, value)
if (not name or not value) then
return "Usage: !set var_name value"
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hset(hash, name, value)
return '('..name..')\n تم اضافه الرد ☑️ '
end
end
local function del_value(msg, name)
if not name then
return
end
local hash = nil
if msg.to.type == 'chat' or msg.to.type == 'channel' then
hash = 'chat:bot:variables'
end
if hash then
redis:hdel(hash, name)
return '('..name..')\n تم حذف الرد ☑️ '
end
end
local function delallchats(msg)
local hash = 'chat:bot:variables'
if hash then
local names = redis:hkeys(hash)
for i=1, #names do
redis:hdel(hash,names[i])
end
return "saved!"
else
return
end
end
local function run(msg, matches)
if is_sudo(msg) then
local name = matches[3]
local value = matches[4]
if matches[2] == 'حذف الجميع' then
local output = delallchats(msg)
return output
end
if matches[2] == 'اضف' then
local name1 = user_print_name(msg.from)
savelog(msg.to.id, name1.." ["..msg.from.id.."] saved ["..name.."] as > "..value )
local text = save_value(msg, name, value)
return text
elseif matches[2] == 'حذف' then
local text = del_value(msg,name)
return text
end
end
if matches[1] == 'الردود' then
local output = list_chats(msg)
return output
else
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /get ".. matches[1])-- save to logs
local text = get_value(msg, matches[1])
return reply_msg(msg.id,text,ok_cb,false)
end
end
return {
patterns = {
"^(الردود)$",
"^(رد) (اضف) ([^%s]+) (.+)$",
"^(رد) (حذف الجميع)$",
"^(رد) (حذف) (.*)$",
"^(.+)$",
},
run = run
}
-- @TH3BOSS
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Waughroon_Shrine/bcnms/rank_2_mission.lua | 9 | 1653 | -----------------------------------
-- Rank 2 Mission
-- Waughroon Shrine mission battlefield
-- !pos -345 104 -260 144
-----------------------------------
require("scripts/globals/battlefield")
require("scripts/globals/keyitems")
require("scripts/globals/missions")
require("scripts/globals/npc_util")
-----------------------------------
function onBattlefieldTick(battlefield, tick)
dsp.battlefield.onBattlefieldTick(battlefield, tick)
end
function onBattlefieldRegister(player, battlefield)
end
function onBattlefieldEnter(player, battlefield)
end
function onBattlefieldLeave(player, battlefield, leavecode)
if leavecode == dsp.battlefield.leaveCode.WON then
local name, clearTime, partySize = battlefield:getRecord()
local arg8 = player:hasCompletedMission(player:getNation(), 5) and 1 or 0
player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 1, battlefield:getLocalVar("[cs]bit"), arg8)
elseif leavecode == dsp.battlefield.leaveCode.LOST then
player:startEvent(32002)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
if csid == 32001 then
if
(
player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_THREE_KINGDOMS_BASTOK2 or
player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.JOURNEY_TO_BASTOK2
) and
player:getCharVar("MissionStatus") == 10
then
npcUtil.giveKeyItem(player, dsp.ki.KINDRED_CREST)
player:setCharVar("MissionStatus", 11)
end
end
end
| gpl-3.0 |
Lsty/ygopro-scripts | c75043725.lua | 9 | 1291 | --冥界の使者
function c75043725.initial_effect(c)
--search
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(75043725,0))
e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c75043725.condition)
e1:SetTarget(c75043725.target)
e1:SetOperation(c75043725.operation)
c:RegisterEffect(e1)
end
function c75043725.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c75043725.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c75043725.filter(c)
return c:IsLevelBelow(3) and c:IsType(TYPE_NORMAL) and c:IsAbleToHand()
end
function c75043725.operation(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g1=Duel.SelectMatchingCard(tp,c75043725.filter,tp,LOCATION_DECK,0,1,1,nil)
local tc1=g1:GetFirst()
Duel.Hint(HINT_SELECTMSG,1-tp,HINTMSG_ATOHAND)
local g2=Duel.SelectMatchingCard(1-tp,c75043725.filter,tp,0,LOCATION_DECK,1,1,nil)
local tc2=g2:GetFirst()
g1:Merge(g2)
Duel.SendtoHand(g1,nil,REASON_EFFECT)
if tc1 then Duel.ConfirmCards(1-tp,tc1) end
if tc2 then Duel.ConfirmCards(tp,tc2) end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c91559748.lua | 3 | 1212 | --棘の妖精
function c91559748.initial_effect(c)
--change position
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(91559748,0))
e1:SetCategory(CATEGORY_POSITION)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_DAMAGE_STEP_END)
e1:SetCondition(c91559748.cpcon)
e1:SetTarget(c91559748.cptg)
e1:SetOperation(c91559748.cpop)
c:RegisterEffect(e1)
--cannot be battle target
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e2:SetRange(LOCATION_MZONE)
e2:SetTargetRange(0,LOCATION_MZONE)
e2:SetValue(c91559748.tg)
c:RegisterEffect(e2)
end
function c91559748.tg(e,c)
return c:IsFaceup() and c:IsRace(RACE_INSECT)
end
function c91559748.cpcon(e,tp,eg,ep,ev,re,r,rp)
local t=e:GetHandler():GetBattleTarget()
e:SetLabelObject(t)
return t and t:IsRelateToBattle()
end
function c91559748.cptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_POSITION,e:GetLabelObject(),1,0,0)
end
function c91559748.cpop(e,tp,eg,ep,ev,re,r,rp)
local g=e:GetLabelObject()
if g:IsRelateToBattle() and g:IsAttackPos() then
Duel.ChangePosition(g,POS_FACEUP_DEFENCE)
end
end
| gpl-2.0 |
mati865/vlc | share/lua/playlist/googlevideo.lua | 113 | 2746 | --[[
$Id$
Copyright © 2007 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function get_url_param( url, name )
local _,_,ret = string.find( url, "[&?]"..name.."=([^&]*)" )
return ret
end
-- Probe function.
function probe()
return vlc.access == "http"
and string.match( vlc.path, "video.google.com" )
and ( string.match( vlc.path, "videoplay" )
or string.match( vlc.path, "videofeed" ) )
end
function get_arg( line, arg )
return string.gsub( line, "^.*"..arg.."=\"(.-)\".*$", "%1" )
end
-- Parse function.
function parse()
local docid = get_url_param( vlc.path, "docid" )
if string.match( vlc.path, "videoplay" ) then
return { { path = "http://video.google.com/videofeed?docid=" .. docid } }
elseif string.match( vlc.path, "videofeed" ) then
local path = nil
local arturl
local duration
local name
local description
while true
do
local line = vlc.readline()
if not line then break end
if string.match( line, "media:content.*flv" )
then
local _,_,s = string.find( line, "<media:content(.-)/>" )
path = vlc.strings.resolve_xml_special_chars(get_arg( s, "url" ))
duration = get_arg( s, "duration" )
end
if string.match( line, "media:thumbnail" )
then
local _,_,s = string.find( line, "<media:thumbnail(.-)/>" )
arturl = vlc.strings.resolve_xml_special_chars(get_arg( s, "url" ))
end
if string.match( line, "media:title" )
then
_,_,name = string.find( line, "<media:title>(.-)</media:title>" )
end
if string.match( line, "media:description" )
then
_,_,description = string.find( line, "<media:description>(.-)</media:description>" )
end
end
return { { path = path; name = name; arturl = arturl; duration = duration; description = description } }
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c98358303.lua | 5 | 2550 | --静寂のサイコウィッチ
function c98358303.initial_effect(c)
--remove
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(98358303,0))
e1:SetCategory(CATEGORY_REMOVE)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e1:SetCode(EVENT_TO_GRAVE)
e1:SetCondition(c98358303.rmcon)
e1:SetTarget(c98358303.rmtg)
e1:SetOperation(c98358303.rmop)
c:RegisterEffect(e1)
--special summon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(98358303,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e2:SetRange(LOCATION_GRAVE)
e2:SetCountLimit(1)
e2:SetCode(EVENT_PHASE+PHASE_STANDBY)
e2:SetCondition(c98358303.spcon)
e2:SetTarget(c98358303.sptg)
e2:SetOperation(c98358303.spop)
e2:SetLabelObject(e1)
c:RegisterEffect(e2)
end
function c98358303.rmcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsReason(REASON_DESTROY)
and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c98358303.filter(c)
return c:IsAttackBelow(2000) and c:IsRace(RACE_PSYCHO) and c:IsAbleToRemove()
end
function c98358303.rmtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c98358303.filter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_REMOVE,nil,1,tp,LOCATION_DECK)
end
function c98358303.rmop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectMatchingCard(tp,c98358303.filter,tp,LOCATION_DECK,0,1,1,nil)
local tc=g:GetFirst()
local c=e:GetHandler()
if tc then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
if c:IsRelateToEffect(e) then
c:RegisterFlagEffect(98358303,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,2)
tc:RegisterFlagEffect(98358303,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,2)
e:SetLabelObject(tc)
end
end
end
function c98358303.spcon(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject():GetLabelObject()
local c=e:GetHandler()
return tc and Duel.GetTurnCount()~=tc:GetTurnID()
and c:GetFlagEffect(98358303)~=0 and tc:GetFlagEffect(98358303)~=0
end
function c98358303.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
local tc=e:GetLabelObject():GetLabelObject()
if chk==0 then return tc:IsCanBeSpecialSummoned(e,0,tp,false,false) end
tc:CreateEffectRelation(e)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,tc,1,0,0)
end
function c98358303.spop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetLabelObject():GetLabelObject()
if tc:IsRelateToEffect(e) then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Frenzie/koreader | spec/unit/persist_spec.lua | 4 | 4690 | describe("Persist module", function()
local Persist
local sample
local bitserInstance, luajitInstance, zstdInstance, dumpInstance, serpentInstance
local fail = { a = function() end, }
local function arrayOf(n)
assert(type(n) == "number", "wrong type (expected number)")
local t = {}
for i = 1, n do
table.insert(t, i, {
a = "sample " .. tostring(i),
b = true,
c = nil,
d = i,
e = {
f = {
g = nil,
h = false,
},
},
})
end
return t
end
setup(function()
require("commonrequire")
Persist = require("persist")
bitserInstance = Persist:new{ path = "test.dat", codec = "bitser" }
luajitInstance = Persist:new{ path = "testj.dat", codec = "luajit" }
zstdInstance = Persist:new{ path = "test.zst", codec = "zstd" }
dumpInstance = Persist:new{ path = "test.lua", codec = "dump" }
serpentInstance = Persist:new{ path = "tests.lua", codec = "serpent" }
sample = arrayOf(1000)
end)
it("should save a table to file", function()
assert.is_true(bitserInstance:save(sample))
assert.is_true(luajitInstance:save(sample))
assert.is_true(zstdInstance:save(sample))
assert.is_true(dumpInstance:save(sample))
assert.is_true(serpentInstance:save(sample))
end)
it("should generate a valid file", function()
assert.is_true(bitserInstance:exists())
assert.is_true(bitserInstance:size() > 0)
assert.is_true(type(bitserInstance:timestamp()) == "number")
assert.is_true(luajitInstance:exists())
assert.is_true(luajitInstance:size() > 0)
assert.is_true(type(luajitInstance:timestamp()) == "number")
assert.is_true(zstdInstance:exists())
assert.is_true(zstdInstance:size() > 0)
assert.is_true(type(zstdInstance:timestamp()) == "number")
end)
it("should load a table from file", function()
assert.are.same(sample, bitserInstance:load())
assert.are.same(sample, luajitInstance:load())
assert.are.same(sample, zstdInstance:load())
assert.are.same(sample, dumpInstance:load())
assert.are.same(sample, serpentInstance:load())
end)
it("should delete the file", function()
bitserInstance:delete()
luajitInstance:delete()
zstdInstance:delete()
dumpInstance:delete()
serpentInstance:delete()
assert.is_nil(bitserInstance:exists())
assert.is_nil(luajitInstance:exists())
assert.is_nil(zstdInstance:exists())
assert.is_nil(dumpInstance:exists())
assert.is_nil(serpentInstance:exists())
end)
it("should return standalone serializers/deserializers", function()
local tab = sample
-- NOTE: zstd only deser from a *file*, not a string.
for _, codec in ipairs({"dump", "serpent", "bitser", "luajit"}) do
assert.is_true(Persist.getCodec(codec).id == codec)
local ser = Persist.getCodec(codec).serialize
local deser = Persist.getCodec(codec).deserialize
local str = ser(tab)
local t, err = deser(str)
if not t then
print(codec, "deser failed:", err)
end
assert.are.same(t, tab)
end
end)
it("should work with huge tables", function()
local tab = arrayOf(100000)
for _, codec in ipairs({"bitser", "luajit"}) do
local ser = Persist.getCodec(codec).serialize
local deser = Persist.getCodec(codec).deserialize
local str = ser(tab)
assert.are.same(deser(str), tab)
end
end)
it("should fail to serialize functions", function()
for _, codec in ipairs({"dump", "bitser", "luajit", "zstd"}) do
assert.is_true(Persist.getCodec(codec).id == codec)
local ser = Persist.getCodec(codec).serialize
local deser = Persist.getCodec(codec).deserialize
local str = ser(fail)
assert.are_not.same(deser(str), fail)
end
end)
it("should successfully serialize functions", function()
for _, codec in ipairs({"serpent"}) do
assert.is_true(Persist.getCodec(codec).id == codec)
local ser = Persist.getCodec(codec).serialize
local deser = Persist.getCodec(codec).deserialize
local str = ser(fail)
assert.are_not.same(deser(str), fail)
end
end)
end)
| agpl-3.0 |
Xasin/TRRIAN | LUA/FactorioLayout/piecelist.lua | 1 | 4277 | require "piece"
deltaplus = 0;
deltaminus = 0;
local cWinner = nil;
local cHeur = 1000000000000;
winnerT = os.time();
newWinner = false;
-- Search through a piece-list and get the best piece-list
function get_best_piece(self)
local bestHeu = 10000000000000;
local bestV = nil;
for k,v in pairs(self) do
if(type(v) == "table" and (v.routes:get_heuristic() <= bestHeu)) then
bestHeu = v.routes:get_heuristic();
bestV = v;
end
end
return bestV;
end
-- Search through the piece-list and try to find a winner
function get_winner_piece(self)
return cWinner or false;
end
-- Insert a new part into the list
function insert(self, piece)
if(piece.routes:all_at_goal() and piece:get_heuristic(1) < cHeur) then
cWinner = piece;
cHeur = piece:get_heuristic(1);
winnerT = os.time();
newWinner = true;
-- Only insert piece if it is actually worth it
elseif(self:get_winner() and self:get_winner():get_heuristic(1) <= piece:get_heuristic(1)) then
return;
end
deltaplus = deltaplus + 1;
local i = 1;
while true do
if(self[i] == nil) then
self[i] = piece;
break;
end
i = i+1;
end
end
-- Remove a part from the list
function remove(self, piece)
deltaminus = deltaminus + 1;
for k,i in pairs(self) do
if(i == piece) then
self[k] = nil;
end
end
end
-- Return the length of this list
function list_length(piecelist)
local i = 0
for k, d in pairs(piecelist) do
if(type(d) == "table") then
i = i + 1
end
end
return i;
end
-- Expand a route to contain all combinations of conveyor belts
function expand_route_belts(self, piece, r)
local route = piece.routes:get(r);
local dX, dY = dir_offset(route.head.r);
local pX, pY = route.head.x + dX, route.head.y + dY;
for i = 0, 3 do
newobject = piece:copy();
if(newobject.map:place_if_viable(pX, pY, "belt", i)) then
newobject.routes:continue(r, pX, pY, i, 1, 1)
insert(self, newobject);
end
end
end
-- Expand a route to contain all combinations of underground belts
function expand_route_ubelts(self, piece, r)
local route = piece.routes:get(r);
local dX, dY = dir_offset(route.head.r);
local pX, pY = route.head.x + dX, route.head.y + dY;
for i = 2, 6 do
newobject = piece:copy();
if(newobject.map:place_if_viable(pX, pY, "underground_belt", route.head.r, i)) then
newobject.routes:continue(r, pX + dX * i, pY + dY * i, route.head.r, i, 8);
insert(self, newobject);
end
end
end
-- Expand a specific piece route!
function expand_piece_route(self, piece, r)
expand_route_belts(self, piece, r);
expand_route_ubelts(self, piece, r);
end
-- Expand a piece!
function expand_piece(self, piece)
remove(self, piece)
if(self:get_winner() and piece:get_heuristic(1) > self:get_winner():get_heuristic(1)) then
return;
end
for k,v in pairs(piece.routes.data) do
if(type(v) == "table" and (not piece.routes:route_at_goal(k))) then
expand_piece_route(self, piece, k);
end
end
end
-- Just expand the best piece
function expand_best_piece(self)
expand_piece(self, get_best_piece(self));
end
-- Iterate through a set until you get a winner!
function iterate_until_winner(self, timeout)
timeout = timeout or 30;
local maxTime = os.time() + timeout;
while(os.time() < maxTime and not self:get_winner() and #self ~= 0) do
self:expand_best();
end
return self:get_winner();
end
-- Iterate through a set until you are either empty or reach the timeout. Used for post-processing of a path.
function iterate_until_timeout(self, timeout)
timeout = timeout or 10;
local maxTime = os.time() + timeout;
while(os.time() < maxTime and not self:get_winner() and #self ~= 0) do
self:expand_best();
end
return self:get_winner();
end
-- Generate a new piecelist
function new_piecelist()
cWinner = nil;
cHeur = 100000000;
winnerT = os.time();
newWinner = false;
local newobject = {}
newobject["insert"] = insert;
newobject["remove"] = remove;
newobject["get_best"] = get_best_piece;
newobject["get_winner"] = get_winner_piece;
newobject["expand"] = expand_piece;
newobject["expand_best"] = expand_best_piece;
newobject["iterate_until_timeout"] = iterate_until_timeout;
newobject["iterate_until_winner"] = iterate_until_winner;
setmetatable(newobject, {_len = list_length});
return newobject;
end
| gpl-3.0 |
GovanifY/Polycode | Examples/Lua/Game_Demos/DemoPlatformer/Scripts/Main.lua | 10 | 2640 |
require "Scripts/Player"
require "Scripts/Alien"
music = Sound("Resources/music/level1.ogg")
music:Play(true)
Services.MaterialManager.premultiplyAlphaOnLoad = true
scene = PhysicsScene2D(1.0, 60)
scene:setGravity(Vector2(0.0, -30.0))
scene:getDefaultCamera():setOrthoSize(0, 14)
level = SceneEntityInstance(scene, "Resources/entities/level.entity")
scene:addChild(level)
playerBody = level:getEntityById("player", true)
player = Player(scene, playerBody)
alienBodies = level:getEntitiesByTag("alien", false)
aliens = {}
for i=1,count(alienBodies) do
local alien = Alien(scene, alienBodies[i], player)
aliens[i] = alien
alien:Respawn()
end
shootTimer = 0.0
platforms = level:getEntitiesByTag("platform", false)
for i=1,count(platforms) do
scene:trackPhysicsChild(platforms[i], PhysicsScene2DEntity.ENTITY_RECT, true, 2.0, 1, 0, false, false)
end
shots = level:getEntitiesByTag("shot", false)
shotDirections = {}
for i=1,count(shots) do
shots[i] = safe_cast(shots[i], SceneSprite)
scene:trackCollisionChild(shots[i], PhysicsScene2DEntity.ENTITY_RECT, -1)
shots[i].backfaceCulled = false
shotDirections[i] = 0.0
end
shotIndex = 1
function onKeyDown(key)
player:onKeyDown(key)
end
function onCollision(t, event)
local physicsEvent = safe_cast(event, PhysicsScene2DEvent)
for i=1,count(shots) do
if physicsEvent.entity2 == shots[i] or physicsEvent.entity1 == shots[i] then
for j=1,count(aliens) do
if aliens[j].body == physicsEvent.entity1 or aliens[j].body == physicsEvent.entity2 then
aliens[j].dead = true
if shots[i]:getPosition().x > aliens[j].body:getPosition().x then
aliens[j].physicsBody:applyImpulse(-230.0, 0.0)
else
aliens[j].physicsBody:applyImpulse(230.0, 0.0)
end
end
end
shots[i]:setPositionX(1000.0)
end
end
end
scene:addEventListener(nil, onCollision, PhysicsScene2DEvent.EVENT_NEW_SHAPE_COLLISION)
function Update(elapsed)
player:Update(elapsed)
shootTimer = shootTimer + elapsed
if Services.Input:getKeyState(KEY_x) then
if shootTimer > 0.15 then
shotDirections[shotIndex] = player:Shoot(shots[shotIndex])
shotIndex = shotIndex +1
if shotIndex > count(shots) then shotIndex = 1 end
shootTimer = 0.0
end
else
shootTimer = 100.0
end
end
function fixedUpdate()
local elapsed = Services.Core:getFixedTimestep()
player:fixedUpdate(elapsed)
for i=1,count(aliens) do
aliens[i]:Update(elapsed)
end
for i=1,count(shots) do
shots[i]:setRoll(shotDirections[i])
shots[i]:Translate(elapsed * 18.0 * cos(shotDirections[i] * 0.0174532925), elapsed * 18.0 * sin(shotDirections[i] * 0.0174532925), 0.0)
end
end | mit |
MalRD/darkstar | scripts/globals/mobskills/final_sting.lua | 10 | 1275 | ---------------------------------------------
-- Final Sting
--
-- Description: Deals damage proportional to HP. Reduces HP to 1 after use. Damage varies with TP.
-- Type: Physical (Slashing)
--
--
---------------------------------------------
require("scripts/globals/settings")
require("scripts/globals/status")
require("scripts/globals/monstertpmoves")
---------------------------------------------
function onMobSkillCheck(target,mob,skill)
local param = skill:getParam()
if (param == 0) then
param = 50
end
if (mob:getHPP() <= param) then
return 0
end
return 1
end
function onMobWeaponSkill(target, mob, skill)
local numhits = 1
local accmod = 1
local dmgmod = 1
local mobHP = mob:getHP()
local hpMod = skill:getMobHPP() / 100
dmgmod = dmgmod + hpMod * 14 + math.random(2,6)
if (mob:isMobType(MOBTYPE_NOTORIOUS)) then
dmgmod = dmgmod * 5
end
mob:setHP(0)
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,1,2,3)
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded)
target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING)
return dmg
end
| gpl-3.0 |
MalRD/darkstar | scripts/zones/AlTaieu/npcs/qm1.lua | 12 | 1121 | -----------------------------------
-- Area: Al'Taieu
-- NPC: ??? (Jailer of Hope Spawn)
-- Allows players to spawn the Jailer of Hope by trading the First Virtue, Deed of Placidity and HQ Phuabo Organ to a ???.
-- !pos -693 -1 -62 33
-----------------------------------
local ID = require("scripts/zones/AlTaieu/IDs");
-----------------------------------
function onTrade(player,npc,trade)
-- JAILER OF HOPE
if (
not GetMobByID(ID.mob.JAILER_OF_HOPE):isSpawned() and
trade:hasItemQty(1850,1) and -- first_virtue
trade:hasItemQty(1851,1) and -- deed_of_placidity
trade:hasItemQty(1852,1) and -- high-quality_phuabo_organ
trade:getItemCount() == 3
) then
player:tradeComplete();
SpawnMob(ID.mob.JAILER_OF_HOPE):updateClaim(player);
end
end;
function onTrigger(player,npc)
end;
function onEventUpdate(player,csid,option)
-- printf("onUpdate CSID: %u",csid);
-- printf("onUpdate RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("onFinish CSID: %u",csid);
-- printf("onFinish RESULT: %u",option);
end;
| gpl-3.0 |
morfeo642/mta_plr_server | module/protocol/net/client.lua | 1 | 6335 |
--[[!
\file
\brief Es un módulo con utilidades para el paso de mensaje cliente/servidor.
\code
-- Registrar un método para que pueda ser invocado por el servidor remotamente.
function __client.sayHello()
outputChatBox("Hallo!");
end;
-- Permitir que el servidor pueda ejecutar todas las funciones del cliente.
__client = _G;
\endcode
\code
-- Invoca una función del servidor llamada foo() con los argumentos ...
__server.foo(nil, ...);
-- Invoca la misma función pero queriendo recibir los valores de retorno de
la función.
__server.foo(function(...) outputDebugString(...); end, ...);
-- Como podemos comprobar si en el cuerpo de la función hubo un aserto o algún error?
__server.foo(
function(success, ...)
local args = {...};
if success then -- La ejecución es satisfactoria.
-- La tabla {...} contedrá los valores de retorno de la función.
print(args);
else -- Error.
-- El siguiente parámetro es un mensaje indicado la descripción del error.
print("Error: " .. args[1]);
end;
end, ...);
\endcode
]]
loadModule("util/assertutils");
--[[! Esta tabla guarda todas las funciones que puede ser llamadas por el servidor ]]
__client = {};
--[[ Guardaremos los callbacks en una tabla auxiliar ]]
local __client_callbacks = {};
local __callback = {};
local __count = {};
setmetatable(__client_callbacks,
{
__newindex =
function(t, index, value)
if not __count[index] then
__count[index] = 1;
__callback[index] = value;
else
__count[index] = __count[index] + 1;
end;
end,
__index =
function(t, index)
-- "usamos" el callback una vez.
__count[index] = __count[index] - 1;
local callback = __callback[index];
if __count[index] == 0 then __count[index] = nil; __callback[index] = nil; end;
return callback;
end
});
--[[! Esta tabla sirve para invocar un método del servidor.
__server.func_name. Para invocar la función, la sintaxis es: __server.func_name(callback, ...)
Donde ... son los argumentos que se pasarán a la función del servidor.
Callback, en caso de error (si la función no existe o bién se lanzó una asercción en el cuerpo de la función en la
parte del servidor), obtendrá los siguientes argumentos: false, msg (mensaje sobre el error producido).
En el caso de que se haya invocado correctamente el método, se recibirá lo siguiente: true, ... Donde ... son los valores
de retorno de la función.
]]
__server = {};
setmetatable(__server,
{
__metatable = false,
__newindex = function() end,
__index =
function(t, index)
local serverFunc = index;
return
function(funcCallback, ...)
localizedAssert((type(funcCallback) == "function") or (funcCallback == nil), 2, "Invalid arguments");
if not funcCallback then
-- invocar método del servidor.
triggerServerEvent("onClientCallServerFunction", resourceRoot, serverFunc, nil, ...);
else
-- Registrar el callback para la respuesta del servidor.
__client_callbacks[tostring(funcCallback)] = funcCallback;
-- invocar método del servidor.
triggerServerEvent("onClientCallServerFunction", resourceRoot, serverFunc, tostring(funcCallback), ...);
end;
end;
end
});
--[[!Es una tabla que permite invocar un método de un cliente remoto. ]]
__remote_client = {};
setmetatable(__remote_client,
{
__metatable = false,
__newindex = function() end,
__index =
function(t, index)
localizedAssert(isElement(index) and (getElementType(index) == "player") and (index ~= localPlayer), 2, "Invalid remote client");
--localizedAssert(isElement(index) and (getElementType(index) == "player"), 2, "Invalid remote client");
local remoteClient = index;
return
setmetatable({},
{
__metatable = false,
__newindex = function() end,
__index =
function(t, index)
local remoteClientFunc = index;
return
function(funcCallback, ...)
localizedAssert((type(funcCallback) == "function") or (funcCallback == nil),2, "Invalid arguments");
if not funcCallback then
triggerServerEvent("onClientCallRemoteClientFunction", resourceRoot, remoteClient, remoteClientFunc, nil, ...);
else
-- Registrar callback
__client_callbacks[tostring(funcCallback)] = funcCallback;
triggerServerEvent("onClientCallRemoteClientFunction", resourceRoot, remoteClient, remoteClientFunc, tostring(funcCallback), ...);
end;
end;
end
});
end
});
--[[ Esta es una tabla auxiliar que accede solamente a las funciones y elementos invocables de la tabla
__client ]]
local __client_funcs = {};
setmetatable(__client_funcs,
{
__metatable = false,
__newindex = function() end,
__index =
function(t, index)
local value = __client[index];
if (type(value) == "function") or
((type(value) == "table") and (getmetatable(value) ~= nil) and (type(getmetatable(value).__call) == "function")) then
return value;
end
end
});
local function call_func(funcName, ...)
local func = assert(__client_funcs[funcName], "Function \"" .. funcName .. "\" not exists");
return func(...);
end;
--[[ Que hacemos cuando el servidor invoca una de las funciones del cliente ? ]]
addEvent("onServerCallClientFunction", true);
addEventHandler("onServerCallClientFunction", resourceRoot,
function(func, funcCallback, ...)
if not funcCallback then
pcall(call_func, func, ...);
else
triggerServerEvent("onServerCallClientFunctionResponse", resourceRoot, funcCallback, pcall(call_func, func, ...));
end;
end);
--[[ Que hacemos cuando recibimos la respuesta del servidor ? ]]
addEvent("onClientCallServerFunctionResponse", true);
addEventHandler("onClientCallServerFunctionResponse", resourceRoot,
function(funcCallback, ...)
__client_callbacks[funcCallback](...);
end);
--[[ Que hacemos cuando recibimos la respuesta del servidor de la ejecución de una función de un cliente remoto ? ]]
addEvent("onClientCallRemoteClientFunctionResponse", true);
addEventHandler("onClientCallRemoteClientFunctionResponse", resourceRoot,
function(remoteClient, funcCallback, ...)
__client_callbacks[funcCallback](...);
end);
| mit |
SmartArduino/nodemcu-firmware | lua_modules/http/http-example.lua | 88 | 1377 | ------------------------------------------------------------------------------
-- HTTP server Hello world example
--
-- LICENCE: http://opensource.org/licenses/MIT
-- Vladimir Dronnikov <dronnikov@gmail.com>
------------------------------------------------------------------------------
require("http").createServer(80, function(req, res)
-- analyse method and url
print("+R", req.method, req.url, node.heap())
-- setup handler of headers, if any
req.onheader = function(self, name, value)
-- print("+H", name, value)
-- E.g. look for "content-type" header,
-- setup body parser to particular format
-- if name == "content-type" then
-- if value == "application/json" then
-- req.ondata = function(self, chunk) ... end
-- elseif value == "application/x-www-form-urlencoded" then
-- req.ondata = function(self, chunk) ... end
-- end
-- end
end
-- setup handler of body, if any
req.ondata = function(self, chunk)
print("+B", chunk and #chunk, node.heap())
-- request ended?
if not chunk then
-- reply
--res:finish("")
res:send(nil, 200)
res:send_header("Connection", "close")
res:send("Hello, world!")
res:finish()
end
end
-- or just do something not waiting till body (if any) comes
--res:finish("Hello, world!")
--res:finish("Salut, monde!")
end)
| mit |
MalRD/darkstar | scripts/zones/Ranguemont_Pass/npcs/Waters_of_Oblivion.lua | 9 | 1460 | -----------------------------------
-- Area: Ranguemont Pass
-- NPC: Waters of Oblivion
-- Finish Quest: Painful Memory (BARD AF1)
-- !pos -284 -45 210 166
-----------------------------------
local ID = require("scripts/zones/Ranguemont_Pass/IDs");
require("scripts/globals/keyitems");
require("scripts/globals/npc_util");
require("scripts/globals/quests");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
TrosKilled = player:getCharVar("TrosKilled");
if (player:hasKeyItem(dsp.ki.MERTAIRES_BRACELET) and
not GetMobByID(ID.mob.TROS):isSpawned() and
(TrosKilled == 0 or (os.time() - player:getCharVar("Tros_Timer")) > 60)
) then
player:messageSpecial(ID.text.SENSE_OF_FOREBODING);
SpawnMob(ID.mob.TROS):updateClaim(player);
elseif (player:hasKeyItem(dsp.ki.MERTAIRES_BRACELET) and TrosKilled == 1) then
player:startEvent(8); -- Finish Quest "Painful Memory"
else
player:messageSpecial(ID.text.NOTHING_OUT_OF_ORDINARY);
end
end;
function onEventUpdate(player,csid,option)
end;
function onEventFinish(player,csid,option)
if (csid == 8) then
if (npcUtil.completeQuest(player, JEUNO, dsp.quest.id.jeuno.PAINFUL_MEMORY, {item=16766})) then
player:delKeyItem(dsp.ki.MERTAIRES_BRACELET);
player:setCharVar("TrosKilled",0);
player:setCharVar("Tros_Timer",0);
end
end
end;
| gpl-3.0 |
MalRD/darkstar | scripts/globals/items/slice_of_roast_mutton.lua | 11 | 1089 | -----------------------------------------
-- ID: 4437
-- Item: slice_of_roast_mutton
-- Food Effect: 180Min, All Races
-----------------------------------------
-- Strength 3
-- Intelligence -1
-- Attack % 27
-- Attack Cap 30
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4437)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.STR, 3)
target:addMod(dsp.mod.INT, -1)
target:addMod(dsp.mod.FOOD_ATTP, 27)
target:addMod(dsp.mod.FOOD_ATT_CAP, 30)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.STR, 3)
target:delMod(dsp.mod.INT, -1)
target:delMod(dsp.mod.FOOD_ATTP, 27)
target:delMod(dsp.mod.FOOD_ATT_CAP, 30)
end
| gpl-3.0 |
Lsty/ygopro-scripts | c5929801.lua | 3 | 2660 | --RR-ファジー・レイニアス
function c5929801.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_HAND)
e1:SetCountLimit(1,5929801)
e1:SetCondition(c5929801.spcon)
e1:SetCost(c5929801.cost)
e1:SetTarget(c5929801.sptg)
e1:SetOperation(c5929801.spop)
c:RegisterEffect(e1)
--to hand
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetProperty(EFFECT_FLAG_DELAY)
e2:SetCountLimit(1,5929802)
e2:SetCost(c5929801.cost)
e2:SetTarget(c5929801.thtg)
e2:SetOperation(c5929801.thop)
c:RegisterEffect(e2)
Duel.AddCustomActivityCounter(5929801,ACTIVITY_SPSUMMON,c5929801.counterfilter)
end
function c5929801.counterfilter(c)
return c:IsSetCard(0xba)
end
function c5929801.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetCustomActivityCount(5929801,tp,ACTIVITY_SPSUMMON)==0 end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_OATH)
e1:SetTargetRange(1,0)
e1:SetTarget(c5929801.splimit)
e1:SetReset(RESET_PHASE+RESET_END)
Duel.RegisterEffect(e1,tp)
end
function c5929801.splimit(e,c,sump,sumtype,sumpos,targetp,se)
return not c:IsSetCard(0xba)
end
function c5929801.cfilter(c)
return c:IsFaceup() and c:IsSetCard(0xba) and not c:IsCode(5929801)
end
function c5929801.spcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.IsExistingMatchingCard(c5929801.cfilter,tp,LOCATION_MZONE,0,1,nil)
end
function c5929801.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c5929801.spop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) then
Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP)
end
end
function c5929801.thfilter(c)
return c:IsCode(5929801) and c:IsAbleToHand()
end
function c5929801.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c5929801.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c5929801.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c5929801.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c34815282.lua | 5 | 2357 | --ミニチュアライズ
function c34815282.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_ATKCHANGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(TIMING_DAMAGE_STEP,TIMING_DAMAGE_STEP+0x1c0)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e1:SetCondition(c34815282.condition)
e1:SetTarget(c34815282.target)
e1:SetOperation(c34815282.operation)
c:RegisterEffect(e1)
--Destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetCondition(c34815282.descon)
e2:SetOperation(c34815282.desop)
c:RegisterEffect(e2)
end
function c34815282.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or not Duel.IsDamageCalculated()
end
function c34815282.filter(c)
return c:IsFaceup() and c:GetBaseAttack()>1000 and c:GetLevel()>0
end
function c34815282.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c34815282.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c34815282.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c34815282.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
end
function c34815282.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsFaceup() and tc:IsRelateToEffect(e) then
c:SetCardTarget(tc)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_SINGLE_RANGE+EFFECT_FLAG_OWNER_RELATE)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(-1000)
e1:SetCondition(c34815282.rcon)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1,true)
local e2=e1:Clone()
e2:SetCode(EFFECT_UPDATE_LEVEL)
e2:SetValue(-1)
tc:RegisterEffect(e2,true)
end
end
function c34815282.rcon(e)
return e:GetOwner():IsHasCardTarget(e:GetHandler())
end
function c34815282.descon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsStatus(STATUS_DESTROY_CONFIRMED) then return false end
local tc=c:GetFirstCardTarget()
return tc and eg:IsContains(tc)
end
function c34815282.desop(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
| gpl-2.0 |
sagarwaghmare69/nn | Add.lua | 61 | 1699 | local Add, parent = torch.class('nn.Add', 'nn.Module')
function Add:__init(inputSize,scalar)
parent.__init(self)
local size = inputSize
if scalar then size=1 end
self.scalar = scalar
self.bias = torch.Tensor(size)
self.gradBias = torch.Tensor(size)
self._ones = torch.Tensor{1}
self:reset()
end
function Add:reset(stdv)
if stdv then
stdv = stdv * math.sqrt(3)
else
stdv = 1./math.sqrt(self.bias:size(1))
end
self.bias:uniform(-stdv, stdv)
end
function Add:updateOutput(input)
self.output:resizeAs(input):copy(input)
if self.scalar then
self.output:add(self.bias[1]);
else
if input:isSameSizeAs(self.bias) then
self.output:add(self.bias)
else
local batchSize = input:size(1)
if self._ones:size(1) ~= batchSize then
self._ones:resize(batchSize):fill(1)
end
local bias = self.bias:view(-1)
local output = self.output:view(batchSize, -1)
output:addr(1, self._ones, bias)
end
end
return self.output
end
function Add:updateGradInput(input, gradOutput)
if self.gradInput then
self.gradInput:resizeAs(gradOutput):copy(gradOutput)
return self.gradInput
end
end
function Add:accGradParameters(input, gradOutput, scale)
scale = scale or 1
if self.gradBias:size(1) == 1 then
self.gradBias[1] = self.gradBias[1] + scale*gradOutput:sum();
else
if input:isSameSizeAs(self.bias) then
self.gradBias:add(scale, gradOutput)
else
local gradOutput = gradOutput:view(input:size(1), -1)
self.gradBias:view(-1):addmv(scale, gradOutput:t(), self._ones)
end
end
end
| bsd-3-clause |
T-L-N/Dev_TLN | plugins/teqrar.lua | 1 | 7598 | --[[
_____ _ _ _ _____ Dev @lIMyIl
|_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il
| |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a
| |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22
|_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI
--]]
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- Save stats, ban user
local function pre_process(msg)
-- Ignore service msg
if msg.service then
return msg
end
if msg.from.id == our_id then
return msg
end
-- Save user on Redis
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id
print('Saving user', hash)
if msg.from.print_name then
redis:hset(hash, 'print_name', msg.from.print_name)
end
if msg.from.first_name then
redis:hset(hash, 'first_name', msg.from.first_name)
end
if msg.from.last_name then
redis:hset(hash, 'last_name', msg.from.last_name)
end
end
-- Save stats on Redis
if msg.to.type == 'chat' then
-- User is on chat
local hash = 'chat:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
redis:sadd(hash, msg.from.id)
end
-- Total user msgs
local hash = 'msgs:'..msg.from.id..':'..msg.to.id
redis:incr(hash)
--Load moderation data
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
--Check if flood is on or off
if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then
return msg
end
end
-- Check flood
if msg.from.type == 'user' then
local hash = 'user:'..msg.from.id..':msgs'
local msgs = tonumber(redis:get(hash) or 0)
local data = load_data(_config.moderation.data)
local NUM_MSG_MAX = 5
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'])--Obtain group flood sensitivity
end
end
local max_msg = NUM_MSG_MAX * 1
if msgs > max_msg then
local user = msg.from.id
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "🎛 | ممہٰٖنوع الہٰٖتكہٰٖرار |🔐😒 "..msg.from.first_name.."\n⚠️ | لہٰان لہٰحہٰيٰتہٰ هوايٰ😒🚶😹 |📛\n⚠️ | تہٰم دفہٰركہٰ من الہٰمجموعه لہٰانكہٰ فہٰرخ تہٰفہٰلہٰيٰش😹🌝 \n⚠️ | عبٰٰر بٰٰوتہٰ الہٰحہٰمايٰه |✔️ \n⚠️ | معرفہٰ الہٰعضو |👥 : @"..(msg.from.username or "لا يوجد " ).."⚜ |القہٰٖنہٰٖاه |✅\n : @Dev_TLN ") savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "⚠️ | ممنوع الہٰتہٰكہٰرار يٰا خراا😒🚶 |🗣 "..msg.from.first_name.."\n⚠️ | لہٰان لہٰحہٰيٰتہٰ هوايٰ😒🚶😹 |📛\n⚠️ | تہٰم دفہٰركہٰ من الہٰمجموعه لہٰانكہٰ فہٰرخ تہٰفہٰلہٰيٰش😹🌝 \n⚠️ | عبٰٰر بٰٰوتہٰ الہٰحہٰمايٰه |✔️ \n⚠️ | معرفہٰ الہٰعضو |👥 : @"..(msg.from.username or "لا يوجد " ).."\n⚠️ | الہٰقناه |🔰 : @Dev_TLN ")
else
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "🎛 | ممہٰٖنوع الہٰٖتكہٰٖرار |🔐😒 "..msg.from.first_name.."\n⚠️ | لہٰان لہٰحہٰيٰتہٰ هوايٰ😒🚶😹 |📛\n⚠️ | تہٰم دفہٰركہٰ من الہٰمجموعه لہٰانكہٰ فہٰرخ تہٰفہٰلہٰيٰش😹🌝 \n⚠️ | عبٰٰر بٰٰوتہٰ الہٰحہٰمايٰه |✔️ \n⚠️ | معرفہٰ الہٰعضو |👥 : @"..(msg.from.username or "لا يوجد " ).."⚜ |القہٰٖنہٰٖاه |✅\n : @Dev_TLN ") savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam") send_large_msg(receiver , "⚠️ | ممنوع الہٰتہٰكہٰرار يٰا خراا😒🚶 |🗣 "..msg.from.first_name.."\n⚠️ | لہٰان لہٰحہٰيٰتہٰ هوايٰ😒🚶😹 |📛\n⚠️ | تہٰم دفہٰركہٰ من الہٰمجموعه لہٰانكہٰ فہٰرخ تہٰفہٰلہٰيٰش😹🌝 \n⚠️ | عبٰٰر بٰٰوتہٰ الہٰحہٰمايٰه |✔️ \n⚠️ | معرفہٰ الہٰعضو |👥 : @"..(msg.from.username or "لا يوجد " ).."\n⚠️ | الہٰقناه |🔰 : @Dev_TLN ")
end
end
-- incr it on redis
local gbanspam = 'gban:spam'..msg.from.id
redis:incr(gbanspam)
local gbanspam = 'gban:spam'..msg.from.id
local gbanspamonredis = redis:get(gbanspam)
--Check if user has spammed is group more than 4 times
if gbanspamonredis then
if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then
--Global ban that user
banall_user(msg.from.id)
local gbanspam = 'gban:spam'..msg.from.id
--reset the counter
redis:set(gbanspam, 0)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
send_large_msg("channel#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." globally banned (spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
end
end
kicktable[user] = true
msg = nil
end
redis:setex(hash, TIME_CHECK, msgs+1)
end
return msg
end
local function cron()
--clear that table on the top of the plugins
kicktable = {}
end
return {
patterns = {},
cron = cron,
pre_process = pre_process
}
end
| gpl-2.0 |
tryroach/vlc | share/lua/intf/luac.lua | 116 | 2333 | --[==========================================================================[
luac.lua: lua compilation module for VLC (duplicates luac)
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
usage =
[[
To compile a lua script to bytecode (luac) run:
vlc -I luaintf --lua-intf --lua-config 'luac={input="file.lua",output="file.luac"}'
Output will be similar to that of the luac command line tool provided with lua with the following arguments:
luac -o file.luac file.lua
]]
require "string"
require "io"
function compile()
vlc.msg.info("About to compile lua file")
vlc.msg.info(" Input is '"..tostring(config.input).."'")
vlc.msg.info(" Output is '"..tostring(config.output).."'")
if not config.input or not config.output then
vlc.msg.err("Input and output config options must be set")
return false
end
local bytecode, msg = loadfile(config.input)
if not bytecode then
vlc.msg.err("Error while loading file '"..config.input.."': "..msg)
return false
end
local output, msg = io.open(config.output, "wb")
if not output then
vlc.msg.err("Error while opening file '"..config.output.."' for output: "..msg)
return false
else
output:write(string.dump(bytecode))
return true
end
end
if not compile() then
for line in string.gmatch(usage,"([^\n]+)\n*") do
vlc.msg.err(line)
end
end
vlc.misc.quit()
| gpl-2.0 |
mikhail-angelov/vlc | share/lua/intf/luac.lua | 116 | 2333 | --[==========================================================================[
luac.lua: lua compilation module for VLC (duplicates luac)
--[==========================================================================[
Copyright (C) 2010 Antoine Cellerier
$Id$
Authors: Antoine Cellerier <dionoea at videolan dot org>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]==========================================================================]
usage =
[[
To compile a lua script to bytecode (luac) run:
vlc -I luaintf --lua-intf --lua-config 'luac={input="file.lua",output="file.luac"}'
Output will be similar to that of the luac command line tool provided with lua with the following arguments:
luac -o file.luac file.lua
]]
require "string"
require "io"
function compile()
vlc.msg.info("About to compile lua file")
vlc.msg.info(" Input is '"..tostring(config.input).."'")
vlc.msg.info(" Output is '"..tostring(config.output).."'")
if not config.input or not config.output then
vlc.msg.err("Input and output config options must be set")
return false
end
local bytecode, msg = loadfile(config.input)
if not bytecode then
vlc.msg.err("Error while loading file '"..config.input.."': "..msg)
return false
end
local output, msg = io.open(config.output, "wb")
if not output then
vlc.msg.err("Error while opening file '"..config.output.."' for output: "..msg)
return false
else
output:write(string.dump(bytecode))
return true
end
end
if not compile() then
for line in string.gmatch(usage,"([^\n]+)\n*") do
vlc.msg.err(line)
end
end
vlc.misc.quit()
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Aydeewa_Subterrane/mobs/Pandemonium_Warden.lua | 9 | 7135 | -----------------------------------
-- Area: Aydeewa Subterrane
-- ZNM: Pandemonium Warden
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
local ID = require("scripts/zones/Aydeewa_Subterrane/IDs");
-- Pet Arrays, we'll alternate between phases
local petIDs = {};
petIDs[0] = {ID.mob.PANDEMONIUM_WARDEN +1, ID.mob.PANDEMONIUM_WARDEN +2, ID.mob.PANDEMONIUM_WARDEN +3, ID.mob.PANDEMONIUM_WARDEN +4, ID.mob.PANDEMONIUM_WARDEN +5, ID.mob.PANDEMONIUM_WARDEN +6, ID.mob.PANDEMONIUM_WARDEN +7, ID.mob.PANDEMONIUM_WARDEN +8};
petIDs[1] = {ID.mob.PANDEMONIUM_WARDEN +9, ID.mob.PANDEMONIUM_WARDEN +10, ID.mob.PANDEMONIUM_WARDEN +11, ID.mob.PANDEMONIUM_WARDEN +12, ID.mob.PANDEMONIUM_WARDEN +13, ID.mob.PANDEMONIUM_WARDEN +14, ID.mob.PANDEMONIUM_WARDEN +15, ID.mob.PANDEMONIUM_WARDEN +16};
-- Phase Arrays Dverg, Char1, Dverg, Char2, Dverg, Char3, Dverg, Char4, Dverg, Mamo, Dverg, Lamia, Dverg, Troll, Dverg, Cerb, Dverg, Hydra, Dverg, Khim, Dverg
-- 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
local triggerHPP = { 95, 1, 95, 1, 95, 1, 95, 1, 95, 1, 95, 1, 95, 1, 95, 1, 95, 1, 95, 1};
local mobHP = { 10000, 147000, 10000, 147000, 10000, 147000, 10000, 147000, 15000, 147000, 15000, 147000, 15000, 147000, 20000, 147000, 20000, 147000, 20000, 147000};
local mobModelID = { 1825, 1840, 1825, 1840, 1825, 1840, 1825, 1840, 1863, 1840, 1865, 1840, 1867, 1840, 1793, 1840, 1796, 1840, 1805, 1840};
local petModelID = { 1823, 1841, 1821, 1841, 1825, 1841, 1824, 1841, 1639, 1841, 1643, 1841, 1680, 1841, 281, 1841, 421, 1841, 1746, 1839};
local skillID = { 1000, 316, 1001, 316, 1002, 316, 1003, 316, 285, 316, 725, 316, 326, 316, 62, 316, 164, 316, 168, 316};
-- Avatar Arrays Shiva, Ramuh, Titan, Ifrit, Levia, Garud, Fenri, Carby
local avatarAbilities = { 917, 918, 914, 913, 915, 916, 839, 919};
local avatarSkins = { 22, 23, 19, 18, 20, 21, 17, 16};
function onMobSpawn(mob)
mob:setMod(dsp.mod.DEF, 450);
mob:setMod(dsp.mod.MEVA, 380);
mob:setMod(dsp.mod.MDEF, 50);
-- Make sure model is reset back to start
mob:setModelId(1840);
-- Prevent death and hide HP until final phase
mob:setUnkillable(true);
mob:hideHP(true);
-- Two hours to forced depop
mob:setLocalVar("PWDespawnTime", os.time() + 7200);
mob:setLocalVar("phase", 1);
mob:setLocalVar("astralFlow", 1);
end;
function onMobDisengage(mob)
-- Make sure model is reset back to start
mob:setModelId(1840);
mob:setMobMod(dsp.mobMod.SKILL_LIST, 316);
-- Prevent death and hide HP until final phase
mob:setUnkillable(true);
mob:hideHP(true);
-- Reset phases (but not despawn timer)
mob:setLocalVar("phase", 1);
mob:setLocalVar("astralFlow", 1);
-- Despawn pets
for i = 0, 1 do
for j = 1, 8 do
if GetMobByID(petIDs[i][j]):isSpawned() then
DespawnMob(petIDs[i][j]);
end
end
end
end;
function onMobEngaged(mob,target)
-- pop pets
for i = 1, 8 do
local pet = GetMobByID(petIDs[1][i]);
pet:setModelId(1841);
pet:spawn();
pet:updateEnmity(target);
end
end;
function onMobFight(mob,target)
-- Init Vars
local mobHPP = mob:getHPP();
local depopTime = mob:getLocalVar("PWDespawnTime");
local phase = mob:getLocalVar("phase");
local astral = mob:getLocalVar("astralFlow");
local pets = {};
for i = 0, 1 do
pets[i] = {};
for j = 1, 8 do
pets[i][j] = GetMobByID(petIDs[i][j]);
end
end
-- Check for phase change
if (phase < 21 and mobHPP <= triggerHPP[phase]) then
if (phase == 20) then -- Prepare for death
mob:hideHP(false);
mob:setUnkillable(false);
end
-- Change phase
mob:setTP(0);
mob:setModelId(mobModelID[phase]);
mob:setHP(mobHP[phase]);
mob:setMobMod(dsp.mobMod.SKILL_LIST,skillID[phase]);
-- Handle pets
for i = 1, 8 do
local oldPet = pets[phase % 2][i];
local newPet = pets[(phase - 1) % 2][i];
newPet:updateEnmity(target);
newPet:setMobMod(dsp.mobMod.MAGIC_DELAY,4);
handlePet(mob, newPet, oldPet, target, petModelID[phase]);
end
-- Increment phase
mob:setLocalVar("phase", phase + 1);
-- Or, check for Astral Flow
elseif (phase == 21 and astral < 9 and mobHPP <= (100 - 25 * astral)) then
for i = 1, 8 do
local oldPet = pets[astral % 2][i];
local newPet = pets[(astral - 1) % 2][i];
if i == 1 then
newPet:updateEnmity(target);
astralRand = math.random(1,8);
handlePet(mob, newPet, oldPet, target, avatarSkins[astralRand]);
newPet:useMobAbility(avatarAbilities[astralRand]);
else
handlePet(mob, newPet, oldPet, target, 1839);
end
end
-- Increment astral
mob:setLocalVar("astralFlow", astral + 1);
-- Or, at least make sure pets weren't drug off...
else
for i = 1, 8 do
local pet = nil;
if phase == 21 then
pet = pets[astral % 2][i];
else
pet = pets[phase % 2][i];
end
end
end
-- Check for time limit, too
if (os.time() > depopTime and mob:actionQueueEmpty() == true) then
for i = 0, 1 do
for j = 1, 8 do
if pets[i][j]:isSpawned() then
DespawnMob(petIDs[i][j]);
end
end
end
DespawnMob(ID.mob.PANDEMONIUM_WARDEN);
-- printf("Timer expired at %i. Despawning Pandemonium Warden.", depopTime);
end
end;
function onMobDeath(mob, player, isKiller)
player:addTitle(dsp.title.PANDEMONIUM_QUELLER);
-- Despawn pets
for i = 0, 1 do
for j = 1, 8 do
if GetMobByID(petIDs[i][j]):isSpawned() then
DespawnMob(petIDs[i][j]);
end
end
end
end;
function onMobDespawn(mob)
-- Despawn pets
for i = 0, 1 do
for j = 1, 8 do
if GetMobByID(petIDs[i][j]):isSpawned() then
DespawnMob(petIDs[i][j]);
end
end
end
end;
function handlePet(mob, newPet, oldPet, target, modelId)
if oldPet:isSpawned() then
DespawnMob(oldPet:getID());
end
newPet:setModelId(modelId);
newPet:spawn();
newPet:setPos(mob:getXPos() + math.random(-2, 2), mob:getYPos(), mob:getZPos() + math.random(-2, 2));
newPet:updateEnmity(target);
end; | gpl-3.0 |
MalRD/darkstar | scripts/globals/items/rice_ball.lua | 11 | 1117 | -----------------------------------------
-- ID: 4405
-- Item: Rice Ball
-- Food Effect: 30Min, All Races
-----------------------------------------
-- HP 10,
-- Vit +2
-- Dex -1
-- hHP +1
-- Effect with enhancing equipment (Note: these are latents on gear with the effect)
-- Def +50
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onItemCheck(target)
local result = 0
if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then
result = dsp.msg.basic.IS_FULL
end
return result
end
function onItemUse(target)
target:addStatusEffect(dsp.effect.FOOD,0,0,1800,4405)
end
function onEffectGain(target, effect)
target:addMod(dsp.mod.HP, 10)
target:addMod(dsp.mod.VIT, 2)
target:addMod(dsp.mod.DEX, -1)
target:addMod(dsp.mod.HPHEAL, 1)
end
function onEffectLose(target, effect)
target:delMod(dsp.mod.HP, 10)
target:delMod(dsp.mod.VIT, 2)
target:delMod(dsp.mod.DEX, -1)
target:delMod(dsp.mod.HPHEAL, 1)
end | gpl-3.0 |
maxrio/luci981213 | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-res.lua | 68 | 2884 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
module = cbimap:section(TypedSection, "module", "Modules", "")
module.anonymous = true
res_config_mysql = module:option(ListValue, "res_config_mysql", "MySQL Config Resource", "")
res_config_mysql:value("yes", "Load")
res_config_mysql:value("no", "Do Not Load")
res_config_mysql:value("auto", "Load as Required")
res_config_mysql.rmempty = true
res_config_odbc = module:option(ListValue, "res_config_odbc", "ODBC Config Resource", "")
res_config_odbc:value("yes", "Load")
res_config_odbc:value("no", "Do Not Load")
res_config_odbc:value("auto", "Load as Required")
res_config_odbc.rmempty = true
res_config_pgsql = module:option(ListValue, "res_config_pgsql", "PGSQL Module", "")
res_config_pgsql:value("yes", "Load")
res_config_pgsql:value("no", "Do Not Load")
res_config_pgsql:value("auto", "Load as Required")
res_config_pgsql.rmempty = true
res_crypto = module:option(ListValue, "res_crypto", "Cryptographic Digital Signatures", "")
res_crypto:value("yes", "Load")
res_crypto:value("no", "Do Not Load")
res_crypto:value("auto", "Load as Required")
res_crypto.rmempty = true
res_features = module:option(ListValue, "res_features", "Call Parking Resource", "")
res_features:value("yes", "Load")
res_features:value("no", "Do Not Load")
res_features:value("auto", "Load as Required")
res_features.rmempty = true
res_indications = module:option(ListValue, "res_indications", "Indications Configuration", "")
res_indications:value("yes", "Load")
res_indications:value("no", "Do Not Load")
res_indications:value("auto", "Load as Required")
res_indications.rmempty = true
res_monitor = module:option(ListValue, "res_monitor", "Call Monitoring Resource", "")
res_monitor:value("yes", "Load")
res_monitor:value("no", "Do Not Load")
res_monitor:value("auto", "Load as Required")
res_monitor.rmempty = true
res_musiconhold = module:option(ListValue, "res_musiconhold", "Music On Hold Resource", "")
res_musiconhold:value("yes", "Load")
res_musiconhold:value("no", "Do Not Load")
res_musiconhold:value("auto", "Load as Required")
res_musiconhold.rmempty = true
res_odbc = module:option(ListValue, "res_odbc", "ODBC Resource", "")
res_odbc:value("yes", "Load")
res_odbc:value("no", "Do Not Load")
res_odbc:value("auto", "Load as Required")
res_odbc.rmempty = true
res_smdi = module:option(ListValue, "res_smdi", "SMDI Module", "")
res_smdi:value("yes", "Load")
res_smdi:value("no", "Do Not Load")
res_smdi:value("auto", "Load as Required")
res_smdi.rmempty = true
res_snmp = module:option(ListValue, "res_snmp", "SNMP Module", "")
res_snmp:value("yes", "Load")
res_snmp:value("no", "Do Not Load")
res_snmp:value("auto", "Load as Required")
res_snmp.rmempty = true
return cbimap
| apache-2.0 |
neverlose1/sickmind | plugins/persian_lang.lua | 20 | 25826 | --------------------------------------------------
-- ____ ____ _____ --
-- | \| _ )_ _|___ ____ __ __ --
-- | |_ ) _ \ | |/ ·__| _ \_| \/ | --
-- |____/|____/ |_|\____/\_____|_/\/\_| --
-- --
--------------------------------------------------
-- --
-- Developers: @Josepdal & @MaSkAoS --
-- Support: @Skneos, @iicc1 & @serx666 --
-- --
-- Translated by: @NimaGame --
-- Translated by: @Iamjavid --
-- --
--------------------------------------------------
local LANG = 'fa'
local function run(msg, matches)
if permissions(msg.from.id, msg.to.id, "lang_install") then
-------------------------
-- Translation version --
-------------------------
set_text(LANG, 'version', '0.3')
set_text(LANG, 'versionExtended', 'نسخه ترجمه : نسخه 0.3')
-------------
-- Plugins --
-------------
-- global plugins --
set_text(LANG, 'require_sudo', 'این پلاگین نیاز به دسترسی سودو دارد.')
set_text(LANG, 'require_admin', 'این پلاگین نیاز به دسترسی ادمین و یا بالا تر دارد.')
set_text(LANG, 'require_mod', 'این پلاگین نیاز به دسترسی مدیر و یا بالا تر دارد.')
-- Spam.lua --
set_text(LANG, 'reportUser', 'کاربر')
set_text(LANG, 'reportReason', 'دلیل ریپورت')
set_text(LANG, 'reportGroup', 'گروه')
set_text(LANG, 'reportMessage', 'پیام')
set_text(LANG, 'allowedSpamT', 'از این به بعد این گروه در مقابل اسپمینگ محافظت نمیشود.')
set_text(LANG, 'allowedSpamL', 'از این به بعد این سوپر گروه در مقابل اسپمینگ محافظت نمیشود.')
set_text(LANG, 'notAllowedSpamT', 'اسپمینگ در این گروه ممنوع میباشد.')
set_text(LANG, 'notAllowedSpamL', 'اسپمینگ در این سوپر گروه ممنوع میباشد.')
-- bot.lua --
set_text(LANG, 'botOn', 'ربات روشن شد')
set_text(LANG, 'botOff', 'ربات خاموش شد')
-- settings.lua --
set_text(LANG, 'user', 'کاربر')
set_text(LANG, 'isFlooding', 'درحال اسپم کردن است.')
set_text(LANG, 'noStickersT', 'استفاده از استیکر در این گروه ممنوع میباشد.')
set_text(LANG, 'noStickersL', 'استفاده از استیکر در این سوپر گروه ممنوع میباشد.')
set_text(LANG, 'stickersT', 'از این به بعد استفاده از استیکر در این گروه آزاد است.')
set_text(LANG, 'stickersL', 'از این به بعد استفاده از استیکر در این سوپر گروه آزاد است.')
set_text(LANG, 'noGiftT', 'استفاده از عکس متحرک در این گروه ممنوع میباشد.')
set_text(LANG, 'noGiftL', 'استفاده از عکس متحرک در این سوپر گروه ممنوع میباشد.')
set_text(LANG, 'GiftT','از این به بعد استفاده از عکس متحرک در این گروه آزاد است.')
set_text(LANG, 'GiftL', 'از این به بعد استفاده از عکس متحرک در این سوپر گروه آزاد است.')
set_text(LANG, 'PhotosT', 'از این به بعد ارسال عکس در این گروه آزاد میباشد.')
set_text(LANG, 'PhotosL', 'از این به بعد ارسال عکس در این سوپر گروه آزاد میباشد.')
set_text(LANG, 'noPhotos،', 'استفاده از عکس در این گروه ممنوع میباشد.')
set_text(LANG, 'noPhotosL', 'استفاده از عکس در این سوپر گروه ممنوع میباشد.')
set_text(LANG, 'noArabicT', 'در این گروه شما نمیتوانید با زبان هایی مانند عربی و... صحبت کنید.')
set_text(LANG, 'noArabicL', 'در این سوپر گروه شما نمیتوانید با زبان هایی مانند عربی و... صحبت کنید.')
set_text(LANG, 'ArabicT', 'از این به بعد استفاده از زبان هایی مانند عربی و... در این گروه آزاد است.')
set_text(LANG, 'ArabicL', 'از این به بعد استفاده از زبان هایی مانند عربی و... در این سوپر گروه آزاد است.')
set_text(LANG, 'audiosT', 'از این به بعد ارسال فایل صوتی به این گروه آزاد است.')
set_text(LANG, 'audiosL', 'از این به بعد ارسال فایل صوتی به این سوپر گروه آزاد است.')
set_text(LANG, 'noAudiosT', 'ارسال فایل صوتی در این گروه ممنوع میباشد.')
set_text(LANG, 'noAudiosL', 'ارسال فایل صوتی در این سوپر گروه ممنوع میباشد.')
set_text(LANG, 'kickmeT', 'از این به بعد استفاده از دستور kickme در این گروه آزاد است.')
set_text(LANG, 'kickmeL', 'از این به بعد استفاده از دستور kickme در این سوپر گروه آزاد است.')
set_text(LANG, 'noKickmeT', 'شما نمیتوانید از این دستور در این گروه استفاده کنید.')
set_text(LANG, 'noKickmeL', 'شما نمیتوانید از این دستور در این سوپر گروه استفاده کنید.')
set_text(LANG, 'floodT', 'از این به بعد اسپمینگ در این گروه محافظت نمیشود.')
set_text(LANG, 'floodL', 'از این به بعد اسپمینگ در این سوپر گروه محافظت نمیشود.')
set_text(LANG, 'noFloodT', 'شما اجازه اسپم در این گروه را ندارید.')
set_text(LANG, 'noFloodL', 'شما اجازه اسپم در این سوپر گروه را ندارید.')
set_text(LANG, 'floodTime', 'زمان برسی فلودینگ در این چت تنظیم شد به هر : ')
set_text(LANG, 'floodMax', 'حداکثر حساسیت سیستم آنتی فلود تنظیم شد به : ')
set_text(LANG, 'gSettings', 'تنظیمات گروه')
set_text(LANG, 'sSettings', 'تنظیمات سوپرگروه')
set_text(LANG, 'allowed', 'امکان پذیر')
set_text(LANG, 'noAllowed', 'ممنوع')
set_text(LANG, 'noSet', 'تنظیم نشده است')
set_text(LANG, 'stickers', 'استیکر')
set_text(LANG, 'links', 'لینک')
set_text(LANG, 'arabic', 'زبان عربی')
set_text(LANG, 'bots', 'ربات')
set_text(LANG, 'gifs', 'عکس متحرک')
set_text(LANG, 'photos', 'عکس')
set_text(LANG, 'audios', 'فایل صوتی')
set_text(LANG, 'kickme', 'Kickme دستور')
set_text(LANG, 'spam', 'اسپم')
set_text(LANG, 'gName', 'نام گروه')
set_text(LANG, 'flood', 'فلود')
set_text(LANG, 'language', 'زبان')
set_text(LANG, 'mFlood', 'حداکثر حساسیت فلود')
set_text(LANG, 'tFlood', 'زمان برسی فلودینگ')
set_text(LANG, 'setphoto', 'تنظیم عکس گروه')
set_text(LANG, 'photoSaved', 'عکس با موفقیت ذخیره شد.')
set_text(LANG, 'photoFailed', 'عملیات ناموفق بود، دوباره سعی کنید!')
set_text(LANG, 'setPhotoAborted', 'متوقف کردن عملیات تنظیم عکس...')
set_text(LANG, 'sendPhoto', 'لطفا عکسی را ارسال کنید.')
set_text(LANG, 'linkSaved', 'لینک جدید با موفقیت ذخیره شد')
set_text(LANG, 'groupLink', 'لینک گروه :')
set_text(LANG, 'sGroupLink', 'لینک سوپرگروه :')
set_text(LANG, 'noLinkSet', 'هیچ لینکی تنظیم نشده است. لطفا با دستور #setlink [link] لینک جدیدی بسازید.')
set_text(LANG, 'chatRename', 'از این به بعد میتوانید اسم گروه را تغییر دهید')
set_text(LANG, 'channelRename', 'از این به بعد میتوانید اسم چنل را تغییر دهید')
set_text(LANG, 'notChatRename', 'دیگر نمی توان نام گروه را تغییر داد.')
set_text(LANG, 'notChannelRename', 'دیگر نمی توان نام چنل را تغییر داد.')
set_text(LANG, 'lockMembersT', 'تعداد اعضا در این چت قفل شده است.')
set_text(LANG, 'lockMembersL', 'تعداد اعضا در این چنل قفل شده است.')
set_text(LANG, 'notLockMembersT', 'قفل تعداد اعضا در این چت باز شد.')
set_text(LANG, 'notLockMembersL', 'قفل تعداد اعضا در این چنل باز شد.')
set_text(LANG, 'langUpdated', 'زبان شما تغییر کرد به :')
set_text(LANG, 'chatUpgrade', 'این گروه با موفقیت به سوپر گروه ارتقا یافت.')
set_text(LANG, 'notInChann', 'شما نمیتوانید آن را در یک سوپر گروه انجام دهید')
set_text(LANG, 'desChanged', 'شرح سوپر گروه با موفقیت تغییر یافت.')
set_text(LANG, 'desOnlyChannels', 'تغییر شرح تنها در سوپر گروه ممکن است.')
set_text(LANG, 'muteAll', 'توانایی صحبت از همه گرفته شد.')
set_text(LANG, 'unmuteAll', 'توانایی صحبت به همه بازپس داده شد.')
set_text(LANG, 'muteAllX:1', 'شما نمی توانید به مدت')
set_text(LANG, 'muteAllX:2', 'ثانیه در این چنل چت کنید..')
set_text(LANG, 'createGroup:1', 'گروه')
set_text(LANG, 'createGroup:2', 'ساخته شد.')
set_text(LANG, 'newGroupWelcome', 'به گروه جدیدتان خوش امدید!')
-- export_gban.lua --
set_text(LANG, 'accountsGban', 'اکانت مورد نظر به صورت جهانی مسدود شد')
-- giverank.lua --
set_text(LANG, 'alreadyAdmin', 'این شخص درحال حاضر ادمین است.')
set_text(LANG, 'alreadyMod', 'این شخص درحال حاضر مدیر است.')
set_text(LANG, 'newAdmin', 'ادمین جدید')
set_text(LANG, 'newMod', 'مدیر جدید')
set_text(LANG, 'nowUser', 'از حالا یک کاربر معمولی است.')
set_text(LANG, 'modList', 'لیست مدیران')
set_text(LANG, 'adminList', 'لیست ادمین')
set_text(LANG, 'modEmpty', 'این چت هیچ مدیری ندارد.')
set_text(LANG, 'adminEmpty', 'درحال حاضر هیچ کسی ادمین نیست.')
-- id.lua --
set_text(LANG, 'user', 'کاربر')
set_text(LANG, 'supergroupName', 'نام سوپرگروه')
set_text(LANG, 'chatName', 'نام چت')
set_text(LANG, 'supergroup', 'سوپرگروه')
set_text(LANG, 'chat', 'چت')
-- moderation.lua --
set_text(LANG, 'userUnmuted:1', 'کاربر')
set_text(LANG, 'userUnmuted:2', 'توانایی چت کردن را دوباره بدست آورد.')
set_text(LANG, 'userMuted:1', 'کاربر')
set_text(LANG, 'userMuted:2', 'توانایی چت کردن را از دست داد.')
set_text(LANG, 'kickUser:1', 'کاربر')
set_text(LANG, 'kickUser:2', 'اخراج شد.')
set_text(LANG, 'banUser:1', 'کاربر')
set_text(LANG, 'banUser:2', 'مسدود شد.')
set_text(LANG, 'unbanUser:1', 'کاربر')
set_text(LANG, 'unbanUser:2', 'از حالت مسدود خارج شد.')
set_text(LANG, 'gbanUser:1', 'کاربر')
set_text(LANG, 'gbanUser:2', 'به صورت جهانی مسدود شد.')
set_text(LANG, 'ungbanUser:1', 'کاربر')
set_text(LANG, 'ungbanUser:2', 'از حالت مسدود جهانی خارج شد.')
set_text(LANG, 'addUser:1', 'کاربر')
set_text(LANG, 'addUser:2', 'به گروه اضافه شد.')
set_text(LANG, 'addUser:3', 'به سوپر گروه اضافه شد')
set_text(LANG, 'kickmeBye', 'خداحافظ')
-- plugins.lua --
set_text(LANG, 'plugins', 'پلاگین ها')
set_text(LANG, 'installedPlugins', 'پلاگین های نصب شده.')
set_text(LANG, 'pEnabled', 'فعال.')
set_text(LANG, 'pDisabled', 'غیرفعال.')
set_text(LANG, 'isEnabled:1', 'پلاگین')
set_text(LANG, 'isEnabled:2', 'فعال است.')
set_text(LANG, 'notExist:1', 'پلاگین')
set_text(LANG, 'notExist:2', 'وجود ندارد.')
set_text(LANG, 'notEnabled:1', 'پلاگین')
set_text(LANG, 'notEnabled:2', 'فعال نیست.')
set_text(LANG, 'pNotExists', 'این پلاگین وجود ندارد.')
set_text(LANG, 'pDisChat:1', 'پلاگین')
set_text(LANG, 'pDisChat:2', 'در این گروه غیرفعال است.')
set_text(LANG, 'anyDisPlugin', 'هیچ پلاگینی غیرفعال نیست.')
set_text(LANG, 'anyDisPluginChat', 'هیچ پلاگینی در این گروه فعال نیست')
set_text(LANG, 'notDisabled', 'این پلاگین غیرفعال نیست.')
set_text(LANG, 'enabledAgain:1', 'پلاگین')
set_text(LANG, 'enabledAgain:2', 'دوباره فعال شد.')
-- commands.lua --
set_text(LANG, 'commandsT', 'دستورات')
set_text(LANG, 'errorNoPlug', 'این پلاگین وجود ندارد و یا فعال نیست.')
-- rules.lua --
set_text(LANG, 'setRules', 'Chat rules have been updated.')
set_text(LANG, 'remRules', 'Chat rules have been removed.')
------------
-- Usages --
------------
-- bot.lua --
set_text(LANG, 'bot:0', 2)
set_text(LANG, 'bot:1', '#bot on : فعال کردن ربات در این گروه')
set_text(LANG, 'bot:2', '#bot off : غیرفعال کردن ربات در این گروه')
-- commands.lua --
set_text(LANG, 'commands:0', 2)
set_text(LANG, 'commands:1', '#commands : نمایش دستورات تمامی پلاگین ها')
set_text(LANG, 'commands:2', '#commands [plugin] : نمایش دستورات پلاگین مورد نظر')
-- export_gban.lua --
set_text(LANG, 'export_gban:0', 2)
set_text(LANG, 'export_gban:1', '#gbans installer : فرستادن لیست مسدود های جهانی به صورت یک فایل لوآ برای اشتراک گذاری با ربات های دیگر')
set_text(LANG, 'export_gban:2', '#gbans list : ارسال لیست مسدود های جهانی')
-- gban_installer.lua --
set_text(LANG, 'gban_installer:0', 1)
set_text(LANG, 'gban_installer:1', '#install gbans : افزودن لیست مسدود های جهانی به پایگاه داده شما')
-- giverank.lua --
set_text(LANG, 'giverank:0', 9)
set_text(LANG, 'giverank:1', '#rank admin (reply) : افزودن ادمین با ریپلی کردن پیام او')
set_text(LANG, 'giverank:2', '#rank admin <user_id>/<user_name> : افزودن ادمین با استفاده از یوزرنیم و یا آیدی او')
set_text(LANG, 'giverank:3', '#rank mod (reply) : افزودن مدیر گروه با ریپلی کردن پیام او')
set_text(LANG, 'giverank:4', '#rank mod <user_id>/<user_name> : افزودن مدیر گروه با استفاده از یوزرنیم و یا آیدی او')
set_text(LANG, 'giverank:5', '#rank guest (reply) : گرفتن مقام ادمین ادمین با ریپلی')
set_text(LANG, 'giverank:6', '#rank guest <user_id>/<user_name> : گرفتن مقام ادمین ادمین بوسیله یوزرنیم و یا آی دی')
set_text(LANG, 'giverank:7', '#admins : لیست تمامی ادمین های موجود این ربات')
set_text(LANG, 'giverank:8', '#mods : لیست تمامی مدیران موجود این گروه')
set_text(LANG, 'giverank:9', '#members : لیست تمامی اعضای این گروه/سوپر گروه')
-- id.lua --
set_text(LANG, 'id:0', 6)
set_text(LANG, 'id:1', '#id : نشان دادن آیدی شما و آیدی گروه / سوپر گروهی که در آن حضور دارید')
set_text(LANG, 'id:2', '#ids chat : نشان دادن آیدی گروهی که در آن هستید')
set_text(LANG, 'id:3', '#ids channel : نشان دادن آیدی سوپر گروهی که در آن هستید')
set_text(LANG, 'id:4', '#id <user_name> : نشان دادن آیدی یک شخص دیگر با استفاده از یوزرنیم او')
set_text(LANG, 'id:5', '#whois <user_id>/<user_name> : نشان دادن یوزرنیم یک شخص دیگر با استفاده از آیدی او')
set_text(LANG, 'id:6', '#whois (reply) : نشان دادن آیدی و یوزرنیم شخص مورد نظر شما با ریپلی کردن پیام او')
-- moderation.lua --
set_text(LANG, 'moderation:0', 18)
set_text(LANG, 'moderation:1', '#add : با ریپلی کردن پیام شخصی ، او را به این گروه/سوپر گروه بیافزایید')
set_text(LANG, 'moderation:2', '#add <id>/<username> : افزودن شخصی به این گروه/سوپر گروه با استفاده از آیدی و یا یوزرنیم او')
set_text(LANG, 'moderation:3', '#kick : با ریپلی کردن پیام شخصی ، او را از گروه بیرون کنید')
set_text(LANG, 'moderation:4', '#kick <id>/<username> : با استفاده از یوزرنیم و یا آیدی شخصی او را از گروه بیرون کنید')
set_text(LANG, 'moderation:5', '#kickme : خودتان را از گروه اخراج کنید')
set_text(LANG, 'moderation:6', '#ban : با ریپلی کردن پیامی از شخصی او را از گروه بیرون و او را مسدود کنید تا توانایی ورود دوباره به گروه را نداشته باشد')
set_text(LANG, 'moderation:7', '#ban <id>/<username> : با استفاده از آیدی و یا یوزرنیم شخصی او را از گروه بیرون و او را مسدود کنید تا توانایی ورود دوباره به گروه را نداشته باشد')
set_text(LANG, 'moderation:8', '#unban : با ریپلی کردن پیام شخصی او را از حالت مسدود خارج کنید')
set_text(LANG, 'moderation:9', '#unban <id>/<username> : با استفاده از آیدی و یا یوزرنیم شخصی او را از حالت مسدود خارج کنید')
set_text(LANG, 'moderation:10', '#gban : با ریپلی کردن پیامی از کاربر او را از تمامی گروه/سوپر گروه ها بیرون و او را مسدود جهانی کنید')
set_text(LANG, 'moderation:11', '#gban <id>/<username> : با استفاده از آیدی و یا یوزرنیم کاربر او را از تمامی گروه/سپر گروه ها بیرون و او را مسدود جهانی کنید')
set_text(LANG, 'moderation:12', '#ungban : با ریپلی کردن پیامی از شخصی او را از حالت مسدود جهانی خارج کنید')
set_text(LANG, 'moderation:13', '#ungban <id>/<username> : با استفاده از آیدی و یا یوزرنیم کاربر او را از حالت مسدود جهانی خارج کنید')
set_text(LANG, 'moderation:14', '#mute : با ریپلی کردن پیامی از شخصی ، اجازه صحبت در این سوپر گروه را از آن بگیرید')
set_text(LANG, 'moderation:15', '#mute <id>/<username> : با استفاده از ایدی و یا یوزرنیم کاربر اجازه صحبت در این سوپر گروه را از آن بگیرید')
set_text(LANG, 'moderation:16', '#unmute : با ریپلی کردن پیامی از کاربر او را از حالت سکوت خارج کنید')
set_text(LANG, 'moderation:17', '#unmute <id>/<username> : با استفاده از آیدی و یا یوزرنیم کاربر او را از حالت سکوت خارج کنید')
set_text(LANG, 'moderation:18', '#rem : با ریپلی کردن پیامی و استفاده از این دستور ، پیام ریپلی شده پاک خواهد شد')
-- settings.lua --
set_text(LANG, 'settings:0', 19)
set_text(LANG, 'settings:1', '#settings stickers enable/disable : وقتی فعال باشد ، ربات تمامی استکیر هارا پاک خواهد کرد')
set_text(LANG, 'settings:2', '#settings links enable/disable : وقتی فعال باشد ، ربات تمامی لینک هارا پاک خواهد کرد')
set_text(LANG, 'settings:3', '#settings arabic enable/disabl : وقتی فعال باشد ، ربات تمامی پیام های فارسی و یا عربی را پاک خواهد کرد')
set_text(LANG, 'settings:4', '#settings bots enable/disable : وقتی فعال باشد ، با افزدون ربات به گروه/سوپر گروه ، ربات حذف خواهد شد')
set_text(LANG, 'settings:5', '#settings gifs enable/disable : وقتی فعال باشد ، ربات تمامی عکس های متحرک را پاک خواهد کرد')
set_text(LANG, 'settings:6', '#settings photos enable/disable : وقتی فعال باشد ربات تمامی عکس هارا پاک خواهد کرد')
set_text(LANG, 'settings:7', '#settings audios enable/disable : وقتی فعال باشد ، ربات تمامی فایل های صوتی را پاک خواهد کرد')
set_text(LANG, 'settings:8', '#settings kickme enable/disable : وقتی فعال باشد ، کاربران نمیتوانند از دستور kickme استفاده کنند')
set_text(LANG, 'settings:9', '#settings spam enable/disable : وقتی فعال باشد ، ربات تمامی اسپم هارا پاک خواهد کرد')
set_text(LANG, 'settings:10', '#settings setphoto enable/disable : وقتی فعال باشد ، در صورت تغییر عکس گروه توسط شخصی ، عکس قبلی دوباره تنظیم میشود')
set_text(LANG, 'settings:11', '#settings setname enable/disable : وقتی فعال باشد ، در صورت تغییر اسم گروه ، ربات اسم قبلی را تنظیم میکند')
set_text(LANG, 'settings:12', '#settings lockmember enable/disable : وقتی فعال باشد ، ربات هر شخصی را که وارد گروه میشود بیرون خواهد کرد')
set_text(LANG, 'settings:13', '#settings floodtime <ثانیه>: تنظیم مقدار زمانی که بات فلود را بررسی می کند')
set_text(LANG, 'settings:14', '#settings maxflood <ثانیه>: حداثکر تعداد فلود را تنظیم می کند')
set_text(LANG, 'settings:15', '#setname <group title> : نام گروه را تغییر می دهد')
set_text(LANG, 'settings:16', '#setphoto <then send photo> : تصویر گروه را تغییر می دهد')
set_text(LANG, 'settings:17', '#lang <language (en, es...)> : زبان ربات را تغییر می دهد')
set_text(LANG, 'settings:18', '#setlink <link> : لینک گروه را ذخیره می کند')
set_text(LANG, 'settings:19', '#link : لینک گروه را ارسال می کند')
-- plugins.lua --
set_text(LANG, 'plugins:0', 4)
set_text(LANG, 'plugins:1', '#plugins : لیست تمامی پلاگین هارا نشان می دهد.')
set_text(LANG, 'plugins:2', '#plugins <enable>/<disable> [plugin] : فعال/غیرفعال کردن پلاگین مورد نظر')
set_text(LANG, 'plugins:3', '#plugins <enable>/<disable> [plugin] chat : فعال ، غیر فعال کردن پلاگین مورد نظر در گروه و یا سوپرگروه کنونی')
set_text(LANG, 'plugins:4', '#plugins reload : بازنگری پلاگین ها.')
-- version.lua --
set_text(LANG, 'version:0', 1)
set_text(LANG, 'version:1', '#version : نشان دادن نسخه ربات')
-- rules.lua --
set_text(LANG, 'rules:0', 1)
set_text(LANG, 'rules:1', '#rules : نشان دادن قوانین سوپر گروه')
if matches[1] == 'install' then
return 'ℹ️ زبان فارسی با موفقیت بر روی ربات شما نصب شد.'
elseif matches[1] == 'update' then
return 'ℹ️ زبان فارسی با موفقیت بروز رسانی شد.'
end
else
return "🚫 این پلاگین نیاز به دسترسی سودو دارد."
end
end
return {
patterns = {
'#(install) (persian_lang)$',
'#(update) (persian_lang)$'
},
run = run
} | gpl-2.0 |
Lsty/ygopro-scripts | c2980764.lua | 7 | 1130 | --聖なるあかり
function c2980764.initial_effect(c)
--battle
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_AVOID_BATTLE_DAMAGE)
e1:SetValue(c2980764.tglimit)
c:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE)
e2:SetValue(c2980764.tglimit)
c:RegisterEffect(e2)
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE)
e3:SetRange(LOCATION_MZONE)
e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e3:SetTarget(c2980764.tglimit)
c:RegisterEffect(e3)
--disable spsummon
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_MZONE)
e4:SetCode(EFFECT_CANNOT_SUMMON)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetTargetRange(1,1)
e4:SetTarget(c2980764.sumlimit)
c:RegisterEffect(e4)
local e5=e4:Clone()
e5:SetCode(EFFECT_CANNOT_SPECIAL_SUMMON)
c:RegisterEffect(e5)
end
function c2980764.tglimit(e,c)
return c:IsAttribute(ATTRIBUTE_DARK)
end
function c2980764.sumlimit(e,c)
return c:IsAttribute(ATTRIBUTE_DARK)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c99795159.lua | 3 | 1302 | --ゴーストリック・ハウス
function c99795159.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--atklimit
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET)
e2:SetRange(LOCATION_SZONE)
e2:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e2:SetValue(c99795159.atlimit)
c:RegisterEffect(e2)
--direct attack
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_FIELD)
e3:SetCode(EFFECT_DIRECT_ATTACK)
e3:SetRange(LOCATION_SZONE)
e3:SetTargetRange(LOCATION_MZONE,LOCATION_MZONE)
e3:SetTarget(c99795159.dirtg)
c:RegisterEffect(e3)
--
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_FIELD)
e4:SetRange(LOCATION_SZONE)
e4:SetCode(EFFECT_CHANGE_DAMAGE)
e4:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e4:SetTargetRange(1,1)
e4:SetValue(c99795159.val)
c:RegisterEffect(e4)
end
function c99795159.atlimit(e,c)
return c:IsFacedown()
end
function c99795159.dirtg(e,c)
return not Duel.IsExistingMatchingCard(Card.IsFaceup,c:GetControler(),0,LOCATION_MZONE,1,nil)
end
function c99795159.val(e,re,dam,r,rp,rc)
if bit.band(r,REASON_EFFECT)~=0 or (rc and not rc:IsSetCard(0x8d)) then
return dam/2
else return dam end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c84962466.lua | 5 | 3210 | --ビーストライザー
function c84962466.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e1:SetHintTiming(TIMING_DAMAGE_STEP)
e1:SetTarget(c84962466.target1)
e1:SetOperation(c84962466.operation)
c:RegisterEffect(e1)
--atk
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(84962466,1))
e2:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
e2:SetType(EFFECT_TYPE_QUICK_O)
e2:SetRange(LOCATION_SZONE)
e2:SetCode(EVENT_FREE_CHAIN)
e2:SetHintTiming(TIMING_DAMAGE_STEP)
e2:SetTarget(c84962466.target2)
e2:SetOperation(c84962466.operation)
c:RegisterEffect(e2)
end
function c84962466.cfilter(c,tp)
return c:IsFaceup() and c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR) and c:IsAbleToRemove()
and Duel.IsExistingTarget(c84962466.filter,tp,LOCATION_MZONE,0,1,c)
end
function c84962466.filter(c)
return c:IsFaceup() and c:IsRace(RACE_BEAST+RACE_BEASTWARRIOR)
end
function c84962466.target1(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c84962466.filter(chkc) end
if chk==0 then
return Duel.GetCurrentPhase()~=PHASE_DAMAGE or Duel.IsExistingMatchingCard(c84962466.cfilter,tp,LOCATION_MZONE,0,1,nil,tp)
end
if Duel.GetCurrentPhase()==PHASE_DAMAGE or
(Duel.IsExistingMatchingCard(c84962466.cfilter,tp,LOCATION_MZONE,0,1,nil,tp) and Duel.SelectYesNo(tp,aux.Stringid(84962466,0))) then
e:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local rg=Duel.SelectMatchingCard(tp,c84962466.cfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
e:SetLabel(rg:GetFirst():GetBaseAttack())
Duel.Remove(rg,POS_FACEUP,REASON_COST)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c84962466.filter,tp,LOCATION_MZONE,0,1,1,nil)
e:GetHandler():RegisterFlagEffect(84962466,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
else e:SetProperty(EFFECT_FLAG_DAMAGE_STEP) end
end
function c84962466.target2(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c84962466.filter(chkc) end
if chk==0 then return e:GetHandler():GetFlagEffect(84962466)==0
and Duel.IsExistingMatchingCard(c84962466.cfilter,tp,LOCATION_MZONE,0,1,nil,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local rg=Duel.SelectMatchingCard(tp,c84962466.cfilter,tp,LOCATION_MZONE,0,1,1,nil,tp)
e:SetLabel(rg:GetFirst():GetBaseAttack())
Duel.Remove(rg,POS_FACEUP,REASON_COST)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP)
Duel.SelectTarget(tp,c84962466.filter,tp,LOCATION_MZONE,0,1,1,nil)
e:GetHandler():RegisterFlagEffect(84962466,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1)
end
function c84962466.operation(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local tc=Duel.GetFirstTarget()
if tc and tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_UPDATE_ATTACK)
e1:SetValue(e:GetLabel())
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
tarulas/luadch | core/scripts.lua | 1 | 7408 | --[[
scripts.lua by blastbeat
- this script manages custom user scripts
]]--
----------------------------------// DECLARATION //--
--// lua functions //--
local type = use "type"
local error = use "error"
local pairs = use "pairs"
local pcall = use "pcall"
local ipairs = use "ipairs"
local setfenv = use "setfenv"
local loadfile = use "loadfile"
local tostring = use "tostring"
local setmetatable = use "setmetatable"
--// lua libs //--
local io = use "io"
local _G = use "_G"
--// lua lib methods //--
local io_open = io.open
--// extern libs //--
local adclib = use "adclib"
local unicode = use "unicode"
--// extern lib methods //--
local utf = unicode.utf8
local utf_sub = utf.sub
local adclib_isUtf8 = adclib.isutf8
--// core scripts //--
local adc = use "adc"
local cfg = use "cfg"
local out = use "out"
local mem = use "mem"
local util = use "util"
--// core methods //--
local cfg_get = cfg.get
local out_put = out.put
local mem_free = mem.free
local out_error = out.error
local handlebom = util.handlebom
local checkfile = util.checkfile
--// functions //--
local init
local index
local newindex
local import
local setenv
local killscripts
local firelistener
local startscripts
local listenermethod
--// tables //--
local _code
local _loaded
local _scripts
local _listeners
local _
local _len -- len of listeners array
----------------------------------// DEFINITION //--
_len = 0
_loaded = { }
_scripts = { } -- script names
_listeners = { } -- array auf listeners tables of scripts
_code = { -- mhh...
hubbypass = 2,
hubdispatch = 1,
scriptsbypass = 8,
scriptsdispatch = 4,
}
index = function( tbl, key )
error( "attempt to read undeclared var: '" .. tostring( key ) .. "'", 2 )
end
newindex = function( tbl, key, value )
error( "attempt to write undeclared var: '" .. tostring( key ) .. " = " .. tostring( value ) .. "'", 2 )
end
setenv = function( tbl )
local mtbl = { }
mtbl.__index = index
mtbl.__newindex = newindex
return setmetatable( tbl, mtbl )
end
listenermethod = function( arg, scriptid )
if arg == "set" then
local listeners = { }
_listeners[ scriptid ] = listeners
_len = _len + 1
return function( ltype, id, func )
listeners[ ltype ] = listeners[ ltype ] or { }
listeners[ ltype ][ id ] = func
end
elseif arg == "get" then
return function( ltype )
local listeners = _listeners[ scriptid ]
return listeners and listeners[ ltype ]
end
end
-- TODO: add remove method
end
firelistener = function( ltype, a1, a2, a3, a4, a5 )
local ret, dispatch
for k = 1, _len do
local listeners = _listeners[ k ][ ltype ]
if listeners then
for i, func in pairs( listeners ) do
local bol, sret = pcall( func, a1, a2, a3, a4, a5 )
if bol then
ret = ret or sret
elseif ltype ~= "onError" then -- no endless loops ^^
out_error( "scripts.lua: script error: ", sret, " (listener: ", ltype, "; script: '", _scripts[ k ], "')" )
end
end
--// ugly shit //--
--[[if ret == 6 or ret == 10 then
dispatch = dispatch or 0
end
if ret == 5 or ret == 9 then
dispatch = dispatch or 1
end
if ret == 9 or ret == 10 then
break
end]]
if ret == 10 then -- PROCESSED should be enough
return true
end
end
end
--return ( dispatch == 0 )
return false
end
startscripts = function( hub )
for key, scriptname in ipairs( cfg_get "scripts" ) do
local path = cfg_get( "script_path" ) .. scriptname
local ret, original, err = checkfile( path )
_ = ret and err and out_put( "scripts.lua: " .. err )
if not ret then
out_error( "scripts.lua: format error in script '", scriptname, "': ", err )
err = nil
end
if ret then -- very ugly hack -___-
local tmpfile = io_open( path, "w+" )
tmpfile:write( ret ) -- write without possible signature
tmpfile:close( )
ret, err = loadfile( path ) -- better to use loadfile instead of loadstring because of error messages
tmpfile = io_open( path, "w+" )
tmpfile:write( original ) -- write with possible signature
tmpfile:close( )
end
if not ret and err then
out_error( "scripts.lua: syntax error in script '", scriptname, "': ", err )
elseif ret then
local hubobject = { }
for name, method in pairs( hub ) do
if utf_sub( name, 1, 1 ) ~= "_" then -- no "hidden" functions...
hubobject[ name ] = method
end
end
local key = _len + 1
hubobject.setlistener = listenermethod( "set", key ) -- this is needed to execute listeners in script order
hubobject.getlistener = listenermethod( "get", key )
local env = { }
--// useful constants //--
--env.DISPATCH_HUB = _code.hubdispatch
--env.DISCARD_HUB = _code.hubbypass
--env.DISPATCH_SCRIPTS = _code.scriptsdispatch
--env.DISCARD_SCRIPTS = _code.scriptsbypass
env.PROCESSED = _code.scriptsbypass + _code.hubbypass -- should be enough
for i, k in pairs( _G ) do
env[ i ] = k
end
env.hub = hubobject
env.utf = utf
env.string = utf
if cfg_get "no_global_scripting" then
setenv( env )
end
setfenv( ret, env )
local bol, ret = pcall( ret )
if not bol then
out_error( "scripts.lua: lua error in script '", scriptname, "': ", ret )
else
_loaded[ scriptname ] = ret
_scripts[ key ] = scriptname
end
end
mem_free( )
end
firelistener "onStart"
end
killscripts = function( )
firelistener "onExit"
_loaded = { }
_scripts = { }
_listeners = { }
_len = 0
mem_free( )
end
import = function( script )
script = tostring( script )
local tbl = _loaded[ script ] or _loaded[ script .. ".lua" ]
if type( tbl ) == "table" then
local ctbl = { }
for i, k in pairs( tbl ) do
ctbl[ i ] = k
end
return setmetatable( ctbl, { __mode = "v" } )
else
return tbl
end
end
init = function( )
out.setlistener( "error", function( msg ) firelistener( "onError", tostring( msg ) ) end )
end
----------------------------------// BEGIN //--
----------------------------------// PUBLIC INTERFACE //--
return {
init = init,
kill = killscripts,
start = startscripts,
import = import,
firelistener = firelistener,
} | gpl-3.0 |
Lsty/ygopro-scripts | c80551130.lua | 3 | 2185 | --奇跡の光臨
function c80551130.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetHintTiming(0,TIMING_END_PHASE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c80551130.target)
e1:SetOperation(c80551130.operation)
c:RegisterEffect(e1)
--Destroy
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_SINGLE)
e2:SetCode(EVENT_LEAVE_FIELD)
e2:SetOperation(c80551130.desop)
c:RegisterEffect(e2)
--Destroy2
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_CONTINUOUS+EFFECT_TYPE_FIELD)
e3:SetRange(LOCATION_SZONE)
e3:SetCode(EVENT_LEAVE_FIELD)
e3:SetCondition(c80551130.descon2)
e3:SetOperation(c80551130.desop2)
c:RegisterEffect(e3)
end
function c80551130.filter(c,e,tp)
return c:IsFaceup() and c:IsRace(RACE_FAIRY) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c80551130.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c80551130.filter(chkc,e,tp) end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c80551130.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectTarget(tp,c80551130.filter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0)
end
function c80551130.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) then
if Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)==0 then return end
c:SetCardTarget(tc)
end
end
function c80551130.desop(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
if tc and tc:IsLocation(LOCATION_MZONE) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
function c80551130.descon2(e,tp,eg,ep,ev,re,r,rp)
local tc=e:GetHandler():GetFirstCardTarget()
return tc and eg:IsContains(tc) and tc:IsReason(REASON_DESTROY)
end
function c80551130.desop2(e,tp,eg,ep,ev,re,r,rp)
Duel.Destroy(e:GetHandler(),REASON_EFFECT)
end
| gpl-2.0 |
carloseduardosx/sky-force-infinite | src/events/collision.lua | 1 | 4198 | local shipAction = require( "src.objects.ship" )
local composer = require( "composer" )
local record = require( "src.model.record" )
local particleDesigner = require( "src.util.particleDesigner" )
local Event = {}
function playExplosion( application, obj )
local explosionEmitter = particleDesigner.newEmitter( "assets/emitters/explosion.pex", "assets/emitters/texture.png" )
explosionEmitter.x = obj.x
explosionEmitter.y = obj.y
timer.performWithDelay( 500, function() explosionEmitter:stop() end )
if ( not audio.isChannelPlaying( 3 ) ) then
audio.play( application.soundTable.enemyExplosion, { channel=3 } )
elseif ( not audio.isChannelPlaying( 4 ) ) then
audio.play( application.soundTable.enemyExplosion, { channel=4 } )
elseif ( not audio.isChannelPlaying( 5 ) ) then
audio.play( application.soundTable.enemyExplosion, { channel=5 } )
end
end
function Event.onCollision( application )
return function( event )
if ( event.phase == "began" ) then
local obj1 = event.object1
local obj2 = event.object2
if ( ( obj1.myName == "laser" and obj2.myName == "easyEnemie" ) or
( obj1.myName == "easyEnemie" and obj2.myName == "laser") )
then
if ( obj1.myName == "easyEnemie" ) then
playExplosion( application, obj1 )
else
playExplosion( application, obj2 )
end
display.remove( obj1 )
display.remove( obj2 )
for i = #application.enemiesTable, 1, -1 do
if ( application.enemiesTable[i] == obj1 or application.enemiesTable[i] == obj2 ) then
table.remove( application.enemiesTable, i )
break
end
end
for i = #application.lasersTable, 1, -1 do
if ( application.lasersTable[i] == obj1 or application.lasersTable[i] == obj2 ) then
table.remove( application.lasersTable, i )
break
end
end
application.score = application.score + 100
application.scoreText.text = "Score: " .. application.score
elseif ( ( obj1.myName == "ship" and obj2.myName == "easyEnemie" ) or
( obj1.myName == "easyEnemie" and obj2.myName == "ship" ) )
then
if ( application.died == false ) then
application.died = true
if ( obj1.myName == "ship" ) then
playExplosion( application, obj1 )
else
playExplosion( application, obj2 )
end
application.lives = application.lives - 1
application.livesText.text = "Lives: " .. application.lives
application.firstTurbineEmitter:stop()
application.secondTurbineEmitter:stop()
if ( application.lives <= 0 ) then
record.insert( application.score )
record.save()
composer.gotoScene( "src.scenes.welcome" )
application.died = false
else
for i = #application.enemiesTable, 1, -1 do
if ( application.enemiesTable[i] == obj1 or application.enemiesTable[i] == obj2 ) then
playExplosion( application, application.enemiesTable[i] )
display.remove( application.enemiesTable[i] )
table.remove( application.enemiesTable, i )
break
end
end
application.ship.alpha = 0
timer.pause( application.laserLoopTimer )
timer.performWithDelay( 1000, shipAction.restore( application ) )
end
end
end
end
end
end
return Event
| apache-2.0 |
Lsty/ygopro-scripts | c71466592.lua | 3 | 1310 | --魔力吸収球体
function c71466592.initial_effect(c)
--Negate
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(71466592,0))
e1:SetCategory(CATEGORY_NEGATE+CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_CHAINING)
e1:SetCondition(c71466592.condition)
e1:SetCost(c71466592.cost)
e1:SetTarget(c71466592.target)
e1:SetOperation(c71466592.activate)
c:RegisterEffect(e1)
end
function c71466592.condition(e,tp,eg,ep,ev,re,r,rp)
return not e:GetHandler():IsStatus(STATUS_BATTLE_DESTROYED) and rp~=tp
and re:IsActiveType(TYPE_SPELL) and re:IsHasType(EFFECT_TYPE_ACTIVATE) and Duel.IsChainNegatable(ev)
and Duel.GetTurnPlayer()~=tp
end
function c71466592.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c71466592.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_NEGATE,eg,1,0,0)
if re:GetHandler():IsDestructable() and re:GetHandler():IsRelateToEffect(re) then
Duel.SetOperationInfo(0,CATEGORY_DESTROY,eg,1,0,0)
end
end
function c71466592.activate(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateActivation(ev)
if re:GetHandler():IsRelateToEffect(re) then
Duel.Destroy(eg,REASON_EFFECT)
end
end
| gpl-2.0 |
Frenzie/koreader | frontend/ui/widget/physicalkeyboard.lua | 4 | 5277 | local Blitbuffer = require("ffi/blitbuffer")
local BottomContainer = require("ui/widget/container/bottomcontainer")
local CenterContainer = require("ui/widget/container/centercontainer")
local Device = require("device")
local Font = require("ui/font")
local FrameContainer = require("ui/widget/container/framecontainer")
local Geom = require("ui/geometry")
local HorizontalGroup = require("ui/widget/horizontalgroup")
local HorizontalSpan = require("ui/widget/horizontalspan")
local InputContainer = require("ui/widget/container/inputcontainer")
local Size = require("ui/size")
local TextWidget = require("ui/widget/textwidget")
local TopContainer = require("ui/widget/container/topcontainer")
local VerticalGroup = require("ui/widget/verticalgroup")
local WidgetContainer = require("ui/widget/container/widgetcontainer")
local logger = require("logger")
local util = require("util")
local Screen = Device.screen
local PhysicalNumericKey = WidgetContainer:extend{
key = nil,
label = nil,
physical_key_label = nil,
keyboard = nil,
callback = nil,
mapping = nil,
width = nil,
height = nil,
bordersize = Size.border.button,
face = Font:getFace("infont"),
pkey_face = Font:getFace("infont", 14),
}
function PhysicalNumericKey:init()
local label_widget = TextWidget:new{
text = self.label,
face = self.face,
}
self[1] = FrameContainer:new{
margin = 0,
bordersize = self.bordersize,
background = Blitbuffer.COLOR_WHITE,
radius = Size.radius.default,
padding = 0,
CenterContainer:new{
dimen = Geom:new{
w = self.width - 2*self.bordersize,
h = self.height - 2*self.bordersize,
},
VerticalGroup:new{
label_widget,
TextWidget:new{
fgcolor = Blitbuffer.COLOR_DARK_GRAY,
text = self.physical_key_label,
face = self.pkey_face,
},
}
},
}
self.dimen = Geom:new{
x = 0,
y = 0,
w = self.width,
h = self.height,
}
end
-- start of PhysicalKeyboard
local PhysicalKeyboard = InputContainer:extend{
is_always_active = true,
inputbox = nil, -- expect ui/widget/inputtext instance
bordersize = Size.border.button,
padding = Size.padding.button,
height = math.max(Screen:getWidth(), Screen:getHeight())*0.33,
key_padding = Size.padding.default,
}
function PhysicalKeyboard:init()
local all_keys = {}
for _,row in ipairs(Device.keyboard_layout) do
util.arrayAppend(all_keys, row)
end
self.key_events.KeyPress = { { all_keys } }
self.dimen = Geom:new{ x = 0, y = 0, w = 0, h = 0 }
self:setType(self.inputbox.input_type)
end
function PhysicalKeyboard:setType(t)
if t == "number" then
self.mapping = {
{"1", "2", "3", "4", "5", "6", "7", "8", "9", "0"}
}
self.key_transformer = {}
for i,row in ipairs(self.mapping) do
for j,key in ipairs(row) do
local pkey = Device.keyboard_layout[i][j]
self.key_transformer[pkey] = self.mapping[i][j]
end
end
self:setupNumericMappingUI()
else
-- default mapping
self.mapping = Device.keyboard_layout
end
end
function PhysicalKeyboard:onKeyPress(ev)
local key = ev.key
if key == "Back" then
logger.warn("TODO: exit keyboard")
elseif key == "Del" then
self.inputbox:delChar()
else
if self.key_transformer then
key = self.key_transformer[key]
end
self.inputbox:addChars(key)
end
end
function PhysicalKeyboard:setupNumericMappingUI()
local key_rows = VerticalGroup:new{}
local key_margin = Size.margin.tiny
local row_len = #self.mapping[1]
local base_key_width = math.floor((self.width - row_len*(self.key_padding+2*key_margin) - 2*self.padding)/10)
local base_key_height = math.floor((self.height - self.key_padding - 2*self.padding)/4)
local key_width = math.floor(base_key_width + self.key_padding)
for i, kb_row in ipairs(self.mapping) do
local row = HorizontalGroup:new{}
for j, key in ipairs(kb_row) do
if j > 1 then
table.insert(row, HorizontalSpan:new{width=key_margin*2})
end
table.insert(row, PhysicalNumericKey:new{
label = key,
physical_key_label = Device.keyboard_layout[i][j],
width = key_width,
height = base_key_height,
})
end
table.insert(key_rows, row)
end
local keyboard_frame = FrameContainer:new{
margin = 0,
bordersize = 0,
radius = 0,
padding = self.padding,
TopContainer:new{
dimen = Geom:new{
w = self.width - 2*self.bordersize -2*self.padding,
h = self.height - 2*self.bordersize -2*self.padding,
},
key_rows,
}
}
self[1] = BottomContainer:new{
dimen = Screen:getSize(),
keyboard_frame,
}
self.dimen = keyboard_frame:getSize()
end
return PhysicalKeyboard
| agpl-3.0 |
MalRD/darkstar | scripts/globals/spells/valor_minuet_iv.lua | 10 | 1569 | -----------------------------------------
-- Spell: Valor Minuet IV
-- Grants Attack bonus to all allies.
-----------------------------------------
require("scripts/globals/status")
require("scripts/globals/msg")
-----------------------------------------
function onMagicCastingCheck(caster,target,spell)
return 0
end
function onSpellCast(caster,target,spell)
local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing
local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED)
local power = 31
if (sLvl+iLvl > 300) then
power = power + math.floor((sLvl+iLvl-300) / 6)
end
if (power >= 112) then
power = 112
end
local iBoost = caster:getMod(dsp.mod.MINUET_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT)
if (iBoost > 0) then
power = power + iBoost*11
end
power = power + caster:getMerit(dsp.merit.MINUET_EFFECT)
if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then
power = power * 2
elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then
power = power * 1.5
end
caster:delStatusEffect(dsp.effect.MARCATO)
local duration = 120
duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1)
if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then
duration = duration * 2
end
if not (target:addBardSong(caster,dsp.effect.MINUET,power,0,duration,caster:getID(), 0, 4)) then
spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT)
end
return dsp.effect.MINUET
end
| gpl-3.0 |
T-L-N/Dev_TLN | plugins/reply.lua | 1 | 13115 | -- made by { @llN00Nll }
do
ws = {}
rs = {}
-- some examples of how to use this :3
ws[1] = "معليك"
rs[1] = " شلون معليه ؟ 😒 اني #الرئاسه تآج راسك 🤖🍷 يلا كول شبيك 😂📝 "
ws[2] = "اريد قناة"
rs[2] = " @Dev_TLN 😌 "
ws[3] = "نجب"
rs[3] = " شنو هذا يا خرا 😒 انت/ي انجب/ي يا ادب سز 🤖🍷 "
ws[4] = "تحبني"
rs[4] = " 😔😹 اححہب كہل النہاس بس انہت #لا "
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] = " @llN00Nll 😻🕷👄 "
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] = "👀ششوف 👀"
ws[35] = "شسمك"
rs[35] = "اسمه اللمبــي 😹❤️"
ws[36] = " شسمج"
rs[36] = "اهوو ضل ضل ساحف كبر طمك😔😹❤️"
ws[37] = "جاو"
rs[37] = "خليك مضوجني 😹❤️"
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] = "اذا اكلك زين شراح تستفاد🤔كمل عندي شغل☹️😹"
ws[55] = "🚶"
rs[55] = "شِـوَفَ ُالُـهـيَـبُّه تْـسِـطِـرَ 🙊😼"
ws[56] = "اكطع"
rs[56] = " القائد من يكول اكطع الكل تسكت✋🌚"
ws[57] = ",زاحف"
rs[57] = "حط رجلك كـ🚶ـذا وحط الثانية كـ🏃ـذا وازحـ🐢ـف ازحـ🐢ـف كـ🐊ـذا وبربـ💃ـس بربـ💃ـس 👌😂"
ws[58] = "بوت"
rs[58] = "بوت مال #حلاقه 😂👌🏿بوت رجالي🐸👬 لو نسائي 😌👭 شهلخره بوت بوت ادري لو طالع عماله افضل مال باقي 😞وياهلعالم هاي 🐸👌🏿 عسها بحضك وبختك #بطوري جابت ححيه ولا جابتك 🙊😌😃"
ws[59] = "مطور"
rs[59] = "@llN00Nll"
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] = "شتحب تسمع (راب_حزين_شعر_ردح_ردح حزين _ موال_ موسيقى ) \n كيفك انته وذوقك 😌❤️"
ws[75] = "اكلك"
rs[75] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐸❤️"
ws[76] = "دي"
rs[76] = "دي تنـڪاڵ لـبوك 🌝🖕"
ws[77] = "ضلع"
rs[77] = "انجب/ي لك/ج 😒⁉️ لتتلوك مو ضلعك/ج اني 😂🍷"
ws[78] = "يا سورس هذا"
rs[78] = "ادخل للقناة 🙊 @Dev_TLN وشوف المطور 😂🚶🏻"
ws[79] = "باي"
rs[79] = " تـوصـل بل سـلامـه ✾ ٱ ٱڵـڵـه وياك 🕊🙊 "
ws[80] = "/help"
rs[80] ="لظهار لاوامر دز الاوامر😍❤️"
ws[81] = "جوعان"
rs[81] = "تـﮩـعال اڪـﮩـلنـي 😐😂"
ws[82] = "😔"
rs[82] = "لـﮩـيـﺵ ضـٲيـﮩـج 😿🖖🏿"
ws[83] = "حلو"
rs[83] = "ٱنـﮩـت الاحـلآ 🌚❤️"
ws[84] = "😒"
rs[84] = "😐 شبيك كالب وجهك "
ws[85] = "الرئاسه"
rs[85] = "اســۣۛـۣۛـيــۣۛـۣۛـادك 🐸🖕🏿بطــۣۛـۣۛـي 🐎 تاج راســۣۛـۣۛـك حاميــۣۛـۣۛـن اعراضــۣۛـۣۛـك✿⇣🌞💋"
ws[86] = "🙃"
rs[86] = "ولخلقه 😐😂"
ws[87] = "اريد بوت"
rs[87] = "؏ـيــ❦ـوني 🙊 راســل احد المــطورين 🤖👇🏿 يكون كروبك فوك 300 🌚 و @llN00Nll او @liknil او @Aaa1R او @x_I_10_I_x"
ws[88] = "🌚"
rs[88] = "هاك صابونةه 🚿 اغسل وجهكك 😳😹🏃🏿"
ws[89] = "تيم"
rs[89] = "مــہٰٰـــو بحــہٰٰـــالكے القــہٰٰـائــہٰٰـد 🎤🚶"
ws[90] = "تيبارا"
rs[90] = "مــہٰٰـــو بحــہٰٰـــالكے القــہٰٰـائــہٰٰـد 🎤🚶"
ws[91] = "انور"
rs[91] = "هہٰٰذا بہٰٰطہٰٰوري وحہٰٰبہٰٰيب كلہٰٰبي @x_I_10_I_x 🙊🌸"
ws[92] = "كرار"
rs[92] = "هہٰٰذا بہٰٰطہٰٰوري وحہٰٰبہٰٰيب كلہٰٰبي @liknil 🙊🌸"
ws[93] = "علاوي"
rs[93] = "هہٰٰذا بہٰٰطہٰٰوري وحہٰٰبہٰٰيب كلہٰٰبي @Aaa1R 🙊🌸"
ws[94] = "وليد"
rs[94] = "هہٰٰذا بہٰٰطہٰٰوري وحہٰٰبہٰٰيب كلہٰٰبي @w_Dev_d 🙊🌸"
ws[95] = "زعيم"
rs[95] = "هہٰٰذا بہٰٰطہٰٰوري وحہٰٰبہٰٰيب كلہٰٰبي @llN00Nll 🙊🌸"
ws[96] = "شنو"
rs[96] = "اي 😪مثل ماسمعت👀"
ws[97] = "شنو"
rs[97] = "اي 😪مثل ماسمعت👀"
ws[98] = "ليث"
rs[98] = " #تہٰٰجہٰٰراسہٰٰك (@lI3l3Il )ليہٰٰث ابہٰٰن العہٰٰراق 🐸💋"
ws[99] = "."
rs[99] = " ينزل رابط الكروب بل تعديل لا يا خرا 💦☹️🚶🏿"
ws[100] = "هلاو"
rs[100] = "هلاوو99وووات نورت/ي 👌🏿😂"
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] = "بالــســ🚗ــيــارﮭﮧ"
-- 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)
-- send him the proper message from the index that { i } assigned to
--send_large_msg ( R , rs[i] );
--send_reply(msg.id, rs[i])
reply_msg(msg.id, rs[i], ok_cb, false )
end
-- don't edit this section
if ( msg.text == "about" ) then
if ( msg.from.username == "li_xXx_il" ) then
R = get_receiver(msg)
send_large_msg ( R , "Made by @li_xXx_il" );
end
end
end
return {
patterns = {
"(.*)"
},
run = run
}
end | gpl-2.0 |
ThingMesh/openwrt-luci | applications/luci-qos/luasrc/model/cbi/qos/qos.lua | 28 | 2629 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("qos", translate("Quality of Service"),
translate("With <abbr title=\"Quality of Service\">QoS</abbr> you " ..
"can prioritize network traffic selected by addresses, " ..
"ports or services."))
s = m:section(TypedSection, "interface", translate("Interfaces"))
s.addremove = true
s.anonymous = false
e = s:option(Flag, "enabled", translate("Enable"))
e.rmempty = false
c = s:option(ListValue, "classgroup", translate("Classification group"))
c:value("Default", translate("default"))
c.default = "Default"
s:option(Flag, "overhead", translate("Calculate overhead"))
s:option(Flag, "halfduplex", translate("Half-duplex"))
dl = s:option(Value, "download", translate("Download speed (kbit/s)"))
dl.datatype = "and(uinteger,min(1))"
ul = s:option(Value, "upload", translate("Upload speed (kbit/s)"))
ul.datatype = "and(uinteger,min(1))"
s = m:section(TypedSection, "classify", translate("Classification Rules"))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
s.sortable = true
t = s:option(ListValue, "target", translate("Target"))
t:value("Priority", translate("priority"))
t:value("Express", translate("express"))
t:value("Normal", translate("normal"))
t:value("Bulk", translate("low"))
t.default = "Normal"
srch = s:option(Value, "srchost", translate("Source host"))
srch.rmempty = true
srch:value("", translate("all"))
wa.cbi_add_knownips(srch)
dsth = s:option(Value, "dsthost", translate("Destination host"))
dsth.rmempty = true
dsth:value("", translate("all"))
wa.cbi_add_knownips(dsth)
l7 = s:option(ListValue, "layer7", translate("Service"))
l7.rmempty = true
l7:value("", translate("all"))
local pats = io.popen("find /etc/l7-protocols/ -type f -name '*.pat'")
if pats then
local l
while true do
l = pats:read("*l")
if not l then break end
l = l:match("([^/]+)%.pat$")
if l then
l7:value(l)
end
end
pats:close()
end
p = s:option(Value, "proto", translate("Protocol"))
p:value("", translate("all"))
p:value("tcp", "TCP")
p:value("udp", "UDP")
p:value("icmp", "ICMP")
p.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("all"))
bytes = s:option(Value, "connbytes", translate("Number of bytes"))
return m
| apache-2.0 |
cshore-firmware/openwrt-luci | applications/luci-app-openvpn/luasrc/model/cbi/openvpn-advanced.lua | 6 | 20307 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.ip")
require("luci.model.uci")
local knownParams = {
--
-- Widget Name Default(s) Description Option(s)
--
{ "Service", {
-- initialisation and daemon options
{ ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") },
{ Flag, "mlock", 0, translate("Disable Paging") },
{ Flag, "disable_occ", 0, translate("Disable options consistency check") },
-- { Value, "user", "root", translate("Set UID to user") },
-- { Value, "group", "root", translate("Set GID to group") },
{ Value, "cd", "/etc/openvpn", translate("Change to directory before initialization") },
{ Value, "chroot", "/var/run", translate("Chroot to directory after initialization") },
-- { Value, "daemon", "Instance-Name", translate("Daemonize after initialization") },
-- { Value, "syslog", "Instance-Name", translate("Output to syslog and do not daemonize") },
{ Flag, "passtos", 0, translate("TOS passthrough (applies to IPv4 only)") },
-- { Value, "inetd", "nowait Instance-Name", translate("Run as an inetd or xinetd server") },
{ Value, "log", "/var/log/openvpn.log", translate("Write log to file") },
{ Value, "log_append", "/var/log/openvpn.log", translate("Append log to file") },
{ Flag, "suppress_timestamps", 0, translate("Don't log timestamps") },
-- { Value, "writepid", "/var/run/openvpn.pid", translate("Write process ID to file") },
{ Value, "nice", 0, translate("Change process priority") },
{ Flag, "fast_io", 0, translate("Optimize TUN/TAP/UDP writes") },
{ Value, "echo", "some params echoed to log", translate("Echo parameters to log") },
{ ListValue, "remap_usr1", { "SIGHUP", "SIGTERM" }, translate("Remap SIGUSR1 signals") },
{ Value, "status", "/var/run/openvpn.status 5", translate("Write status to file every n seconds") },
{ Value, "status_version", { 1, 2 }, translate("Status file format version") }, -- status
{ Value, "mute", 5, translate("Limit repeated log messages") },
{ Value, "up", "/usr/bin/ovpn-up", translate("Shell cmd to execute after tun device open") },
{ Value, "up_delay", 5, translate("Delay tun/tap open and up script execution") },
{ Value, "down", "/usr/bin/ovpn-down", translate("Shell cmd to run after tun device close") },
{ Flag, "down_pre", 0, translate("Call down cmd/script before TUN/TAP close") },
{ Flag, "up_restart", 0, translate("Run up/down scripts for all restarts") },
{ Value, "route_up", "/usr/bin/ovpn-routeup", translate("Execute shell cmd after routes are added") },
{ Value, "ipchange", "/usr/bin/ovpn-ipchange", translate("Execute shell command on remote ip change"), { mode="p2p" } },
{ DynamicList, "setenv", { "VAR1 value1", "VAR2 value2" }, translate("Pass environment variables to script") },
{ Value, "tls_verify", "/usr/bin/ovpn-tlsverify", translate("Shell command to verify X509 name") },
{ Value, "client_connect", "/usr/bin/ovpn-clientconnect", translate("Run script cmd on client connection") },
{ Flag, "client_disconnect", 0, translate("Run script cmd on client disconnection") },
{ Value, "learn_address", "/usr/bin/ovpn-learnaddress", translate("Executed in server mode whenever an IPv4 address/route or MAC address is added to OpenVPN's internal routing table") },
{ Value, "auth_user_pass_verify", "/usr/bin/ovpn-userpass via-env", translate("Executed in server mode on new client connections, when the client is still untrusted") },
{ ListValue, "script_security", { 0, 1, 2, 3 }, translate("Policy level over usage of external programs and scripts") },
} },
{ "Networking", {
-- socket config
{ ListValue, "mode", { "p2p", "server" }, translate("Major mode") },
{ Value, "local", "0.0.0.0", translate("Local host name or ip address") },
{ Value, "port", 1194, translate("TCP/UDP port # for both local and remote") },
{ Value, "lport", 1194, translate("TCP/UDP port # for local (default=1194)") },
{ Value, "rport", 1194, translate("TCP/UDP port # for remote (default=1194)") },
{ Flag, "float", 0, translate("Allow remote to change its IP or port") },
{ Flag, "nobind", 0, translate("Do not bind to local address and port") },
{ Value, "dev", "tun0", translate("tun/tap device") },
{ ListValue, "dev_type", { "tun", "tap" }, translate("Type of used device") },
{ Value, "dev_node", "/dev/net/tun", translate("Use tun/tap device node") },
{ Flag, "tun_ipv6", 0, translate("Make tun device IPv6 capable") },
{ Value, "ifconfig", "10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") },
{ Flag, "ifconfig_noexec", 0, translate("Don't actually execute ifconfig") },
{ Flag, "ifconfig_nowarn", 0, translate("Don't warn on ifconfig inconsistencies") },
{ DynamicList, "route", "10.123.0.0 255.255.0.0", translate("Add route after establishing connection") },
{ Value, "route_gateway", "10.234.1.1", translate("Specify a default gateway for routes") },
{ Value, "route_delay", 0, translate("Delay n seconds after connection") },
{ Flag, "route_noexec", 0, translate("Don't add routes automatically") },
{ Flag, "route_nopull", 0, translate("Don't pull routes automatically") },
{ ListValue, "mtu_disc", { "yes", "maybe", "no" }, translate("Enable Path MTU discovery") },
{ Flag, "mtu_test", 0, translate("Empirically measure MTU") },
{ ListValue, "comp_lzo", { "yes", "no", "adaptive" }, translate("Use fast LZO compression") },
{ Flag, "comp_noadapt", 0, translate("Don't use adaptive lzo compression"), { comp_lzo=1 } },
{ Value, "link_mtu", 1500, translate("Set TCP/UDP MTU") },
{ Value, "tun_mtu", 1500, translate("Set tun/tap device MTU") },
{ Value, "tun_mtu_extra", 1500, translate("Set tun/tap device overhead") },
{ Value, "fragment", 1500, translate("Enable internal datagram fragmentation"), { proto="udp" } },
{ Value, "mssfix", 1500, translate("Set upper bound on TCP MSS"), { proto="udp" } },
{ Value, "sndbuf", 65536, translate("Set the TCP/UDP send buffer size") },
{ Value, "rcvbuf", 65536, translate("Set the TCP/UDP receive buffer size") },
{ Value, "txqueuelen", 100, translate("Set tun/tap TX queue length") },
{ Value, "shaper", 10240, translate("Shaping for peer bandwidth") },
{ Value, "inactive", 240, translate("tun/tap inactivity timeout") },
{ Value, "keepalive", "10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") },
{ Value, "ping", 30, translate("Ping remote every n seconds over TCP/UDP port") },
{ Value, "ping_exit", 120, translate("Remote ping timeout") },
{ Value, "ping_restart", 60, translate("Restart after remote ping timeout") },
{ Flag, "ping_timer_rem", 0, translate("Only process ping timeouts if routes exist") },
{ Flag, "persist_tun", 0, translate("Keep tun/tap device open on restart") },
{ Flag, "persist_key", 0, translate("Don't re-read key on restart") },
{ Flag, "persist_local_ip", 0, translate("Keep local IP address on restart") },
{ Flag, "persist_remote_ip", 0, translate("Keep remote IP address on restart") },
-- management channel
{ Value, "management", "127.0.0.1 31194 /etc/openvpn/mngmt-pwds", translate("Enable management interface on <em>IP</em> <em>port</em>") },
{ Flag, "management_query_passwords", 0, translate("Query management channel for private key") }, -- management
{ Flag, "management_hold", 0, translate("Start OpenVPN in a hibernating state") }, -- management
{ Value, "management_log_cache", 100, translate("Number of lines for log file history") }, -- management
{ ListValue, "topology", { "net30", "p2p", "subnet" }, translate("'net30', 'p2p', or 'subnet'"), {dev_type="tun" } },
} },
{ "VPN", {
{ Value, "server", "10.200.200.0 255.255.255.0", translate("Configure server mode"), { server_mode="1" } },
{ Value, "server_bridge", "10.200.200.1 255.255.255.0 10.200.200.200 10.200.200.250", translate("Configure server bridge"), { server_mode="1" } },
{ DynamicList, "push", { "redirect-gateway", "comp-lzo" }, translate("Push options to peer"), { server_mode="1" } },
{ Flag, "push_reset", 0, translate("Don't inherit global push options"), { server_mode="1" } },
{ Flag, "disable", 0, translate("Client is disabled"), { server_mode="1" } },
{ Value, "ifconfig_pool", "10.200.200.100 10.200.200.150 255.255.255.0", translate("Set aside a pool of subnets"), { server_mode="1" } },
{ Value, "ifconfig_pool_persist", "/etc/openvpn/ipp.txt 600", translate("Persist/unpersist ifconfig-pool"), { server_mode="1" } },
-- { Flag, "ifconfig_pool_linear", 0, translate("Use individual addresses rather than /30 subnets"), { server_mode="1" } }, -- deprecated and replaced by --topology p2p
{ Value, "ifconfig_push", "10.200.200.1 255.255.255.255", translate("Push an ifconfig option to remote"), { server_mode="1" } },
{ Value, "iroute", "10.200.200.0 255.255.255.0", translate("Route subnet to client"), { server_mode="1" } },
{ Flag, "client_to_client", 0, translate("Allow client-to-client traffic"), { server_mode="1" } },
{ Flag, "duplicate_cn", 0, translate("Allow multiple clients with same certificate"), { server_mode="1" } },
{ Value, "client_config_dir", "/etc/openvpn/ccd", translate("Directory for custom client config files"), { server_mode="1" } },
{ Flag, "ccd_exclusive", 0, translate("Refuse connection if no custom client config"), { server_mode="1" } },
{ Value, "tmp_dir", "/var/run/openvpn", translate("Temporary directory for client-connect return file"), { server_mode="1" } },
{ Value, "hash_size", "256 256", translate("Set size of real and virtual address hash tables"), { server_mode="1" } },
{ Value, "bcast_buffers", 256, translate("Number of allocated broadcast buffers"), { server_mode="1" } },
{ Value, "tcp_queue_limit", 64, translate("Maximum number of queued TCP output packets"), { server_mode="1" } },
{ Value, "max_clients", 10, translate("Allowed maximum of connected clients"), { server_mode="1" } },
{ Value, "max_routes_per_client", 256, translate("Allowed maximum of internal"), { server_mode="1" } },
{ Value, "connect_freq", "3 10", translate("Allowed maximum of new connections"), { server_mode="1" } },
{ Flag, "client_cert_not_required", 0, translate("Don't require client certificate"), { server_mode="1" } },
{ Flag, "username_as_common_name", 0, translate("Use username as common name"), { server_mode="1" } },
{ Flag, "client", 0, translate("Configure client mode"), { server_mode="0" }, { server_mode="" } },
{ Flag, "pull", 0, translate("Accept options pushed from server"), { client="1" } },
{ Value, "auth_user_pass", "/etc/openvpn/userpass.txt", translate("Authenticate using username/password"), { client="1" } },
{ ListValue, "auth_retry", { "none", "nointeract", "interact" }, translate("Handling of authentication failures"), { client="1" } },
{ Value, "explicit_exit_notify", 1, translate("Send notification to peer on disconnect"), { client="1" } },
{ DynamicList, "remote", "1.2.3.4", translate("Remote host name or ip address"), { client="1" } },
{ Flag, "remote_random", 1, translate("Randomly choose remote server"), { client="1" } },
{ ListValue, "proto", { "udp", "tcp-client", "tcp-server" }, translate("Use protocol"), { client="1" } },
{ Value, "connect_retry", 5, translate("Connection retry interval"), { proto="tcp-client" }, { client="1" } },
{ Value, "http_proxy", "192.168.1.100 8080", translate("Connect to remote host through an HTTP proxy"), { client="1" } },
{ Flag, "http_proxy_retry", 0, translate("Retry indefinitely on HTTP proxy errors"), { client="1" } },
{ Value, "http_proxy_timeout", 5, translate("Proxy timeout in seconds"), { client="1" } },
{ DynamicList, "http_proxy_option", { "VERSION 1.0", "AGENT OpenVPN/2.0.9" }, translate("Set extended HTTP proxy options"), { client="1" } },
{ Value, "socks_proxy", "192.168.1.200 1080", translate("Connect through Socks5 proxy"), { client="1" } },
{ Value, "socks_proxy_retry", 5, translate("Retry indefinitely on Socks proxy errors"), { client="1" } }, -- client && socks_proxy
{ Value, "resolv_retry", "infinite", translate("If hostname resolve fails, retry"), { client="1" } },
{ ListValue, "redirect_gateway", { "", "local", "def1", "local def1" }, translate("Automatically redirect default route"), { client="1" } },
} },
{ "Cryptography", {
{ FileUpload, "secret", "/etc/openvpn/secret.key", translate("Enable Static Key encryption mode (non-TLS)") },
{ Value, "auth", "SHA1", translate("HMAC authentication for packets") }, -- parse
{ Value, "cipher", "BF-CBC", translate("Encryption cipher for packets") }, -- parse
{ Value, "keysize", 1024, translate("Size of cipher key") }, -- parse
{ Value, "engine", "dynamic", translate("Enable OpenSSL hardware crypto engines") }, -- parse
{ Flag, "no_replay", 0, translate("Disable replay protection") },
{ Value, "replay_window", "64 15", translate("Replay protection sliding window size") },
{ Flag, "mute_replay_warnings", 0, translate("Silence the output of replay warnings") },
{ Value, "replay_persist", "/var/run/openvpn-replay-state", translate("Persist replay-protection state") },
{ Flag, "no_iv", 0, translate("Disable cipher initialisation vector") },
{ Flag, "tls_server", 0, translate("Enable TLS and assume server role"), { tls_client="" }, { tls_client="0" } },
{ Flag, "tls_client", 0, translate("Enable TLS and assume client role"), { tls_server="" }, { tls_server="0" } },
{ FileUpload, "ca", "/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") },
{ FileUpload, "dh", "/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") },
{ FileUpload, "cert", "/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") },
{ FileUpload, "key", "/etc/easy-rsa/keys/some-client.key", translate("Local private key") },
{ FileUpload, "pkcs12", "/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") },
{ ListValue, "key_method", { 1, 2 }, translate("Enable TLS and assume client role") },
{ Value, "tls_cipher", "DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:EDH-RSA-DES-CBC-SHA:EDH-DSS-DES-CBC-SHA:DES-CBC-SHA:EXP-EDH-RSA-DES-CBC-SHA:EXP-EDH-DSS-DES-CBC-SHA:EXP-DES-CBC-SHA:EXP-RC2-CBC-MD5:EXP-RC4-MD5",
translate("TLS cipher") },
{ Value, "tls_timeout", 2, translate("Retransmit timeout on TLS control channel") },
{ Value, "reneg_bytes", 1024, translate("Renegotiate data chan. key after bytes") },
{ Value, "reneg_pkts", 100, translate("Renegotiate data chan. key after packets") },
{ Value, "reneg_sec", 3600, translate("Renegotiate data chan. key after seconds") },
{ Value, "hand_window", 60, translate("Timeframe for key exchange") },
{ Value, "tran_window", 3600, translate("Key transition window") },
{ Flag, "single_session", 0, translate("Allow only one session") },
{ Flag, "tls_exit", 0, translate("Exit on TLS negotiation failure") },
{ Value, "tls_auth", "/etc/openvpn/tlsauth.key", translate("Additional authentication over TLS") },
--{ Value, "askpass", "[file]", translate("Get PEM password from controlling tty before we daemonize") },
{ Flag, "auth_nocache", 0, translate("Don't cache --askpass or --auth-user-pass passwords") },
{ Value, "tls_remote", "remote_x509_name", translate("Only accept connections from given X509 name") },
{ ListValue, "ns_cert_type", { "client", "server" }, translate("Require explicit designation on certificate") },
{ ListValue, "remote_cert_tls", { "client", "server" }, translate("Require explicit key usage on certificate") },
{ Value, "crl_verify", "/etc/easy-rsa/keys/crl.pem", translate("Check peer certificate against a CRL") },
{ Value, "tls_version_min", "1.0", translate("The lowest supported TLS version") },
{ Value, "tls_version_max", "1.2", translate("The highest supported TLS version") },
{ Value, "key_direction", "1", translate("The key direction for 'tls-auth' and 'secret' options") },
} }
}
local cts = { }
local params = { }
local m = Map("openvpn")
local p = m:section( SimpleSection )
p.template = "openvpn/pageswitch"
p.mode = "advanced"
p.instance = arg[1]
p.category = arg[2] or "Service"
for _, c in ipairs(knownParams) do
cts[#cts+1] = c[1]
if c[1] == p.category then params = c[2] end
end
p.categories = cts
local s = m:section(
NamedSection, arg[1], "openvpn",
translate("%s" % arg[2])
)
s.title = translate("%s" % arg[2])
s.addremove = false
s.anonymous = true
for _, option in ipairs(params) do
local o = s:option(
option[1], option[2],
option[2], option[4]
)
if option[1] == DummyValue then
o.value = option[3]
else
if option[1] == DynamicList then
function o.cfgvalue(...)
local val = AbstractValue.cfgvalue(...)
return ( val and type(val) ~= "table" ) and { val } or val
end
end
o.optional = true
if type(option[3]) == "table" then
if o.optional then o:value("", "-- remove --") end
for _, v in ipairs(option[3]) do
v = tostring(v)
o:value(v)
end
o.default = tostring(option[3][1])
else
o.default = tostring(option[3])
end
end
for i=5,#option do
if type(option[i]) == "table" then
o:depends(option[i])
end
end
end
return m
| apache-2.0 |
Lsty/ygopro-scripts | c55046718.lua | 7 | 2646 | --ヴァイロン・コンポーネント
function c55046718.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c55046718.target)
e1:SetOperation(c55046718.operation)
c:RegisterEffect(e1)
--Pierce
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e2)
--Equip limit
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE)
e3:SetCode(EFFECT_EQUIP_LIMIT)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetValue(c55046718.eqlimit)
c:RegisterEffect(e3)
--Search
local e4=Effect.CreateEffect(c)
e4:SetDescription(aux.Stringid(55046718,0))
e4:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e4:SetProperty(EFFECT_FLAG_DELAY+EFFECT_FLAG_DAMAGE_STEP)
e4:SetCode(EVENT_TO_GRAVE)
e4:SetCondition(c55046718.thcon)
e4:SetTarget(c55046718.thtg)
e4:SetOperation(c55046718.thop)
c:RegisterEffect(e4)
end
function c55046718.eqlimit(e,c)
return c:IsSetCard(0x30)
end
function c55046718.filter(c)
return c:IsFaceup() and c:IsSetCard(0x30)
end
function c55046718.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c55046718.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c55046718.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c55046718.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c55046718.operation(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local tc=Duel.GetFirstTarget()
if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,c,tc)
end
end
function c55046718.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousPosition(POS_FACEUP)
and e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c55046718.thfilter(c)
return c:IsSetCard(0x30) and c:IsType(TYPE_SPELL) and c:IsAbleToHand()
end
function c55046718.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c55046718.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c55046718.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c55046718.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c5728014.lua | 5 | 1502 | --ライバル登場!
function c5728014.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c5728014.target)
e1:SetOperation(c5728014.activate)
c:RegisterEffect(e1)
end
function c5728014.filter(c,e,tp)
local lv=c:GetLevel()
return c:IsFaceup() and lv>0 and Duel.IsExistingMatchingCard(c5728014.spfilter,tp,LOCATION_HAND,0,1,nil,e,tp,lv)
end
function c5728014.spfilter(c,e,tp,lv)
return c:GetLevel()==lv and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c5728014.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return false end
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and Duel.IsExistingTarget(c5728014.filter,tp,0,LOCATION_MZONE,1,nil,e,tp) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_OPPO)
Duel.SelectTarget(tp,c5728014.filter,tp,0,LOCATION_MZONE,1,1,nil,e,tp)
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c5728014.activate(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c5728014.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp,tc:GetLevel())
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c55935416.lua | 6 | 1252 | --No.56 ゴールドラット
function c55935416.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,1,3)
c:EnableReviveLimit()
--damage
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(55935416,0))
e1:SetCategory(CATEGORY_DRAW+CATEGORY_TODECK)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c55935416.drcost)
e1:SetTarget(c55935416.drtg)
e1:SetOperation(c55935416.drop)
c:RegisterEffect(e1)
end
c55935416.xyz_number=56
function c55935416.drcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c55935416.drtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsPlayerCanDraw(tp,1) end
Duel.SetTargetPlayer(tp)
Duel.SetTargetParam(1)
Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,tp,1)
end
function c55935416.drop(e,tp,eg,ep,ev,re,r,rp)
local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM)
local ct=Duel.Draw(p,d,REASON_EFFECT)
if ct~=0 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,aux.TRUE,tp,LOCATION_HAND,0,1,1,nil)
Duel.SendtoDeck(g,nil,2,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/RuLude_Gardens/npcs/Pherimociel.lua | 9 | 2711 | -----------------------------------
-- Area: Ru'Lude Gardens
-- NPC: Pherimociel
-- Involved in mission: COP 1-2
-- !pos -31.627 1.002 67.956 243
-----------------------------------
require("scripts/globals/missions");
-----------------------------------
function onTrade(player,npc,trade)
end;
function onTrigger(player,npc)
local Hrandom =math.random();
if (player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(24);
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.BELOW_THE_ARKS and player:getCharVar("PromathiaStatus") == 1) then
player:startEvent(25);
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.THREE_PATHS and player:getCharVar("COP_Tenzen_s_Path") == 3) then
player:startEvent(58);
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.FOR_WHOM_THE_VERSE_IS_SUNG and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(10046);
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.A_PLACE_TO_RETURN and player:getCharVar("PromathiaStatus") == 1) then
if (Hrandom<0.2) then
player:startEvent(27);
elseif (Hrandom<0.6) then
player:startEvent(28);
else
player:startEvent(29);
end
elseif (player:getCurrentMission(COP) == dsp.mission.id.cop.MORE_QUESTIONS_THAN_ANSWERS and player:getCharVar("PromathiaStatus") == 0) then
player:startEvent(10049);
elseif (player:getCurrentMission(TOAU) == dsp.mission.id.toau.UNRAVELING_REASON) then
if (player:getCharVar("TOAUM40_STARTDAY") ~= VanadielDayOfTheYear() and player:needToZone() == false) then
player:startEvent(10098,0,0,0,0,0,0,0,0);
else
player:startEvent(10099);
end
else
player:startEvent(155);
end
end;
function onEventUpdate(player,csid,option)
-- printf("Update CSID: %u",csid);
-- printf("Update RESULT: %u",option);
end;
function onEventFinish(player,csid,option)
-- printf("Finish CSID: %u",csid);
-- printf("Finish RESULT: %u",option);
if (csid == 10098) then
player:setPos(0,0,0,0,51);
elseif (csid == 24) then
player:setCharVar("PromathiaStatus",1); -- first cs mission 1.2 has been seen YOU CAN NOW ENTER TO PROMYVION
player:setCharVar("FirstPromyvionHolla",1);
player:setCharVar("FirstPromyvionMea",1);
player:setCharVar("FirstPromyvionDem",1);
elseif (csid == 58) then
player:setCharVar("COP_Tenzen_s_Path",4);
elseif (csid == 10046 or 10049) then
player:setCharVar("PromathiaStatus",1);
end
end;
| gpl-3.0 |
tryroach/vlc | share/lua/meta/fetcher/tvrage.lua | 66 | 2629 | --[[
Gets metas for tv episode using tvrage.
$Id$
Copyright © 2010 the VideoLAN team
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston MA 02110-1301, USA.
--]]
function descriptor()
return { scope="network" }
end
-- Replace non alphanumeric char by +
function get_query( title )
-- If we have a .EXT remove the extension.
str = string.gsub( title, "(.*)%....$", "%1" )
return string.gsub( str, "([^%w ])",
function (c) return string.format ("%%%02X", string.byte(c)) end)
end
function fetch_meta()
local metas = vlc.item:metas()
local showName = metas["showName"]
if not showName then
return false
end
local seasonNumber = metas["seasonNumber"];
if not seasonNumber then
return false
end
local episodeNumber = metas["episodeNumber"];
if not episodeNumber then
return false
end
local fd = vlc.stream("http://services.tvrage.com/feeds/search.php?show=" .. get_query(showName))
if not fd then return nil end
local page = fd:read( 65653 )
fd = nil
_, _, showid = string.find( page, "<showid>(.-)</showid>" )
if not showid then
return false
end
fd = vlc.stream("http://services.tvrage.com/feeds/full_show_info.php?sid=" .. showid)
if not fd then return nil end
page = fd:read( 65653 )
fd = nil
_, _, season = string.find(page, "<Season no=\""..seasonNumber.."\">(.-)</Season>")
if not season then
return false
end
_, _, episode = string.find(season, "<episode>(.-<seasonnum>"..episodeNumber.."</seasonnum>.-)</episode>")
if not episode then
return false
end
_, _, title, artwork = string.find(episode, "<title>(.-)</title><screencap>(.-)</screencap>")
if not title then
return false
end
vlc.item:set_meta("title", showName.. " S"..seasonNumber.."E"..episodeNumber.." - ".. title)
vlc.item:set_meta("artwork_url", artwork)
vlc.item:set_meta("episodeName", title)
return true
end
| gpl-2.0 |
chu11/flux-core | src/bindings/lua/Test/Builder/Tester.lua | 8 | 3207 |
--
-- lua-TestMore : <http://fperrad.github.com/lua-TestMore/>
--
local error = error
local pairs = pairs
local tostring = tostring
local type = type
local _G = _G
local debug = require 'debug'
local tb = require 'Test.Builder'.new()
local out = require 'Test.Builder.Tester.File'.new 'out'
local err = require 'Test.Builder.Tester.File'.new 'err'
_ENV = nil
local m = {}
-- for remembering that we're testing and where we're testing at
local testing = false
local testing_num
-- remembering where the file handles were originally connected
local original_output_handle
local original_failure_handle
local original_todo_handle
local function _start_testing ()
-- remember what the handles were set to
original_output_handle = tb:output()
original_failure_handle = tb:failure_output()
original_todo_handle = tb:todo_output()
-- switch out to our own handles
tb:output(out)
tb:failure_output(err)
tb:todo_output(err)
-- clear the expected list
out:reset()
err:reset()
-- remeber that we're testing
testing = true
testing_num = tb:current_test()
tb:current_test(0)
-- look, we shouldn't do the ending stuff
tb.no_ending = true
end
function m.test_out (...)
if not testing then
_start_testing()
end
out:expect(...)
end
function m.test_err (...)
if not testing then
_start_testing()
end
err:expect(...)
end
function m.test_fail (offset)
offset = offset or 0
if not testing then
_start_testing()
end
local info = debug.getinfo(2)
local prog = info.short_src
local line = info.currentline + offset
err:expect("# Failed test (" .. prog .. " at line " .. tostring(line) .. ")")
end
function m.test_diag (...)
local arg = {...}
if not testing then
_start_testing()
end
for i = 1, #arg do
err:expect("# " .. arg[i])
end
end
function m.test_test (args)
local mess
if type(args) == 'table' then
mess = args[1]
else
mess = args
args = {}
end
if not testing then
error "Not testing. You must declare output with a test function first."
end
-- okay, reconnect the test suite back to the saved handles
tb:output(original_output_handle)
tb:failure_output(original_failure_handle)
tb:todo_output(original_todo_handle)
-- restore the test no, etc, back to the original point
tb:current_test(testing_num)
testing = false
-- check the output we've stashed
local pass = (args.skip_out or out:check())
and (args.skip_err or err:check())
tb:ok(pass, mess)
if not pass then
-- print out the diagnostic information about why this
-- test failed
if not out:check() then
tb:diag(out:complaint())
end
if not err:check() then
tb:diag(err:complaint())
end
end
end
function m.line_num ()
return debug.getinfo(2).currentline
end
for k, v in pairs(m) do -- injection
_G[k] = v
end
return m
--
-- Copyright (c) 2009-2012 Francois Perrad
--
-- This library is licensed under the terms of the MIT/X11 license,
-- like Lua itself.
--
| lgpl-3.0 |
imebeh/openwrt-packages | net/mwan3-luci/files/usr/lib/lua/luci/controller/mwan3.lua | 36 | 10850 | module("luci.controller.mwan3", package.seeall)
sys = require "luci.sys"
ut = require "luci.util"
function index()
if not nixio.fs.access("/etc/config/mwan3") then
return
end
entry({"admin", "network", "mwan"},
alias("admin", "network", "mwan", "overview"),
_("Load Balancing"), 600)
entry({"admin", "network", "mwan", "overview"},
alias("admin", "network", "mwan", "overview", "overview_interface"),
_("Overview"), 10)
entry({"admin", "network", "mwan", "overview", "overview_interface"},
template("mwan/overview_interface"))
entry({"admin", "network", "mwan", "overview", "interface_status"},
call("interfaceStatus"))
entry({"admin", "network", "mwan", "overview", "overview_detailed"},
template("mwan/overview_detailed"))
entry({"admin", "network", "mwan", "overview", "detailed_status"},
call("detailedStatus"))
entry({"admin", "network", "mwan", "configuration"},
alias("admin", "network", "mwan", "configuration", "interface"),
_("Configuration"), 20)
entry({"admin", "network", "mwan", "configuration", "interface"},
arcombine(cbi("mwan/interface"), cbi("mwan/interfaceconfig")),
_("Interfaces"), 10).leaf = true
entry({"admin", "network", "mwan", "configuration", "member"},
arcombine(cbi("mwan/member"), cbi("mwan/memberconfig")),
_("Members"), 20).leaf = true
entry({"admin", "network", "mwan", "configuration", "policy"},
arcombine(cbi("mwan/policy"), cbi("mwan/policyconfig")),
_("Policies"), 30).leaf = true
entry({"admin", "network", "mwan", "configuration", "rule"},
arcombine(cbi("mwan/rule"), cbi("mwan/ruleconfig")),
_("Rules"), 40).leaf = true
entry({"admin", "network", "mwan", "advanced"},
alias("admin", "network", "mwan", "advanced", "hotplugscript"),
_("Advanced"), 100)
entry({"admin", "network", "mwan", "advanced", "hotplugscript"},
form("mwan/advanced_hotplugscript"))
entry({"admin", "network", "mwan", "advanced", "mwanconfig"},
form("mwan/advanced_mwanconfig"))
entry({"admin", "network", "mwan", "advanced", "networkconfig"},
form("mwan/advanced_networkconfig"))
entry({"admin", "network", "mwan", "advanced", "diagnostics"},
template("mwan/advanced_diagnostics"))
entry({"admin", "network", "mwan", "advanced", "diagnostics_display"},
call("diagnosticsData"), nil).leaf = true
entry({"admin", "network", "mwan", "advanced", "troubleshooting"},
template("mwan/advanced_troubleshooting"))
entry({"admin", "network", "mwan", "advanced", "troubleshooting_display"},
call("troubleshootingData"))
end
function getInterfaceStatus(ruleNumber, interfaceName)
if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".enabled")) == "1" then
if ut.trim(sys.exec("ip route list table " .. ruleNumber)) ~= "" then
if ut.trim(sys.exec("uci -p /var/state get mwan3." .. interfaceName .. ".track_ip")) ~= "" then
return "online"
else
return "notMonitored"
end
else
return "offline"
end
else
return "notEnabled"
end
end
function getInterfaceName()
local ruleNumber, status = 0, ""
uci.cursor():foreach("mwan3", "interface",
function (section)
ruleNumber = ruleNumber+1
status = status .. section[".name"] .. "[" .. getInterfaceStatus(ruleNumber, section[".name"]) .. "]"
end
)
return status
end
function interfaceStatus()
local ntm = require "luci.model.network".init()
local mArray = {}
-- overview status
local statusString = getInterfaceName()
if statusString ~= "" then
mArray.wans = {}
wansid = {}
for wanName, interfaceState in string.gfind(statusString, "([^%[]+)%[([^%]]+)%]") do
local wanInterfaceName = ut.trim(sys.exec("uci -p /var/state get network." .. wanName .. ".ifname"))
if wanInterfaceName == "" then
wanInterfaceName = "X"
end
local wanDeviceLink = ntm:get_interface(wanInterfaceName)
wanDeviceLink = wanDeviceLink and wanDeviceLink:get_network()
wanDeviceLink = wanDeviceLink and wanDeviceLink:adminlink() or "#"
wansid[wanName] = #mArray.wans + 1
mArray.wans[wansid[wanName]] = { name = wanName, link = wanDeviceLink, ifname = wanInterfaceName, status = interfaceState }
end
end
-- overview status log
local mwanLog = ut.trim(sys.exec("logread | grep mwan3 | tail -n 50 | sed 'x;1!H;$!d;x'"))
if mwanLog ~= "" then
mArray.mwanlog = { mwanLog }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function detailedStatus()
local mArray = {}
-- detailed mwan status
local detailStatusInfo = ut.trim(sys.exec("/usr/sbin/mwan3 status"))
if detailStatusInfo ~= "" then
mArray.mwandetail = { detailStatusInfo }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function diagnosticsData(interface, tool, task)
function getInterfaceNumber()
local number = 0
uci.cursor():foreach("mwan3", "interface",
function (section)
number = number+1
if section[".name"] == interface then
interfaceNumber = number
end
end
)
end
local mArray = {}
local results = ""
if tool == "service" then
os.execute("/usr/sbin/mwan3 " .. task)
if task == "restart" then
results = "MWAN3 restarted"
elseif task == "stop" then
results = "MWAN3 stopped"
else
results = "MWAN3 started"
end
else
local interfaceDevice = ut.trim(sys.exec("uci -p /var/state get network." .. interface .. ".ifname"))
if interfaceDevice ~= "" then
if tool == "ping" then
local gateway = ut.trim(sys.exec("route -n | awk '{if ($8 == \"" .. interfaceDevice .. "\" && $1 == \"0.0.0.0\" && $3 == \"0.0.0.0\") print $2}'"))
if gateway ~= "" then
if task == "gateway" then
local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. gateway
results = pingCommand .. "\n\n" .. sys.exec(pingCommand)
else
local tracked = ut.trim(sys.exec("uci -p /var/state get mwan3." .. interface .. ".track_ip"))
if tracked ~= "" then
for z in tracked:gmatch("[^ ]+") do
local pingCommand = "ping -c 3 -W 2 -I " .. interfaceDevice .. " " .. z
results = results .. pingCommand .. "\n\n" .. sys.exec(pingCommand) .. "\n\n"
end
else
results = "No tracking IP addresses configured on " .. interface
end
end
else
results = "No default gateway for " .. interface .. " found. Default route does not exist or is configured incorrectly"
end
elseif tool == "rulechk" then
getInterfaceNumber()
local rule1 = sys.exec("ip rule | grep $(echo $((" .. interfaceNumber .. " + 1000)))")
local rule2 = sys.exec("ip rule | grep $(echo $((" .. interfaceNumber .. " + 2000)))")
if rule1 ~= "" and rule2 ~= "" then
results = "All required interface IP rules found:\n\n" .. rule1 .. rule2
elseif rule1 ~= "" or rule2 ~= "" then
results = "Missing 1 of the 2 required interface IP rules\n\n\nRules found:\n\n" .. rule1 .. rule2
else
results = "Missing both of the required interface IP rules"
end
elseif tool == "routechk" then
getInterfaceNumber()
local routeTable = sys.exec("ip route list table " .. interfaceNumber)
if routeTable ~= "" then
results = "Interface routing table " .. interfaceNumber .. " was found:\n\n" .. routeTable
else
results = "Missing required interface routing table " .. interfaceNumber
end
elseif tool == "hotplug" then
if task == "ifup" then
os.execute("/usr/sbin/mwan3 ifup " .. interface)
results = "Hotplug ifup sent to interface " .. interface .. "..."
else
os.execute("/usr/sbin/mwan3 ifdown " .. interface)
results = "Hotplug ifdown sent to interface " .. interface .. "..."
end
end
else
results = "Unable to perform diagnostic tests on " .. interface .. ". There is no physical or virtual device associated with this interface"
end
end
if results ~= "" then
results = ut.trim(results)
mArray.diagnostics = { results }
end
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
function troubleshootingData()
local ver = require "luci.version"
local mArray = {}
-- software versions
local wrtRelease = ut.trim(ver.distversion)
if wrtRelease ~= "" then
wrtRelease = "OpenWrt - " .. wrtRelease
else
wrtRelease = "OpenWrt - unknown"
end
local luciRelease = ut.trim(ver.luciversion)
if luciRelease ~= "" then
luciRelease = "\nLuCI - " .. luciRelease
else
luciRelease = "\nLuCI - unknown"
end
local mwanVersion = ut.trim(sys.exec("opkg info mwan3 | grep Version | awk '{print $2}'"))
if mwanVersion ~= "" then
mwanVersion = "\n\nmwan3 - " .. mwanVersion
else
mwanVersion = "\n\nmwan3 - unknown"
end
local mwanLuciVersion = ut.trim(sys.exec("opkg info luci-app-mwan3 | grep Version | awk '{print $2}'"))
if mwanLuciVersion ~= "" then
mwanLuciVersion = "\nmwan3-luci - " .. mwanLuciVersion
else
mwanLuciVersion = "\nmwan3-luci - unknown"
end
mArray.versions = { wrtRelease .. luciRelease .. mwanVersion .. mwanLuciVersion }
-- mwan config
local mwanConfig = ut.trim(sys.exec("cat /etc/config/mwan3"))
if mwanConfig == "" then
mwanConfig = "No data found"
end
mArray.mwanconfig = { mwanConfig }
-- network config
local networkConfig = ut.trim(sys.exec("cat /etc/config/network | sed -e 's/.*username.*/ USERNAME HIDDEN/' -e 's/.*password.*/ PASSWORD HIDDEN/'"))
if networkConfig == "" then
networkConfig = "No data found"
end
mArray.netconfig = { networkConfig }
-- ifconfig
local ifconfig = ut.trim(sys.exec("ifconfig"))
if ifconfig == "" then
ifconfig = "No data found"
end
mArray.ifconfig = { ifconfig }
-- route -n
local routeShow = ut.trim(sys.exec("route -n"))
if routeShow == "" then
routeShow = "No data found"
end
mArray.routeshow = { routeShow }
-- ip rule show
local ipRuleShow = ut.trim(sys.exec("ip rule show"))
if ipRuleShow == "" then
ipRuleShow = "No data found"
end
mArray.iprule = { ipRuleShow }
-- ip route list table 1-250
local routeList, routeString = ut.trim(sys.exec("ip rule | sed 's/://g' | awk '$1>=2001 && $1<=2250' | awk '{print $NF}'")), ""
if routeList ~= "" then
for line in routeList:gmatch("[^\r\n]+") do
routeString = routeString .. line .. "\n" .. sys.exec("ip route list table " .. line)
end
routeString = ut.trim(routeString)
else
routeString = "No data found"
end
mArray.routelist = { routeString }
-- default firewall output policy
local firewallOut = ut.trim(sys.exec("uci -p /var/state get firewall.@defaults[0].output"))
if firewallOut == "" then
firewallOut = "No data found"
end
mArray.firewallout = { firewallOut }
-- iptables
local iptables = ut.trim(sys.exec("iptables -L -t mangle -v -n"))
if iptables == "" then
iptables = "No data found"
end
mArray.iptables = { iptables }
luci.http.prepare_content("application/json")
luci.http.write_json(mArray)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c8649148.lua | 3 | 1247 | --ディープ・スィーパー
function c8649148.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(8649148,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetType(EFFECT_TYPE_IGNITION)
e1:SetRange(LOCATION_MZONE)
e1:SetCost(c8649148.cost)
e1:SetTarget(c8649148.target)
e1:SetOperation(c8649148.operation)
c:RegisterEffect(e1)
end
function c8649148.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsReleasable() end
Duel.Release(e:GetHandler(),REASON_COST)
end
function c8649148.filter(c)
return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable()
end
function c8649148.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsOnField() and c8649148.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c8649148.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c8649148.filter,tp,LOCATION_ONFIELD,LOCATION_ONFIELD,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
end
function c8649148.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsRelateToEffect(e) then
Duel.Destroy(tc,REASON_EFFECT)
end
end
| gpl-2.0 |
MalRD/darkstar | scripts/zones/Castle_Zvahl_Keep/Zone.lua | 12 | 2910 | -----------------------------------
--
-- Zone: Castle_Zvahl_Keep (162)
--
-----------------------------------
local ID = require("scripts/zones/Castle_Zvahl_Keep/IDs")
require("scripts/globals/conquest")
require("scripts/globals/treasure")
-----------------------------------
function onInitialize(zone)
zone:registerRegion(1, -301,-50,-22, -297,-49,-17) -- central porter on map 3
zone:registerRegion(2, -275,-54,3, -271,-53,7) -- NE porter on map 3
zone:registerRegion(3, -275,-54,-47, -271,-53,-42) -- SE porter on map 3
zone:registerRegion(4, -330,-54,3, -326,-53,7) -- NW porter on map 3
zone:registerRegion(5, -328,-54,-47, -324,-53,-42) -- SW porter on map 3
zone:registerRegion(6, -528,-74,84, -526,-73,89) -- N porter on map 4
zone:registerRegion(7, -528,-74,30, -526,-73,36) -- S porter on map 4
dsp.treasure.initZone(zone)
end
function onConquestUpdate(zone, updatetype)
dsp.conq.onConquestUpdate(zone, updatetype)
end
function onZoneIn(player,prevZone)
local cs = -1
if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then
player:setPos(-555.996,-71.691,59.989,254)
end
return cs
end
function onRegionEnter(player,region)
switch (region:GetRegionID()): caseof
{
---------------------------------
[1] = function (x) --
---------------------------------
player:startEvent(0) -- ports player to far NE corner
end,
---------------------------------
[2] = function (x) --
---------------------------------
player:startEvent(2) -- ports player to
end,
---------------------------------
[3] = function (x) --
---------------------------------
player:startEvent(1) -- ports player to far SE corner
end,
---------------------------------
[4] = function (x) --
---------------------------------
player:startEvent(1) -- ports player to far SE corner
end,
---------------------------------
[5] = function (x) --
---------------------------------
player:startEvent(5) -- ports player to H-7 on map 4 (south or north part, randomly)
end,
---------------------------------
[6] = function (x) --
---------------------------------
player:startEvent(6) -- ports player to position "A" on map 2
end,
---------------------------------
[7] = function (x) --
---------------------------------
player:startEvent(7) -- ports player to position G-8 on map 2
end,
default = function (x)
-- print("default")
end,
}
end
function onRegionLeave(player,region)
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end | gpl-3.0 |
cleytonk/globalfull | data/migrations/13.lua | 58 | 2963 | function onUpdateDatabase()
print("> Updating database to version 14 (account_bans, ip_bans and player_bans)")
db.query("CREATE TABLE IF NOT EXISTS `account_bans` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB")
db.query("CREATE TABLE IF NOT EXISTS `account_ban_history` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expired_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB")
db.query("CREATE TABLE IF NOT EXISTS `ip_bans` (`ip` int(10) unsigned NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`ip`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB")
db.query("CREATE TABLE IF NOT EXISTS `player_namelocks` (`player_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `namelocked_at` bigint(20) NOT NULL, `namelocked_by` int(11) NOT NULL, PRIMARY KEY (`player_id`), KEY `namelocked_by` (`namelocked_by`), FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`namelocked_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB")
local resultId = db.storeQuery("SELECT `player`, `time` FROM `bans` WHERE `type` = 2")
if resultId ~= false then
local stmt = "INSERT INTO `player_namelocks` (`player_id`, `namelocked_at`, `namelocked_by`) VALUES "
repeat
stmt = stmt .. "(" .. result.getDataInt(resultId, "player") .. "," .. result.getDataInt(resultId, "time") .. "," .. result.getDataInt(resultId, "player") .. "),"
until not result.next(resultId)
result.free(resultId)
local stmtLen = string.len(stmt)
if stmtLen > 86 then
stmt = string.sub(stmt, 1, stmtLen - 1)
db.query(stmt)
end
end
db.query("DROP TRIGGER `ondelete_accounts`")
db.query("DROP TRIGGER `ondelete_players`")
db.query("ALTER TABLE `accounts` DROP `warnings`")
db.query("DROP TABLE `bans`")
print("Run this query in your database to create the ondelete_players trigger:")
print("DELIMITER //")
print("CREATE TRIGGER `ondelete_players` BEFORE DELETE ON `players`")
print(" FOR EACH ROW BEGIN")
print(" UPDATE `houses` SET `owner` = 0 WHERE `owner` = OLD.`id`;")
print("END //")
return true
end
| gpl-2.0 |
zhaozg/lit | deps/coro-websocket.lua | 2 | 4331 | --[[lit-meta
name = "creationix/coro-websocket"
version = "3.1.1"
dependencies = {
"luvit/http-codec@3.0.0",
"creationix/websocket-codec@3.0.0",
"creationix/coro-net@3.3.0",
}
homepage = "https://github.com/luvit/lit/blob/master/deps/coro-websocket.lua"
description = "Websocket helpers assuming coro style I/O."
tags = {"coro", "websocket"}
license = "MIT"
author = { name = "Tim Caswell" }
]]
local uv = require('uv')
local httpCodec = require('http-codec')
local websocketCodec = require('websocket-codec')
local net = require('coro-net')
local function parseUrl(url)
local protocol, host, port, pathname = string.match(url, "^(wss?)://([^:/]+):?(%d*)(/?[^#?]*)")
local tls
if protocol == "ws" then
port = tonumber(port) or 80
tls = false
elseif protocol == "wss" then
port = tonumber(port) or 443
tls = true
else
return nil, "Sorry, only ws:// or wss:// protocols supported"
end
return {
host = host,
port = port,
tls = tls,
pathname = pathname
}
end
local function wrapIo(rawRead, rawWrite, options)
local closeSent = false
local timer
local function cleanup()
if timer then
if not timer:is_closing() then
timer:close()
end
timer = nil
end
end
local function write(message)
if message then
message.mask = options.mask
if message.opcode == 8 then
closeSent = true
rawWrite(message)
cleanup()
return rawWrite()
end
else
if not closeSent then
return write({
opcode = 8,
payload = ""
})
end
end
return rawWrite(message)
end
local function read()
while true do
local message = rawRead()
if not message then
return cleanup()
end
if message.opcode < 8 then
return message
end
if not closeSent then
if message.opcode == 8 then
write {
opcode = 8,
payload = message.payload
}
elseif message.opcode == 9 then
write {
opcode = 10,
payload = message.payload
}
end
return message
end
end
end
if options.heartbeat then
local interval = options.heartbeat
timer = uv.new_timer()
timer:unref()
timer:start(interval, interval, function ()
coroutine.wrap(function ()
local success, err = write {
opcode = 10,
payload = ""
}
if not success then
timer:close()
print(err)
end
end)()
end)
end
return read, write
end
-- options table to configure connection
-- options.path
-- options.host
-- options.port
-- options.tls
-- options.pathname
-- options.subprotocol
-- options.headers (as list of header/value pairs)
-- options.timeout
-- options.heartbeat
-- returns res, read, write (res.socket has socket)
local function connect(options)
options = options or {}
local config = {
path = options.path,
host = options.host,
port = options.port,
tls = options.tls,
encoder = httpCodec.encoder,
decoder = httpCodec.decoder,
}
local read, write, socket, updateDecoder, updateEncoder
= net.connect(config, options.timeout or 10000)
if not read then
return nil, write
end
local res
local success, err = websocketCodec.handshake({
host = options.host,
path = options.pathname,
protocol = options.subprotocol
}, function (req)
local headers = options.headers
if headers then
for i = 1, #headers do
req[#req + 1] = headers[i]
end
end
write(req)
res = read()
if not res then error("Missing server response") end
if res.code == 400 then
-- p { req = req, res = res }
local reason = read() or res.reason
error("Invalid request: " .. reason)
end
return res
end)
if not success then
return nil, err
end
-- Upgrade the protocol to websocket
updateDecoder(websocketCodec.decode)
updateEncoder(websocketCodec.encode)
read, write = wrapIo(read, write, {
mask = true,
heartbeat = options.heartbeat
})
res.socket = socket
return res, read, write
end
return {
parseUrl = parseUrl,
wrapIo = wrapIo,
connect = connect,
}
| apache-2.0 |
cleytonk/globalfull | data/actions/scripts/other/fluids.lua | 5 | 2573 | local drunk = Condition(CONDITION_DRUNK)
drunk:setParameter(CONDITION_PARAM_TICKS, 60000)
local poison = Condition(CONDITION_POISON)
poison:setParameter(CONDITION_PARAM_DELAYED, true)
poison:setParameter(CONDITION_PARAM_MINVALUE, -50)
poison:setParameter(CONDITION_PARAM_MAXVALUE, -120)
poison:setParameter(CONDITION_PARAM_STARTVALUE, -5)
poison:setParameter(CONDITION_PARAM_TICKINTERVAL, 4000)
poison:setParameter(CONDITION_PARAM_FORCEUPDATE, true)
local fluidType = {3, 4, 5, 7, 10, 11, 13, 15, 19}
local fluidMessage = {"Aah...", "Urgh!", "Mmmh.", "Aaaah...", "Aaaah...", "Urgh!", "Urgh!", "Aah...", "Urgh!"}
function onUse(cid, item, fromPosition, itemEx, toPosition)
local itemExType = ItemType(itemEx.itemid)
if itemExType and itemExType:isFluidContainer() then
if itemEx.type == 0 and item.type ~= 0 then
Item(itemEx.uid):transform(itemEx.itemid, item.type)
Item(item.uid):transform(item.itemid, 0)
return true
elseif itemEx.type ~= 0 and item.type == 0 then
Item(itemEx.uid):transform(itemEx.itemid, 0)
Item(item.uid):transform(item.itemid, itemEx.type)
return true
end
end
if itemEx.itemid == 1 then
if item.type == 0 then
Player(cid):sendTextMessage(MESSAGE_STATUS_SMALL, "It is empty.")
elseif itemEx.uid == cid then
local player = Player(cid)
Item(item.uid):transform(item.itemid, 0)
if item.type == 3 or item.type == 15 then
doTargetCombatCondition(0, cid, drunk, CONST_ME_NONE)
elseif item.type == 4 then
doTargetCombatCondition(0, cid, poison, CONST_ME_NONE)
elseif item.type == 7 then
player:addMana(math.random(50, 150))
fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE)
elseif item.type == 10 then
player:addHealth(60)
fromPosition:sendMagicEffect(CONST_ME_MAGIC_BLUE)
end
for i = 0, #fluidType do
if item.type == fluidType[i] then
player:say(fluidMessage[i], TALKTYPE_MONSTER_SAY)
return true
end
end
player:say("Gulp.", TALKTYPE_MONSTER_SAY)
else
Item(item.uid):transform(item.itemid, 0)
Game.createItem(2016, item.type, toPosition):decay()
end
else
local fluidSource = itemExType and itemExType:getFluidSource() or 0
if fluidSource ~= 0 then
Item(item.uid):transform(item.itemid, fluidSource)
elseif item.type == 0 then
Player(cid):sendTextMessage(MESSAGE_STATUS_SMALL, "It is empty.")
else
if toPosition.x == CONTAINER_POSITION then
toPosition = Player(cid):getPosition()
end
Item(item.uid):transform(item.itemid, 0)
Game.createItem(2016, item.type, toPosition):decay()
end
end
return true
end
| gpl-2.0 |
Lsty/ygopro-scripts | c16960351.lua | 5 | 1954 | --幻界突破
function c16960351.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(16960351,0))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_SZONE)
e2:SetCountLimit(1)
e2:SetCost(c16960351.spcost)
e2:SetTarget(c16960351.sptg)
e2:SetOperation(c16960351.spop)
c:RegisterEffect(e2)
end
function c16960351.rfilter(c,e,tp)
local lv=c:GetOriginalLevel()
return lv>0 and c:IsRace(RACE_DRAGON) and c:IsReleasable()
and Duel.IsExistingMatchingCard(c16960351.spfilter,tp,LOCATION_DECK,0,1,nil,e,tp,lv)
end
function c16960351.spfilter(c,e,tp,lv)
return c:GetLevel()==lv and c:IsRace(RACE_WYRM) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c16960351.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.CheckReleaseGroup(tp,c16960351.rfilter,1,nil,e,tp) end
local g=Duel.SelectReleaseGroup(tp,c16960351.rfilter,1,1,nil,e,tp)
local tc=g:GetFirst()
e:SetLabel(tc:GetOriginalLevel())
Duel.Release(g,REASON_COST)
end
function c16960351.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1 end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_DECK)
end
function c16960351.spop(e,tp,eg,ep,ev,re,r,rp)
if not e:GetHandler():IsRelateToEffect(e) then return end
local lv=e:GetLabel()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c16960351.spfilter,tp,LOCATION_DECK,0,1,1,nil,e,tp,lv)
local tc=g:GetFirst()
if tc then
Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_BATTLE_DESTROY_REDIRECT)
e1:SetValue(LOCATION_DECKSHF)
e1:SetReset(RESET_EVENT+0x1fe0000)
tc:RegisterEffect(e1)
end
end
| gpl-2.0 |
sagarwaghmare69/nn | MapTable.lua | 4 | 2475 | local MapTable, parent = torch.class('nn.MapTable', 'nn.Container')
function MapTable:__init(module, shared)
parent.__init(self)
self.shared = shared or {'weight', 'bias', 'gradWeight', 'gradBias'}
self.output = {}
self.gradInput = {}
self:add(module)
end
function MapTable:_extend(n)
self.modules[1] = self.module
for i = 2, n do
if not self.modules[i] then
self.modules[i] = self.module:clone(table.unpack(self.shared))
end
end
end
function MapTable:resize(n)
self:_extend(n)
for i = n + 1, #self.modules do
self.modules[i] = nil
end
end
function MapTable:add(module)
assert(not self.module, 'Single module required')
self.module = module
self.modules[1] = self.module
return self
end
function MapTable:updateOutput(input)
self.output = {}
self:_extend(#input)
for i = 1, #input do
self.output[i] = self:rethrowErrors(self.modules[i], i, 'updateOutput', input[i])
end
return self.output
end
function MapTable:updateGradInput(input, gradOutput)
self.gradInput = {}
self:_extend(#input)
for i = 1, #input do
self.gradInput[i] = self:rethrowErrors(self.modules[i], i, 'updateGradInput', input[i], gradOutput[i])
end
return self.gradInput
end
function MapTable:accGradParameters(input, gradOutput, scale)
scale = scale or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accGradParameters', input[i], gradOutput[i], scale)
end
end
function MapTable:accUpdateGradParameters(input, gradOutput, lr)
lr = lr or 1
self:_extend(#input)
for i = 1, #input do
self:rethrowErrors(self.modules[i], i, 'accUpdateGradParameters', input[i], gradOutput[i], lr)
end
end
function MapTable:zeroGradParameters()
if self.module then
self.module:zeroGradParameters()
end
end
function MapTable:updateParameters(learningRate)
if self.module then
self.module:updateParameters(learningRate)
end
end
function MapTable:clearState()
for i = 2, #self.modules do
self.modules[i] = nil
end
parent.clearState(self)
end
function MapTable:__tostring__()
local tab = ' '
local line = '\n'
local extlast = ' '
local str = torch.type(self)
if self.module then
str = str .. ' {' .. line .. tab
str = str .. tostring(self.module):gsub(line, line .. tab .. extlast) .. line .. '}'
else
str = str .. ' { }'
end
return str
end
| bsd-3-clause |
elant/cardpeek | dot_cardpeek_dir/scripts/calypso/c250n921.lua | 17 | 5797 | --
-- This file is part of Cardpeek, the smartcard reader utility.
--
-- Copyright 2009 by 'L1L1' and 2013-2014 by 'kalon33'
--
-- Cardpeek is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>.
--
---------------------------------------------------------------------
-- Most of the data and coding ideas in this file
-- was contributed by 'Pascal Terjan', based on location
-- data from 'Nicolas Derive'.
---------------------------------------------------------------------
require('lib.strict')
require('etc.gironde-transgironde')
SERVICE_PROVIDERS = {
[21] = "TBC",
[16] = "Transgironde"
}
TRANSITION_LIST = {
[1] = "Entrée",
[6] = "Correspondance"
}
function navigo_process_events(ctx)
local EVENTS
local RECORD
local REF
local rec_index
local code_value
local route_number_value
local vehicle_number_value
local code_transport
local code_transition
local code_transport_string
local code_transition_string
local code_string
local service_provider_value
local location_id_value
local sector_id
local station_id
local location_string
EVENTS = ui.tree_find_node(ctx,"Event logs, parsed");
if EVENTS==nil then
log.print(log.WARNING,"No event found in card")
return 0
end
for rec_index=1,16 do
RECORD = ui.tree_find_node(EVENTS,"record",rec_index)
if RECORD==nil then break end
REF = ui.tree_find_node(RECORD,"EventServiceProvider")
service_provider_value = bytes.tonumber(ui.tree_get_value(REF))
if service_provider_value == 21 then
TRANSPORT_LIST = {
[0] = "Information de mode de transport absente (ordinateur de bord non configuré)",
[1] = "Tram",
[5] = "Bus" -- apparently bus, maybe tram B in some conditions, needs verification --> seems that a "lost" vehicle (without line information) is a bus by default.
}
else
TRANSPORT_LIST = {
[1] = "Car"
}
end
ui.tree_set_alt_value(REF,SERVICE_PROVIDERS[service_provider_value])
REF = ui.tree_find_node(RECORD,"EventRouteNumber")
route_number_value = bytes.tonumber(ui.tree_get_value(REF))
if (route_number_value >= 1 and route_number_value <= 16) then
ui.tree_set_alt_value(REF,"Liane "..route_number_value)
else
if ((route_number_value >= 20 and route_number_value <= 30) or (route_number_value >= 62 and route_number_value <= 67) or (route_number_value >= 70 and route_number_value <=96)) then
ui.tree_set_alt_value(REF,"Ligne "..route_number_value)
else
if ((route_number_value >= 32 and route_number_value <= 37)) then
ui.tree_set_alt_value(REF,"Corol "..route_number_value)
else
if ((route_number_value == 38) or (route_number_value >= 48 and route_number_value <= 49) or (route_number_value == 68)) then
ui.tree_set_alt_value(REF,"Flexo "..route_number_value)
else
if ((route_number_value >= 51 and route_number_value <= 58) and not (route_number_value == 53) and not (route_number_value == 56)) then
ui.tree_set_alt_value(REF,"Flexo de nuit "..route_number_value)
else
if (route_number_value == 53 or route_number_value == 56) then
ui.tree_set_alt_value(REF,"Ligne "..route_number_value.." Express")
else
if (route_number_value == 59) then
ui.tree_set_alt_value(REF,"Ligne A")
else
if (route_number_value == 60) then
ui.tree_set_alt_value(REF,"Ligne B")
else
if (route_number_value == 61) then
ui.tree_set_alt_value(REF,"Ligne C")
else
if service_provider_value == 16 then
ui.tree_set_alt_value(REF,"Ligne "..route_number_value)
else
ui.tree_set_alt_value(REF,"Ligne inconnue (ou non définie dans l'ordinateur de bord au moment du badgeage)")
end
end
end
end
end
end
end
end
end
REF = ui.tree_find_node(RECORD,"EventVehiculeId")
vehicle_number_value = bytes.tonumber((ui.tree_get_value(REF)))
ui.tree_set_alt_value(REF,"Véhicule n°"..vehicle_number_value)
REF = ui.tree_find_node(RECORD,"EventCode")
code_value = bytes.tonumber(ui.tree_get_value(REF))
code_transport = bit.SHR(code_value,4)
code_transport_string = TRANSPORT_LIST[code_transport]
if code_transport_string==nil then code_transport_string = code_transport end
code_transition = bit.AND(code_value,0xF)
if (code_transition == 6) and (route_number_value == 0) then code_transition = 0 end
code_transition_string = TRANSITION_LIST[code_transition]
if (code_transition_string==nil) then code_transition_string = code_transition end
ui.tree_set_alt_value(REF,code_transport_string.." - "..code_transition_string)
REF = ui.tree_find_node(RECORD,"EventLocationId")
location_id_value = bytes.tonumber(ui.tree_get_value(REF))
if location_id_value == 0 then ui.tree_set_alt_value(REF,"Aucun positionnement précis disponible")
else
if TRANSGIRONDE_STOPS_LIST[location_id_value] then
location_string = "arrêt "..TRANSGIRONDE_STOPS_LIST[location_id_value]
ui.tree_set_alt_value(REF, location_string)
else
-- ui.tree_set_alt_value(REF, location_id_value)
ui.tree_set_alt_value(REF, TRANSGIRONDE_STOPS_LIST[location_id_value])
end
end
end
end
end
navigo_process_events(CARD)
| gpl-3.0 |
morfeo642/mta_plr_server | hedit/client/gui/guimanager.lua | 1 | 20419 | --[[
guiCreateID ( element gui, string id )
guiGetElementFromID ( string id )
guiGetElementParent ( element gui )
guiGetElementInputType ( element gui ) -- Only for menu items!
guiGetElementProperty ( element gui ) -- Only for config menu items!
guiGetElementInfo ( element gui )
guiGetElementEvents ( element gui )
toggleEditor ( )
setVisible ( bool visible )
setPointedElement ( element guiElement, bool pointing )
showOriginalValue ( string key, string state )
showPreviousValue ( string key, string state )
handleKeyState ( string "up"/"down" )
guiSetInfoText ( string header, string text )
guiSetStaticInfoText ( string header, string text )
guiResetInfoText ( )
guiResetStaticInfoText ( )
guiToggleUtilityDropDown ( [string utility = all] )
guiShowMenu ( string menu )
guiUpdateMenu ( )
guiTemplateGetUtilButtonText ( string utilbutton )
guiTemplateGetMenuButtonText ( string menubutton )
guiTemplateGetItemText ( string menu, string item )
getMenuShortName ( string menu )
getMenuLongName ( string menu )
getMenuRedirect ( string menu )
guiCreateWarningMessage ( string text, int level, table {function1, args... }, table {function2, args...} )
guiDestroyWarningWindow ( )
]]
function guiSetElementID ( guiElement, id )
if not isElement ( guiElement ) then
return false
end
if type ( id ) ~= "string" then
return false
end
if guiID[id] and DEBUGMODE then
outputDebugString ( "Overwriting guiID "..tostring(id) )
end
guiID[id] = guiElement
return true
end
function guiGetElementFromID ( id )
if not guiID[id] then
if DEBUGMODE then
outputDebugString ( "Unexisting guiID '"..tostring(id) )
end
return false
end
return guiID[id]
end
function guiGetElementParent ( guiElement )
if guiElements[guiElement] then
return guiElements[guiElement][1]
end
return nil
end
function guiGetElementInputType ( guiElement )
if guiGetElementParent ( guiElement ) ~= "menuItem" then
return false
end
if guiElements[guiElement] then
return guiElements[guiElement][2]
end
return nil
end
function guiGetElementProperty ( guiElement )
if guiGetElementParent ( guiElement ) ~= "menuItem" then
return false
end
local inputType = guiGetElementInputType ( guiElement )
if inputType ~= "infolabel" and inputType ~= "config" then
return false
end
return guiElements[guiElement][3]
end
function guiGetElementInfo ( guiElement )
if guiElements[guiElement] then
return guiElements[guiElement][4]
end
return nil
end
function guiGetElementEvents ( guiElement )
if guiElements[guiElement] then
return guiElements[guiElement][5]
end
return nil
end
function toggleEditor ( )
local window = heditGUI.window
if guiGetVisible ( window ) then
guiToggleUtilityDropDown ( currentUtil )
if heditGUI.prevLockState == false then
setVehicleLocked(pVehicle, false)
heditGUI.prevLockState = nil
end
setVisible ( false )
return true
end
if pVehicle then
-- When you abort entering a vehicle, hedit will still think you own a vehicle. Hax for thiz
-- I need onClientVehicleAbortEnter, NOAW
if not getPedOccupiedVehicle ( localPlayer ) then
if DEBUGMODE then
outputDebugString ( "pVehicle exist, but you do not own a vehicle!" )
end
pVehicle = false
guiCreateWarningMessage(getText ( "needVehicle" ), 1)
return false
end
local vehicleController = getVehicleController ( pVehicle )
if vehicleController ~= localPlayer --[[and not setting.allowPassengersToEdit]] then
guiCreateWarningMessage ( getText ( "restrictedPassenger" ), 1)
return false
end
-- Hack to destroy the warning messages from "Youre not in a vehicle" when opening the editor WITH a vehicle
if isElement ( warningWnd ) and guiGetVisible ( warningWnd ) then
guiDestroyWarningWindow ( )
end
-- Show the editor before notifying updates or upgrades.
setVisible ( true )
-- Lock the vehicle, if the user has set the setting.
if getUserConfig("lockVehicleWhenEditing") then
if not isVehicleLocked(pVehicle) then
setVehicleLocked(pVehicle, true)
heditGUI.prevLockState = false
end
end
-- If a server runs an older version, or doesnt meet your version of data files, show a message.
local ver = tonumber ( getUserConfig ( "version" ) )
local minver = tonumber ( getUserConfig ( "minVersion" ) )
if ver > HREV then
if minver > HMREV then
guiCreateWarningMessage ( getText ( "outdatedUpgrade" ), 0 )
else
guiCreateWarningMessage ( getText ( "outdatedUpdate" ), 1 )
end
end
-- Notify the player upon an update or upgrade
if getUserConfig ( "notifyUpdate" ) == "true" then
guiDestroyWarningWindow ( )
guiCreateWarningMessage ( getText ( "notifyUpdate" ), 2, {guiShowMenu,"updatelist"} )
setUserConfig ( "notifyUpdate", "false" )
elseif getUserConfig ( "notifyUpgrade" ) == "true" then
guiDestroyWarningWindow ( )
guiCreateWarningMessage ( getText ( "notifyUpgrade" ), 2, {guiShowMenu,"updatelist"} )
setUserConfig ( "notifyUpgrade", "false" )
elseif tonumber ( getUserConfig ( "mtaVersion" ) ) < MTAVER then
guiDestroyWarningWindow ( )
guiCreateWarningMessage ( getText ( "mtaUpdate" ), 1)
setUserConfig ( "mtaVersion", tostring ( MTAVER ) )
end
return true
end
guiCreateWarningMessage ( getText ( "needVehicle" ), 1 )
return false
end
function setVisible ( bool )
if type ( bool ) ~= "boolean" then
if DEBUGMODE then
error ( "No boolean value at 'setVisible'!", 2 )
end
return false
end
local window = heditGUI.window
-- We shouldnt call all the stuff when the state of the window is already the state we want
-- Otherwise we will call showCursor again, which will cause major problems with hiding or showing it
if guiGetVisible ( window ) == bool then
return false
end
local bind = unbindKey
if bool then
bind = bindKey
guiSetInputMode ( "no_binds_when_editing" )
end
bind ( "lctrl", "both", showOriginalValue )
bind ( "rctrl", "both", showOriginalValue )
bind ( "lshift", "both", showPreviousValue )
bind ( "rshift", "both", showPreviousValue )
--[[bind ( "mouse_wheel_up", "up", onScroll, "up" )
bind ( "mouse_wheel_down", "up", onScroll, "down" )
bind ( "delete", "down", tryDelete )]]
guiSetVisible ( window, bool )
if isElement ( warningWnd ) then
guiSetVisible ( warningWnd, bool )
end
showCursor ( bool, bool )
return true
end
function setPointedElement ( element, bool ) -- Consider another name!
if element == pointedButton and buttonValue then
guiSetText ( pointedButton, buttonValue )
guiSetProperty ( pointedButton, "HoverTextColour", buttonHoverColor )
buttonValue = nil
pressedKey = nil
end
if bool then
pointedButton = element
buttonHoverColor = guiGetProperty ( element, "HoverTextColour" )
handleKeyState ( "down" )
return true
end
pointedButton = nil
buttonHoverColor = nil
--handleKeyState ( "up" )
return true
end
function showOriginalValue ( key, state ) -- Maybe merge with showPreviousValue?
if pointedButton then
if state == "down" then
if pressedKey ~= "shift" then
local property = guiGetElementProperty ( pointedButton )
local original = getOriginalHandling ( getElementModel ( pVehicle ) )[property]
if property == "centerOfMass" then
local hnd = getOriginalHandling ( getElementModel ( pVehicle ) )
original = math.round ( hnd.centerOfMassX )..", "..math.round ( hnd.centerOfMassY )..", "..math.round ( hnd.centerOfMassZ )
end
buttonValue = guiGetText ( pointedButton )
guiSetText ( pointedButton, valueToString ( property, original ) )
guiSetProperty ( pointedButton, "HoverTextColour", "FF68F000" )
pressedKey = "ctrl"
end
return true
end
if buttonValue then
guiSetText ( pointedButton, buttonValue )
guiSetProperty ( pointedButton, "HoverTextColour", buttonHoverColor )
buttonValue = nil
pressedKey = nil
handleKeyState ( "down" )
return true
end
return true
end
return false
end
function showPreviousValue ( key, state ) -- Maybe merge with showOriginalValue?
if pointedButton then
if state == "down" then
if pressedKey ~= "ctrl" then
local property = guiGetElementProperty ( pointedButton )
local previous = getHandlingPreviousValue ( pVehicle, property )
if previous then
buttonValue = guiGetText ( pointedButton )
guiSetText ( pointedButton, valueToString ( property, previous ) )
guiSetProperty ( pointedButton, "HoverTextColour", "FFF0D400" )
pressedKey = "shift"
end
end
return true
end
if buttonValue then
guiSetText ( pointedButton, buttonValue )
guiSetProperty ( pointedButton, "HoverTextColour", buttonHoverColor )
buttonValue = nil
pressedKey = nil
handleKeyState ( "down" )
return true
end
return true
end
return false
end
function handleKeyState ( state )
if getKeyState ( "lctrl" ) or getKeyState ( "rctrl" ) then
showOriginalValue ( "lctrl", state )
elseif getKeyState ( "lshift" ) or getKeyState ( "rshift" ) then
showPreviousValue ( "lshift", state )
end
end
function guiSetInfoText ( header, text )
local infobox = heditGUI.specials.infobox
guiSetText ( infobox.header, header )
guiSetText ( infobox.text, text )
return true
end
function guiSetStaticInfoText ( header, text )
local infobox = heditGUI.specials.infobox
guiSetText ( infobox.header, header )
guiSetText ( infobox.text, text )
staticinfo.header = header
staticinfo.text = text
return true
end
function guiResetInfoText ( )
local infobox = heditGUI.specials.infobox
guiSetText ( infobox.header, staticinfo.header )
guiSetText ( infobox.text, staticinfo.text )
return true
end
function guiResetStaticInfoText ( )
local infobox = heditGUI.specials.infobox
if guiGetText ( infobox.header ) == staticinfo.header then
guiSetText ( infobox.header, "" )
guiSetText ( infobox.text, "" )
end
staticinfo.header = ""
staticinfo.text = ""
return true
end
function toggleMenuItemsVisibility ( menu, bool )
local function toggleVisibility ( tab )
if type ( tab ) ~= "table" then
if DEBUGMODE then
outputChatBox ( "Error when showing menu items from menu '"..tostring ( menu ).."'" )
end
else
for k,gui in pairs ( tab ) do
if type ( gui ) == "table" then
toggleVisibility ( gui )
else
guiSetVisible ( gui, bool )
guiSetEnabled(gui, isHandlingPropertyEnabled(guiGetElementProperty(gui)))
end
end
end
end
toggleVisibility ( heditGUI.menuItems[menu].guiItems )
return true
end
function guiToggleUtilityDropDown ( util )
if not util then
for util,tab in pairs ( heditGUI.utilItems ) do
for i,gui in ipairs ( tab ) do
guiSetVisible ( gui, false )
end
end
currentUtil = nil
return true
end
if currentUtil then
for i,gui in ipairs ( heditGUI.utilItems[currentUtil] ) do
guiSetVisible ( gui, false )
end
end
if util == currentUtil then
currentUtil = nil
return false
end
local show = not guiGetVisible ( heditGUI.utilItems[util][1] )
for i,gui in ipairs ( heditGUI.utilItems[util] ) do
guiSetVisible ( gui, show )
guiBringToFront ( gui )
end
currentUtil = util
return true
end
function guiShowMenu ( menu )
if menu == "previous" then
guiShowMenu ( previousMenu )
return true
end
if menu == currentMenu then
guiUpdateMenu ( currentMenu )
return false
end
if not heditGUI.menuItems[menu] then
guiCreateWarningMessage ( getText ( "invalidMenu" ), 0 )
return false
end
if heditGUI.menuItems[menu].requireLogin and not pData.loggedin then
guiCreateWarningMessage ( getText ( "needLogin" ), 1 )
return false
end
if heditGUI.menuItems[menu].requireAdmin and not pData.isadmin then
guiCreateWarningMessage ( getText ( "needAdmin" ), 1 )
return false
end
if heditGUI.menuItems[menu].disabled then
guiCreateWarningMessage ( getText ( "disabledMenu" ), 1 )
return false
end
guiSetText ( heditGUI.specials.menuheader, getMenuLongName ( menu ) )
destroyEditBox ( )
guiUpdateMenu ( menu )
if currentMenu then
if type ( heditGUI.menuItems[currentMenu].onClose ) == "function" then
heditGUI.menuItems[currentMenu].onClose ( heditGUI.menuItems[currentMenu].guiItems )
end
toggleMenuItemsVisibility ( currentMenu, false )
end
toggleMenuItemsVisibility ( menu, true )
if type ( heditGUI.menuItems[menu].onOpen ) == "function" then
heditGUI.menuItems[menu].onOpen ( heditGUI.menuItems[menu].guiItems )
end
previousMenu = currentMenu
currentMenu = menu
return true
end
addEvent ( "showMenu", true )
addEventHandler ( "showMenu", root, guiShowMenu )
function guiUpdateMenu ( menu )
if menu then
local veh = getPedOccupiedVehicle ( localPlayer )
if not veh or veh ~= pVehicle then
if DEBUGMODE then
outputDebugString ( "guiUpdateMenu is called while your vehicle differs from pVehicle or dont have a vehicle!" )
end
return false
end
destroyEditBox ( )
local redirect = getMenuRedirect ( menu )
if redirect == "handlingconfig" then
local content = heditGUI.menuItems[menu].guiItems
local handling = getVehicleHandling ( pVehicle )
for i,gui in ipairs ( content ) do
local input = guiGetElementInputType ( gui )
if input == "config" then
local property = guiGetElementProperty ( gui )
local config = handling[property]
if handlingLimits[property] and handlingLimits[property].options then
local id = getHandlingOptionID ( property, string.lower ( config ) )
guiComboBoxSetSelected ( gui, id-1 )
else
local str = valueToString ( property, config )
if property == "centerOfMass" then
local x,y,z = handling.centerOfMassX,handling.centerOfMassY,handling.centerOfMassZ
str = math.round ( x )..", "..math.round ( y )..", "..math.round ( z )
end
if pressedKey and pointedButton == gui then
if pressedKey == "ctrl" then
guiSetText ( gui, str )
buttonValue = str
elseif pressedKey == "shift" then
guiSetText ( gui, buttonValue )
buttonValue = str
end
else
guiSetText ( gui, str )
end
end
end
end
elseif redirect == "handlingflags" then
local content = heditGUI.menuItems[menu].guiItems
local property = guiGetElementProperty ( content[1]["1"] )
local config = getVehicleHandling ( pVehicle )[property]
local reversedHex = string.reverse ( config )..string.rep ( "0", 8 - string.len ( config ) )
local num = 1
for byte in string.gmatch ( reversedHex, "." ) do
local enabled = getEnabledValuesFromByteValue ( byte )
local byteEnabled = {}
for i,v in ipairs ( enabled ) do
byteEnabled[v] = true
end
for value,gui in pairs ( content[num] ) do
guiCheckBoxSetSelected ( gui, byteEnabled[value] or false )
end
num = num + 1
end
end
return false
end
return false
end
addEvent ( "updateClientMenu", true )
addEventHandler ( "updateClientMenu", root, guiUpdateMenu )
function vehicleTextUpdater ( )
local vehicleName = getVehicleName ( source )
local saved = isVehicleSaved ( source )
local t_vehicle = getText ( "vehicle" )
local t_unsaved = getText ( "unsaved" )
if saved then
guiSetText ( heditGUI.specials.vehicleinfo, t_vehicle..": "..vehicleName )
guiLabelSetColor ( heditGUI.specials.vehicleinfo, 255, 255, 255 )
return true
end
guiSetText ( heditGUI.specials.vehicleinfo, t_vehicle..": "..vehicleName.." ("..t_unsaved..")" )
guiLabelSetColor ( heditGUI.specials.vehicleinfo, 255, 0, 0 )
return true
end
addEvent ( "updateVehicleText", true )
addEventHandler ( "updateVehicleText", root, vehicleTextUpdater )
function guiTemplateGetUtilButtonText ( util )
return getText ( "utilbuttons", util )
end
function guiTemplateGetMenuButtonText ( menu )
return getText ( "menubuttons", menu )
end
function guiTemplateGetItemText ( menu, item )
local text = getText ( "menuinfo", menu, "itemtext", item )
return text == "NO_TEXT" and "" or text
end
function getMenuShortName ( menu )
return getText ( "menuinfo", menu, "shortname" )
end
function getMenuLongName ( menu )
return getText ( "menuinfo", menu, "longname" )
end
function getMenuRedirect ( menu )
if heditGUI.menuItems and heditGUI.menuItems[menu] and heditGUI.menuItems[menu].redirect then
return heditGUI.menuItems[menu].redirect
end
return false
end
function destroyEditBox ( )
if openedEditBox then
guiResetStaticInfoText ( )
guiSetVisible ( hiddenEditBox, true )
destroyElement ( openedEditBox )
openedEditBox = nil
end
end | mit |
Lsty/ygopro-scripts | c21219755.lua | 3 | 1194 | --破壊指輪
function c21219755.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_DESTROY+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c21219755.target)
e1:SetOperation(c21219755.activate)
c:RegisterEffect(e1)
end
function c21219755.filter(c)
return c:IsFaceup() and c:IsDestructable()
end
function c21219755.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c21219755.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c21219755.filter,tp,LOCATION_MZONE,0,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY)
local g=Duel.SelectTarget(tp,c21219755.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,PLAYER_ALL,1000)
end
function c21219755.activate(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
if Duel.Destroy(tc,REASON_EFFECT)>0 then
Duel.Damage(1-tp,1000,REASON_EFFECT)
Duel.Damage(tp,1000,REASON_EFFECT)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c84117021.lua | 3 | 3239 | --魔力隔壁
function c84117021.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetTarget(c84117021.target)
e1:SetOperation(c84117021.activate)
c:RegisterEffect(e1)
end
function c84117021.filter(c)
return c:IsFaceup() and c:IsRace(RACE_SPELLCASTER)
end
function c84117021.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local opt=0
if Duel.IsExistingTarget(c84117021.filter,tp,LOCATION_MZONE,0,1,nil) then
opt=Duel.SelectOption(tp,aux.Stringid(84117021,0),aux.Stringid(84117021,1))
end
Duel.SetTargetParam(opt)
if opt==0 then
e:SetProperty(0)
else
e:SetProperty(EFFECT_FLAG_CARD_TARGET)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TARGET)
Duel.SelectTarget(tp,c84117021.filter,tp,LOCATION_MZONE,0,1,1,nil)
end
end
function c84117021.activate(e,tp,eg,ep,ev,re,r,rp)
local opt=Duel.GetChainInfo(0,CHAININFO_TARGET_PARAM)
if opt==0 then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CANNOT_DISABLE_SUMMON)
e1:SetProperty(EFFECT_FLAG_IGNORE_RANGE+EFFECT_FLAG_SET_AVAILABLE)
e1:SetTarget(aux.TargetBoolFunction(Card.IsRace,RACE_SPELLCASTER))
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_CANNOT_DISABLE_SPSUMMON)
Duel.RegisterEffect(e2,tp)
local e3=e1:Clone()
e3:SetCode(EFFECT_CANNOT_DISABLE_FLIP_SUMMON)
Duel.RegisterEffect(e3,tp)
local e4=Effect.CreateEffect(e:GetHandler())
e4:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e4:SetCode(EVENT_SUMMON_SUCCESS)
e4:SetCondition(c84117021.sumcon)
e4:SetOperation(c84117021.sumsuc)
e4:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e4,tp)
local e5=e4:Clone()
e5:SetCode(EVENT_SPSUMMON_SUCCESS)
Duel.RegisterEffect(e5,tp)
local e6=e4:Clone()
e6:SetCode(EVENT_FLIP_SUMMON_SUCCESS)
Duel.RegisterEffect(e6,tp)
else
local tc=Duel.GetFirstTarget()
if tc:IsFaceup() and tc:IsRelateToEffect(e) then
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_ATTACK_ANNOUNCE)
e1:SetOperation(c84117021.atkop)
e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END)
tc:RegisterEffect(e1)
end
end
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_CHANGE_DAMAGE)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetTargetRange(0,1)
e1:SetValue(0)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
local e2=e1:Clone()
e2:SetCode(EFFECT_NO_EFFECT_DAMAGE)
e2:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e2,tp)
end
function c84117021.sumcon(e,tp,eg,ep,ev,re,r,rp)
return eg:IsExists(c84117021.filter,1,nil)
end
function c84117021.sumsuc(e,tp,eg,ep,ev,re,r,rp)
Duel.SetChainLimitTillChainEnd(c84117021.efun)
end
function c84117021.efun(e,ep,tp)
return ep==tp
end
function c84117021.atkop(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET)
e1:SetCode(EFFECT_CANNOT_ACTIVATE)
e1:SetTargetRange(0,1)
e1:SetValue(1)
e1:SetReset(RESET_PHASE+PHASE_DAMAGE)
Duel.RegisterEffect(e1,tp)
end
| gpl-2.0 |
openwrt/luci | applications/luci-app-dnscrypt-proxy/luasrc/model/cbi/dnscrypt-proxy/overview_tab.lua | 10 | 9479 | -- Copyright 2017-2018 Dirk Brenken (dev@brenken.org)
-- This is free software, licensed under the Apache License, Version 2.0
local fs = require("nixio.fs")
local uci = require("luci.model.uci").cursor()
local util = require("luci.util")
local res_input = "/usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv"
local res_dir = fs.dirname(res_input)
local dump = util.ubus("network.interface", "dump", {})
local plug_cnt = tonumber(luci.sys.exec("env -i /usr/sbin/dnscrypt-proxy --version | grep 'Support for plugins: present' | wc -l"))
local res_list = {}
local url = "https://raw.githubusercontent.com/dyne/dnscrypt-proxy/master/dnscrypt-resolvers.csv"
local _, date = pcall(require, "luci.http.date")
if not date then
_, date = pcall(require, "luci.http.protocol.date")
end
if not fs.access(res_input) then
if not fs.access("/lib/libustream-ssl.so") then
m = SimpleForm("error", nil, translate("No default resolver list and no SSL support available.<br />")
.. translate("Please install a resolver list to '/usr/share/dnscrypt-proxy/dnscrypt-resolvers.csv' to use this package."))
m.submit = false
m.reset = false
return m
else
luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1")
end
end
if not uci:get_first("dnscrypt-proxy", "global") then
uci:add("dnscrypt-proxy", "global")
uci:save("dnscrypt-proxy")
uci:commit("dnscrypt-proxy")
end
if fs.access(res_input) then
for line in io.lines(res_input) or {} do
local name,
location,
dnssec,
nolog = line:match("^([^,]+),.-,\".-\",\"*(.-)\"*,.-,[0-9],\"*([yesno]+)\"*,\"*([yesno]+)\"*,.*")
if name ~= "" and name ~= "Name" then
if location == "" then
location = "-"
end
if dnssec == "" then
dnssec = "-"
end
if nolog == "" then
nolog = "-"
end
res_list[#res_list + 1] = { name = name, location = location, dnssec = dnssec, nolog = nolog }
end
end
end
m = Map("dnscrypt-proxy", translate("DNSCrypt-Proxy"),
translate("Configuration of the DNSCrypt-Proxy package. ")
.. translatef("For further information "
.. "<a href=\"%s\" target=\"_blank\">"
.. "see the wiki online</a>", "https://openwrt.org/docs/guide-user/services/dns/dnscrypt"))
m:chain("dhcp")
function m.on_after_commit(self)
function d1.validate(self, value, s1)
if value == "1" then
uci:commit("dnscrypt-proxy")
uci:set("dhcp", s1, "noresolv", 1)
if not fs.access("/etc/resolv-crypt.conf") or fs.stat("/etc/resolv-crypt.conf").size == 0 then
uci:set("dhcp", s1, "resolvfile", "/tmp/resolv.conf.auto")
else
uci:set("dhcp", s1, "resolvfile", "/etc/resolv-crypt.conf")
end
local server_list = {}
local cnt = 1
uci:foreach("dnscrypt-proxy", "dnscrypt-proxy", function(s)
server_list[cnt] = s['address'] .. "#" .. s['port']
cnt = cnt + 1
end)
server_list[cnt] = "/pool.ntp.org/8.8.8.8"
uci:set_list("dhcp", s1, "server", server_list)
if cnt > 2 then
uci:set("dhcp", s1, "allservers", 1)
else
uci:set("dhcp", s1, "allservers", 0)
end
uci:save("dhcp")
uci:commit("dhcp")
end
return value
end
luci.sys.call("env -i /etc/init.d/dnscrypt-proxy restart >/dev/null 2>&1")
luci.sys.call("env -i /etc/init.d/dnsmasq restart >/dev/null 2>&1")
end
s = m:section(TypedSection, "global", translate("General Options"))
s.anonymous = true
-- Main dnscrypt-proxy resource list
o1 = s:option(DummyValue, "", translate("Default Resolver List"))
o1.template = "dnscrypt-proxy/res_options"
o1.value = res_input
o2 = s:option(DummyValue, "", translate("File Date"))
o2.template = "dnscrypt-proxy/res_options"
if fs.access(res_input) then
o2.value = date.to_http(fs.stat(res_input).mtime)
else
o2.value = "-"
end
o3 = s:option(DummyValue, "", translate("File Checksum"))
o3.template = "dnscrypt-proxy/res_options"
if fs.access(res_input) then
o3.value = luci.sys.exec("sha256sum " .. res_input .. " | awk '{print $1}'")
else
o3.value = "-"
end
if fs.access("/lib/libustream-ssl.so") then
btn1 = s:option(Button, "", translate("Refresh Resolver List"),
translate("Download the current resolver list from 'github.com/dyne/dnscrypt-proxy'."))
btn1.inputtitle = translate("Refresh List")
btn1.inputstyle = "apply"
btn1.disabled = false
function btn1.write()
if not fs.access(res_dir) then
fs.mkdir(res_dir)
end
luci.sys.call("env -i /bin/uclient-fetch --no-check-certificate -O " .. res_input .. " " .. url .. " >/dev/null 2>&1")
luci.http.redirect(luci.dispatcher.build_url("admin", "services", "dnscrypt-proxy"))
end
else
btn1 = s:option(Button, "", translate("Refresh Resolver List"),
translate("No SSL support available.<br />")
.. translate("Please install a 'libustream-ssl' library to download the current resolver list from 'github.com/dyne/dnscrypt-proxy'."))
btn1.inputtitle = translate("-------")
btn1.inputstyle = "button"
btn1.disabled = true
end
if not fs.access("/etc/resolv-crypt.conf") or fs.stat("/etc/resolv-crypt.conf").size == 0 then
btn2 = s:option(Button, "", translate("Create Custom Config File"),
translate("Create '/etc/resolv-crypt.conf' with 'options timeout:1' to reduce DNS upstream timeouts with multiple DNSCrypt instances.<br />")
.. translatef("For further information "
.. "<a href=\"%s\" target=\"_blank\">"
.. "see the wiki online</a>", "https://openwrt.org/docs/guide-user/services/dns/dnscrypt"))
btn2.inputtitle = translate("Create Config File")
btn2.inputstyle = "apply"
btn2.disabled = false
function btn2.write()
luci.sys.call("env -i echo 'options timeout:1' > '/etc/resolv-crypt.conf'")
luci.http.redirect(luci.dispatcher.build_url("admin", "services", "dnscrypt-proxy"))
end
else
btn2 = s:option(Button, "", translate("Create Custom Config File"),
translate("The config file '/etc/resolv-crypt.conf' already exist.<br />")
.. translate("Please edit the file manually in the 'Advanced' section."))
btn2.inputtitle = translate("-------")
btn2.inputstyle = "button"
btn2.disabled = true
end
-- Trigger settings
t = s:option(ListValue, "procd_trigger", translate("Startup Trigger"),
translate("By default the DNSCrypt-Proxy startup will be triggered by ifup events of 'All' available network interfaces.<br />")
.. translate("To restrict the trigger, select only the relevant network interface. Usually the 'wan' interface should work for most users."))
t:value("", "All")
if dump then
local i, v
for i, v in ipairs(dump.interface) do
if v.interface ~= "loopback" then
t:value(v.interface)
end
end
end
t.default = procd_trigger or "All"
t.rmempty = true
-- Mandatory options per instance
s = m:section(TypedSection, "dnscrypt-proxy", translate("Instance Options"))
s.anonymous = true
s.addremove = true
i1 = s:option(Value, "address", translate("IP Address"),
translate("The local IPv4 or IPv6 address. The latter one should be specified within brackets, e.g. '[::1]'."))
i1.default = address or "127.0.0.1"
i1.rmempty = false
i2 = s:option(Value, "port", translate("Port"),
translate("The listening port for DNS queries."))
i2.datatype = "port"
i2.default = port
i2.rmempty = false
i3 = s:option(ListValue, "resolver", translate("Resolver (LOC/SEC/NOLOG)"),
translate("Name of the remote DNS service for resolving queries incl. Location, DNSSEC- and NOLOG-Flag."))
i3.datatype = "hostname"
i3.widget = "select"
local i, v
for i, v in ipairs(res_list) do
if v.name then
i3:value(v.name, v.name .. " (" .. v.location .. "/" .. v.dnssec .. "/" .. v.nolog .. ")")
end
end
i3.default = resolver
i3.rmempty = false
-- Extra options per instance
e1 = s:option(Value, "resolvers_list", translate("Alternate Resolver List"),
translate("Specify a non-default Resolver List."))
e1.datatype = "file"
e1.optional = true
e2 = s:option(Value, "ephemeral_keys", translate("Ephemeral Keys"),
translate("Improve privacy by using an ephemeral public key for each query. ")
.. translate("This option requires extra CPU cycles and is useless with most DNSCrypt server."))
e2.datatype = "bool"
e2.value = 1
e2.optional = true
if plug_cnt > 0 then
e3 = s:option(DynamicList, "blacklist", translate("Blacklist"),
translate("Local blacklists allow you to block abuse sites by domains or ip addresses. ")
.. translate("The value for this property is the blocklist type and path to the file, e.g.'domains:/path/to/dbl.txt' or 'ips:/path/to/ipbl.txt'."))
e3.optional = true
e4 = s:option(Value, "block_ipv6", translate("Block IPv6"),
translate("Disable IPv6 to speed up DNSCrypt-Proxy."))
e4.datatype = "bool"
e4.value = 1
e4.optional = true
e5 = s:option(Value, "local_cache", translate("Local Cache"),
translate("Enable Caching to speed up DNSCcrypt-Proxy."))
e5.datatype = "bool"
e5.value = 1
e5.optional = true
e6 = s:option(Value, "query_log_file", translate("DNS Query Logfile"),
translate("Log the received DNS queries to a file, so you can watch in real-time what is happening on the network."))
e6.optional = true
end
-- Dnsmasq options
m1 = Map("dhcp")
s1 = m1:section(TypedSection, "dnsmasq", translate("Dnsmasq Options"))
s1.anonymous = true
d1 = s1:option(Flag, "", translate("Transfer Options To Dnsmasq"),
translate("Apply DNSCrypt-Proxy specific settings to the Dnsmasq configuration.<br />")
.. translate("Please note: This may change the values for 'noresolv', 'resolvfile', 'allservers' and the list 'server' settings."))
d1.default = d1.enabled
d1.rmempty = false
return m, m1
| apache-2.0 |
MalRD/darkstar | scripts/zones/Southern_San_dOria/npcs/Pourette.lua | 11 | 1337 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Pourette
-- Derfland Regional Merchant
-----------------------------------
local ID = require("scripts/zones/Southern_San_dOria/IDs")
require("scripts/globals/events/harvest_festivals")
require("scripts/globals/conquest")
require("scripts/globals/npc_util")
require("scripts/globals/quests")
function onTrade(player,npc,trade)
if player:getQuestStatus(SANDORIA, dsp.quest.id.sandoria.FLYERS_FOR_REGINE) == QUEST_ACCEPTED and npcUtil.tradeHas(trade, 532) then
player:messageSpecial(ID.text.FLYER_REFUSED)
else
onHalloweenTrade(player, trade, npc)
end
end
function onTrigger(player,npc)
if GetRegionOwner(dsp.region.DERFLAND) ~= dsp.nation.SANDORIA then
player:showText(npc, ID.text.POURETTE_CLOSED_DIALOG)
else
local stock =
{
4352, 128, -- Derfland Pear
617, 142, -- Ginger
4545, 62, -- Gysahl Greens
1412, 1656, -- Olive Flower
633, 14, -- Olive Oil
951, 110, -- Wijnruit
}
player:showText(npc, ID.text.POURETTE_OPEN_DIALOG)
dsp.shop.general(player, stock, SANDORIA)
end
end
function onEventUpdate(player,csid,option)
end
function onEventFinish(player,csid,option)
end
| gpl-3.0 |
cshore-firmware/openwrt-luci | modules/luci-mod-admin-full/luasrc/controller/admin/network.lua | 7 | 10712 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2011-2015 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.controller.admin.network", package.seeall)
function index()
local uci = require("luci.model.uci").cursor()
local page
page = node("admin", "network")
page.target = firstchild()
page.title = _("Network")
page.order = 50
page.index = true
-- if page.inreq then
local has_switch = false
uci:foreach("network", "switch",
function(s)
has_switch = true
return false
end)
if has_switch then
page = node("admin", "network", "vlan")
page.target = cbi("admin_network/vlan")
page.title = _("Switch")
page.order = 20
page = entry({"admin", "network", "switch_status"}, call("switch_status"), nil)
page.leaf = true
end
local has_wifi = false
uci:foreach("wireless", "wifi-device",
function(s)
has_wifi = true
return false
end)
if has_wifi then
page = entry({"admin", "network", "wireless_join"}, post("wifi_join"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless_add"}, post("wifi_add"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless_delete"}, post("wifi_delete"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless_status"}, call("wifi_status"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless_reconnect"}, post("wifi_reconnect"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless_shutdown"}, post("wifi_shutdown"), nil)
page.leaf = true
page = entry({"admin", "network", "wireless"}, arcombine(template("admin_network/wifi_overview"), cbi("admin_network/wifi")), _("Wireless"), 15)
page.leaf = true
page.subindex = true
if page.inreq then
local wdev
local net = require "luci.model.network".init(uci)
for _, wdev in ipairs(net:get_wifidevs()) do
local wnet
for _, wnet in ipairs(wdev:get_wifinets()) do
entry(
{"admin", "network", "wireless", wnet:id()},
alias("admin", "network", "wireless"),
wdev:name() .. ": " .. wnet:shortname()
)
end
end
end
end
page = entry({"admin", "network", "iface_add"}, cbi("admin_network/iface_add"), nil)
page.leaf = true
page = entry({"admin", "network", "iface_delete"}, post("iface_delete"), nil)
page.leaf = true
page = entry({"admin", "network", "iface_status"}, call("iface_status"), nil)
page.leaf = true
page = entry({"admin", "network", "iface_reconnect"}, post("iface_reconnect"), nil)
page.leaf = true
page = entry({"admin", "network", "iface_shutdown"}, post("iface_shutdown"), nil)
page.leaf = true
page = entry({"admin", "network", "network"}, arcombine(cbi("admin_network/network"), cbi("admin_network/ifaces")), _("Interfaces"), 10)
page.leaf = true
page.subindex = true
if page.inreq then
uci:foreach("network", "interface",
function (section)
local ifc = section[".name"]
if ifc ~= "loopback" then
entry({"admin", "network", "network", ifc},
true, ifc:upper())
end
end)
end
if nixio.fs.access("/etc/config/dhcp") then
page = node("admin", "network", "dhcp")
page.target = cbi("admin_network/dhcp")
page.title = _("DHCP and DNS")
page.order = 30
page = entry({"admin", "network", "dhcplease_status"}, call("lease_status"), nil)
page.leaf = true
page = node("admin", "network", "hosts")
page.target = cbi("admin_network/hosts")
page.title = _("Hostnames")
page.order = 40
end
page = node("admin", "network", "routes")
page.target = cbi("admin_network/routes")
page.title = _("Static Routes")
page.order = 50
page = node("admin", "network", "diagnostics")
page.target = template("admin_network/diagnostics")
page.title = _("Diagnostics")
page.order = 60
page = entry({"admin", "network", "diag_ping"}, post("diag_ping"), nil)
page.leaf = true
page = entry({"admin", "network", "diag_nslookup"}, post("diag_nslookup"), nil)
page.leaf = true
page = entry({"admin", "network", "diag_traceroute"}, post("diag_traceroute"), nil)
page.leaf = true
page = entry({"admin", "network", "diag_ping6"}, post("diag_ping6"), nil)
page.leaf = true
page = entry({"admin", "network", "diag_traceroute6"}, post("diag_traceroute6"), nil)
page.leaf = true
-- end
end
function wifi_join()
local tpl = require "luci.template"
local http = require "luci.http"
local dev = http.formvalue("device")
local ssid = http.formvalue("join")
if dev and ssid then
local cancel = (http.formvalue("cancel") or http.formvalue("cbi.cancel"))
if not cancel then
local cbi = require "luci.cbi"
local map = luci.cbi.load("admin_network/wifi_add")[1]
if map:parse() ~= cbi.FORM_DONE then
tpl.render("header")
map:render()
tpl.render("footer")
end
return
end
end
tpl.render("admin_network/wifi_join")
end
function wifi_add()
local dev = luci.http.formvalue("device")
local ntm = require "luci.model.network".init()
dev = dev and ntm:get_wifidev(dev)
if dev then
local net = dev:add_wifinet({
mode = "ap",
ssid = "OpenWrt",
encryption = "none"
})
ntm:save("wireless")
luci.http.redirect(net:adminlink())
end
end
function wifi_delete(network)
local ntm = require "luci.model.network".init()
local wnet = ntm:get_wifinet(network)
if wnet then
local dev = wnet:get_device()
local nets = wnet:get_networks()
if dev then
ntm:del_wifinet(network)
ntm:commit("wireless")
local _, net
for _, net in ipairs(nets) do
if net:is_empty() then
ntm:del_network(net:name())
ntm:commit("network")
end
end
luci.sys.call("env -i /bin/ubus call network reload >/dev/null 2>/dev/null")
end
end
luci.http.redirect(luci.dispatcher.build_url("admin/network/wireless"))
end
function iface_status(ifaces)
local netm = require "luci.model.network".init()
local rv = { }
local iface
for iface in ifaces:gmatch("[%w%.%-_]+") do
local net = netm:get_network(iface)
local device = net and net:get_interface()
if device then
local data = {
id = iface,
proto = net:proto(),
uptime = net:uptime(),
gwaddr = net:gwaddr(),
ipaddrs = net:ipaddrs(),
ip6addrs = net:ip6addrs(),
dnsaddrs = net:dnsaddrs(),
name = device:shortname(),
type = device:type(),
ifname = device:name(),
macaddr = device:mac(),
is_up = device:is_up(),
rx_bytes = device:rx_bytes(),
tx_bytes = device:tx_bytes(),
rx_packets = device:rx_packets(),
tx_packets = device:tx_packets(),
subdevices = { }
}
for _, device in ipairs(net:get_interfaces() or {}) do
data.subdevices[#data.subdevices+1] = {
name = device:shortname(),
type = device:type(),
ifname = device:name(),
macaddr = device:mac(),
macaddr = device:mac(),
is_up = device:is_up(),
rx_bytes = device:rx_bytes(),
tx_bytes = device:tx_bytes(),
rx_packets = device:rx_packets(),
tx_packets = device:tx_packets(),
}
end
rv[#rv+1] = data
else
rv[#rv+1] = {
id = iface,
name = iface,
type = "ethernet"
}
end
end
if #rv > 0 then
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
return
end
luci.http.status(404, "No such device")
end
function iface_reconnect(iface)
local netmd = require "luci.model.network".init()
local net = netmd:get_network(iface)
if net then
luci.sys.call("env -i /sbin/ifup %q >/dev/null 2>/dev/null" % iface)
luci.http.status(200, "Reconnected")
return
end
luci.http.status(404, "No such interface")
end
function iface_shutdown(iface)
local netmd = require "luci.model.network".init()
local net = netmd:get_network(iface)
if net then
luci.sys.call("env -i /sbin/ifdown %q >/dev/null 2>/dev/null" % iface)
luci.http.status(200, "Shutdown")
return
end
luci.http.status(404, "No such interface")
end
function iface_delete(iface)
local netmd = require "luci.model.network".init()
local net = netmd:del_network(iface)
if net then
luci.sys.call("env -i /sbin/ifdown %q >/dev/null 2>/dev/null" % iface)
luci.http.redirect(luci.dispatcher.build_url("admin/network/network"))
netmd:commit("network")
netmd:commit("wireless")
return
end
luci.http.status(404, "No such interface")
end
function wifi_status(devs)
local s = require "luci.tools.status"
local rv = { }
local dev
for dev in devs:gmatch("[%w%.%-]+") do
rv[#rv+1] = s.wifi_network(dev)
end
if #rv > 0 then
luci.http.prepare_content("application/json")
luci.http.write_json(rv)
return
end
luci.http.status(404, "No such device")
end
local function wifi_reconnect_shutdown(shutdown, wnet)
local netmd = require "luci.model.network".init()
local net = netmd:get_wifinet(wnet)
local dev = net:get_device()
if dev and net then
dev:set("disabled", nil)
net:set("disabled", shutdown and 1 or nil)
netmd:commit("wireless")
luci.sys.call("env -i /bin/ubus call network reload >/dev/null 2>/dev/null")
luci.http.status(200, shutdown and "Shutdown" or "Reconnected")
return
end
luci.http.status(404, "No such radio")
end
function wifi_reconnect(wnet)
wifi_reconnect_shutdown(false, wnet)
end
function wifi_shutdown(wnet)
wifi_reconnect_shutdown(true, wnet)
end
function lease_status()
local s = require "luci.tools.status"
luci.http.prepare_content("application/json")
luci.http.write('[')
luci.http.write_json(s.dhcp_leases())
luci.http.write(',')
luci.http.write_json(s.dhcp6_leases())
luci.http.write(']')
end
function switch_status(switches)
local s = require "luci.tools.status"
luci.http.prepare_content("application/json")
luci.http.write_json(s.switch_status(switches))
end
function diag_command(cmd, addr)
if addr and addr:match("^[a-zA-Z0-9%-%.:_]+$") then
luci.http.prepare_content("text/plain")
local util = io.popen(cmd % addr)
if util then
while true do
local ln = util:read("*l")
if not ln then break end
luci.http.write(ln)
luci.http.write("\n")
end
util:close()
end
return
end
luci.http.status(500, "Bad address")
end
function diag_ping(addr)
diag_command("ping -c 5 -W 1 %q 2>&1", addr)
end
function diag_traceroute(addr)
diag_command("traceroute -q 1 -w 1 -n %q 2>&1", addr)
end
function diag_nslookup(addr)
diag_command("nslookup %q 2>&1", addr)
end
function diag_ping6(addr)
diag_command("ping6 -c 5 %q 2>&1", addr)
end
function diag_traceroute6(addr)
diag_command("traceroute6 -q 1 -w 2 -n %q 2>&1", addr)
end
| apache-2.0 |
vadi2/Mudlet | src/mudlet-lua/lua/geyser/GeyserMapper.lua | 5 | 3939 | --------------------------------------
-- --
-- The Geyser Layout Manager by guy --
-- createMapper support by Vadi --
-- --
--------------------------------------
--- Represents a mapper primitive
-- @class table
-- @name Geyser.Mapper
-- @field wrapAt Where line wrapping occurs. Default is 300 characters.
Geyser.Mapper = Geyser.Window:new({
name = "MapperClass"
})
-- Save a reference to our parent constructor
Geyser.Mapper.parent = Geyser.Window
-- Overridden reposition function - mapper does it differently right now
-- automatic repositioning/resizing won't work with map widget
function Geyser.Mapper:reposition()
if self.hidden or self.auto_hidden then
return
end
if self.embedded then
createMapper(self.windowname, self:get_x(), self:get_y(), self:get_width(), self:get_height())
end
end
-- Overridden move and resize function - map widget does it differently right now
function Geyser.Mapper:move(x, y)
if self.hidden or self.auto_hidden then
return
end
Geyser.Container.move (self, x, y)
if not self.embedded then
moveMapWidget(self:get_x(), self:get_y())
end
end
function Geyser.Mapper:resize(width, height)
if self.hidden or self.auto_hidden then
return
end
Geyser.Container.resize (self, width, height)
if not self.embedded then
resizeMapWidget(self:get_width(), self:get_height())
end
end
function Geyser.Mapper:hide_impl()
if self.embedded then
createMapper(self.windowname, self:get_x(), self:get_y(), 0, 0)
else
closeMapWidget()
end
end
function Geyser.Mapper:show_impl()
if self.embedded then
createMapper(self.windowname, self:get_x(), self:get_y(), self:get_width(), self:get_height())
else
openMapWidget()
end
end
-- Overridden raise and lower functions
function Geyser.Mapper:raise()
raiseWindow("mapper")
end
function Geyser.Mapper:lower()
lowerWindow("mapper")
end
function Geyser.Mapper:setDockPosition(pos)
if not self.embedded then
return openMapWidget(pos)
end
end
function Geyser.Mapper:setTitle(text)
self.titleText = text
return setMapWindowTitle(text)
end
function Geyser.Mapper:resetTitle()
self.titleText = ""
return resetMapWindowTitle()
end
-- Overridden constructor
function Geyser.Mapper:new (cons, container)
cons = cons or {}
cons.type = cons.type or "mapper"
-- Call parent's constructor
local me = self.parent:new(cons, container)
me.windowname = me.windowname or me.container.windowname or "main"
me.was_hidden = false
-- Set the metatable.
setmetatable(me, self)
self.__index = self
if me.embedded == nil and not me.dockPosition then
me.embedded = true
end
-----------------------------------------------------------
-- Now create the Mapper using primitives
if me.dockPosition and me.dockPosition:lower() == "floating" then
me.dockPosition = "f"
end
if me.embedded then
createMapper(me.windowname, me:get_x(), me:get_y(),
me:get_width(), me:get_height())
else
me.embedded = false
if me.dockPosition and me.dockPosition ~= "f" then
openMapWidget(me.dockPosition)
elseif me.dockPosition == "f" or cons.x or cons.y or cons.width or cons.height then
openMapWidget(me:get_x(), me:get_y(),
me:get_width(), me:get_height())
else
openMapWidget()
end
if me.titleText then
me:setTitle(me.titleText)
else
me:resetTitle()
end
end
-- This only has an effect if add2 is being used as for the standard add method me.hidden and me.auto_hidden is always false at creation/initialisation
if me.hidden or me.auto_hidden then
me:hide_impl()
end
-- Set any defined colors
Geyser.Color.applyColors(me)
--print(" New in " .. self.name .. " : " .. me.name)
return me
end
--- Overridden constructor to use add2
function Geyser.Mapper:new2 (cons, container)
cons = cons or {}
cons.useAdd2 = true
local me = self:new(cons, container)
return me
end
| gpl-2.0 |
Lsty/ygopro-scripts | c23118924.lua | 3 | 1779 | --エレメント・デビル
function c23118924.initial_effect(c)
--disable
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_BATTLED)
e1:SetCondition(c23118924.discon)
e1:SetOperation(c23118924.disop)
c:RegisterEffect(e1)
--chain attack
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(23118924,0))
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_BATTLED)
e2:SetCondition(c23118924.atcon)
e2:SetOperation(c23118924.atop)
c:RegisterEffect(e2)
end
function c23118924.filter(c,att)
return c:IsFaceup() and c:IsAttribute(att)
end
function c23118924.discon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
return bc and bc:IsStatus(STATUS_BATTLE_DESTROYED) and not c:IsStatus(STATUS_BATTLE_DESTROYED)
and Duel.IsExistingMatchingCard(c23118924.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,ATTRIBUTE_EARTH)
end
function c23118924.disop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_DISABLE)
e1:SetReset(RESET_EVENT+0x17a0000)
bc:RegisterEffect(e1)
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_DISABLE_EFFECT)
e2:SetReset(RESET_EVENT+0x17a0000)
bc:RegisterEffect(e2)
end
function c23118924.atcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
local bc=c:GetBattleTarget()
return bc and bc:IsStatus(STATUS_BATTLE_DESTROYED) and c:IsChainAttackable() and c:IsStatus(STATUS_OPPO_BATTLE)
and not c:IsDisabled() and Duel.IsExistingMatchingCard(c23118924.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil,ATTRIBUTE_WIND)
end
function c23118924.atop(e,tp,eg,ep,ev,re,r,rp)
Duel.ChainAttack()
end
| gpl-2.0 |
Lsty/ygopro-scripts | c73285669.lua | 3 | 1500 | --剣闘獣エセダリ
function c73285669.initial_effect(c)
--fusion material
c:EnableReviveLimit()
aux.AddFusionProcFunRep(c,aux.FilterBoolFunction(Card.IsSetCard,0x19),2,true)
--spsummon condition
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetCode(EFFECT_SPSUMMON_CONDITION)
e1:SetValue(c73285669.splimit)
c:RegisterEffect(e1)
--special summon rule
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_FIELD)
e2:SetCode(EFFECT_SPSUMMON_PROC)
e2:SetProperty(EFFECT_FLAG_UNCOPYABLE)
e2:SetRange(LOCATION_EXTRA)
e2:SetCondition(c73285669.sprcon)
e2:SetOperation(c73285669.sprop)
c:RegisterEffect(e2)
end
function c73285669.splimit(e,se,sp,st)
return e:GetHandler():GetLocation()~=LOCATION_EXTRA
end
function c73285669.spfilter(c)
return c:IsSetCard(0x19) and c:IsCanBeFusionMaterial() and c:IsAbleToDeckOrExtraAsCost()
end
function c73285669.sprcon(e,c)
if c==nil then return true end
local tp=c:GetControler()
return Duel.GetLocationCount(tp,LOCATION_MZONE)>-2
and Duel.IsExistingMatchingCard(c73285669.spfilter,tp,LOCATION_MZONE,0,2,nil)
end
function c73285669.sprop(e,tp,eg,ep,ev,re,r,rp,c)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_TODECK)
local g=Duel.SelectMatchingCard(tp,c73285669.spfilter,tp,LOCATION_MZONE,0,2,2,nil)
local tc=g:GetFirst()
while tc do
if not tc:IsFaceup() then Duel.ConfirmCards(1-tp,tc) end
tc=g:GetNext()
end
Duel.SendtoDeck(g,nil,2,REASON_COST)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c62782218.lua | 3 | 2605 | --スカル・コンダクター
function c62782218.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(62782218,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCode(EVENT_PHASE+PHASE_BATTLE)
e1:SetTarget(c62782218.destg)
e1:SetOperation(c62782218.desop)
c:RegisterEffect(e1)
--spsummon
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(62782218,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_IGNITION)
e2:SetRange(LOCATION_HAND)
e2:SetCost(c62782218.spcost)
e2:SetTarget(c62782218.sptg)
e2:SetOperation(c62782218.spop)
c:RegisterEffect(e2)
end
function c62782218.destg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0)
end
function c62782218.desop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
if c:IsRelateToEffect(e) and c:IsFaceup() then
Duel.Destroy(c,REASON_EFFECT)
end
end
function c62782218.spcost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():IsAbleToGraveAsCost() end
Duel.SendtoGrave(e:GetHandler(),REASON_COST)
end
function c62782218.spfilter(c,e,tp,satk)
local atk=c:GetAttack()
return atk>=0 and (not satk or atk==satk) and c:IsRace(RACE_ZOMBIE)
and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c62782218.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return false end
if ft==1 then return Duel.IsExistingMatchingCard(c62782218.spfilter,tp,LOCATION_HAND,0,1,e:GetHandler(),e,tp,2000)
else
local g=Duel.GetMatchingGroup(c62782218.spfilter,tp,LOCATION_HAND,0,e:GetHandler(),e,tp)
return g:CheckWithSumEqual(Card.GetAttack,2000,1,2)
end
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND)
end
function c62782218.spop(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
if ft==1 then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c62782218.spfilter,tp,LOCATION_HAND,0,1,1,nil,e,tp,2000)
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
else
local g=Duel.GetMatchingGroup(c62782218.spfilter,tp,LOCATION_HAND,0,nil,e,tp)
if g:CheckWithSumEqual(Card.GetAttack,2000,1,2) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:SelectWithSumEqual(tp,Card.GetAttack,2000,1,2)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c64161630.lua | 5 | 2139 | --パージ・レイ
function c64161630.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCost(c64161630.cost)
e1:SetTarget(c64161630.target)
e1:SetOperation(c64161630.activate)
c:RegisterEffect(e1)
end
function c64161630.cfilter(c,e,tp)
local rk=c:GetRank()
return rk>1 and c:IsType(TYPE_XYZ)
and Duel.IsExistingMatchingCard(c64161630.filter,tp,LOCATION_EXTRA,0,1,nil,rk-1,c:GetRace(),e,tp)
end
function c64161630.filter(c,rk,rc,e,tp)
return c:IsType(TYPE_XYZ) and c:IsSetCard(0x48)
and c:GetRank()==rk and c:IsRace(rc) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c64161630.cost(e,tp,eg,ep,ev,re,r,rp,chk)
e:SetLabel(100)
if chk==0 then return Duel.CheckReleaseGroup(tp,c64161630.cfilter,1,nil,e,tp) end
local g=Duel.SelectReleaseGroup(tp,c64161630.cfilter,1,1,nil,e,tp)
e:SetLabel(g:GetFirst():GetRank())
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetLabel(g:GetFirst():GetRace())
Duel.RegisterEffect(e1,tp)
e:SetLabelObject(e1)
Duel.Release(g,REASON_COST)
end
function c64161630.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
if e:GetLabel()~=100 then return false end
e:SetLabel(0)
return Duel.GetLocationCount(tp,LOCATION_MZONE)>-1
end
end
function c64161630.activate(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetCountLimit(1)
e1:SetOperation(c64161630.spop)
e1:SetReset(RESET_PHASE+PHASE_END)
e1:SetLabel(e:GetLabel())
e1:SetLabelObject(e:GetLabelObject())
Duel.RegisterEffect(e1,tp)
end
function c64161630.spop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_CARD,0,64161630)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local rk=e:GetLabel()
local rc=e:GetLabelObject():GetLabel()
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c64161630.filter,tp,LOCATION_EXTRA,0,1,1,nil,rk-1,rc,e,tp)
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c74440055.lua | 3 | 1138 | --サボウ・ファイター
function c74440055.initial_effect(c)
--special summon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(74440055,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_DESTROYING)
e1:SetCondition(c74440055.condition)
e1:SetTarget(c74440055.target)
e1:SetOperation(c74440055.operation)
c:RegisterEffect(e1)
end
function c74440055.condition(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsRelateToBattle() and c:GetBattleTarget():IsType(TYPE_MONSTER)
end
function c74440055.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_TOKEN,nil,1,tp,0)
end
function c74440055.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetLocationCount(1-tp,LOCATION_MZONE)>0
and Duel.IsPlayerCanSpecialSummonMonster(tp,74440056,0,0x4011,500,500,1,RACE_PLANT,ATTRIBUTE_EARTH,POS_FACEUP_DEFENCE,1-tp) then
local token=Duel.CreateToken(tp,74440056)
Duel.SpecialSummon(token,0,tp,1-tp,false,false,POS_FACEUP_DEFENCE)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c39897277.lua | 3 | 1663 | --エルフの光
function c39897277.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_EQUIP)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetTarget(c39897277.target)
e1:SetOperation(c39897277.operation)
c:RegisterEffect(e1)
--atk up
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_EQUIP)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(400)
c:RegisterEffect(e2)
--def down
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_EQUIP)
e3:SetCode(EFFECT_UPDATE_DEFENCE)
e3:SetValue(-200)
c:RegisterEffect(e3)
--equip limit
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_EQUIP_LIMIT)
e4:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e4:SetValue(c39897277.eqlimit)
c:RegisterEffect(e4)
end
function c39897277.eqlimit(e,c)
return c:IsAttribute(ATTRIBUTE_LIGHT)
end
function c39897277.filter(c)
return c:IsFaceup() and c:IsAttribute(ATTRIBUTE_LIGHT)
end
function c39897277.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsLocation(LOCATION_MZONE) and c39897277.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c39897277.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP)
Duel.SelectTarget(tp,c39897277.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil)
Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0)
end
function c39897277.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if e:GetHandler():IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then
Duel.Equip(tp,e:GetHandler(),tc)
end
end
| gpl-2.0 |
GovanifY/Polycode | Examples/Lua/Graphics/SceneEntities/Scripts/ScreenEntities.lua | 10 | 1052 | --
-- This example demonstrates entity hierarchy by simulating a simple solar system.
-- Since entity transformations are always relative to the entity's parent
-- so the moon's rotation takes places around the planet, which is its parent.
--
scene = Scene(Scene.SCENE_2D)
sun = ScenePrimitive(ScenePrimitive.TYPE_CIRCLE, 0.2,0.2, 30)
sun:setColor(0.9, 0.8, 0, 1)
sun.colorAffectsChildren = false
scene:addChild(sun)
planet = ScenePrimitive(ScenePrimitive.TYPE_CIRCLE, 0.1,0.1, 30)
planet:setPosition(0.3,0)
planet:setColor(0.2, 0.8, 0, 1)
planet.colorAffectsChildren = false
sun:addChild(planet)
moon = ScenePrimitive(ScenePrimitive.TYPE_CIRCLE, 0.05, 0.05, 30)
moon:setPosition(0.1,0)
moon:setColor(1, 1, 0.6, 1)
planet:addChild(moon)
planetRotation = 0
moonRotation = 0
function Update(elapsed)
planetRotation = planetRotation + elapsed
moonRotation = moonRotation + (elapsed * 6)
planet:setPosition(cos(planetRotation)*0.3, sin(planetRotation)*0.3)
moon:setPosition(cos(moonRotation)*0.1, sin(moonRotation)*0.1)
end
| mit |
maxrio/luci981213 | applications/luci-app-asterisk/luasrc/model/cbi/asterisk-voice.lua | 68 | 1280 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
cbimap = Map("asterisk", "asterisk", "")
voicegeneral = cbimap:section(TypedSection, "voicegeneral", "Voicemail general options", "")
serveremail = voicegeneral:option(Value, "serveremail", "From Email address of server", "")
voicemail = cbimap:section(TypedSection, "voicemail", "Voice Mail boxes", "")
voicemail.addremove = true
attach = voicemail:option(Flag, "attach", "Email contains attachment", "")
attach.rmempty = true
email = voicemail:option(Value, "email", "Email", "")
email.rmempty = true
name = voicemail:option(Value, "name", "Display Name", "")
name.rmempty = true
password = voicemail:option(Value, "password", "Password", "")
password.rmempty = true
zone = voicemail:option(ListValue, "zone", "Voice Zone", "")
cbimap.uci:foreach( "asterisk", "voicezone", function(s) zone:value(s['.name']) end )
voicezone = cbimap:section(TypedSection, "voicezone", "Voice Zone settings", "")
voicezone.addremove = true
message = voicezone:option(Value, "message", "Message Format", "")
message.rmempty = true
zone = voicezone:option(Value, "zone", "Time Zone", "")
zone.rmempty = true
return cbimap
| apache-2.0 |
Lsty/ygopro-scripts | c38109772.lua | 3 | 1883 | --竜の騎士
function c38109772.initial_effect(c)
--spsummon
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(38109772,0))
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_CHAINING)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c38109772.condition)
e1:SetCost(c38109772.cost)
e1:SetTarget(c38109772.target)
e1:SetOperation(c38109772.operation)
c:RegisterEffect(e1)
local g=Group.CreateGroup()
g:KeepAlive()
e1:SetLabelObject(g)
end
function c38109772.filter(c,tp,dg)
return c:IsControler(tp) and dg:IsContains(c)
end
function c38109772.condition(e,tp,eg,ep,ev,re,r,rp)
if rp==tp or not re:IsActiveType(TYPE_MONSTER) or not re:IsHasProperty(EFFECT_FLAG_CARD_TARGET) then return false end
local tg=Duel.GetChainInfo(ev,CHAININFO_TARGET_CARDS)
if not tg or tg:GetCount()==0 then return false end
local ex,dg,dc=Duel.GetOperationInfo(ev,CATEGORY_DESTROY)
if not ex or not dg then return false end
local cg=tg:Filter(c38109772.filter,nil,tp,dg)
if cg:GetCount()>0 then
e:GetLabelObject():Clear()
e:GetLabelObject():Merge(cg)
return true
end
return false
end
function c38109772.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetLabelObject():FilterCount(Card.IsAbleToGraveAsCost,nil)==e:GetLabelObject():GetCount() end
Duel.SendtoGrave(e:GetLabelObject(),REASON_COST)
end
function c38109772.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then
local ct=e:GetLabelObject():FilterCount(Card.IsLocation,nil,LOCATION_MZONE)
return Duel.GetLocationCount(tp,LOCATION_MZONE)>-ct and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false)
end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,eg,1,0,0)
end
function c38109772.operation(e,tp,eg,ep,ev,re,r,rp)
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c72167543.lua | 9 | 1119 | --ダウナード・マジシャン
function c72167543.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_SPELLCASTER),4,2,c72167543.ovfilter,aux.Stringid(72167543,0))
c:EnableReviveLimit()
--pierce
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE)
e1:SetCode(EFFECT_PIERCE)
c:RegisterEffect(e1)
--atkup
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e2:SetRange(LOCATION_MZONE)
e2:SetCode(EFFECT_UPDATE_ATTACK)
e2:SetValue(c72167543.atkval)
c:RegisterEffect(e2)
--remove material
local e3=Effect.CreateEffect(c)
e3:SetDescription(aux.Stringid(72167543,1))
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e3:SetCode(EVENT_BATTLED)
e3:SetOperation(c72167543.rmop)
c:RegisterEffect(e3)
end
function c72167543.ovfilter(c)
return c:IsFaceup() and c:IsRankBelow(3) and Duel.GetCurrentPhase()==PHASE_MAIN2
end
function c72167543.atkval(e,c)
return c:GetOverlayCount()*200
end
function c72167543.rmop(e,tp,eg,ep,ev,re,r,rp)
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_EFFECT)
end
| gpl-2.0 |
maxrio/luci981213 | modules/luci-mod-admin-mini/luasrc/model/cbi/mini/dhcp.lua | 62 | 2782 | -- Copyright 2008 Steven Barth <steven@midlink.org>
-- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local uci = require "luci.model.uci".cursor()
local ipc = require "luci.ip"
local wa = require "luci.tools.webadmin"
local fs = require "nixio.fs"
m = Map("dhcp", "DHCP")
s = m:section(TypedSection, "dhcp", "DHCP-Server")
s.anonymous = true
s.addremove = false
s.dynamic = false
s:depends("interface", "lan")
enable = s:option(ListValue, "ignore", translate("enable"), "")
enable:value(0, translate("enable"))
enable:value(1, translate("disable"))
start = s:option(Value, "start", translate("First leased address"))
start.rmempty = true
start:depends("ignore", "0")
limit = s:option(Value, "limit", translate("Number of leased addresses"), "")
limit:depends("ignore", "0")
function limit.cfgvalue(self, section)
local value = Value.cfgvalue(self, section)
if value then
return tonumber(value) + 1
end
end
function limit.write(self, section, value)
value = tonumber(value) - 1
return Value.write(self, section, value)
end
limit.rmempty = true
time = s:option(Value, "leasetime")
time:depends("ignore", "0")
time.rmempty = true
local leasefn, leasefp, leases
uci:foreach("dhcp", "dnsmasq",
function(section)
leasefn = section.leasefile
end
)
local leasefp = leasefn and fs.access(leasefn) and io.lines(leasefn)
if leasefp then
leases = {}
for lease in leasefp do
table.insert(leases, luci.util.split(lease, " "))
end
end
if leases then
v = m:section(Table, leases, translate("Active Leases"))
name = v:option(DummyValue, 4, translate("Hostname"))
function name.cfgvalue(self, ...)
local value = DummyValue.cfgvalue(self, ...)
return (value == "*") and "?" or value
end
ip = v:option(DummyValue, 3, translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
mac = v:option(DummyValue, 2, translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"))
ltime = v:option(DummyValue, 1, translate("Leasetime remaining"))
function ltime.cfgvalue(self, ...)
local value = DummyValue.cfgvalue(self, ...)
return wa.date_format(os.difftime(tonumber(value), os.time()))
end
end
s2 = m:section(TypedSection, "host", translate("Static Leases"))
s2.addremove = true
s2.anonymous = true
s2.template = "cbi/tblsection"
name = s2:option(Value, "name", translate("Hostname"))
mac = s2:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address"))
ip = s2:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address"))
ipc.neighbors({ family = 4 }, function(n)
if n.mac and n.dest then
ip:value(n.dest:string())
mac:value(n.mac, "%s (%s)" %{ n.mac, n.dest:string() })
end
end)
return m
| apache-2.0 |
Lsty/ygopro-scripts | c20785975.lua | 5 | 2911 | --CNo.103 神葬零嬢ラグナ・インフィニティ
function c20785975.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,nil,5,3)
c:EnableReviveLimit()
--
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(20785975,0))
e1:SetCategory(CATEGORY_REMOVE+CATEGORY_DAMAGE)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetProperty(EFFECT_FLAG_CARD_TARGET)
e1:SetRange(LOCATION_MZONE)
e1:SetCountLimit(1)
e1:SetCost(c20785975.cost)
e1:SetTarget(c20785975.target)
e1:SetOperation(c20785975.operation)
c:RegisterEffect(e1)
--
local e2=Effect.CreateEffect(c)
e2:SetDescription(aux.Stringid(20785975,1))
e2:SetCategory(CATEGORY_SPECIAL_SUMMON)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetCondition(c20785975.spcon)
e2:SetTarget(c20785975.sptg)
e2:SetOperation(c20785975.spop)
c:RegisterEffect(e2)
end
c20785975.xyz_number=103
function c20785975.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c20785975.filter(c)
return c:IsFaceup() and c:GetAttack()~=c:GetBaseAttack() and c:IsAbleToRemove()
end
function c20785975.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c20785975.filter(chkc) end
if chk==0 then return Duel.IsExistingTarget(c20785975.filter,tp,0,LOCATION_MZONE,1,nil) end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE)
local g=Duel.SelectTarget(tp,c20785975.filter,tp,0,LOCATION_MZONE,1,1,nil)
local tc=g:GetFirst()
local atk=math.abs(tc:GetAttack()-tc:GetBaseAttack())
Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0)
Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,1,1-tp,atk)
end
function c20785975.operation(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
local atk=math.abs(tc:GetAttack()-tc:GetBaseAttack())
if tc:IsRelateToEffect(e) and tc:IsFaceup() and Duel.Damage(1-tp,atk,REASON_EFFECT)~=0 then
Duel.Remove(tc,POS_FACEUP,REASON_EFFECT)
end
end
function c20785975.spcon(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
return c:IsReason(REASON_DESTROY) and c:IsPreviousLocation(LOCATION_MZONE) and c:GetOverlayCount()>0
end
function c20785975.sptg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0
and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,false,false)
and Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,0,1,nil,94380860) end
Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0)
end
function c20785975.spop(e,tp,eg,ep,ev,re,r,rp)
if not Duel.IsExistingMatchingCard(Card.IsCode,tp,LOCATION_GRAVE,0,1,nil,94380860) then return end
if e:GetHandler():IsRelateToEffect(e) then
Duel.SpecialSummon(e:GetHandler(),0,tp,tp,false,false,POS_FACEUP)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c3758046.lua | 3 | 2949 | --DDD怒濤王シーザー
function c3758046.initial_effect(c)
--xyz summon
aux.AddXyzProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_FIEND),4,2)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_QUICK_O)
e1:SetRange(LOCATION_MZONE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCountLimit(1,3758046)
e1:SetCost(c3758046.cost)
e1:SetOperation(c3758046.operation)
c:RegisterEffect(e1)
--search
local e2=Effect.CreateEffect(c)
e2:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH)
e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O)
e2:SetCode(EVENT_TO_GRAVE)
e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY)
e2:SetCountLimit(1,3758047)
e2:SetCondition(c3758046.thcon)
e2:SetTarget(c3758046.thtg)
e2:SetOperation(c3758046.thop)
c:RegisterEffect(e2)
end
function c3758046.cost(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end
e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST)
end
function c3758046.operation(e,tp,eg,ep,ev,re,r,rp)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_BATTLE)
e1:SetCountLimit(1)
e1:SetOperation(c3758046.spop)
e1:SetReset(RESET_PHASE+PHASE_END)
Duel.RegisterEffect(e1,tp)
end
function c3758046.filter(c,e,tp,id)
return c:IsReason(REASON_DESTROY) and c:GetTurnID()==id and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c3758046.spop(e,tp,eg,ep,ev,re,r,rp)
local ft=Duel.GetLocationCount(tp,LOCATION_MZONE)
if ft<=0 then return end
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local g=Duel.SelectMatchingCard(tp,c3758046.filter,tp,LOCATION_GRAVE,0,ft,ft,nil,e,tp,Duel.GetTurnCount())
if g:GetCount()>0 then
Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP)
local e1=Effect.CreateEffect(e:GetHandler())
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_STANDBY)
e1:SetCountLimit(1)
e1:SetLabel(g:GetCount())
e1:SetReset(RESET_PHASE+PHASE_STANDBY)
e1:SetOperation(c3758046.damop)
Duel.RegisterEffect(e1,tp)
end
end
function c3758046.damop(e,tp,eg,ep,ev,re,r,rp)
Duel.Damage(tp,e:GetLabel()*1000,REASON_EFFECT)
end
function c3758046.thcon(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD)
end
function c3758046.thfilter(c)
return c:IsSetCard(0xae) and c:IsAbleToHand()
end
function c3758046.thtg(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.IsExistingMatchingCard(c3758046.thfilter,tp,LOCATION_DECK,0,1,nil) end
Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK)
end
function c3758046.thop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND)
local g=Duel.SelectMatchingCard(tp,c3758046.thfilter,tp,LOCATION_DECK,0,1,1,nil)
if g:GetCount()>0 then
Duel.SendtoHand(g,nil,REASON_EFFECT)
Duel.ConfirmCards(1-tp,g)
end
end
| gpl-2.0 |
Lsty/ygopro-scripts | c14291024.lua | 3 | 2772 | --オプション
function c14291024.initial_effect(c)
c:EnableReviveLimit()
--special summon
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_FIELD)
e1:SetCode(EFFECT_SPSUMMON_PROC)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetRange(LOCATION_HAND)
e1:SetCondition(c14291024.spcon)
c:RegisterEffect(e1)
--spsummon con
local e2=Effect.CreateEffect(c)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(EFFECT_SPSUMMON_CONDITION)
e2:SetValue(c14291024.splimit)
c:RegisterEffect(e2)
--set target
local e3=Effect.CreateEffect(c)
e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e3:SetCode(EVENT_SPSUMMON_SUCCESS)
e3:SetProperty(EFFECT_FLAG_CANNOT_DISABLE)
e3:SetOperation(c14291024.tgop)
c:RegisterEffect(e3)
--atk.def
local e4=Effect.CreateEffect(c)
e4:SetType(EFFECT_TYPE_SINGLE)
e4:SetCode(EFFECT_SET_ATTACK_FINAL)
e4:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e4:SetRange(LOCATION_MZONE)
e4:SetCondition(c14291024.adcon)
e4:SetValue(c14291024.atkval)
c:RegisterEffect(e4)
local e5=Effect.CreateEffect(c)
e5:SetType(EFFECT_TYPE_SINGLE)
e5:SetCode(EFFECT_SET_DEFENCE_FINAL)
e5:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e5:SetRange(LOCATION_MZONE)
e5:SetCondition(c14291024.adcon)
e5:SetValue(c14291024.defval)
c:RegisterEffect(e5)
--destroy
local e6=Effect.CreateEffect(c)
e6:SetType(EFFECT_TYPE_SINGLE)
e6:SetCode(EFFECT_SELF_DESTROY)
e6:SetProperty(EFFECT_FLAG_SINGLE_RANGE)
e6:SetRange(LOCATION_MZONE)
e6:SetCondition(c14291024.sdcon)
c:RegisterEffect(e6)
end
function c14291024.filter(c)
return c:IsFaceup() and c:IsCode(10992251)
end
function c14291024.spcon(e,c)
if c==nil then return true end
return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>0
and Duel.IsExistingMatchingCard(c14291024.filter,c:GetControler(),LOCATION_MZONE,0,1,nil)
end
function c14291024.splimit(e,se,sp,st,pos,top)
if bit.band(pos,POS_FACEDOWN)~=0 then return false end
return Duel.IsExistingMatchingCard(c14291024.filter,top,LOCATION_MZONE,0,1,nil)
end
function c14291024.tgop(e,tp,eg,ep,ev,re,r,rp)
local c=e:GetHandler()
Duel.Hint(HINT_SELECTMSG,tp,aux.Stringid(14291024,0))
local g=Duel.SelectMatchingCard(tp,c14291024.filter,tp,LOCATION_MZONE,0,1,1,nil)
Duel.HintSelection(g)
c:SetCardTarget(g:GetFirst())
c:RegisterFlagEffect(14291024,RESET_EVENT+0x1ff0000,0,1)
end
function c14291024.adcon(e)
return e:GetHandler():GetFirstCardTarget()~=nil
end
function c14291024.atkval(e,c)
return c:GetFirstCardTarget():GetAttack()
end
function c14291024.defval(e,c)
return c:GetFirstCardTarget():GetDefence()
end
function c14291024.sdcon(e)
return e:GetHandler():GetFirstCardTarget()==nil and e:GetHandler():GetFlagEffect(14291024)~=0
end
| gpl-2.0 |
intel2TM/intel | libs/dkjson.lua | 3282 | 26558 | -- 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
--> | gpl-2.0 |
mohammad25253/new43 | libs/dkjson.lua | 3282 | 26558 | -- 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
--> | gpl-2.0 |
hafez16/-Assassin- | libs/dkjson.lua | 3282 | 26558 | -- 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
--> | gpl-2.0 |
Attractive1/Attractive-Robot | libs/dkjson.lua | 3282 | 26558 | -- 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
--> | gpl-2.0 |
moody2020/TH3_BOSS | libs/dkjson.lua | 3282 | 26558 | -- 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
--> | gpl-2.0 |
MalRD/darkstar | scripts/commands/spawnmob.lua | 22 | 1221 | ---------------------------------------------------------------------------------------------------
-- func: spawnmob
-- desc: Spawns a mob.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "iii"
};
function error(player, msg)
player:PrintToPlayer(msg);
player:PrintToPlayer("!spawnmob <mob ID> {despawntime} {respawntime}");
end;
function onTrigger(player, mobId, despawntime, respawntime)
-- validate mobId
if (mobId == nil) then
error(player, "You must provide a mob ID.");
return;
end
local targ = GetMobByID(mobId);
if (targ == nil) then
error(player, "Invalid mob ID.");
return;
end
-- validate despawntime
if (despawntime ~= nil and despawntime < 0) then
error(player, "Invalid despawn time.");
return;
end
-- validate respawntime
if (respawntime ~= nil and respawntime < 0) then
error(player, "Invalid respawn time.");
return;
end
SpawnMob( targ:getID(), despawntime, respawntime );
player:PrintToPlayer( string.format("Spawned %s %s.", targ:getName(), targ:getID()) );
end | gpl-3.0 |
sagarwaghmare69/nn | VolumetricMaxPooling.lua | 9 | 2555 | local VolumetricMaxPooling, parent = torch.class('nn.VolumetricMaxPooling', 'nn.Module')
VolumetricMaxPooling.__version = 2
function VolumetricMaxPooling:__init(kT, kW, kH, dT, dW, dH, padT, padW, padH)
parent.__init(self)
dT = dT or kT
dW = dW or kW
dH = dH or kH
self.kT = kT
self.kH = kH
self.kW = kW
self.dT = dT
self.dW = dW
self.dH = dH
self.padT = padT or 0
self.padW = padW or 0
self.padH = padH or 0
self.ceil_mode = false
self.indices = torch.LongTensor()
end
function VolumetricMaxPooling:ceil()
self.ceil_mode = true
return self
end
function VolumetricMaxPooling:floor()
self.ceil_mode = false
return self
end
function VolumetricMaxPooling:updateOutput(input)
local dims = input:dim()
self.itime = input:size(dims-2)
self.iheight = input:size(dims-1)
self.iwidth = input:size(dims)
self.indices = self.indices or torch.LongTensor()
if torch.typename(input):find('torch%.Cuda.*Tensor') then
self.indices = torch.CudaLongTensor and self.indices:cudaLong() or self.indices
else
self.indices = self.indices:long()
end
input.THNN.VolumetricMaxPooling_updateOutput(
input:cdata(),
self.output:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.ceil_mode
)
return self.output
end
function VolumetricMaxPooling:updateGradInput(input, gradOutput)
input.THNN.VolumetricMaxPooling_updateGradInput(
input:cdata(),
gradOutput:cdata(),
self.gradInput:cdata(),
self.indices:cdata(),
self.kT, self.kW, self.kH,
self.dT, self.dW, self.dH,
self.padT, self.padW, self.padH,
self.ceil_mode
)
return self.gradInput
end
function VolumetricMaxPooling:empty()
self:clearState()
end
function VolumetricMaxPooling:clearState()
if self.indices then self.indices:set() end
return parent.clearState(self)
end
function VolumetricMaxPooling:read(file, version)
parent.read(self, file)
if version < 2 then
self.ceil_mode = false
end
end
function VolumetricMaxPooling:__tostring__()
local s = string.format('%s(%dx%dx%d, %d,%d,%d', torch.type(self),
self.kT, self.kW, self.kH, self.dT, self.dW, self.dH)
if (self.padT or self.padW or self.padH) and
(self.padT ~= 0 or self.padW ~= 0 or self.padH ~= 0) then
s = s .. ', ' .. self.padT.. ',' .. self.padW .. ','.. self.padH
end
s = s .. ')'
return s
end
| bsd-3-clause |
Lsty/ygopro-scripts | c62161698.lua | 3 | 1904 | --イリュージョン・バルーン
function c62161698.initial_effect(c)
--Activate
local e1=Effect.CreateEffect(c)
e1:SetCategory(CATEGORY_SPECIAL_SUMMON)
e1:SetType(EFFECT_TYPE_ACTIVATE)
e1:SetCode(EVENT_FREE_CHAIN)
e1:SetCondition(c62161698.condition)
e1:SetTarget(c62161698.target)
e1:SetOperation(c62161698.operation)
c:RegisterEffect(e1)
if not c62161698.global_check then
c62161698.global_check=true
local ge1=Effect.CreateEffect(c)
ge1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
ge1:SetCode(EVENT_DESTROYED)
ge1:SetOperation(c62161698.checkop)
Duel.RegisterEffect(ge1,0)
end
end
function c62161698.checkop(e,tp,eg,ep,ev,re,r,rp)
local tc=eg:GetFirst()
local p1=false
local p2=false
while tc do
if tc:IsPreviousLocation(LOCATION_MZONE) then
if tc:GetPreviousControler()==0 then p1=true else p2=true end
end
tc=eg:GetNext()
end
if p1 then Duel.RegisterFlagEffect(0,62161698,RESET_PHASE+PHASE_END,0,1) end
if p2 then Duel.RegisterFlagEffect(1,62161698,RESET_PHASE+PHASE_END,0,1) end
end
function c62161698.condition(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetFlagEffect(tp,62161698)~=0
end
function c62161698.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)>4 end
end
function c62161698.filter(c,e,tp)
return c:IsSetCard(0x9f) and c:IsCanBeSpecialSummoned(e,0,tp,false,false)
end
function c62161698.operation(e,tp,eg,ep,ev,re,r,rp)
if Duel.GetFieldGroupCount(tp,LOCATION_DECK,0)==0 then return end
Duel.ConfirmDecktop(tp,5)
if Duel.GetLocationCount(tp,LOCATION_MZONE)<=0 then return end
local g=Duel.GetDecktopGroup(tp,5):Filter(c62161698.filter,nil,e,tp)
if g:GetCount()>0 and Duel.SelectYesNo(tp,aux.Stringid(62161698,0)) then
Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON)
local sg=g:Select(tp,1,1,nil)
Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP)
end
Duel.ShuffleDeck(tp)
end
| gpl-2.0 |
Lsty/ygopro-scripts | c13846680.lua | 3 | 1087 | --ヘルプロミネンス
function c13846680.initial_effect(c)
--destroy
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(13846680,0))
e1:SetCategory(CATEGORY_DESTROY)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_BATTLE_DESTROYED)
e1:SetCondition(c13846680.condition)
e1:SetTarget(c13846680.target)
e1:SetOperation(c13846680.operation)
c:RegisterEffect(e1)
end
function c13846680.condition(e,tp,eg,ep,ev,re,r,rp)
return e:GetHandler():IsLocation(LOCATION_GRAVE) and e:GetHandler():IsReason(REASON_BATTLE)
end
function c13846680.filter(c)
return (c:IsFacedown() or c:GetAttribute()~=ATTRIBUTE_FIRE) and c:IsDestructable()
end
function c13846680.target(e,tp,eg,ep,ev,re,r,rp,chk)
if chk==0 then return true end
local g=Duel.GetMatchingGroup(c13846680.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0)
end
function c13846680.operation(e,tp,eg,ep,ev,re,r,rp)
local g=Duel.GetMatchingGroup(c13846680.filter,tp,LOCATION_MZONE,LOCATION_MZONE,nil)
Duel.Destroy(g,REASON_EFFECT)
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.